blob: 5fed05fa75bc95b787eabb1dd6f23cabe95cf149 [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]420ae012009-04-24 05:16:3240#include "chrome/browser/search_engines/template_url_fetcher.h"
41#include "chrome/browser/search_engines/template_url_model.h"
[email protected]35f7d212009-04-29 21:19:2742#include "chrome/common/chrome_switches.h"
[email protected]bfd04a62009-02-01 18:16:5643#include "chrome/common/notification_service.h"
[email protected]ce5c4502009-05-06 16:46:1144#include "chrome/common/page_action.h"
initial.commit09911bf2008-07-26 23:55:2945#include "chrome/common/pref_names.h"
[email protected]1eb89e82008-08-15 12:27:0346#include "chrome/common/pref_service.h"
[email protected]420ae012009-04-24 05:16:3247#include "chrome/common/render_messages.h"
[email protected]96d185d2009-04-24 03:28:5448#include "chrome/common/url_constants.h"
[email protected]8897c382009-05-06 17:53:2649#include "grit/generated_resources.h"
[email protected]420ae012009-04-24 05:16:3250#include "grit/locale_settings.h"
51#include "net/base/mime_util.h"
52#include "net/base/net_errors.h"
[email protected]d686e812009-06-03 19:10:2953#include "net/base/net_util.h"
[email protected]420ae012009-04-24 05:16:3254#include "net/base/registry_controlled_domain.h"
[email protected]3e45ba92009-02-20 21:09:0055
56#if defined(OS_WIN)
[email protected]66ba4932009-06-04 19:22:1357// For CRect
[email protected]9041a302009-06-04 19:36:3358#include <atlbase.h>
[email protected]326f7112009-06-04 19:30:2959#include <atlapp.h>
[email protected]66ba4932009-06-04 19:22:1360#include <atlmisc.h>
[email protected]3e45ba92009-02-20 21:09:0061// TODO(port): some of these headers should be ported.
[email protected]420ae012009-04-24 05:16:3262#include "chrome/browser/modal_html_dialog_delegate.h"
[email protected]2362e4f2009-05-08 00:34:0563#include "views/controls/scrollbar/native_scroll_bar.h"
[email protected]3e45ba92009-02-20 21:09:0064#endif
initial.commit09911bf2008-07-26 23:55:2965
[email protected]420ae012009-04-24 05:16:3266// Cross-Site Navigations
67//
68// If a TabContents is told to navigate to a different web site (as determined
69// by SiteInstance), it will replace its current RenderViewHost with a new
70// RenderViewHost dedicated to the new SiteInstance. This works as follows:
71//
72// - Navigate determines whether the destination is cross-site, and if so,
73// it creates a pending_render_view_host_ and moves into the PENDING
74// RendererState.
75// - The pending RVH is "suspended," so that no navigation messages are sent to
76// its renderer until the onbeforeunload JavaScript handler has a chance to
77// run in the current RVH.
78// - The pending RVH tells CrossSiteRequestManager (a thread-safe singleton)
79// that it has a pending cross-site request. ResourceDispatcherHost will
80// check for this when the response arrives.
81// - The current RVH runs its onbeforeunload handler. If it returns false, we
82// cancel all the pending logic and go back to NORMAL. Otherwise we allow
83// the pending RVH to send the navigation request to its renderer.
84// - ResourceDispatcherHost receives a ResourceRequest on the IO thread. It
85// checks CrossSiteRequestManager to see that the RVH responsible has a
86// pending cross-site request, and then installs a CrossSiteEventHandler.
87// - When RDH receives a response, the BufferedEventHandler determines whether
88// it is a download. If so, it sends a message to the new renderer causing
89// it to cancel the request, and the download proceeds in the download
90// thread. For now, we stay in a PENDING state (with a pending RVH) until
[email protected]57c6a652009-05-04 07:58:3491// the next DidNavigate event for this TabContents. This isn't ideal, but it
[email protected]420ae012009-04-24 05:16:3292// doesn't affect any functionality.
93// - After RDH receives a response and determines that it is safe and not a
94// download, it pauses the response to first run the old page's onunload
95// handler. It does this by asynchronously calling the OnCrossSiteResponse
[email protected]57c6a652009-05-04 07:58:3496// method of TabContents on the UI thread, which sends a ClosePage message
[email protected]420ae012009-04-24 05:16:3297// to the current RVH.
98// - Once the onunload handler is finished, a ClosePage_ACK message is sent to
99// the ResourceDispatcherHost, who unpauses the response. Data is then sent
100// to the pending RVH.
101// - The pending renderer sends a FrameNavigate message that invokes the
102// DidNavigate method. This replaces the current RVH with the
103// pending RVH and goes back to the NORMAL RendererState.
104
105namespace {
106
107// Amount of time we wait between when a key event is received and the renderer
108// is queried for its state and pushed to the NavigationEntry.
109const int kQueryStateDelay = 5000;
110
111const int kSyncWaitDelay = 40;
112
113// If another javascript message box is displayed within
114// kJavascriptMessageExpectedDelay of a previous javascript message box being
115// dismissed, display an option to suppress future message boxes from this
116// contents.
117const int kJavascriptMessageExpectedDelay = 1000;
118
[email protected]420ae012009-04-24 05:16:32119const char kLinkDoctorBaseURL[] =
120 "http://linkhelp.clients.google.com/tbproxy/lh/fixurl";
121
122// The printer icon in shell32.dll. That's a standard icon user will quickly
123// recognize.
124const int kShell32PrinterIcon = 17;
125
126// The list of prefs we want to observe.
127const wchar_t* kPrefsToObserve[] = {
128 prefs::kAlternateErrorPagesEnabled,
129 prefs::kWebKitJavaEnabled,
130 prefs::kWebKitJavascriptEnabled,
131 prefs::kWebKitLoadsImagesAutomatically,
132 prefs::kWebKitPluginsEnabled,
133 prefs::kWebKitUsesUniversalDetector,
[email protected]96d3fb52009-05-27 14:51:21134 prefs::kWebKitDeveloperExtrasEnabled,
[email protected]420ae012009-04-24 05:16:32135 prefs::kWebKitSerifFontFamily,
136 prefs::kWebKitSansSerifFontFamily,
137 prefs::kWebKitFixedFontFamily,
138 prefs::kWebKitDefaultFontSize,
139 prefs::kWebKitDefaultFixedFontSize,
140 prefs::kDefaultCharset
141 // kWebKitStandardFontIsSerif needs to be added
142 // if we let users pick which font to use, serif or sans-serif when
143 // no font is specified or a CSS generic family (serif or sans-serif)
144 // is not specified.
145};
146
147const int kPrefsToObserveLength = arraysize(kPrefsToObserve);
148
149// Limit on the number of suggestions to appear in the pop-up menu under an
150// text input element in a form.
151const int kMaxAutofillMenuItems = 6;
152
153// Returns true if the entry's transition type is FORM_SUBMIT.
154bool IsFormSubmit(const NavigationEntry* entry) {
155 return (PageTransition::StripQualifier(entry->transition_type()) ==
156 PageTransition::FORM_SUBMIT);
157}
158
159#if defined(OS_WIN)
160
161BOOL CALLBACK InvalidateWindow(HWND hwnd, LPARAM lparam) {
162 // Note: erase is required to properly paint some widgets borders. This can
163 // be seen with textfields.
164 InvalidateRect(hwnd, NULL, TRUE);
165 return TRUE;
166}
167#endif
168
[email protected]57c6a652009-05-04 07:58:34169// TODO(brettw) TabContents should be removed, then this hack is unnecessary.
170TabContents* AsWC(TabContents* tc) {
171 return static_cast<TabContents*>(tc);
[email protected]420ae012009-04-24 05:16:32172}
173
174} // namespace
175
176// -----------------------------------------------------------------------------
177
[email protected]fdd61c62009-04-22 19:22:57178// static
179int TabContents::find_request_id_counter_ = -1;
180
[email protected]420ae012009-04-24 05:16:32181class TabContents::GearsCreateShortcutCallbackFunctor {
182 public:
183 explicit GearsCreateShortcutCallbackFunctor(TabContents* contents)
184 : contents_(contents) {}
185
186 void Run(const GearsShortcutData2& shortcut_data, bool success) {
187 if (contents_)
188 contents_->OnGearsCreateShortcutDone(shortcut_data, success);
189 delete this;
190 }
191 void Cancel() {
192 contents_ = NULL;
193 }
194
195 private:
196 TabContents* contents_;
197};
198
[email protected]57c6a652009-05-04 07:58:34199// TODO(brettw) many of the data members here have casts to TabContents.
200// This object is the same as TabContents and is currently being merged.
[email protected]fdd61c62009-04-22 19:22:57201// When this merge is done, the casts can be removed.
[email protected]420ae012009-04-24 05:16:32202TabContents::TabContents(Profile* profile,
203 SiteInstance* site_instance,
204 int routing_id,
205 base::WaitableEvent* modal_dialog_event)
[email protected]b680ad22009-04-15 23:19:42206 : delegate_(NULL),
[email protected]66ba4932009-06-04 19:22:13207 ALLOW_THIS_IN_INITIALIZER_LIST(controller_(this, profile)),
208 ALLOW_THIS_IN_INITIALIZER_LIST(view_(
209 TabContentsView::Create(static_cast<TabContents*>(this)))),
[email protected]fdd61c62009-04-22 19:22:57210 ALLOW_THIS_IN_INITIALIZER_LIST(render_manager_(
[email protected]57c6a652009-05-04 07:58:34211 static_cast<TabContents*>(this),
212 static_cast<TabContents*>(this))),
[email protected]fdd61c62009-04-22 19:22:57213 property_bag_(),
214 registrar_(),
[email protected]66ba4932009-06-04 19:22:13215 ALLOW_THIS_IN_INITIALIZER_LIST(printing_(
216 *static_cast<TabContents*>(this))),
[email protected]fdd61c62009-04-22 19:22:57217 save_package_(),
218 cancelable_consumer_(),
219 autofill_manager_(),
220 password_manager_(),
221 plugin_installer_(),
222 ALLOW_THIS_IN_INITIALIZER_LIST(fav_icon_helper_(
[email protected]57c6a652009-05-04 07:58:34223 static_cast<TabContents*>(this))),
[email protected]fdd61c62009-04-22 19:22:57224 select_file_dialog_(),
225 pending_install_(),
[email protected]d5f942ba2008-09-26 19:30:34226 is_loading_(false),
initial.commit09911bf2008-07-26 23:55:29227 is_crashed_(false),
[email protected]d5f942ba2008-09-26 19:30:34228 waiting_for_response_(false),
[email protected]d5f942ba2008-09-26 19:30:34229 max_page_id_(-1),
[email protected]fdd61c62009-04-22 19:22:57230 current_load_start_(),
231 load_state_(net::LOAD_STATE_IDLE),
232 load_state_host_(),
233 received_page_title_(false),
234 is_starred_(false),
235 contents_mime_type_(),
236 encoding_(),
[email protected]332af7732009-03-11 13:21:35237 blocked_popups_(NULL),
[email protected]fdd61c62009-04-22 19:22:57238 infobar_delegates_(),
[email protected]fdd61c62009-04-22 19:22:57239 find_ui_active_(false),
240 find_op_aborted_(false),
241 current_find_request_id_(find_request_id_counter_++),
242 find_text_(),
[email protected]e491f1c2009-05-22 20:28:12243 last_search_case_sensitive_(false),
244 last_search_prepopulate_text_(NULL),
245 last_search_result_(),
[email protected]fdd61c62009-04-22 19:22:57246 capturing_contents_(false),
247 is_being_destroyed_(false),
248 notify_disconnection_(false),
249 history_requests_(),
250#if defined(OS_WIN)
251 message_box_active_(CreateEvent(NULL, TRUE, FALSE, NULL)),
252#endif
253 last_javascript_message_dismissal_(),
254 suppress_javascript_messages_(false) {
[email protected]420ae012009-04-24 05:16:32255 pending_install_.page_id = 0;
256 pending_install_.callback_functor = NULL;
257
258 render_manager_.Init(profile, site_instance, routing_id, modal_dialog_event);
259
260 view_->CreateView();
261
262 // Register for notifications about all interested prefs change.
263 PrefService* prefs = profile->GetPrefs();
264 if (prefs) {
265 for (int i = 0; i < kPrefsToObserveLength; ++i)
266 prefs->AddPrefObserver(kPrefsToObserve[i], this);
267 }
268
269 // Register for notifications about URL starredness changing on any profile.
270 registrar_.Add(this, NotificationType::URLS_STARRED,
271 NotificationService::AllSources());
272 registrar_.Add(this, NotificationType::BOOKMARK_MODEL_LOADED,
273 NotificationService::AllSources());
274 registrar_.Add(this, NotificationType::RENDER_WIDGET_HOST_DESTROYED,
275 NotificationService::AllSources());
276
277 // Keep a global copy of the previous search string (if any).
278 static string16 global_last_search = string16();
[email protected]e491f1c2009-05-22 20:28:12279 last_search_prepopulate_text_ = &global_last_search;
[email protected]332af7732009-03-11 13:21:35280}
initial.commit09911bf2008-07-26 23:55:29281
282TabContents::~TabContents() {
[email protected]420ae012009-04-24 05:16:32283 is_being_destroyed_ = true;
284
285 // We don't want any notifications while we're runnign our destructor.
286 registrar_.RemoveAll();
287
288 // Unregister the notifications of all observed prefs change.
289 PrefService* prefs = profile()->GetPrefs();
290 if (prefs) {
291 for (int i = 0; i < kPrefsToObserveLength; ++i)
292 prefs->RemovePrefObserver(kPrefsToObserve[i], this);
293 }
294
295 // Clean up subwindows like plugins and the find in page bar.
296 view_->OnContentsDestroy();
297
298 NotifyDisconnected();
[email protected]8897c382009-05-06 17:53:26299 HungRendererDialog::HideForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:32300
301 if (pending_install_.callback_functor)
302 pending_install_.callback_functor->Cancel();
303
304 // First cleanly close all child windows.
305 // TODO(mpcomplete): handle case if MaybeCloseChildWindows() already asked
306 // some of these to close. CloseWindows is async, so it might get called
307 // twice before it runs.
308 int size = static_cast<int>(child_windows_.size());
309 for (int i = size - 1; i >= 0; --i) {
310 ConstrainedWindow* window = child_windows_[i];
311 if (window)
312 window->CloseConstrainedWindow();
313 }
314
[email protected]66ba4932009-06-04 19:22:13315 if (blocked_popups_)
316 blocked_popups_->Destroy();
317
[email protected]420ae012009-04-24 05:16:32318 // Notify any observer that have a reference on this tab contents.
319 NotificationService::current()->Notify(
320 NotificationType::TAB_CONTENTS_DESTROYED,
321 Source<TabContents>(this),
322 NotificationService::NoDetails());
323
[email protected]1e5e74f2009-05-27 20:55:12324 // Notify any lasting InfobarDelegates that have not yet been removed that
325 // whatever infobar they were handling in this TabContents has closed,
326 // because the TabContents is going away entirely.
327 // This must happen after the TAB_CONTENTS_DESTROYED notification as the
328 // notification may trigger infobars calls that access their delegate. (and
329 // some implementations of InfoBarDelegate do delete themselves on
330 // InfoBarClosed()).
331 for (int i = 0; i < infobar_delegate_count(); ++i) {
332 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
333 delegate->InfoBarClosed();
334 }
335 infobar_delegates_.clear();
336
[email protected]420ae012009-04-24 05:16:32337 // TODO(brettw) this should be moved to the view.
338#if defined(OS_WIN)
339 // If we still have a window handle, destroy it. GetNativeView can return
340 // NULL if this contents was part of a window that closed.
341 if (GetNativeView())
342 ::DestroyWindow(GetNativeView());
343#endif
initial.commit09911bf2008-07-26 23:55:29344}
345
[email protected]d5f942ba2008-09-26 19:30:34346// static
347void TabContents::RegisterUserPrefs(PrefService* prefs) {
[email protected]420ae012009-04-24 05:16:32348 prefs->RegisterBooleanPref(prefs::kAlternateErrorPagesEnabled, true);
349
350 WebPreferences pref_defaults;
351 prefs->RegisterBooleanPref(prefs::kWebKitJavascriptEnabled,
352 pref_defaults.javascript_enabled);
353 prefs->RegisterBooleanPref(prefs::kWebKitWebSecurityEnabled,
354 pref_defaults.web_security_enabled);
355 prefs->RegisterBooleanPref(
356 prefs::kWebKitJavascriptCanOpenWindowsAutomatically, true);
357 prefs->RegisterBooleanPref(prefs::kWebKitLoadsImagesAutomatically,
358 pref_defaults.loads_images_automatically);
359 prefs->RegisterBooleanPref(prefs::kWebKitPluginsEnabled,
360 pref_defaults.plugins_enabled);
361 prefs->RegisterBooleanPref(prefs::kWebKitDomPasteEnabled,
362 pref_defaults.dom_paste_enabled);
363 prefs->RegisterBooleanPref(prefs::kWebKitShrinksStandaloneImagesToFit,
364 pref_defaults.shrinks_standalone_images_to_fit);
365 prefs->RegisterBooleanPref(prefs::kWebKitDeveloperExtrasEnabled,
[email protected]96d3fb52009-05-27 14:51:21366 pref_defaults.developer_extras_enabled);
[email protected]0df30122009-06-03 12:13:08367 prefs->RegisterStringPref(prefs::kWebKitInspectorSettings,
368 pref_defaults.inspector_settings);
[email protected]420ae012009-04-24 05:16:32369 prefs->RegisterBooleanPref(prefs::kWebKitTextAreasAreResizable,
370 pref_defaults.text_areas_are_resizable);
371 prefs->RegisterBooleanPref(prefs::kWebKitJavaEnabled,
372 pref_defaults.java_enabled);
373
374 prefs->RegisterLocalizedStringPref(prefs::kAcceptLanguages,
375 IDS_ACCEPT_LANGUAGES);
376 prefs->RegisterLocalizedStringPref(prefs::kDefaultCharset,
377 IDS_DEFAULT_ENCODING);
378 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitStandardFontIsSerif,
379 IDS_STANDARD_FONT_IS_SERIF);
380 prefs->RegisterLocalizedStringPref(prefs::kWebKitFixedFontFamily,
381 IDS_FIXED_FONT_FAMILY);
382 prefs->RegisterLocalizedStringPref(prefs::kWebKitSerifFontFamily,
383 IDS_SERIF_FONT_FAMILY);
384 prefs->RegisterLocalizedStringPref(prefs::kWebKitSansSerifFontFamily,
385 IDS_SANS_SERIF_FONT_FAMILY);
386 prefs->RegisterLocalizedStringPref(prefs::kWebKitCursiveFontFamily,
387 IDS_CURSIVE_FONT_FAMILY);
388 prefs->RegisterLocalizedStringPref(prefs::kWebKitFantasyFontFamily,
389 IDS_FANTASY_FONT_FAMILY);
390 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFontSize,
391 IDS_DEFAULT_FONT_SIZE);
392 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFixedFontSize,
393 IDS_DEFAULT_FIXED_FONT_SIZE);
394 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumFontSize,
395 IDS_MINIMUM_FONT_SIZE);
396 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumLogicalFontSize,
397 IDS_MINIMUM_LOGICAL_FONT_SIZE);
398 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitUsesUniversalDetector,
399 IDS_USES_UNIVERSAL_DETECTOR);
400 prefs->RegisterLocalizedStringPref(prefs::kStaticEncodings,
401 IDS_STATIC_ENCODING_LIST);
initial.commit09911bf2008-07-26 23:55:29402}
403
[email protected]d5f942ba2008-09-26 19:30:34404bool TabContents::SupportsURL(GURL* url) {
[email protected]6e95706d2009-04-23 22:55:01405 // TODO(brettw) remove this function.
[email protected]9423d9412009-04-14 22:13:55406 return true;
[email protected]d5f942ba2008-09-26 19:30:34407}
408
[email protected]6e95706d2009-04-23 22:55:01409AutofillManager* TabContents::GetAutofillManager() {
410 if (autofill_manager_.get() == NULL)
411 autofill_manager_.reset(new AutofillManager(this));
412 return autofill_manager_.get();
413}
414
415PasswordManager* TabContents::GetPasswordManager() {
416 if (password_manager_.get() == NULL)
417 password_manager_.reset(new PasswordManager(this));
418 return password_manager_.get();
419}
420
421PluginInstaller* TabContents::GetPluginInstaller() {
422 if (plugin_installer_.get() == NULL)
423 plugin_installer_.reset(new PluginInstaller(this));
424 return plugin_installer_.get();
425}
426
[email protected]d5f942ba2008-09-26 19:30:34427const GURL& TabContents::GetURL() const {
428 // We may not have a navigation entry yet
[email protected]ce3fa3c2009-04-20 19:55:57429 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34430 return entry ? entry->display_url() : GURL::EmptyGURL();
431}
432
[email protected]96d185d2009-04-24 03:28:54433const string16& TabContents::GetTitle() const {
434 DOMUI* our_dom_ui = render_manager_.pending_dom_ui() ?
435 render_manager_.pending_dom_ui() : render_manager_.dom_ui();
436 if (our_dom_ui) {
437 // Don't override the title in view source mode.
438 NavigationEntry* entry = controller_.GetActiveEntry();
439 if (!(entry && entry->IsViewSourceMode())) {
440 // Give the DOM UI the chance to override our title.
441 const string16& title = our_dom_ui->overridden_title();
442 if (!title.empty())
443 return title;
444 }
445 }
446
447 // We use the title for the last committed entry rather than a pending
448 // navigation entry. For example, when the user types in a URL, we want to
449 // keep the old page's title until the new load has committed and we get a new
450 // title.
451 // The exception is with transient pages, for which we really want to use
452 // their title, as they are not committed.
453 NavigationEntry* entry = controller_.GetTransientEntry();
454 if (entry)
455 return entry->GetTitleForDisplay(&controller_);
456
457 entry = controller_.GetLastCommittedEntry();
458 if (entry)
459 return entry->GetTitleForDisplay(&controller_);
460 else if (controller_.LoadingURLLazily())
461 return controller_.GetLazyTitle();
462 return EmptyString16();
463}
464
[email protected]d5f942ba2008-09-26 19:30:34465int32 TabContents::GetMaxPageID() {
466 if (GetSiteInstance())
467 return GetSiteInstance()->max_page_id();
468 else
469 return max_page_id_;
470}
471
472void TabContents::UpdateMaxPageID(int32 page_id) {
473 // Ensure both the SiteInstance and RenderProcessHost update their max page
[email protected]57c6a652009-05-04 07:58:34474 // IDs in sync. Only TabContents will also have site instances, except during
[email protected]d5f942ba2008-09-26 19:30:34475 // testing.
476 if (GetSiteInstance())
477 GetSiteInstance()->UpdateMaxPageID(page_id);
[email protected]57c6a652009-05-04 07:58:34478 process()->UpdateMaxPageID(page_id);
[email protected]d5f942ba2008-09-26 19:30:34479}
480
[email protected]96d185d2009-04-24 03:28:54481SiteInstance* TabContents::GetSiteInstance() const {
482 return render_manager_.current_host()->site_instance();
483}
484
[email protected]d5f942ba2008-09-26 19:30:34485const std::wstring TabContents::GetDefaultTitle() const {
486 return l10n_util::GetString(IDS_DEFAULT_TAB_TITLE);
487}
488
[email protected]96d185d2009-04-24 03:28:54489bool TabContents::ShouldDisplayURL() {
490 // Don't hide the url in view source mode.
491 NavigationEntry* entry = controller_.GetActiveEntry();
492 if (entry && entry->IsViewSourceMode())
493 return true;
494 DOMUI* dom_ui = GetDOMUIForCurrentState();
495 if (dom_ui)
496 return !dom_ui->should_hide_url();
497 return true;
498}
499
[email protected]d5f942ba2008-09-26 19:30:34500SkBitmap TabContents::GetFavIcon() const {
501 // Like GetTitle(), we also want to use the favicon for the last committed
502 // entry rather than a pending navigation entry.
[email protected]ce3fa3c2009-04-20 19:55:57503 NavigationEntry* entry = controller_.GetTransientEntry();
[email protected]cbab76d2008-10-13 22:42:47504 if (entry)
505 return entry->favicon().bitmap();
506
[email protected]ce3fa3c2009-04-20 19:55:57507 entry = controller_.GetLastCommittedEntry();
[email protected]d5f942ba2008-09-26 19:30:34508 if (entry)
509 return entry->favicon().bitmap();
[email protected]ce3fa3c2009-04-20 19:55:57510 else if (controller_.LoadingURLLazily())
511 return controller_.GetLazyFavIcon();
[email protected]d5f942ba2008-09-26 19:30:34512 return SkBitmap();
513}
514
[email protected]96d185d2009-04-24 03:28:54515bool TabContents::ShouldDisplayFavIcon() {
516 // Always display a throbber during pending loads.
517 if (controller_.GetLastCommittedEntry() && controller_.pending_entry())
518 return true;
519
520 DOMUI* dom_ui = GetDOMUIForCurrentState();
521 if (dom_ui)
522 return !dom_ui->hide_favicon();
523 return true;
524}
525
[email protected]3e45ba92009-02-20 21:09:00526#if defined(OS_WIN)
[email protected]d5f942ba2008-09-26 19:30:34527SecurityStyle TabContents::GetSecurityStyle() const {
528 // We may not have a navigation entry yet.
[email protected]ce3fa3c2009-04-20 19:55:57529 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34530 return entry ? entry->ssl().security_style() : SECURITY_STYLE_UNKNOWN;
531}
532
533bool TabContents::GetSSLEVText(std::wstring* ev_text,
534 std::wstring* ev_tooltip_text) const {
535 DCHECK(ev_text && ev_tooltip_text);
536 ev_text->clear();
537 ev_tooltip_text->clear();
538
[email protected]ce3fa3c2009-04-20 19:55:57539 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34540 if (!entry ||
541 net::IsCertStatusError(entry->ssl().cert_status()) ||
542 ((entry->ssl().cert_status() & net::CERT_STATUS_IS_EV) == 0))
543 return false;
544
545 scoped_refptr<net::X509Certificate> cert;
546 CertStore::GetSharedInstance()->RetrieveCert(entry->ssl().cert_id(), &cert);
547 if (!cert.get()) {
548 NOTREACHED();
549 return false;
550 }
551
552 return SSLManager::GetEVCertNames(*cert, ev_text, ev_tooltip_text);
553}
[email protected]76f68dc2009-03-10 20:31:32554#endif
[email protected]d5f942ba2008-09-26 19:30:34555
[email protected]96d185d2009-04-24 03:28:54556std::wstring TabContents::GetStatusText() const {
557 if (!is_loading() || load_state_ == net::LOAD_STATE_IDLE)
558 return std::wstring();
559
560 switch (load_state_) {
561 case net::LOAD_STATE_WAITING_FOR_CACHE:
562 return l10n_util::GetString(IDS_LOAD_STATE_WAITING_FOR_CACHE);
563 case net::LOAD_STATE_RESOLVING_PROXY_FOR_URL:
564 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_PROXY_FOR_URL);
565 case net::LOAD_STATE_RESOLVING_HOST:
566 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_HOST);
567 case net::LOAD_STATE_CONNECTING:
568 return l10n_util::GetString(IDS_LOAD_STATE_CONNECTING);
569 case net::LOAD_STATE_SENDING_REQUEST:
570 return l10n_util::GetString(IDS_LOAD_STATE_SENDING_REQUEST);
571 case net::LOAD_STATE_WAITING_FOR_RESPONSE:
572 return l10n_util::GetStringF(IDS_LOAD_STATE_WAITING_FOR_RESPONSE,
573 load_state_host_);
574 // Ignore net::LOAD_STATE_READING_RESPONSE and net::LOAD_STATE_IDLE
575 case net::LOAD_STATE_IDLE:
576 case net::LOAD_STATE_READING_RESPONSE:
577 break;
578 }
579
580 return std::wstring();
581}
582
[email protected]d5f942ba2008-09-26 19:30:34583void TabContents::SetIsCrashed(bool state) {
584 if (state == is_crashed_)
585 return;
586
587 is_crashed_ = state;
[email protected]c9cd2222009-05-06 05:16:50588 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]d5f942ba2008-09-26 19:30:34589}
590
[email protected]ce5c4502009-05-06 16:46:11591void TabContents::EnablePageAction(const PageAction* page_action) {
592 DCHECK(page_action);
593
594 if (IsPageActionEnabled(page_action))
595 return; // Already enabled.
596
597 enabled_page_actions_.insert(page_action);
598}
599
600bool TabContents::IsPageActionEnabled(const PageAction* page_action) {
601 DCHECK(page_action);
602 return enabled_page_actions_.end() != enabled_page_actions_.find(page_action);
603}
604
605
[email protected]d5f942ba2008-09-26 19:30:34606void TabContents::NotifyNavigationStateChanged(unsigned changed_flags) {
607 if (delegate_)
608 delegate_->NavigationStateChanged(this, changed_flags);
609}
610
[email protected]96d185d2009-04-24 03:28:54611void TabContents::DidBecomeSelected() {
612 controller_.SetActive(true);
613
614 if (render_widget_host_view())
615 render_widget_host_view()->DidBecomeSelected();
616
617 // If pid() is -1, that means the RenderProcessHost still hasn't been
618 // initialized. It'll register with CacheManagerHost when it is.
619 if (process()->pid() != -1)
620 WebCacheManager::GetInstance()->ObserveActivity(process()->pid());
621}
622
623void TabContents::WasHidden() {
624 if (!capturing_contents()) {
625 // |render_view_host()| can be NULL if the user middle clicks a link to open
626 // a tab in then background, then closes the tab before selecting it. This
627 // is because closing the tab calls TabContents::Destroy(), which removes
628 // the |render_view_host()|; then when we actually destroy the window,
629 // OnWindowPosChanged() notices and calls HideContents() (which calls us).
630 if (render_widget_host_view())
631 render_widget_host_view()->WasHidden();
632
633 // Loop through children and send WasHidden to them, too.
634 int count = static_cast<int>(child_windows_.size());
635 for (int i = count - 1; i >= 0; --i) {
636 ConstrainedWindow* window = child_windows_.at(i);
637 window->WasHidden();
638 }
639 }
640
641 NotificationService::current()->Notify(
642 NotificationType::TAB_CONTENTS_HIDDEN,
643 Source<TabContents>(this),
644 NotificationService::NoDetails());
645}
646
[email protected]d5f942ba2008-09-26 19:30:34647void TabContents::Activate() {
648 if (delegate_)
649 delegate_->ActivateContents(this);
650}
651
[email protected]96d185d2009-04-24 03:28:54652void TabContents::ShowContents() {
653 if (render_widget_host_view())
654 render_widget_host_view()->DidBecomeSelected();
655
656 // Loop through children and send DidBecomeSelected to them, too.
657 int count = static_cast<int>(child_windows_.size());
658 for (int i = count - 1; i >= 0; --i) {
659 ConstrainedWindow* window = child_windows_.at(i);
660 window->DidBecomeSelected();
661 }
662}
663
664void TabContents::HideContents() {
665 // TODO(pkasting): http://b/1239839 Right now we purposefully don't call
666 // our superclass HideContents(), because some callers want to be very picky
667 // about the order in which these get called. In addition to making the code
668 // here practically impossible to understand, this also means we end up
669 // calling TabContents::WasHidden() twice if callers call both versions of
[email protected]57c6a652009-05-04 07:58:34670 // HideContents() on a TabContents.
[email protected]96d185d2009-04-24 03:28:54671 WasHidden();
672}
673
[email protected]c0588052008-10-27 23:01:50674void TabContents::OpenURL(const GURL& url, const GURL& referrer,
[email protected]d5f942ba2008-09-26 19:30:34675 WindowOpenDisposition disposition,
676 PageTransition::Type transition) {
677 if (delegate_)
[email protected]c0588052008-10-27 23:01:50678 delegate_->OpenURLFromTab(this, url, referrer, disposition, transition);
[email protected]d5f942ba2008-09-26 19:30:34679}
680
681bool TabContents::NavigateToPendingEntry(bool reload) {
[email protected]96d185d2009-04-24 03:28:54682 const NavigationEntry& entry = *controller_.pending_entry();
683
684 RenderViewHost* dest_render_view_host = render_manager_.Navigate(entry);
685 if (!dest_render_view_host)
686 return false; // Unable to create the desired render view host.
687
688 // Tell DevTools agent that it is attached prior to the navigation.
[email protected]684b4ba22009-05-07 06:27:41689 DevToolsManager* devtools_manager = g_browser_process->devtools_manager();
[email protected]7e8e6b62009-05-08 11:28:32690 if (devtools_manager) { // NULL in unit tests.
[email protected]684b4ba22009-05-07 06:27:41691 devtools_manager->OnNavigatingToPendingEntry(
692 render_view_host(),
693 dest_render_view_host,
694 controller_.pending_entry()->url());
[email protected]7e8e6b62009-05-08 11:28:32695 }
[email protected]96d185d2009-04-24 03:28:54696
697 // Used for page load time metrics.
698 current_load_start_ = base::TimeTicks::Now();
699
700 // Navigate in the desired RenderViewHost.
701 dest_render_view_host->NavigateToEntry(entry, reload);
702
703 if (entry.page_id() == -1) {
704 // HACK!! This code suppresses javascript: URLs from being added to
705 // session history, which is what we want to do for javascript: URLs that
706 // do not generate content. What we really need is a message from the
707 // renderer telling us that a new page was not created. The same message
708 // could be used for mailto: URLs and the like.
709 if (entry.url().SchemeIs(chrome::kJavaScriptScheme))
710 return false;
711 }
712
713 // Clear any provisional password saves - this stops password infobars
714 // showing up on pages the user navigates to while the right page is
715 // loading.
716 GetPasswordManager()->ClearProvisionalSave();
717
718 if (reload && !profile()->IsOffTheRecord()) {
719 HistoryService* history =
720 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
721 if (history)
722 history->SetFavIconOutOfDateForPage(entry.url());
723 }
724
[email protected]d5f942ba2008-09-26 19:30:34725 return true;
726}
727
[email protected]96d185d2009-04-24 03:28:54728void TabContents::Stop() {
729 render_manager_.Stop();
730 printing_.Stop();
731}
732
733void TabContents::Cut() {
734 render_view_host()->Cut();
735}
736
737void TabContents::Copy() {
738 render_view_host()->Copy();
739}
740
741void TabContents::Paste() {
742 render_view_host()->Paste();
743}
744
745void TabContents::DisassociateFromPopupCount() {
746 render_view_host()->DisassociateFromPopupCount();
747}
748
749TabContents* TabContents::Clone() {
750 // We create a new SiteInstance so that the new tab won't share processes
751 // with the old one. This can be changed in the future if we need it to share
752 // processes for some reason.
[email protected]420ae012009-04-24 05:16:32753 TabContents* tc = new TabContents(profile(),
[email protected]96d185d2009-04-24 03:28:54754 SiteInstance::CreateSiteInstance(profile()),
755 MSG_ROUTING_NONE, NULL);
756 tc->controller().CopyStateFrom(controller_);
757 return tc;
758}
759
[email protected]420ae012009-04-24 05:16:32760void TabContents::CreateShortcut() {
761 NavigationEntry* entry = controller_.GetLastCommittedEntry();
762 if (!entry)
763 return;
764
765 // We only allow one pending install request. By resetting the page id we
766 // effectively cancel the pending install request.
767 pending_install_.page_id = entry->page_id();
768 pending_install_.icon = GetFavIcon();
769 pending_install_.title = UTF16ToWideHack(GetTitle());
770 pending_install_.url = GetURL();
771 if (pending_install_.callback_functor) {
772 pending_install_.callback_functor->Cancel();
773 pending_install_.callback_functor = NULL;
774 }
775 DCHECK(!pending_install_.icon.isNull()) << "Menu item should be disabled.";
776 if (pending_install_.title.empty())
777 pending_install_.title = UTF8ToWide(GetURL().spec());
778
779 // Request the application info. When done OnDidGetApplicationInfo is invoked
780 // and we'll create the shortcut.
781 render_view_host()->GetApplicationInfo(pending_install_.page_id);
782}
783
[email protected]76f68dc2009-03-10 20:31:32784#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29785ConstrainedWindow* TabContents::CreateConstrainedDialog(
[email protected]c2dacc92008-10-16 23:51:38786 views::WindowDelegate* window_delegate,
787 views::View* contents_view) {
initial.commit09911bf2008-07-26 23:55:29788 ConstrainedWindow* window =
789 ConstrainedWindow::CreateConstrainedDialog(
790 this, gfx::Rect(), contents_view, window_delegate);
791 child_windows_.push_back(window);
792 return window;
793}
[email protected]f3332e12009-03-23 15:28:57794#endif
initial.commit09911bf2008-07-26 23:55:29795
796void TabContents::AddNewContents(TabContents* new_contents,
797 WindowOpenDisposition disposition,
798 const gfx::Rect& initial_pos,
[email protected]c88a70fe2009-05-05 20:00:22799 bool user_gesture,
800 const GURL& creator_url) {
initial.commit09911bf2008-07-26 23:55:29801 if (!delegate_)
802 return;
803
[email protected]f3332e12009-03-23 15:28:57804#if defined(OS_WIN)
[email protected]2c4410d2009-05-06 23:46:22805 bool constrain_popup = false;
[email protected]35f7d212009-04-29 21:19:27806 if ((disposition == NEW_POPUP) && !user_gesture &&
807 !CommandLine::ForCurrentProcess()->HasSwitch(
808 switches::kDisablePopupBlocking)) {
[email protected]2c4410d2009-05-06 23:46:22809 // Unrequested popups from normal pages are constrained unless they're in
[email protected]b6c874582009-05-08 19:38:31810 // the whitelist. The popup owner will handle checking this.
811 delegate_->GetConstrainingContents(this)->AddPopup(new_contents,
812 initial_pos,
813 creator_url.is_valid() ? creator_url.host() : std::string());
814 } else {
[email protected]0aa55312008-10-17 21:53:08815 new_contents->DisassociateFromPopupCount();
initial.commit09911bf2008-07-26 23:55:29816 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
817 user_gesture);
818 }
[email protected]b6c874582009-05-08 19:38:31819 PopupNotificationVisibilityChanged(ShowingBlockedPopupNotification());
[email protected]f3332e12009-03-23 15:28:57820#else
821 // TODO(port): implement the popup blocker stuff
822 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
823 user_gesture);
824#endif
initial.commit09911bf2008-07-26 23:55:29825}
826
initial.commit09911bf2008-07-26 23:55:29827void TabContents::CloseAllSuppressedPopups() {
[email protected]d6598c052008-11-05 19:03:25828 if (blocked_popups_)
[email protected]2c4410d2009-05-06 23:46:22829 blocked_popups_->CloseAll();
initial.commit09911bf2008-07-26 23:55:29830}
831
[email protected]96d185d2009-04-24 03:28:54832void TabContents::PopupNotificationVisibilityChanged(bool visible) {
833 render_view_host()->PopupNotificationVisibilityChanged(visible);
834}
835
836gfx::NativeView TabContents::GetContentNativeView() {
837 return view_->GetContentNativeView();
838}
839
840gfx::NativeView TabContents::GetNativeView() const {
841 return view_->GetNativeView();
842}
843
844void TabContents::GetContainerBounds(gfx::Rect *out) const {
845 view_->GetContainerBounds(out);
846}
847
848void TabContents::Focus() {
849 view_->Focus();
850}
851
852void TabContents::SetInitialFocus(bool reverse) {
853 render_view_host()->SetInitialFocus(reverse);
854}
855
856bool TabContents::FocusLocationBarByDefault() {
857 DOMUI* dom_ui = GetDOMUIForCurrentState();
858 if (dom_ui)
859 return dom_ui->focus_location_bar_by_default();
860 return false;
861}
862
[email protected]616ed5a2008-11-21 22:27:24863void TabContents::AddInfoBar(InfoBarDelegate* delegate) {
864 // Look through the existing InfoBarDelegates we have for a match. If we've
865 // already got one that matches, then we don't add the new one.
[email protected]f86a07022008-11-25 01:06:05866 for (int i = 0; i < infobar_delegate_count(); ++i) {
[email protected]616ed5a2008-11-21 22:27:24867 if (GetInfoBarDelegateAt(i)->EqualsDelegate(delegate))
868 return;
869 }
870
871 infobar_delegates_.push_back(delegate);
[email protected]bfd04a62009-02-01 18:16:56872 NotificationService::current()->Notify(
873 NotificationType::TAB_CONTENTS_INFOBAR_ADDED,
874 Source<TabContents>(this),
875 Details<InfoBarDelegate>(delegate));
[email protected]616ed5a2008-11-21 22:27:24876
877 // Add ourselves as an observer for navigations the first time a delegate is
878 // added. We use this notification to expire InfoBars that need to expire on
879 // page transitions.
880 if (infobar_delegates_.size() == 1) {
[email protected]bfd04a62009-02-01 18:16:56881 registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57882 Source<NavigationController>(&controller_));
[email protected]616ed5a2008-11-21 22:27:24883 }
884}
885
886void TabContents::RemoveInfoBar(InfoBarDelegate* delegate) {
887 std::vector<InfoBarDelegate*>::iterator it =
888 find(infobar_delegates_.begin(), infobar_delegates_.end(), delegate);
889 if (it != infobar_delegates_.end()) {
890 InfoBarDelegate* delegate = *it;
[email protected]bfd04a62009-02-01 18:16:56891 NotificationService::current()->Notify(
892 NotificationType::TAB_CONTENTS_INFOBAR_REMOVED,
893 Source<TabContents>(this),
894 Details<InfoBarDelegate>(delegate));
[email protected]f86a07022008-11-25 01:06:05895 infobar_delegates_.erase(it);
[email protected]616ed5a2008-11-21 22:27:24896
[email protected]6a02963e2009-01-06 16:58:03897 // Remove ourselves as an observer if we are tracking no more InfoBars.
898 if (infobar_delegates_.empty()) {
[email protected]bfd04a62009-02-01 18:16:56899 registrar_.Remove(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57900 Source<NavigationController>(&controller_));
[email protected]6a02963e2009-01-06 16:58:03901 }
[email protected]616ed5a2008-11-21 22:27:24902 }
903}
[email protected]3edd9522009-03-04 22:19:41904
[email protected]96d185d2009-04-24 03:28:54905bool TabContents::IsBookmarkBarAlwaysVisible() {
906 // See GetDOMUIForCurrentState() comment for more info. This case is very
907 // similar, but for non-first loads, we want to use the committed entry. This
908 // is so the bookmarks bar disappears at the same time the page does.
909 if (controller_.GetLastCommittedEntry()) {
910 // Not the first load, always use the committed DOM UI.
911 if (render_manager_.dom_ui())
912 return render_manager_.dom_ui()->force_bookmark_bar_visible();
913 return false; // Default.
914 }
915
916 // When it's the first load, we know either the pending one or the committed
917 // one will have the DOM UI in it (see GetDOMUIForCurrentState), and only one
918 // of them will be valid, so we can just check both.
919 if (render_manager_.pending_dom_ui())
920 return render_manager_.pending_dom_ui()->force_bookmark_bar_visible();
921 if (render_manager_.dom_ui())
922 return render_manager_.dom_ui()->force_bookmark_bar_visible();
923 return false; // Default.
924}
925
[email protected]3edd9522009-03-04 22:19:41926void TabContents::ToolbarSizeChanged(bool is_animating) {
927 TabContentsDelegate* d = delegate();
928 if (d)
929 d->ToolbarSizeChanged(this, is_animating);
930}
[email protected]616ed5a2008-11-21 22:27:24931
[email protected]d5f942ba2008-09-26 19:30:34932void TabContents::OnStartDownload(DownloadItem* download) {
933 DCHECK(download);
[email protected]d5f942ba2008-09-26 19:30:34934
935 // Download in a constrained popup is shown in the tab that opened it.
[email protected]b6c874582009-05-08 19:38:31936 TabContents* tab_contents = delegate()->GetConstrainingContents(this);
[email protected]d5f942ba2008-09-26 19:30:34937
[email protected]59560e0b2009-06-04 03:30:22938 if (tab_contents && tab_contents->delegate())
939 tab_contents->delegate()->OnStartDownload(download);
[email protected]3edd9522009-03-04 22:19:41940}
[email protected]3edd9522009-03-04 22:19:41941
[email protected]d5f942ba2008-09-26 19:30:34942void TabContents::WillClose(ConstrainedWindow* window) {
943 ConstrainedWindowList::iterator it =
944 find(child_windows_.begin(), child_windows_.end(), window);
945 if (it != child_windows_.end())
946 child_windows_.erase(it);
[email protected]66ba4932009-06-04 19:22:13947}
[email protected]d5f942ba2008-09-26 19:30:34948
[email protected]66ba4932009-06-04 19:22:13949void TabContents::WillCloseBlockedPopupContainer(
950 BlockedPopupContainer* container) {
951 DCHECK(blocked_popups_ == container);
952 blocked_popups_ = NULL;
[email protected]d5f942ba2008-09-26 19:30:34953}
954
[email protected]d5f942ba2008-09-26 19:30:34955void TabContents::DidMoveOrResize(ConstrainedWindow* window) {
[email protected]332af7732009-03-11 13:21:35956#if defined(OS_WIN)
[email protected]92edc472009-02-10 20:32:06957 UpdateWindow(GetNativeView());
[email protected]332af7732009-03-11 13:21:35958#endif
[email protected]d5f942ba2008-09-26 19:30:34959}
960
[email protected]e491f1c2009-05-22 20:28:12961void TabContents::StartFinding(string16 find_text,
962 bool forward_direction,
963 bool case_sensitive) {
[email protected]6e95706d2009-04-23 22:55:01964 // If find_text is empty, it means FindNext was pressed with a keyboard
965 // shortcut so unless we have something to search for we return early.
[email protected]e491f1c2009-05-22 20:28:12966 if (find_text.empty() && find_text_.empty()) {
967 if (last_search_prepopulate_text_->empty())
968 return;
969 // Try whatever we searched for last in any tab.
970 find_text = *last_search_prepopulate_text_;
971 }
[email protected]6e95706d2009-04-23 22:55:01972
973 // This is a FindNext operation if we are searching for the same text again,
974 // or if the passed in search text is empty (FindNext keyboard shortcut). The
975 // exception to this is if the Find was aborted (then we don't want FindNext
976 // because the highlighting has been cleared and we need it to reappear). We
977 // therefore treat FindNext after an aborted Find operation as a full fledged
978 // Find.
979 bool find_next = (find_text_ == find_text || find_text.empty()) &&
[email protected]e491f1c2009-05-22 20:28:12980 (last_search_case_sensitive_ == case_sensitive) &&
[email protected]6e95706d2009-04-23 22:55:01981 !find_op_aborted_;
982 if (!find_next)
983 current_find_request_id_ = find_request_id_counter_++;
984
985 if (!find_text.empty())
986 find_text_ = find_text;
[email protected]e491f1c2009-05-22 20:28:12987 last_search_case_sensitive_ = case_sensitive;
[email protected]6e95706d2009-04-23 22:55:01988
989 find_op_aborted_ = false;
990
991 // Keep track of what the last search was across the tabs.
[email protected]e491f1c2009-05-22 20:28:12992 *last_search_prepopulate_text_ = find_text;
[email protected]6e95706d2009-04-23 22:55:01993
994 render_view_host()->StartFinding(current_find_request_id_,
995 find_text_,
996 forward_direction,
[email protected]e491f1c2009-05-22 20:28:12997 case_sensitive,
[email protected]6e95706d2009-04-23 22:55:01998 find_next);
999}
1000
1001void TabContents::StopFinding(bool clear_selection) {
1002 find_ui_active_ = false;
1003 find_op_aborted_ = true;
[email protected]e491f1c2009-05-22 20:28:121004 last_search_result_ = FindNotificationDetails();
[email protected]6e95706d2009-04-23 22:55:011005 render_view_host()->StopFinding(clear_selection);
1006}
1007
[email protected]420ae012009-04-24 05:16:321008void TabContents::OnJavaScriptMessageBoxClosed(IPC::Message* reply_msg,
1009 bool success,
1010 const std::wstring& prompt) {
1011 last_javascript_message_dismissal_ = base::TimeTicks::Now();
1012 render_manager_.OnJavaScriptMessageBoxClosed(reply_msg, success, prompt);
1013}
1014
[email protected]571e31152009-05-15 19:34:021015void TabContents::OnJavaScriptMessageBoxWindowDestroyed() {
1016 render_manager_.OnJavaScriptMessageBoxWindowDestroyed();
1017}
1018
[email protected]420ae012009-04-24 05:16:321019void TabContents::OnSavePage() {
1020 // If we can not save the page, try to download it.
1021 if (!SavePackage::IsSavableContents(contents_mime_type())) {
1022 DownloadManager* dlm = profile()->GetDownloadManager();
1023 const GURL& current_page_url = GetURL();
1024 if (dlm && current_page_url.is_valid())
[email protected]c9825a42009-05-01 22:51:501025 dlm->DownloadUrl(current_page_url, GURL(), "", AsWC(this));
[email protected]420ae012009-04-24 05:16:321026 return;
1027 }
1028
1029 Stop();
1030
1031 // Create the save package and possibly prompt the user for the name to save
1032 // the page as. The user prompt is an asynchronous operation that runs on
1033 // another thread.
1034 save_package_ = new SavePackage(AsWC(this));
1035 save_package_->GetSaveInfo();
1036}
1037
1038// Used in automated testing to bypass prompting the user for file names.
1039// Instead, the names and paths are hard coded rather than running them through
1040// file name sanitation and extension / mime checking.
1041void TabContents::SavePage(const std::wstring& main_file,
1042 const std::wstring& dir_path,
1043 SavePackage::SavePackageType save_type) {
1044 // Stop the page from navigating.
1045 Stop();
1046
1047 save_package_ = new SavePackage(AsWC(this), save_type,
1048 FilePath::FromWStringHack(main_file),
1049 FilePath::FromWStringHack(dir_path));
1050 save_package_->Init();
1051}
1052
1053void TabContents::PrintPreview() {
1054 // We don't show the print preview yet, only the print dialog.
1055 PrintNow();
1056}
1057
1058bool TabContents::PrintNow() {
1059 // We can't print interstitial page for now.
1060 if (showing_interstitial_page())
1061 return false;
1062
1063 return render_view_host()->PrintPages();
1064}
1065
1066bool TabContents::IsActiveEntry(int32 page_id) {
1067 NavigationEntry* active_entry = controller_.GetActiveEntry();
1068 return (active_entry != NULL &&
1069 active_entry->site_instance() == GetSiteInstance() &&
1070 active_entry->page_id() == page_id);
1071}
1072
[email protected]96d185d2009-04-24 03:28:541073// Notifies the RenderWidgetHost instance about the fact that the page is
1074// loading, or done loading and calls the base implementation.
1075void TabContents::SetIsLoading(bool is_loading,
1076 LoadNotificationDetails* details) {
1077 if (is_loading == is_loading_)
1078 return;
1079
1080 if (!is_loading) {
1081 load_state_ = net::LOAD_STATE_IDLE;
1082 load_state_host_.clear();
1083 }
1084
1085 render_manager_.SetIsLoading(is_loading);
1086
1087 is_loading_ = is_loading;
1088 waiting_for_response_ = is_loading;
1089
1090 if (delegate_)
1091 delegate_->LoadingStateChanged(this);
[email protected]329581b2009-04-28 06:52:351092 NotifyNavigationStateChanged(INVALIDATE_LOAD);
[email protected]96d185d2009-04-24 03:28:541093
1094 NotificationType type = is_loading ? NotificationType::LOAD_START :
1095 NotificationType::LOAD_STOP;
[email protected]ce5c4502009-05-06 16:46:111096 NotificationDetails det = NotificationService::NoDetails();
[email protected]96d185d2009-04-24 03:28:541097 if (details)
1098 det = Details<LoadNotificationDetails>(details);
1099 NotificationService::current()->Notify(type,
1100 Source<NavigationController>(&controller_),
1101 det);
1102}
1103
[email protected]76f68dc2009-03-10 20:31:321104#if defined(OS_WIN)
[email protected]2c4410d2009-05-06 23:46:221105void TabContents::CreateBlockedPopupContainerIfNecessary() {
1106 if (blocked_popups_)
1107 return;
1108
1109 CRect client_rect;
1110 GetClientRect(GetNativeView(), &client_rect);
1111 gfx::Point anchor_position(
1112 client_rect.Width() - views::NativeScrollBar::GetVerticalScrollBarWidth(),
1113 client_rect.Height());
1114 blocked_popups_ = BlockedPopupContainer::Create(this, profile(),
1115 anchor_position);
[email protected]2c4410d2009-05-06 23:46:221116}
1117
[email protected]b6c874582009-05-08 19:38:311118void TabContents::AddPopup(TabContents* new_contents,
1119 const gfx::Rect& initial_pos,
1120 const std::string& host) {
[email protected]2c4410d2009-05-06 23:46:221121 CreateBlockedPopupContainerIfNecessary();
1122 blocked_popups_->AddTabContents(new_contents, initial_pos, host);
[email protected]2c4410d2009-05-06 23:46:221123}
[email protected]66ba4932009-06-04 19:22:131124#endif
[email protected]2c4410d2009-05-06 23:46:221125
[email protected]e69bce3dd2009-04-20 22:05:121126// TODO(brettw) This should be on the TabContentsView.
[email protected]66ba4932009-06-04 19:22:131127void TabContents::RepositionSupressedPopupsToFit() {
[email protected]d6598c052008-11-05 19:03:251128 if (blocked_popups_)
[email protected]66ba4932009-06-04 19:22:131129 blocked_popups_->RepositionBlockedPopupContainer(GetNativeView());
[email protected]d5f942ba2008-09-26 19:30:341130}
1131
[email protected]b9681312008-11-07 00:08:261132bool TabContents::ShowingBlockedPopupNotification() const {
1133 return blocked_popups_ != NULL &&
[email protected]2c4410d2009-05-06 23:46:221134 blocked_popups_->GetBlockedPopupCount() != 0;
[email protected]b9681312008-11-07 00:08:261135}
[email protected]616ed5a2008-11-21 22:27:241136
1137namespace {
1138bool TransitionIsReload(PageTransition::Type transition) {
1139 return PageTransition::StripQualifier(transition) == PageTransition::RELOAD;
1140}
1141}
1142
1143void TabContents::ExpireInfoBars(
1144 const NavigationController::LoadCommittedDetails& details) {
1145 // Only hide InfoBars when the user has done something that makes the main
1146 // frame load. We don't want various automatic or subframe navigations making
1147 // it disappear.
1148 if (!details.is_user_initiated_main_frame_load())
1149 return;
1150
[email protected]f86a07022008-11-25 01:06:051151 for (int i = infobar_delegate_count() - 1; i >= 0; --i) {
[email protected]616ed5a2008-11-21 22:27:241152 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
[email protected]f86a07022008-11-25 01:06:051153 if (delegate->ShouldExpire(details))
[email protected]616ed5a2008-11-21 22:27:241154 RemoveInfoBar(delegate);
[email protected]616ed5a2008-11-21 22:27:241155 }
1156}
[email protected]fdd61c62009-04-22 19:22:571157
1158void TabContents::OnGearsCreateShortcutDone(
1159 const GearsShortcutData2& shortcut_data, bool success) {
1160 NavigationEntry* current_entry = controller_.GetLastCommittedEntry();
1161 bool same_page =
1162 current_entry && pending_install_.page_id == current_entry->page_id();
1163
1164 if (success && same_page) {
1165 // Only switch to app mode if the user chose to create a shortcut and
1166 // we're still on the same page that it corresponded to.
1167 if (delegate())
1168 delegate()->ConvertContentsToApplication(this);
1169 }
1170
1171 // Reset the page id to indicate no requests are pending.
1172 pending_install_.page_id = 0;
1173 pending_install_.callback_functor = NULL;
1174}
[email protected]96d185d2009-04-24 03:28:541175
1176DOMUI* TabContents::GetDOMUIForCurrentState() {
1177 // When there is a pending navigation entry, we want to use the pending DOMUI
1178 // that goes along with it to control the basic flags. For example, we want to
1179 // show the pending URL in the URL bar, so we want the display_url flag to
1180 // be from the pending entry.
1181 //
1182 // The confusion comes because there are multiple possibilities for the
1183 // initial load in a tab as a side effect of the way the RenderViewHostManager
1184 // works.
1185 //
1186 // - For the very first tab the load looks "normal". The new tab DOM UI is
1187 // the pending one, and we want it to apply here.
1188 //
1189 // - For subsequent new tabs, they'll get a new SiteInstance which will then
1190 // get switched to the one previously associated with the new tab pages.
1191 // This switching will cause the manager to commit the RVH/DOMUI. So we'll
1192 // have a committed DOM UI in this case.
1193 //
1194 // This condition handles all of these cases:
1195 //
1196 // - First load in first tab: no committed nav entry + pending nav entry +
1197 // pending dom ui:
1198 // -> Use pending DOM UI if any.
1199 //
1200 // - First load in second tab: no committed nav entry + pending nav entry +
1201 // no pending DOM UI:
1202 // -> Use the committed DOM UI if any.
1203 //
1204 // - Second navigation in any tab: committed nav entry + pending nav entry:
1205 // -> Use pending DOM UI if any.
1206 //
1207 // - Normal state with no load: committed nav entry + no pending nav entry:
1208 // -> Use committed DOM UI.
1209 if (controller_.pending_entry() &&
1210 (controller_.GetLastCommittedEntry() ||
1211 render_manager_.pending_dom_ui()))
1212 return render_manager_.pending_dom_ui();
1213 return render_manager_.dom_ui();
1214}
[email protected]420ae012009-04-24 05:16:321215
1216void TabContents::DidNavigateMainFramePostCommit(
1217 const NavigationController::LoadCommittedDetails& details,
1218 const ViewHostMsg_FrameNavigate_Params& params) {
[email protected]420ae012009-04-24 05:16:321219 if (details.is_user_initiated_main_frame_load()) {
1220 // Clear the status bubble. This is a workaround for a bug where WebKit
1221 // doesn't let us know that the cursor left an element during a
1222 // transition (this is also why the mouse cursor remains as a hand after
1223 // clicking on a link); see bugs 1184641 and 980803. We don't want to
1224 // clear the bubble when a user navigates to a named anchor in the same
1225 // page.
1226 UpdateTargetURL(details.entry->page_id(), GURL());
1227
1228 // UpdateHelpersForDidNavigate will handle the case where the password_form
1229 // origin is valid.
1230 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1231 // cleaned up and covered by tests.
1232 if (!params.password_form.origin.is_valid())
1233 GetPasswordManager()->DidNavigate();
1234 }
1235
1236 // The keyword generator uses the navigation entries, so must be called after
1237 // the commit.
1238 GenerateKeywordIfNecessary(params);
1239
1240 // Allow the new page to set the title again.
1241 received_page_title_ = false;
1242
1243 // Get the favicon, either from history or request it from the net.
1244 fav_icon_helper_.FetchFavIcon(details.entry->url());
1245
[email protected]ce5c4502009-05-06 16:46:111246 // Disable all page actions.
1247 enabled_page_actions_.clear();
1248
[email protected]420ae012009-04-24 05:16:321249 // Close constrained popups if necessary.
1250 MaybeCloseChildWindows(details.previous_url, details.entry->url());
1251
1252 // Update the starred state.
1253 UpdateStarredStateForCurrentURL();
1254}
1255
1256void TabContents::DidNavigateAnyFramePostCommit(
1257 RenderViewHost* render_view_host,
1258 const NavigationController::LoadCommittedDetails& details,
1259 const ViewHostMsg_FrameNavigate_Params& params) {
1260 // If we navigate, start showing messages again. This does nothing to prevent
1261 // a malicious script from spamming messages, since the script could just
1262 // reload the page to stop blocking.
1263 suppress_javascript_messages_ = false;
1264
1265 // Update history. Note that this needs to happen after the entry is complete,
1266 // which WillNavigate[Main,Sub]Frame will do before this function is called.
1267 if (params.should_update_history) {
1268 // Most of the time, the displayURL matches the loaded URL, but for about:
1269 // URLs, we use a data: URL as the real value. We actually want to save
1270 // the about: URL to the history db and keep the data: URL hidden. This is
1271 // what the TabContents' URL getter does.
1272 UpdateHistoryForNavigation(GetURL(), params);
1273 }
1274
1275 // Notify the password manager of the navigation or form submit.
1276 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1277 // cleaned up and covered by tests.
1278 if (params.password_form.origin.is_valid())
1279 GetPasswordManager()->ProvisionallySavePassword(params.password_form);
1280}
1281
1282void TabContents::MaybeCloseChildWindows(const GURL& previous_url,
1283 const GURL& current_url) {
1284 if (net::RegistryControlledDomainService::SameDomainOrHost(
1285 previous_url, current_url))
1286 return;
1287
1288 // Clear out any child windows since we are leaving this page entirely.
1289 // We use indices instead of iterators in case CloseWindow does something
1290 // that may invalidate an iterator.
1291 int size = static_cast<int>(child_windows_.size());
1292 for (int i = size - 1; i >= 0; --i) {
1293 ConstrainedWindow* window = child_windows_[i];
1294 if (window)
1295 window->CloseConstrainedWindow();
1296 }
1297}
1298
1299void TabContents::UpdateStarredStateForCurrentURL() {
1300 BookmarkModel* model = profile()->GetBookmarkModel();
1301 const bool old_state = is_starred_;
1302 is_starred_ = (model && model->IsBookmarked(GetURL()));
1303
1304 if (is_starred_ != old_state && delegate())
1305 delegate()->URLStarredChanged(this, is_starred_);
1306}
1307
1308void TabContents::UpdateAlternateErrorPageURL() {
1309 GURL url = GetAlternateErrorPageURL();
1310 render_view_host()->SetAlternateErrorPageURL(url);
1311}
1312
1313void TabContents::UpdateWebPreferences() {
1314 render_view_host()->UpdateWebPreferences(GetWebkitPrefs());
1315}
1316
1317void TabContents::UpdateMaxPageIDIfNecessary(SiteInstance* site_instance,
1318 RenderViewHost* rvh) {
1319 // If we are creating a RVH for a restored controller, then we might
1320 // have more page IDs than the SiteInstance's current max page ID. We must
1321 // make sure that the max page ID is larger than any restored page ID.
1322 // Note that it is ok for conflicting page IDs to exist in another tab
1323 // (i.e., NavigationController), but if any page ID is larger than the max,
1324 // the back/forward list will get confused.
1325 int max_restored_page_id = controller_.max_restored_page_id();
1326 if (max_restored_page_id > 0) {
1327 int curr_max_page_id = site_instance->max_page_id();
1328 if (max_restored_page_id > curr_max_page_id) {
1329 // Need to update the site instance immediately.
1330 site_instance->UpdateMaxPageID(max_restored_page_id);
1331
1332 // Also tell the renderer to update its internal representation. We
1333 // need to reserve enough IDs to make all restored page IDs less than
1334 // the max.
1335 if (curr_max_page_id < 0)
1336 curr_max_page_id = 0;
1337 rvh->ReservePageIDRange(max_restored_page_id - curr_max_page_id);
1338 }
1339 }
1340}
1341
1342void TabContents::UpdateHistoryForNavigation(
1343 const GURL& display_url,
1344 const ViewHostMsg_FrameNavigate_Params& params) {
1345 if (profile()->IsOffTheRecord())
1346 return;
1347
1348 // Add to history service.
1349 HistoryService* hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1350 if (hs) {
1351 if (PageTransition::IsMainFrame(params.transition) &&
1352 display_url != params.url) {
1353 // Hack on the "display" URL so that it will appear in history. For some
1354 // types of URLs, we will display a magic URL that is different from where
1355 // the page is actually navigated. We want the user to see in history
1356 // what they saw in the URL bar, so we add the display URL as a redirect.
1357 // This only applies to the main frame, as the display URL doesn't apply
1358 // to sub-frames.
1359 std::vector<GURL> redirects = params.redirects;
1360 if (!redirects.empty())
1361 redirects.back() = display_url;
1362 hs->AddPage(display_url, this, params.page_id, params.referrer,
1363 params.transition, redirects);
1364 } else {
1365 hs->AddPage(params.url, this, params.page_id, params.referrer,
1366 params.transition, params.redirects);
1367 }
1368 }
1369}
1370
1371bool TabContents::UpdateTitleForEntry(NavigationEntry* entry,
1372 const std::wstring& title) {
1373 // For file URLs without a title, use the pathname instead. In the case of a
1374 // synthesized title, we don't want the update to count toward the "one set
1375 // per page of the title to history."
1376 std::wstring final_title;
1377 bool explicit_set;
1378 if (entry->url().SchemeIsFile() && title.empty()) {
1379 final_title = UTF8ToWide(entry->url().ExtractFileName());
1380 explicit_set = false; // Don't count synthetic titles toward the set limit.
1381 } else {
1382 TrimWhitespace(title, TRIM_ALL, &final_title);
1383 explicit_set = true;
1384 }
1385
1386 if (final_title == UTF16ToWideHack(entry->title()))
1387 return false; // Nothing changed, don't bother.
1388
1389 entry->set_title(WideToUTF16Hack(final_title));
1390
1391 // Update the history system for this page.
1392 if (!profile()->IsOffTheRecord() && !received_page_title_) {
1393 HistoryService* hs =
1394 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1395 if (hs)
1396 hs->SetPageTitle(entry->display_url(), final_title);
1397
1398 // Don't allow the title to be saved again for explicitly set ones.
1399 received_page_title_ = explicit_set;
1400 }
1401
1402 // Lastly, set the title for the view.
1403 view_->SetPageTitle(final_title);
1404
1405 return true;
1406}
1407
1408void TabContents::NotifySwapped() {
1409 // After sending out a swap notification, we need to send a disconnect
1410 // notification so that clients that pick up a pointer to |this| can NULL the
1411 // pointer. See Bug 1230284.
1412 notify_disconnection_ = true;
1413 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341414 NotificationType::TAB_CONTENTS_SWAPPED,
1415 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321416 NotificationService::NoDetails());
1417}
1418
1419void TabContents::NotifyConnected() {
1420 notify_disconnection_ = true;
1421 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341422 NotificationType::TAB_CONTENTS_CONNECTED,
1423 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321424 NotificationService::NoDetails());
1425}
1426
1427void TabContents::NotifyDisconnected() {
1428 if (!notify_disconnection_)
1429 return;
1430
1431 notify_disconnection_ = false;
1432 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341433 NotificationType::TAB_CONTENTS_DISCONNECTED,
1434 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321435 NotificationService::NoDetails());
1436}
1437
1438void TabContents::GenerateKeywordIfNecessary(
1439 const ViewHostMsg_FrameNavigate_Params& params) {
1440 if (!params.searchable_form_url.is_valid())
1441 return;
1442
1443 if (profile()->IsOffTheRecord())
1444 return;
1445
1446 int last_index = controller_.last_committed_entry_index();
1447 // When there was no previous page, the last index will be 0. This is
1448 // normally due to a form submit that opened in a new tab.
1449 // TODO(brettw) bug 916126: we should support keywords when form submits
1450 // happen in new tabs.
1451 if (last_index <= 0)
1452 return;
1453 const NavigationEntry* previous_entry =
1454 controller_.GetEntryAtIndex(last_index - 1);
1455 if (IsFormSubmit(previous_entry)) {
1456 // Only generate a keyword if the previous page wasn't itself a form
1457 // submit.
1458 return;
1459 }
1460
1461 GURL keyword_url = previous_entry->user_typed_url().is_valid() ?
1462 previous_entry->user_typed_url() : previous_entry->url();
1463 std::wstring keyword =
1464 TemplateURLModel::GenerateKeyword(keyword_url, true); // autodetected
1465 if (keyword.empty())
1466 return;
1467
1468 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
1469 if (!url_model)
1470 return;
1471
1472 if (!url_model->loaded()) {
1473 url_model->Load();
1474 return;
1475 }
1476
1477 const TemplateURL* current_url;
1478 std::wstring url = UTF8ToWide(params.searchable_form_url.spec());
1479 if (!url_model->CanReplaceKeyword(keyword, url, &current_url))
1480 return;
1481
1482 if (current_url) {
1483 if (current_url->originating_url().is_valid()) {
1484 // The existing keyword was generated from an OpenSearch description
1485 // document, don't regenerate.
1486 return;
1487 }
1488 url_model->Remove(current_url);
1489 }
1490 TemplateURL* new_url = new TemplateURL();
1491 new_url->set_keyword(keyword);
1492 new_url->set_short_name(keyword);
1493 new_url->SetURL(url, 0, 0);
1494 new_url->add_input_encoding(params.searchable_form_encoding);
1495 DCHECK(controller_.GetLastCommittedEntry());
1496 const GURL& favicon_url =
1497 controller_.GetLastCommittedEntry()->favicon().url();
1498 if (favicon_url.is_valid()) {
1499 new_url->SetFavIconURL(favicon_url);
1500 } else {
1501 // The favicon url isn't valid. This means there really isn't a favicon,
1502 // or the favicon url wasn't obtained before the load started. This assumes
1503 // the later.
1504 // TODO(sky): Need a way to set the favicon that doesn't involve generating
1505 // its url.
1506 new_url->SetFavIconURL(TemplateURL::GenerateFaviconURL(params.referrer));
1507 }
1508 new_url->set_safe_for_autoreplace(true);
1509 url_model->Add(new_url);
1510}
1511
1512RenderViewHostDelegate::View* TabContents::GetViewDelegate() const {
1513 return view_.get();
1514}
1515
1516RenderViewHostDelegate::Save* TabContents::GetSaveDelegate() const {
1517 return save_package_.get(); // May be NULL, but we can return NULL.
1518}
1519
[email protected]6dfed102009-04-28 03:09:531520ExtensionFunctionDispatcher* TabContents::CreateExtensionFunctionDispatcher(
1521 RenderViewHost* render_view_host,
1522 const std::string& extension_id) {
1523 return delegate()->CreateExtensionFunctionDispatcher(render_view_host,
1524 extension_id);
1525}
1526
[email protected]57c6a652009-05-04 07:58:341527TabContents* TabContents::GetAsTabContents() {
1528 return this;
1529}
1530
[email protected]420ae012009-04-24 05:16:321531void TabContents::RenderViewCreated(RenderViewHost* render_view_host) {
1532 NavigationEntry* entry = controller_.GetActiveEntry();
1533 if (!entry)
1534 return;
1535
1536 // When we're creating views, we're still doing initial setup, so we always
1537 // use the pending DOM UI rather than any possibly existing committed one.
1538 if (render_manager_.pending_dom_ui()) {
1539 render_manager_.pending_dom_ui()->RenderViewCreated(render_view_host);
1540 }
1541
1542 if (entry->IsViewSourceMode()) {
1543 // Put the renderer in view source mode.
1544 render_view_host->Send(
1545 new ViewMsg_EnableViewSourceMode(render_view_host->routing_id()));
1546 }
[email protected]0666aef2009-05-13 19:48:081547
1548 view()->RenderViewCreated(render_view_host);
[email protected]420ae012009-04-24 05:16:321549}
1550
1551void TabContents::RenderViewReady(RenderViewHost* rvh) {
1552 if (rvh != render_view_host()) {
1553 // Don't notify the world, since this came from a renderer in the
1554 // background.
1555 return;
1556 }
1557
1558 NotifyConnected();
1559 SetIsCrashed(false);
1560}
1561
1562void TabContents::RenderViewGone(RenderViewHost* rvh) {
1563 // Ask the print preview if this renderer was valuable.
1564 if (!printing_.OnRenderViewGone(rvh))
1565 return;
1566 if (rvh != render_view_host()) {
1567 // The pending page's RenderViewHost is gone.
1568 return;
1569 }
1570
1571 SetIsLoading(false, NULL);
1572 NotifyDisconnected();
1573 SetIsCrashed(true);
1574
1575 // Force an invalidation to render sad tab. The view will notice we crashed
1576 // when it paints.
1577 view_->Invalidate();
1578
1579 // Hide any visible hung renderer warning for this web contents' process.
[email protected]8897c382009-05-06 17:53:261580 HungRendererDialog::HideForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:321581}
1582
1583void TabContents::DidNavigate(RenderViewHost* rvh,
1584 const ViewHostMsg_FrameNavigate_Params& params) {
1585 if (PageTransition::IsMainFrame(params.transition))
1586 render_manager_.DidNavigateMainFrame(rvh);
1587
1588 // Update the site of the SiteInstance if it doesn't have one yet.
1589 if (!GetSiteInstance()->has_site())
1590 GetSiteInstance()->SetSite(params.url);
1591
1592 // Need to update MIME type here because it's referred to in
1593 // UpdateNavigationCommands() called by RendererDidNavigate() to
1594 // determine whether or not to enable the encoding menu.
1595 // It's updated only for the main frame. For a subframe,
1596 // RenderView::UpdateURL does not set params.contents_mime_type.
1597 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
1598 // TODO(jungshik): Add a test for the encoding menu to avoid
1599 // regressing it again.
1600 if (PageTransition::IsMainFrame(params.transition))
1601 contents_mime_type_ = params.contents_mime_type;
1602
1603 NavigationController::LoadCommittedDetails details;
1604 if (!controller_.RendererDidNavigate(params, &details))
1605 return; // No navigation happened.
1606
1607 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
1608 // for the appropriate notification (best) or you can add it to
1609 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
1610 // necessary, please).
1611
1612 // Run post-commit tasks.
1613 if (details.is_main_frame)
1614 DidNavigateMainFramePostCommit(details, params);
1615 DidNavigateAnyFramePostCommit(rvh, details, params);
1616}
1617
1618void TabContents::UpdateState(RenderViewHost* rvh,
1619 int32 page_id,
1620 const std::string& state) {
1621 DCHECK(rvh == render_view_host());
1622
1623 // We must be prepared to handle state updates for any page, these occur
1624 // when the user is scrolling and entering form data, as well as when we're
1625 // leaving a page, in which case our state may have already been moved to
1626 // the next page. The navigation controller will look up the appropriate
1627 // NavigationEntry and update it when it is notified via the delegate.
1628
1629 int entry_index = controller_.GetEntryIndexWithPageID(
1630 GetSiteInstance(), page_id);
1631 if (entry_index < 0)
1632 return;
1633 NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
1634
1635 if (state == entry->content_state())
1636 return; // Nothing to update.
1637 entry->set_content_state(state);
1638 controller_.NotifyEntryChanged(entry, entry_index);
1639}
1640
1641void TabContents::UpdateTitle(RenderViewHost* rvh,
1642 int32 page_id, const std::wstring& title) {
1643 // If we have a title, that's a pretty good indication that we've started
1644 // getting useful data.
1645 SetNotWaitingForResponse();
1646
1647 DCHECK(rvh == render_view_host());
1648 NavigationEntry* entry = controller_.GetEntryWithPageID(GetSiteInstance(),
1649 page_id);
1650 if (!entry || !UpdateTitleForEntry(entry, title))
1651 return;
1652
1653 // Broadcast notifications when the UI should be updated.
1654 if (entry == controller_.GetEntryAtOffset(0))
[email protected]c9cd2222009-05-06 05:16:501655 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:321656}
1657
[email protected]420ae012009-04-24 05:16:321658void TabContents::UpdateEncoding(RenderViewHost* render_view_host,
1659 const std::wstring& encoding) {
1660 set_encoding(encoding);
1661}
1662
1663void TabContents::UpdateTargetURL(int32 page_id, const GURL& url) {
1664 if (delegate())
1665 delegate()->UpdateTargetURL(this, url);
1666}
1667
1668void TabContents::UpdateThumbnail(const GURL& url,
1669 const SkBitmap& bitmap,
1670 const ThumbnailScore& score) {
1671 // Tell History about this thumbnail
1672 HistoryService* hs;
1673 if (!profile()->IsOffTheRecord() &&
1674 (hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS))) {
1675 hs->SetPageThumbnail(url, bitmap, score);
1676 }
1677}
1678
[email protected]0df30122009-06-03 12:13:081679void TabContents::UpdateInspectorSettings(const std::wstring& raw_settings) {
1680 profile()->GetPrefs()->SetString(prefs::kWebKitInspectorSettings,
1681 raw_settings);
1682}
1683
[email protected]420ae012009-04-24 05:16:321684void TabContents::Close(RenderViewHost* rvh) {
1685 // Ignore this if it comes from a RenderViewHost that we aren't showing.
1686 if (delegate() && rvh == render_view_host())
1687 delegate()->CloseContents(this);
1688}
1689
1690void TabContents::RequestMove(const gfx::Rect& new_bounds) {
1691 if (delegate() && delegate()->IsPopup(this))
1692 delegate()->MoveContents(this, new_bounds);
1693}
1694
[email protected]329581b2009-04-28 06:52:351695void TabContents::DidStartLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321696 SetIsLoading(true, NULL);
1697}
1698
[email protected]329581b2009-04-28 06:52:351699void TabContents::DidStopLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321700 scoped_ptr<LoadNotificationDetails> details;
1701
1702 NavigationEntry* entry = controller_.GetActiveEntry();
1703 // An entry may not exist for a stop when loading an initial blank page or
1704 // if an iframe injected by script into a blank page finishes loading.
1705 if (entry) {
1706 scoped_ptr<base::ProcessMetrics> metrics(
1707 base::ProcessMetrics::CreateProcessMetrics(
1708 process()->process().handle()));
1709
1710 base::TimeDelta elapsed = base::TimeTicks::Now() - current_load_start_;
1711
1712 details.reset(new LoadNotificationDetails(
1713 entry->display_url(),
1714 entry->transition_type(),
1715 elapsed,
1716 &controller_,
1717 controller_.GetCurrentEntryIndex()));
1718 }
1719
1720 // Tell PasswordManager we've finished a page load, which serves as a
1721 // green light to save pending passwords and reset itself.
1722 GetPasswordManager()->DidStopLoading();
1723
1724 SetIsLoading(false, details.get());
1725}
1726
1727void TabContents::DidStartProvisionalLoadForFrame(
1728 RenderViewHost* render_view_host,
1729 bool is_main_frame,
1730 const GURL& url) {
1731 ProvisionalLoadDetails details(is_main_frame,
1732 controller_.IsURLInPageNavigation(url),
1733 url, std::string(), false);
1734 NotificationService::current()->Notify(
1735 NotificationType::FRAME_PROVISIONAL_LOAD_START,
1736 Source<NavigationController>(&controller_),
1737 Details<ProvisionalLoadDetails>(&details));
1738}
1739
1740void TabContents::DidRedirectProvisionalLoad(int32 page_id,
1741 const GURL& source_url,
1742 const GURL& target_url) {
1743 NavigationEntry* entry;
1744 if (page_id == -1)
1745 entry = controller_.pending_entry();
1746 else
1747 entry = controller_.GetEntryWithPageID(GetSiteInstance(), page_id);
1748 if (!entry || entry->url() != source_url)
1749 return;
1750 entry->set_url(target_url);
1751}
1752
1753void TabContents::DidLoadResourceFromMemoryCache(
1754 const GURL& url,
1755 const std::string& frame_origin,
1756 const std::string& main_frame_origin,
1757 const std::string& security_info) {
1758 // Send out a notification that we loaded a resource from our memory cache.
1759 int cert_id = 0, cert_status = 0, security_bits = 0;
1760 SSLManager::DeserializeSecurityInfo(security_info,
1761 &cert_id, &cert_status,
1762 &security_bits);
1763 LoadFromMemoryCacheDetails details(url, frame_origin, main_frame_origin,
[email protected]9ae66cbf2009-05-12 16:21:031764 process()->pid(), cert_id, cert_status);
[email protected]420ae012009-04-24 05:16:321765
1766 NotificationService::current()->Notify(
1767 NotificationType::LOAD_FROM_MEMORY_CACHE,
1768 Source<NavigationController>(&controller_),
1769 Details<LoadFromMemoryCacheDetails>(&details));
1770}
1771
1772void TabContents::DidFailProvisionalLoadWithError(
1773 RenderViewHost* render_view_host,
1774 bool is_main_frame,
1775 int error_code,
1776 const GURL& url,
1777 bool showing_repost_interstitial) {
1778 if (net::ERR_ABORTED == error_code) {
1779 // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
1780 // This means that the interstitial won't be torn down properly, which is
1781 // bad. But if we have an interstitial, go back to another tab type, and
1782 // then load the same interstitial again, we could end up getting the first
1783 // interstitial's "failed" message (as a result of the cancel) when we're on
1784 // the second one.
1785 //
1786 // We can't tell this apart, so we think we're tearing down the current page
1787 // which will cause a crash later one. There is also some code in
1788 // RenderViewHostManager::RendererAbortedProvisionalLoad that is commented
1789 // out because of this problem.
1790 //
1791 // http://code.google.com/p/chromium/issues/detail?id=2855
1792 // Because this will not tear down the interstitial properly, if "back" is
1793 // back to another tab type, the interstitial will still be somewhat alive
1794 // in the previous tab type. If you navigate somewhere that activates the
1795 // tab with the interstitial again, you'll see a flash before the new load
1796 // commits of the interstitial page.
1797 if (showing_interstitial_page()) {
1798 LOG(WARNING) << "Discarding message during interstitial.";
1799 return;
1800 }
1801
1802 // This will discard our pending entry if we cancelled the load (e.g., if we
1803 // decided to download the file instead of load it). Only discard the
1804 // pending entry if the URLs match, otherwise the user initiated a navigate
1805 // before the page loaded so that the discard would discard the wrong entry.
1806 NavigationEntry* pending_entry = controller_.pending_entry();
1807 if (pending_entry && pending_entry->url() == url)
1808 controller_.DiscardNonCommittedEntries();
1809
1810 render_manager_.RendererAbortedProvisionalLoad(render_view_host);
1811 }
1812
1813 // Send out a notification that we failed a provisional load with an error.
1814 ProvisionalLoadDetails details(is_main_frame,
1815 controller_.IsURLInPageNavigation(url),
1816 url, std::string(), false);
1817 details.set_error_code(error_code);
1818
1819 NotificationService::current()->Notify(
1820 NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR,
1821 Source<NavigationController>(&controller_),
1822 Details<ProvisionalLoadDetails>(&details));
1823}
1824
1825void TabContents::UpdateFavIconURL(RenderViewHost* render_view_host,
1826 int32 page_id,
1827 const GURL& icon_url) {
1828 fav_icon_helper_.SetFavIconURL(icon_url);
1829}
1830
1831void TabContents::DidDownloadImage(
1832 RenderViewHost* render_view_host,
1833 int id,
1834 const GURL& image_url,
1835 bool errored,
1836 const SkBitmap& image) {
1837 // A notification for downloading would be more flexible, but for now I'm
1838 // forwarding to the two places that could possibly have initiated the
1839 // request. If we end up with another place invoking DownloadImage, probably
1840 // best to refactor out into notification service, or something similar.
1841 if (errored)
1842 fav_icon_helper_.FavIconDownloadFailed(id);
1843 else
1844 fav_icon_helper_.SetFavIcon(id, image_url, image);
1845}
1846
1847void TabContents::RequestOpenURL(const GURL& url, const GURL& referrer,
1848 WindowOpenDisposition disposition) {
1849 if (render_manager_.dom_ui()) {
1850 // When we're a DOM UI, it will provide a page transition type for us (this
1851 // is so the new tab page can specify AUTO_BOOKMARK for automatically
1852 // generated suggestions).
1853 //
1854 // Note also that we hide the referrer for DOM UI pages. We don't really
[email protected]60e448982009-05-06 04:21:161855 // want web sites to see a referrer of "chrome://blah" (and some
1856 // chrome: URLs might have search terms or other stuff we don't want to
[email protected]420ae012009-04-24 05:16:321857 // send to the site), so we send no referrer.
1858 OpenURL(url, GURL(), disposition,
1859 render_manager_.dom_ui()->link_transition_type());
1860 } else {
1861 OpenURL(url, referrer, disposition, PageTransition::LINK);
1862 }
1863}
1864
1865void TabContents::DomOperationResponse(const std::string& json_string,
1866 int automation_id) {
1867 DomOperationNotificationDetails details(json_string, automation_id);
1868 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341869 NotificationType::DOM_OPERATION_RESPONSE, Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321870 Details<DomOperationNotificationDetails>(&details));
1871}
1872
1873void TabContents::ProcessDOMUIMessage(const std::string& message,
1874 const std::string& content) {
1875 if (!render_manager_.dom_ui()) {
1876 // We shouldn't get a DOM UI message when we haven't enabled the DOM UI.
1877 // Because the renderer might be owned and sending random messages, we need
1878 // to ignore these inproper ones.
1879 NOTREACHED();
1880 return;
1881 }
1882 render_manager_.dom_ui()->ProcessDOMUIMessage(message, content);
1883}
1884
1885void TabContents::ProcessExternalHostMessage(const std::string& message,
1886 const std::string& origin,
1887 const std::string& target) {
1888 if (delegate())
1889 delegate()->ForwardMessageToExternalHost(message, origin, target);
1890}
1891
1892void TabContents::GoToEntryAtOffset(int offset) {
1893 controller_.GoToOffset(offset);
1894}
1895
1896void TabContents::GetHistoryListCount(int* back_list_count,
1897 int* forward_list_count) {
1898 int current_index = controller_.last_committed_entry_index();
1899 *back_list_count = current_index;
1900 *forward_list_count = controller_.entry_count() - current_index - 1;
1901}
1902
1903void TabContents::RunFileChooser(bool multiple_files,
1904 const string16& title,
1905 const FilePath& default_file) {
1906 if (!select_file_dialog_.get())
1907 select_file_dialog_ = SelectFileDialog::Create(this);
1908 SelectFileDialog::Type dialog_type =
1909 multiple_files ? SelectFileDialog::SELECT_OPEN_MULTI_FILE :
1910 SelectFileDialog::SELECT_OPEN_FILE;
1911 select_file_dialog_->SelectFile(dialog_type, title, default_file,
1912 NULL, 0, FILE_PATH_LITERAL(""),
1913 view_->GetTopLevelNativeWindow(), NULL);
1914}
1915
1916void TabContents::RunJavaScriptMessage(
1917 const std::wstring& message,
1918 const std::wstring& default_prompt,
1919 const GURL& frame_url,
1920 const int flags,
1921 IPC::Message* reply_msg,
1922 bool* did_suppress_message) {
1923 // Suppress javascript messages when requested and when inside a constrained
1924 // popup window (because that activates them and breaks them out of the
1925 // constrained window jail).
1926 bool suppress_this_message = suppress_javascript_messages_;
1927 if (delegate())
1928 suppress_this_message |=
[email protected]b6c874582009-05-08 19:38:311929 (delegate()->GetConstrainingContents(this) != this);
[email protected]420ae012009-04-24 05:16:321930
1931 *did_suppress_message = suppress_this_message;
1932
1933 if (!suppress_this_message) {
1934 base::TimeDelta time_since_last_message(
1935 base::TimeTicks::Now() - last_javascript_message_dismissal_);
1936 bool show_suppress_checkbox = false;
1937 // Show a checkbox offering to suppress further messages if this message is
1938 // being displayed within kJavascriptMessageExpectedDelay of the last one.
1939 if (time_since_last_message <
1940 base::TimeDelta::FromMilliseconds(kJavascriptMessageExpectedDelay))
1941 show_suppress_checkbox = true;
1942
1943 RunJavascriptMessageBox(AsWC(this), frame_url, flags, message, default_prompt,
1944 show_suppress_checkbox, reply_msg);
1945 } else {
1946 // If we are suppressing messages, just reply as is if the user immediately
1947 // pressed "Cancel".
1948 OnJavaScriptMessageBoxClosed(reply_msg, false, std::wstring());
1949 }
1950}
1951
1952void TabContents::RunBeforeUnloadConfirm(const std::wstring& message,
1953 IPC::Message* reply_msg) {
1954 RunBeforeUnloadDialog(AsWC(this), message, reply_msg);
1955}
1956
1957void TabContents::ShowModalHTMLDialog(const GURL& url, int width, int height,
1958 const std::string& json_arguments,
1959 IPC::Message* reply_msg) {
1960 if (delegate()) {
1961 HtmlDialogUIDelegate* dialog_delegate =
1962 new ModalHtmlDialogDelegate(url, width, height, json_arguments,
1963 reply_msg, AsWC(this));
1964 delegate()->ShowHtmlDialog(dialog_delegate, NULL);
1965 }
1966}
1967
1968void TabContents::PasswordFormsSeen(
1969 const std::vector<PasswordForm>& forms) {
1970 GetPasswordManager()->PasswordFormsSeen(forms);
1971}
1972
1973void TabContents::AutofillFormSubmitted(
1974 const AutofillForm& form) {
1975 GetAutofillManager()->AutofillFormSubmitted(form);
1976}
1977
1978void TabContents::GetAutofillSuggestions(const std::wstring& field_name,
1979 const std::wstring& user_text, int64 node_id, int request_id) {
1980 GetAutofillManager()->FetchValuesForName(field_name, user_text,
1981 kMaxAutofillMenuItems, node_id, request_id);
1982}
1983
1984void TabContents::RemoveAutofillEntry(const std::wstring& field_name,
1985 const std::wstring& value) {
1986 GetAutofillManager()->RemoveValueForName(field_name, value);
1987}
1988
1989// Checks to see if we should generate a keyword based on the OSDD, and if
1990// necessary uses TemplateURLFetcher to download the OSDD and create a keyword.
1991void TabContents::PageHasOSDD(RenderViewHost* render_view_host,
1992 int32 page_id, const GURL& url,
1993 bool autodetected) {
1994 // Make sure page_id is the current page, and the TemplateURLModel is loaded.
1995 DCHECK(url.is_valid());
1996 if (!IsActiveEntry(page_id))
1997 return;
1998 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
1999 if (!url_model)
2000 return;
2001 if (!url_model->loaded()) {
2002 url_model->Load();
2003 return;
2004 }
2005 if (!profile()->GetTemplateURLFetcher())
2006 return;
2007
2008 if (profile()->IsOffTheRecord())
2009 return;
2010
2011 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
2012 DCHECK(entry);
2013
2014 const NavigationEntry* base_entry = entry;
2015 if (IsFormSubmit(base_entry)) {
2016 // If the current page is a form submit, find the last page that was not
2017 // a form submit and use its url to generate the keyword from.
2018 int index = controller_.last_committed_entry_index() - 1;
2019 while (index >= 0 && IsFormSubmit(controller_.GetEntryAtIndex(index)))
2020 index--;
2021 if (index >= 0)
2022 base_entry = controller_.GetEntryAtIndex(index);
2023 else
2024 base_entry = NULL;
2025 }
2026
2027 // We want to use the user typed URL if available since that represents what
2028 // the user typed to get here, and fall back on the regular URL if not.
2029 if (!base_entry)
2030 return;
2031 GURL keyword_url = base_entry->user_typed_url().is_valid() ?
2032 base_entry->user_typed_url() : base_entry->url();
2033 if (!keyword_url.is_valid())
2034 return;
2035 std::wstring keyword = TemplateURLModel::GenerateKeyword(keyword_url,
2036 autodetected);
2037 if (keyword.empty())
2038 return;
2039 const TemplateURL* template_url =
2040 url_model->GetTemplateURLForKeyword(keyword);
2041 if (template_url && (!template_url->safe_for_autoreplace() ||
2042 template_url->originating_url() == url)) {
2043 // Either there is a user created TemplateURL for this keyword, or the
2044 // keyword has the same OSDD url and we've parsed it.
2045 return;
2046 }
2047
2048 // Download the OpenSearch description document. If this is successful a
2049 // new keyword will be created when done.
2050#if defined(OS_WIN)
2051 gfx::NativeView ancestor = GetAncestor(view_->GetNativeView(), GA_ROOT);
2052#else
2053 gfx::NativeView ancestor = NULL;
2054#endif
2055 profile()->GetTemplateURLFetcher()->ScheduleDownload(
2056 keyword,
2057 url,
2058 base_entry->favicon().url(),
2059 ancestor,
2060 autodetected);
2061}
2062
2063void TabContents::InspectElementReply(int num_resources) {
2064 // We have received reply from inspect element request. Notify the
2065 // automation provider in case we need to notify automation client.
2066 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:342067 NotificationType::DOM_INSPECT_ELEMENT_RESPONSE, Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:322068 Details<int>(&num_resources));
2069}
2070
2071void TabContents::DidGetPrintedPagesCount(int cookie, int number_pages) {
2072 printing_.DidGetPrintedPagesCount(cookie, number_pages);
2073}
2074
2075void TabContents::DidPrintPage(const ViewHostMsg_DidPrintPage_Params& params) {
2076 printing_.DidPrintPage(params);
2077}
2078
2079GURL TabContents::GetAlternateErrorPageURL() const {
2080 GURL url;
2081 // Disable alternate error pages when in OffTheRecord/Incognito mode.
2082 if (profile()->IsOffTheRecord())
2083 return url;
2084
2085 PrefService* prefs = profile()->GetPrefs();
2086 DCHECK(prefs);
2087 if (prefs->GetBoolean(prefs::kAlternateErrorPagesEnabled)) {
2088 url = google_util::AppendGoogleLocaleParam(GURL(kLinkDoctorBaseURL));
2089 url = google_util::AppendGoogleTLDParam(url);
2090 }
2091 return url;
2092}
2093
2094WebPreferences TabContents::GetWebkitPrefs() {
2095 PrefService* prefs = render_view_host()->process()->profile()->GetPrefs();
2096 bool isDomUI = false;
2097 return RenderViewHostDelegateHelper::GetWebkitPrefs(prefs, isDomUI);
2098}
2099
2100void TabContents::OnMissingPluginStatus(int status) {
2101#if defined(OS_WIN)
2102// TODO(PORT): pull in when plug-ins work
2103 GetPluginInstaller()->OnMissingPluginStatus(status);
2104#endif
2105}
2106
2107void TabContents::OnCrashedPlugin(const FilePath& plugin_path) {
2108#if defined(OS_WIN)
2109// TODO(PORT): pull in when plug-ins work
2110 DCHECK(!plugin_path.value().empty());
2111
2112 std::wstring plugin_name = plugin_path.ToWStringHack();
2113 scoped_ptr<FileVersionInfo> version_info(
2114 FileVersionInfo::CreateFileVersionInfo(plugin_path));
2115 if (version_info.get()) {
2116 const std::wstring& product_name = version_info->product_name();
2117 if (!product_name.empty())
2118 plugin_name = product_name;
2119 }
2120 AddInfoBar(new SimpleAlertInfoBarDelegate(
2121 this, l10n_util::GetStringF(IDS_PLUGIN_CRASHED_PROMPT, plugin_name),
2122 NULL));
2123#endif
2124}
2125
2126void TabContents::OnCrashedWorker() {
2127 AddInfoBar(new SimpleAlertInfoBarDelegate(
2128 this, l10n_util::GetString(IDS_WEBWORKER_CRASHED_PROMPT),
2129 NULL));
2130}
2131
2132void TabContents::OnJSOutOfMemory() {
2133 AddInfoBar(new SimpleAlertInfoBarDelegate(
2134 this, l10n_util::GetString(IDS_JS_OUT_OF_MEMORY_PROMPT), NULL));
2135}
2136
2137void TabContents::ShouldClosePage(bool proceed) {
2138 render_manager_.ShouldClosePage(proceed);
2139}
2140
2141void TabContents::OnCrossSiteResponse(int new_render_process_host_id,
2142 int new_request_id) {
[email protected]57c6a652009-05-04 07:58:342143 // Allows the TabContents to react when a cross-site response is ready to be
[email protected]420ae012009-04-24 05:16:322144 // delivered to a pending RenderViewHost. We must first run the onunload
2145 // handler of the old RenderViewHost before we can allow it to proceed.
2146 render_manager_.OnCrossSiteResponse(new_render_process_host_id,
2147 new_request_id);
2148}
2149
2150bool TabContents::CanBlur() const {
2151 return delegate() ? delegate()->CanBlur() : true;
2152}
2153
2154gfx::Rect TabContents::GetRootWindowResizerRect() const {
2155 if (delegate())
2156 return delegate()->GetRootWindowResizerRect();
2157 return gfx::Rect();
2158}
2159
2160void TabContents::RendererUnresponsive(RenderViewHost* rvh,
2161 bool is_during_unload) {
2162 if (is_during_unload) {
2163 // Hang occurred while firing the beforeunload/unload handler.
2164 // Pretend the handler fired so tab closing continues as if it had.
[email protected]829e7612009-04-25 01:15:112165 rvh->set_sudden_termination_allowed(true);
[email protected]420ae012009-04-24 05:16:322166
2167 if (!render_manager_.ShouldCloseTabOnUnresponsiveRenderer())
2168 return;
2169
2170 // If the tab hangs in the beforeunload/unload handler there's really
2171 // nothing we can do to recover. Pretend the unload listeners have
2172 // all fired and close the tab. If the hang is in the beforeunload handler
2173 // then the user will not have the option of cancelling the close.
2174 Close(rvh);
2175 return;
2176 }
2177
2178 if (render_view_host() && render_view_host()->IsRenderViewLive())
[email protected]8897c382009-05-06 17:53:262179 HungRendererDialog::ShowForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:322180}
2181
2182void TabContents::RendererResponsive(RenderViewHost* render_view_host) {
[email protected]8897c382009-05-06 17:53:262183 HungRendererDialog::HideForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:322184}
2185
2186void TabContents::LoadStateChanged(const GURL& url,
2187 net::LoadState load_state) {
2188 load_state_ = load_state;
[email protected]d686e812009-06-03 19:10:292189 std::wstring languages =
2190 profile()->GetPrefs()->GetString(prefs::kAcceptLanguages);
2191 load_state_host_.clear();
2192 std::string host = url.host();
2193 net::IDNToUnicode(host.c_str(), host.size(), languages, &load_state_host_);
[email protected]420ae012009-04-24 05:16:322194 if (load_state_ == net::LOAD_STATE_READING_RESPONSE)
2195 SetNotWaitingForResponse();
2196 if (is_loading())
[email protected]c9cd2222009-05-06 05:16:502197 NotifyNavigationStateChanged(INVALIDATE_LOAD | INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:322198}
2199
2200void TabContents::OnDidGetApplicationInfo(
2201 int32 page_id,
2202 const webkit_glue::WebApplicationInfo& info) {
2203 if (pending_install_.page_id != page_id)
2204 return; // The user clicked create on a separate page. Ignore this.
2205
2206 pending_install_.callback_functor =
2207 new GearsCreateShortcutCallbackFunctor(this);
2208 GearsCreateShortcut(
2209 info, pending_install_.title, pending_install_.url, pending_install_.icon,
2210 NewCallback(pending_install_.callback_functor,
2211 &GearsCreateShortcutCallbackFunctor::Run));
2212}
2213
[email protected]14ce83f2009-05-28 18:35:242214void TabContents::OnUserGesture() {
2215 // See comment in RenderViewHostDelegate::OnUserGesture as to why we do this.
2216#if defined(OS_WIN) || defined(OS_LINUX)
[email protected]420ae012009-04-24 05:16:322217 DownloadRequestManager* drm = g_browser_process->download_request_manager();
2218 if (drm)
2219 drm->OnUserGesture(this);
2220#endif
2221}
2222
2223void TabContents::OnFindReply(int request_id,
2224 int number_of_matches,
2225 const gfx::Rect& selection_rect,
2226 int active_match_ordinal,
2227 bool final_update) {
2228 // Ignore responses for requests other than the one we have most recently
2229 // issued. That way we won't act on stale results when the user has
2230 // already typed in another query.
2231 if (request_id != current_find_request_id_)
2232 return;
2233
2234 if (number_of_matches == -1)
[email protected]e491f1c2009-05-22 20:28:122235 number_of_matches = last_search_result_.number_of_matches();
[email protected]420ae012009-04-24 05:16:322236 if (active_match_ordinal == -1)
[email protected]e491f1c2009-05-22 20:28:122237 active_match_ordinal = last_search_result_.active_match_ordinal();
[email protected]420ae012009-04-24 05:16:322238
[email protected]2c355c282009-05-21 23:24:432239 gfx::Rect selection = selection_rect;
2240 if (selection.IsEmpty())
[email protected]e491f1c2009-05-22 20:28:122241 selection = last_search_result_.selection_rect();
[email protected]2c355c282009-05-21 23:24:432242
[email protected]420ae012009-04-24 05:16:322243 // Notify the UI, automation and any other observers that a find result was
2244 // found.
[email protected]e491f1c2009-05-22 20:28:122245 last_search_result_ = FindNotificationDetails(request_id, number_of_matches,
2246 selection, active_match_ordinal,
2247 final_update);
[email protected]420ae012009-04-24 05:16:322248 NotificationService::current()->Notify(
2249 NotificationType::FIND_RESULT_AVAILABLE,
2250 Source<TabContents>(this),
[email protected]e491f1c2009-05-22 20:28:122251 Details<FindNotificationDetails>(&last_search_result_));
[email protected]420ae012009-04-24 05:16:322252}
2253
[email protected]829e7612009-04-25 01:15:112254bool TabContents::IsExternalTabContainer() const {
[email protected]420ae012009-04-24 05:16:322255 if (!delegate())
[email protected]829e7612009-04-25 01:15:112256 return false;
[email protected]420ae012009-04-24 05:16:322257
[email protected]829e7612009-04-25 01:15:112258 return delegate()->IsExternalTabContainer();
[email protected]420ae012009-04-24 05:16:322259}
2260
2261void TabContents::FileSelected(const FilePath& path,
2262 int index, void* params) {
2263 render_view_host()->FileSelected(path);
2264}
2265
2266void TabContents::MultiFilesSelected(const std::vector<FilePath>& files,
2267 void* params) {
2268 render_view_host()->MultiFilesSelected(files);
2269}
2270
2271void TabContents::FileSelectionCanceled(void* params) {
2272 // If the user cancels choosing a file to upload we pass back an
2273 // empty vector.
2274 render_view_host()->MultiFilesSelected(std::vector<FilePath>());
2275}
2276
2277void TabContents::BeforeUnloadFiredFromRenderManager(
2278 bool proceed,
2279 bool* proceed_to_fire_unload) {
2280 if (delegate())
2281 delegate()->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
2282}
2283
2284void TabContents::UpdateRenderViewSizeForRenderManager() {
2285 // TODO(brettw) this is a hack. See TabContentsView::SizeContents.
2286 view_->SizeContents(view_->GetContainerSize());
2287}
2288
2289DOMUI* TabContents::CreateDOMUIForRenderManager(const GURL& url) {
2290 return DOMUIFactory::CreateDOMUIForURL(AsWC(this), url);
2291}
2292
2293NavigationEntry*
2294TabContents::GetLastCommittedNavigationEntryForRenderManager() {
2295 return controller_.GetLastCommittedEntry();
2296}
2297
2298bool TabContents::CreateRenderViewForRenderManager(
2299 RenderViewHost* render_view_host) {
2300 // When we're running a DOM UI, the RenderViewHost needs to be put in DOM UI
2301 // mode before CreateRenderView is called. When we're asked to create a
2302 // RenderView, that means it's for the pending entry, so we have to use the
2303 // pending DOM UI.
2304 if (render_manager_.pending_dom_ui())
2305 render_view_host->AllowDOMUIBindings();
2306
[email protected]1adff062009-06-02 18:39:552307 // Ditto for extension bindings.
2308 if (controller().pending_entry()->url().SchemeIs(chrome::kExtensionScheme))
2309 render_view_host->AllowExtensionBindings();
2310
[email protected]420ae012009-04-24 05:16:322311 RenderWidgetHostView* rwh_view = view_->CreateViewForWidget(render_view_host);
2312 if (!render_view_host->CreateRenderView())
2313 return false;
2314
2315 // Now that the RenderView has been created, we need to tell it its size.
2316 rwh_view->SetSize(view_->GetContainerSize());
2317
2318 UpdateMaxPageIDIfNecessary(render_view_host->site_instance(),
2319 render_view_host);
2320 return true;
2321}
2322
2323void TabContents::Observe(NotificationType type,
2324 const NotificationSource& source,
2325 const NotificationDetails& details) {
2326 switch (type.value) {
2327 case NotificationType::BOOKMARK_MODEL_LOADED:
2328 // BookmarkModel finished loading, fall through to update starred state.
2329 case NotificationType::URLS_STARRED: {
2330 // Somewhere, a URL has been starred.
2331 // Ignore notifications for profiles other than our current one.
2332 Profile* source_profile = Source<Profile>(source).ptr();
2333 if (!source_profile || !source_profile->IsSameProfile(profile()))
2334 return;
2335
2336 UpdateStarredStateForCurrentURL();
2337 break;
2338 }
2339 case NotificationType::PREF_CHANGED: {
2340 std::wstring* pref_name_in = Details<std::wstring>(details).ptr();
2341 DCHECK(Source<PrefService>(source).ptr() == profile()->GetPrefs());
2342 if (*pref_name_in == prefs::kAlternateErrorPagesEnabled) {
2343 UpdateAlternateErrorPageURL();
2344 } else if (*pref_name_in == prefs::kDefaultCharset ||
2345 StartsWithASCII(WideToUTF8(*pref_name_in), "webkit.webprefs.", true)
2346 ) {
2347 UpdateWebPreferences();
2348 } else {
2349 NOTREACHED() << "unexpected pref change notification" << *pref_name_in;
2350 }
2351 break;
2352 }
2353 case NotificationType::RENDER_WIDGET_HOST_DESTROYED:
2354 view_->RenderWidgetHostDestroyed(Source<RenderWidgetHost>(source).ptr());
2355 break;
2356
2357 case NotificationType::NAV_ENTRY_COMMITTED: {
2358 DCHECK(&controller_ == Source<NavigationController>(source).ptr());
2359
2360 NavigationController::LoadCommittedDetails& committed_details =
2361 *(Details<NavigationController::LoadCommittedDetails>(details).ptr());
2362 ExpireInfoBars(committed_details);
2363 break;
2364 }
2365
2366 default:
2367 NOTREACHED();
2368 }
2369}