blob: b417f3446b290fef93b0db5224049bf451386474 [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"
[email protected]fd694982009-07-03 17:32:3735#include "chrome/browser/renderer_host/resource_request_details.h"
[email protected]96d185d2009-04-24 03:28:5436#include "chrome/browser/renderer_host/web_cache_manager.h"
[email protected]bd1ad682009-05-15 22:19:1737#include "chrome/browser/tab_contents/infobar_delegate.h"
[email protected]7e383692009-06-12 19:14:5438#include "chrome/browser/tab_contents/interstitial_page.h"
[email protected]f3ec7742009-01-15 00:59:1639#include "chrome/browser/tab_contents/navigation_entry.h"
[email protected]de34a962009-06-26 23:22:4340#include "chrome/browser/tab_contents/provisional_load_details.h"
[email protected]f3ec7742009-01-15 00:59:1641#include "chrome/browser/tab_contents/tab_contents_delegate.h"
[email protected]fdd61c62009-04-22 19:22:5742#include "chrome/browser/tab_contents/tab_contents_view.h"
[email protected]58dca552009-06-17 00:35:0243#include "chrome/browser/tab_contents/thumbnail_generator.h"
[email protected]449478302009-06-09 20:04:2844#include "chrome/browser/thumbnail_store.h"
[email protected]420ae012009-04-24 05:16:3245#include "chrome/browser/search_engines/template_url_fetcher.h"
46#include "chrome/browser/search_engines/template_url_model.h"
[email protected]35f7d212009-04-29 21:19:2747#include "chrome/common/chrome_switches.h"
[email protected]bfd04a62009-02-01 18:16:5648#include "chrome/common/notification_service.h"
[email protected]ce5c4502009-05-06 16:46:1149#include "chrome/common/page_action.h"
initial.commit09911bf2008-07-26 23:55:2950#include "chrome/common/pref_names.h"
[email protected]1eb89e82008-08-15 12:27:0351#include "chrome/common/pref_service.h"
[email protected]420ae012009-04-24 05:16:3252#include "chrome/common/render_messages.h"
[email protected]1ee614862009-07-06 20:29:1853#include "chrome/common/renderer_preferences.h"
[email protected]96d185d2009-04-24 03:28:5454#include "chrome/common/url_constants.h"
[email protected]8897c382009-05-06 17:53:2655#include "grit/generated_resources.h"
[email protected]420ae012009-04-24 05:16:3256#include "grit/locale_settings.h"
57#include "net/base/mime_util.h"
58#include "net/base/net_errors.h"
[email protected]d686e812009-06-03 19:10:2959#include "net/base/net_util.h"
[email protected]420ae012009-04-24 05:16:3260#include "net/base/registry_controlled_domain.h"
[email protected]1ee614862009-07-06 20:29:1861#include "webkit/glue/password_form.h"
62#include "webkit/glue/webpreferences.h"
[email protected]3e45ba92009-02-20 21:09:0063
64#if defined(OS_WIN)
[email protected]66ba4932009-06-04 19:22:1365// For CRect
[email protected]9041a302009-06-04 19:36:3366#include <atlbase.h>
[email protected]326f7112009-06-04 19:30:2967#include <atlapp.h>
[email protected]66ba4932009-06-04 19:22:1368#include <atlmisc.h>
[email protected]3e45ba92009-02-20 21:09:0069// TODO(port): some of these headers should be ported.
[email protected]420ae012009-04-24 05:16:3270#include "chrome/browser/modal_html_dialog_delegate.h"
[email protected]2362e4f2009-05-08 00:34:0571#include "views/controls/scrollbar/native_scroll_bar.h"
[email protected]3e45ba92009-02-20 21:09:0072#endif
initial.commit09911bf2008-07-26 23:55:2973
[email protected]420ae012009-04-24 05:16:3274// Cross-Site Navigations
75//
76// If a TabContents is told to navigate to a different web site (as determined
77// by SiteInstance), it will replace its current RenderViewHost with a new
78// RenderViewHost dedicated to the new SiteInstance. This works as follows:
79//
80// - Navigate determines whether the destination is cross-site, and if so,
81// it creates a pending_render_view_host_ and moves into the PENDING
82// RendererState.
83// - The pending RVH is "suspended," so that no navigation messages are sent to
84// its renderer until the onbeforeunload JavaScript handler has a chance to
85// run in the current RVH.
86// - The pending RVH tells CrossSiteRequestManager (a thread-safe singleton)
87// that it has a pending cross-site request. ResourceDispatcherHost will
88// check for this when the response arrives.
89// - The current RVH runs its onbeforeunload handler. If it returns false, we
90// cancel all the pending logic and go back to NORMAL. Otherwise we allow
91// the pending RVH to send the navigation request to its renderer.
92// - ResourceDispatcherHost receives a ResourceRequest on the IO thread. It
93// checks CrossSiteRequestManager to see that the RVH responsible has a
94// pending cross-site request, and then installs a CrossSiteEventHandler.
95// - When RDH receives a response, the BufferedEventHandler determines whether
96// it is a download. If so, it sends a message to the new renderer causing
97// it to cancel the request, and the download proceeds in the download
98// thread. For now, we stay in a PENDING state (with a pending RVH) until
[email protected]57c6a652009-05-04 07:58:3499// the next DidNavigate event for this TabContents. This isn't ideal, but it
[email protected]420ae012009-04-24 05:16:32100// doesn't affect any functionality.
101// - After RDH receives a response and determines that it is safe and not a
102// download, it pauses the response to first run the old page's onunload
103// handler. It does this by asynchronously calling the OnCrossSiteResponse
[email protected]57c6a652009-05-04 07:58:34104// method of TabContents on the UI thread, which sends a ClosePage message
[email protected]420ae012009-04-24 05:16:32105// to the current RVH.
106// - Once the onunload handler is finished, a ClosePage_ACK message is sent to
107// the ResourceDispatcherHost, who unpauses the response. Data is then sent
108// to the pending RVH.
109// - The pending renderer sends a FrameNavigate message that invokes the
110// DidNavigate method. This replaces the current RVH with the
111// pending RVH and goes back to the NORMAL RendererState.
112
113namespace {
114
115// Amount of time we wait between when a key event is received and the renderer
116// is queried for its state and pushed to the NavigationEntry.
117const int kQueryStateDelay = 5000;
118
119const int kSyncWaitDelay = 40;
120
121// If another javascript message box is displayed within
122// kJavascriptMessageExpectedDelay of a previous javascript message box being
123// dismissed, display an option to suppress future message boxes from this
124// contents.
125const int kJavascriptMessageExpectedDelay = 1000;
126
[email protected]420ae012009-04-24 05:16:32127const char kLinkDoctorBaseURL[] =
128 "http://linkhelp.clients.google.com/tbproxy/lh/fixurl";
129
[email protected]420ae012009-04-24 05:16:32130// The list of prefs we want to observe.
131const wchar_t* kPrefsToObserve[] = {
132 prefs::kAlternateErrorPagesEnabled,
133 prefs::kWebKitJavaEnabled,
134 prefs::kWebKitJavascriptEnabled,
135 prefs::kWebKitLoadsImagesAutomatically,
136 prefs::kWebKitPluginsEnabled,
137 prefs::kWebKitUsesUniversalDetector,
138 prefs::kWebKitSerifFontFamily,
139 prefs::kWebKitSansSerifFontFamily,
140 prefs::kWebKitFixedFontFamily,
141 prefs::kWebKitDefaultFontSize,
142 prefs::kWebKitDefaultFixedFontSize,
143 prefs::kDefaultCharset
144 // kWebKitStandardFontIsSerif needs to be added
145 // if we let users pick which font to use, serif or sans-serif when
146 // no font is specified or a CSS generic family (serif or sans-serif)
147 // is not specified.
148};
149
150const int kPrefsToObserveLength = arraysize(kPrefsToObserve);
151
152// Limit on the number of suggestions to appear in the pop-up menu under an
153// text input element in a form.
154const int kMaxAutofillMenuItems = 6;
155
156// Returns true if the entry's transition type is FORM_SUBMIT.
157bool IsFormSubmit(const NavigationEntry* entry) {
158 return (PageTransition::StripQualifier(entry->transition_type()) ==
159 PageTransition::FORM_SUBMIT);
160}
161
162#if defined(OS_WIN)
163
164BOOL CALLBACK InvalidateWindow(HWND hwnd, LPARAM lparam) {
165 // Note: erase is required to properly paint some widgets borders. This can
166 // be seen with textfields.
167 InvalidateRect(hwnd, NULL, TRUE);
168 return TRUE;
169}
170#endif
171
[email protected]056de2d2009-06-26 16:41:34172void MakeNavigateParams(const NavigationEntry& entry, bool reload,
173 ViewMsg_Navigate_Params* params) {
174 params->page_id = entry.page_id();
175 params->url = entry.url();
176 params->referrer = entry.referrer();
177 params->transition = entry.transition_type();
178 params->state = entry.content_state();
179 params->reload = reload;
180 params->request_time = base::Time::Now();
181}
182
[email protected]420ae012009-04-24 05:16:32183} // namespace
184
185// -----------------------------------------------------------------------------
186
[email protected]fdd61c62009-04-22 19:22:57187// static
188int TabContents::find_request_id_counter_ = -1;
189
[email protected]420ae012009-04-24 05:16:32190class TabContents::GearsCreateShortcutCallbackFunctor {
191 public:
192 explicit GearsCreateShortcutCallbackFunctor(TabContents* contents)
193 : contents_(contents) {}
194
195 void Run(const GearsShortcutData2& shortcut_data, bool success) {
196 if (contents_)
197 contents_->OnGearsCreateShortcutDone(shortcut_data, success);
198 delete this;
199 }
200 void Cancel() {
201 contents_ = NULL;
202 }
203
204 private:
205 TabContents* contents_;
206};
207
[email protected]420ae012009-04-24 05:16:32208TabContents::TabContents(Profile* profile,
209 SiteInstance* site_instance,
210 int routing_id,
211 base::WaitableEvent* modal_dialog_event)
[email protected]b680ad22009-04-15 23:19:42212 : delegate_(NULL),
[email protected]66ba4932009-06-04 19:22:13213 ALLOW_THIS_IN_INITIALIZER_LIST(controller_(this, profile)),
214 ALLOW_THIS_IN_INITIALIZER_LIST(view_(
[email protected]d82ed61e2009-06-16 02:46:22215 TabContentsView::Create(this))),
216 ALLOW_THIS_IN_INITIALIZER_LIST(render_manager_(this, this)),
[email protected]fdd61c62009-04-22 19:22:57217 property_bag_(),
218 registrar_(),
[email protected]d82ed61e2009-06-16 02:46:22219 ALLOW_THIS_IN_INITIALIZER_LIST(printing_(*this)),
[email protected]fdd61c62009-04-22 19:22:57220 save_package_(),
221 cancelable_consumer_(),
222 autofill_manager_(),
223 password_manager_(),
224 plugin_installer_(),
[email protected]d82ed61e2009-06-16 02:46:22225 ALLOW_THIS_IN_INITIALIZER_LIST(fav_icon_helper_(this)),
[email protected]fdd61c62009-04-22 19:22:57226 select_file_dialog_(),
227 pending_install_(),
[email protected]d5f942ba2008-09-26 19:30:34228 is_loading_(false),
initial.commit09911bf2008-07-26 23:55:29229 is_crashed_(false),
[email protected]d5f942ba2008-09-26 19:30:34230 waiting_for_response_(false),
[email protected]d5f942ba2008-09-26 19:30:34231 max_page_id_(-1),
[email protected]fdd61c62009-04-22 19:22:57232 current_load_start_(),
233 load_state_(net::LOAD_STATE_IDLE),
234 load_state_host_(),
235 received_page_title_(false),
236 is_starred_(false),
237 contents_mime_type_(),
238 encoding_(),
[email protected]332af7732009-03-11 13:21:35239 blocked_popups_(NULL),
[email protected]fdd61c62009-04-22 19:22:57240 infobar_delegates_(),
[email protected]fdd61c62009-04-22 19:22:57241 find_ui_active_(false),
242 find_op_aborted_(false),
243 current_find_request_id_(find_request_id_counter_++),
244 find_text_(),
[email protected]e491f1c2009-05-22 20:28:12245 last_search_case_sensitive_(false),
246 last_search_prepopulate_text_(NULL),
247 last_search_result_(),
[email protected]fdd61c62009-04-22 19:22:57248 capturing_contents_(false),
249 is_being_destroyed_(false),
250 notify_disconnection_(false),
251 history_requests_(),
252#if defined(OS_WIN)
253 message_box_active_(CreateEvent(NULL, TRUE, FALSE, NULL)),
254#endif
255 last_javascript_message_dismissal_(),
256 suppress_javascript_messages_(false) {
[email protected]420ae012009-04-24 05:16:32257 pending_install_.page_id = 0;
258 pending_install_.callback_functor = NULL;
259
[email protected]16779842009-07-08 23:45:29260#if defined(OS_CHROMEOS)
[email protected]58dca552009-06-17 00:35:02261 // Make sure the thumbnailer is started before starting the render manager.
262 // The thumbnailer will want to listen for RVH creations, one of which will
263 // happen in RVHManager::Init.
264 ThumbnailGenerator* generator = g_browser_process->GetThumbnailGenerator();
265 if (generator)
266 generator->StartThumbnailing();
267#endif
268
[email protected]420ae012009-04-24 05:16:32269 render_manager_.Init(profile, site_instance, routing_id, modal_dialog_event);
270
271 view_->CreateView();
272
273 // Register for notifications about all interested prefs change.
274 PrefService* prefs = profile->GetPrefs();
275 if (prefs) {
276 for (int i = 0; i < kPrefsToObserveLength; ++i)
277 prefs->AddPrefObserver(kPrefsToObserve[i], this);
278 }
279
280 // Register for notifications about URL starredness changing on any profile.
281 registrar_.Add(this, NotificationType::URLS_STARRED,
282 NotificationService::AllSources());
283 registrar_.Add(this, NotificationType::BOOKMARK_MODEL_LOADED,
284 NotificationService::AllSources());
285 registrar_.Add(this, NotificationType::RENDER_WIDGET_HOST_DESTROYED,
286 NotificationService::AllSources());
287
288 // Keep a global copy of the previous search string (if any).
289 static string16 global_last_search = string16();
[email protected]e491f1c2009-05-22 20:28:12290 last_search_prepopulate_text_ = &global_last_search;
[email protected]332af7732009-03-11 13:21:35291}
initial.commit09911bf2008-07-26 23:55:29292
293TabContents::~TabContents() {
[email protected]420ae012009-04-24 05:16:32294 is_being_destroyed_ = true;
295
296 // We don't want any notifications while we're runnign our destructor.
297 registrar_.RemoveAll();
298
299 // Unregister the notifications of all observed prefs change.
300 PrefService* prefs = profile()->GetPrefs();
301 if (prefs) {
302 for (int i = 0; i < kPrefsToObserveLength; ++i)
303 prefs->RemovePrefObserver(kPrefsToObserve[i], this);
304 }
305
306 // Clean up subwindows like plugins and the find in page bar.
307 view_->OnContentsDestroy();
308
309 NotifyDisconnected();
[email protected]d82ed61e2009-06-16 02:46:22310 HungRendererDialog::HideForTabContents(this);
[email protected]420ae012009-04-24 05:16:32311
312 if (pending_install_.callback_functor)
313 pending_install_.callback_functor->Cancel();
314
315 // First cleanly close all child windows.
316 // TODO(mpcomplete): handle case if MaybeCloseChildWindows() already asked
317 // some of these to close. CloseWindows is async, so it might get called
318 // twice before it runs.
319 int size = static_cast<int>(child_windows_.size());
320 for (int i = size - 1; i >= 0; --i) {
321 ConstrainedWindow* window = child_windows_[i];
322 if (window)
323 window->CloseConstrainedWindow();
324 }
325
[email protected]66ba4932009-06-04 19:22:13326 if (blocked_popups_)
327 blocked_popups_->Destroy();
328
[email protected]420ae012009-04-24 05:16:32329 // Notify any observer that have a reference on this tab contents.
330 NotificationService::current()->Notify(
331 NotificationType::TAB_CONTENTS_DESTROYED,
332 Source<TabContents>(this),
333 NotificationService::NoDetails());
334
[email protected]1e5e74f2009-05-27 20:55:12335 // Notify any lasting InfobarDelegates that have not yet been removed that
336 // whatever infobar they were handling in this TabContents has closed,
337 // because the TabContents is going away entirely.
338 // This must happen after the TAB_CONTENTS_DESTROYED notification as the
339 // notification may trigger infobars calls that access their delegate. (and
340 // some implementations of InfoBarDelegate do delete themselves on
341 // InfoBarClosed()).
342 for (int i = 0; i < infobar_delegate_count(); ++i) {
343 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
344 delegate->InfoBarClosed();
345 }
346 infobar_delegates_.clear();
347
[email protected]420ae012009-04-24 05:16:32348 // TODO(brettw) this should be moved to the view.
349#if defined(OS_WIN)
350 // If we still have a window handle, destroy it. GetNativeView can return
351 // NULL if this contents was part of a window that closed.
352 if (GetNativeView())
353 ::DestroyWindow(GetNativeView());
354#endif
initial.commit09911bf2008-07-26 23:55:29355}
356
[email protected]d5f942ba2008-09-26 19:30:34357// static
358void TabContents::RegisterUserPrefs(PrefService* prefs) {
[email protected]420ae012009-04-24 05:16:32359 prefs->RegisterBooleanPref(prefs::kAlternateErrorPagesEnabled, true);
360
361 WebPreferences pref_defaults;
362 prefs->RegisterBooleanPref(prefs::kWebKitJavascriptEnabled,
363 pref_defaults.javascript_enabled);
364 prefs->RegisterBooleanPref(prefs::kWebKitWebSecurityEnabled,
365 pref_defaults.web_security_enabled);
366 prefs->RegisterBooleanPref(
367 prefs::kWebKitJavascriptCanOpenWindowsAutomatically, true);
368 prefs->RegisterBooleanPref(prefs::kWebKitLoadsImagesAutomatically,
369 pref_defaults.loads_images_automatically);
370 prefs->RegisterBooleanPref(prefs::kWebKitPluginsEnabled,
371 pref_defaults.plugins_enabled);
372 prefs->RegisterBooleanPref(prefs::kWebKitDomPasteEnabled,
373 pref_defaults.dom_paste_enabled);
374 prefs->RegisterBooleanPref(prefs::kWebKitShrinksStandaloneImagesToFit,
375 pref_defaults.shrinks_standalone_images_to_fit);
[email protected]0df30122009-06-03 12:13:08376 prefs->RegisterStringPref(prefs::kWebKitInspectorSettings,
377 pref_defaults.inspector_settings);
[email protected]420ae012009-04-24 05:16:32378 prefs->RegisterBooleanPref(prefs::kWebKitTextAreasAreResizable,
379 pref_defaults.text_areas_are_resizable);
380 prefs->RegisterBooleanPref(prefs::kWebKitJavaEnabled,
381 pref_defaults.java_enabled);
382
383 prefs->RegisterLocalizedStringPref(prefs::kAcceptLanguages,
384 IDS_ACCEPT_LANGUAGES);
385 prefs->RegisterLocalizedStringPref(prefs::kDefaultCharset,
386 IDS_DEFAULT_ENCODING);
387 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitStandardFontIsSerif,
388 IDS_STANDARD_FONT_IS_SERIF);
389 prefs->RegisterLocalizedStringPref(prefs::kWebKitFixedFontFamily,
390 IDS_FIXED_FONT_FAMILY);
391 prefs->RegisterLocalizedStringPref(prefs::kWebKitSerifFontFamily,
392 IDS_SERIF_FONT_FAMILY);
393 prefs->RegisterLocalizedStringPref(prefs::kWebKitSansSerifFontFamily,
394 IDS_SANS_SERIF_FONT_FAMILY);
395 prefs->RegisterLocalizedStringPref(prefs::kWebKitCursiveFontFamily,
396 IDS_CURSIVE_FONT_FAMILY);
397 prefs->RegisterLocalizedStringPref(prefs::kWebKitFantasyFontFamily,
398 IDS_FANTASY_FONT_FAMILY);
399 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFontSize,
400 IDS_DEFAULT_FONT_SIZE);
401 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFixedFontSize,
402 IDS_DEFAULT_FIXED_FONT_SIZE);
403 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumFontSize,
404 IDS_MINIMUM_FONT_SIZE);
405 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumLogicalFontSize,
406 IDS_MINIMUM_LOGICAL_FONT_SIZE);
407 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitUsesUniversalDetector,
408 IDS_USES_UNIVERSAL_DETECTOR);
409 prefs->RegisterLocalizedStringPref(prefs::kStaticEncodings,
410 IDS_STATIC_ENCODING_LIST);
initial.commit09911bf2008-07-26 23:55:29411}
412
[email protected]13367f72009-07-08 16:39:02413// Returns true if contains content rendered by an extension.
414bool TabContents::HostsExtension() const {
415 return GetURL().SchemeIs(chrome::kExtensionScheme);
[email protected]d5f942ba2008-09-26 19:30:34416}
417
[email protected]6e95706d2009-04-23 22:55:01418AutofillManager* TabContents::GetAutofillManager() {
419 if (autofill_manager_.get() == NULL)
420 autofill_manager_.reset(new AutofillManager(this));
421 return autofill_manager_.get();
422}
423
424PasswordManager* TabContents::GetPasswordManager() {
425 if (password_manager_.get() == NULL)
426 password_manager_.reset(new PasswordManager(this));
427 return password_manager_.get();
428}
429
430PluginInstaller* TabContents::GetPluginInstaller() {
431 if (plugin_installer_.get() == NULL)
432 plugin_installer_.reset(new PluginInstaller(this));
433 return plugin_installer_.get();
434}
435
[email protected]d5f942ba2008-09-26 19:30:34436const GURL& TabContents::GetURL() const {
437 // We may not have a navigation entry yet
[email protected]ce3fa3c2009-04-20 19:55:57438 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34439 return entry ? entry->display_url() : GURL::EmptyGURL();
440}
441
[email protected]96d185d2009-04-24 03:28:54442const string16& TabContents::GetTitle() const {
[email protected]4c6092c5b2009-06-06 00:23:55443 // Transient entries take precedence. They are used for interstitial pages
444 // that are shown on top of existing pages.
445 NavigationEntry* entry = controller_.GetTransientEntry();
446 if (entry)
447 return entry->GetTitleForDisplay(&controller_);
448
[email protected]96d185d2009-04-24 03:28:54449 DOMUI* our_dom_ui = render_manager_.pending_dom_ui() ?
450 render_manager_.pending_dom_ui() : render_manager_.dom_ui();
451 if (our_dom_ui) {
452 // Don't override the title in view source mode.
[email protected]4c6092c5b2009-06-06 00:23:55453 entry = controller_.GetActiveEntry();
[email protected]96d185d2009-04-24 03:28:54454 if (!(entry && entry->IsViewSourceMode())) {
455 // Give the DOM UI the chance to override our title.
456 const string16& title = our_dom_ui->overridden_title();
457 if (!title.empty())
458 return title;
459 }
460 }
461
462 // We use the title for the last committed entry rather than a pending
463 // navigation entry. For example, when the user types in a URL, we want to
464 // keep the old page's title until the new load has committed and we get a new
465 // title.
[email protected]96d185d2009-04-24 03:28:54466 entry = controller_.GetLastCommittedEntry();
467 if (entry)
468 return entry->GetTitleForDisplay(&controller_);
469 else if (controller_.LoadingURLLazily())
470 return controller_.GetLazyTitle();
471 return EmptyString16();
472}
473
[email protected]d5f942ba2008-09-26 19:30:34474int32 TabContents::GetMaxPageID() {
475 if (GetSiteInstance())
476 return GetSiteInstance()->max_page_id();
477 else
478 return max_page_id_;
479}
480
481void TabContents::UpdateMaxPageID(int32 page_id) {
482 // Ensure both the SiteInstance and RenderProcessHost update their max page
[email protected]57c6a652009-05-04 07:58:34483 // IDs in sync. Only TabContents will also have site instances, except during
[email protected]d5f942ba2008-09-26 19:30:34484 // testing.
485 if (GetSiteInstance())
486 GetSiteInstance()->UpdateMaxPageID(page_id);
[email protected]57c6a652009-05-04 07:58:34487 process()->UpdateMaxPageID(page_id);
[email protected]d5f942ba2008-09-26 19:30:34488}
489
[email protected]96d185d2009-04-24 03:28:54490SiteInstance* TabContents::GetSiteInstance() const {
491 return render_manager_.current_host()->site_instance();
492}
493
[email protected]d5f942ba2008-09-26 19:30:34494const std::wstring TabContents::GetDefaultTitle() const {
495 return l10n_util::GetString(IDS_DEFAULT_TAB_TITLE);
496}
497
[email protected]96d185d2009-04-24 03:28:54498bool TabContents::ShouldDisplayURL() {
499 // Don't hide the url in view source mode.
500 NavigationEntry* entry = controller_.GetActiveEntry();
501 if (entry && entry->IsViewSourceMode())
502 return true;
[email protected]83e3895b2009-06-11 00:07:16503
[email protected]96d185d2009-04-24 03:28:54504 DOMUI* dom_ui = GetDOMUIForCurrentState();
505 if (dom_ui)
506 return !dom_ui->should_hide_url();
507 return true;
508}
509
[email protected]d5f942ba2008-09-26 19:30:34510SkBitmap TabContents::GetFavIcon() const {
511 // Like GetTitle(), we also want to use the favicon for the last committed
512 // entry rather than a pending navigation entry.
[email protected]ce3fa3c2009-04-20 19:55:57513 NavigationEntry* entry = controller_.GetTransientEntry();
[email protected]cbab76d2008-10-13 22:42:47514 if (entry)
515 return entry->favicon().bitmap();
516
[email protected]ce3fa3c2009-04-20 19:55:57517 entry = controller_.GetLastCommittedEntry();
[email protected]d5f942ba2008-09-26 19:30:34518 if (entry)
519 return entry->favicon().bitmap();
[email protected]ce3fa3c2009-04-20 19:55:57520 else if (controller_.LoadingURLLazily())
521 return controller_.GetLazyFavIcon();
[email protected]d5f942ba2008-09-26 19:30:34522 return SkBitmap();
523}
524
[email protected]96d185d2009-04-24 03:28:54525bool TabContents::ShouldDisplayFavIcon() {
526 // Always display a throbber during pending loads.
527 if (controller_.GetLastCommittedEntry() && controller_.pending_entry())
528 return true;
529
530 DOMUI* dom_ui = GetDOMUIForCurrentState();
531 if (dom_ui)
532 return !dom_ui->hide_favicon();
533 return true;
534}
535
[email protected]96d185d2009-04-24 03:28:54536std::wstring TabContents::GetStatusText() const {
537 if (!is_loading() || load_state_ == net::LOAD_STATE_IDLE)
538 return std::wstring();
539
540 switch (load_state_) {
541 case net::LOAD_STATE_WAITING_FOR_CACHE:
542 return l10n_util::GetString(IDS_LOAD_STATE_WAITING_FOR_CACHE);
543 case net::LOAD_STATE_RESOLVING_PROXY_FOR_URL:
544 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_PROXY_FOR_URL);
545 case net::LOAD_STATE_RESOLVING_HOST:
546 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_HOST);
547 case net::LOAD_STATE_CONNECTING:
548 return l10n_util::GetString(IDS_LOAD_STATE_CONNECTING);
549 case net::LOAD_STATE_SENDING_REQUEST:
550 return l10n_util::GetString(IDS_LOAD_STATE_SENDING_REQUEST);
551 case net::LOAD_STATE_WAITING_FOR_RESPONSE:
552 return l10n_util::GetStringF(IDS_LOAD_STATE_WAITING_FOR_RESPONSE,
553 load_state_host_);
554 // Ignore net::LOAD_STATE_READING_RESPONSE and net::LOAD_STATE_IDLE
555 case net::LOAD_STATE_IDLE:
556 case net::LOAD_STATE_READING_RESPONSE:
557 break;
558 }
559
560 return std::wstring();
561}
562
[email protected]d5f942ba2008-09-26 19:30:34563void TabContents::SetIsCrashed(bool state) {
564 if (state == is_crashed_)
565 return;
566
567 is_crashed_ = state;
[email protected]c9cd2222009-05-06 05:16:50568 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]d5f942ba2008-09-26 19:30:34569}
570
[email protected]f9b1a7b2009-06-22 17:26:38571void TabContents::SetPageActionEnabled(const PageAction* page_action,
[email protected]d7eaf572009-07-01 21:57:00572 bool enable,
573 const std::string& title,
574 int icon_id) {
[email protected]ce5c4502009-05-06 16:46:11575 DCHECK(page_action);
576
[email protected]d7eaf572009-07-01 21:57:00577 if (!enable &&
578 enabled_page_actions_.end() == enabled_page_actions_.find(page_action)) {
579 return; // Don't need to disable twice.
580 }
[email protected]ce5c4502009-05-06 16:46:11581
[email protected]d7eaf572009-07-01 21:57:00582 if (enable) {
583 enabled_page_actions_[page_action].reset(
584 new PageActionState(title, icon_id));
585 } else {
[email protected]f9b1a7b2009-06-22 17:26:38586 enabled_page_actions_.erase(page_action);
[email protected]d7eaf572009-07-01 21:57:00587 }
[email protected]ce5c4502009-05-06 16:46:11588}
589
[email protected]d7eaf572009-07-01 21:57:00590const PageActionState* TabContents::GetPageActionState(
591 const PageAction* page_action) {
592 if (enabled_page_actions_.end() == enabled_page_actions_.find(page_action))
593 return NULL;
[email protected]ce5c4502009-05-06 16:46:11594
[email protected]d7eaf572009-07-01 21:57:00595 return enabled_page_actions_[page_action].get();
596}
[email protected]ce5c4502009-05-06 16:46:11597
[email protected]d5f942ba2008-09-26 19:30:34598void TabContents::NotifyNavigationStateChanged(unsigned changed_flags) {
599 if (delegate_)
600 delegate_->NavigationStateChanged(this, changed_flags);
601}
602
[email protected]96d185d2009-04-24 03:28:54603void TabContents::DidBecomeSelected() {
604 controller_.SetActive(true);
605
606 if (render_widget_host_view())
607 render_widget_host_view()->DidBecomeSelected();
608
609 // If pid() is -1, that means the RenderProcessHost still hasn't been
610 // initialized. It'll register with CacheManagerHost when it is.
611 if (process()->pid() != -1)
612 WebCacheManager::GetInstance()->ObserveActivity(process()->pid());
613}
614
615void TabContents::WasHidden() {
616 if (!capturing_contents()) {
617 // |render_view_host()| can be NULL if the user middle clicks a link to open
618 // a tab in then background, then closes the tab before selecting it. This
619 // is because closing the tab calls TabContents::Destroy(), which removes
620 // the |render_view_host()|; then when we actually destroy the window,
621 // OnWindowPosChanged() notices and calls HideContents() (which calls us).
622 if (render_widget_host_view())
623 render_widget_host_view()->WasHidden();
[email protected]96d185d2009-04-24 03:28:54624 }
625
626 NotificationService::current()->Notify(
627 NotificationType::TAB_CONTENTS_HIDDEN,
628 Source<TabContents>(this),
629 NotificationService::NoDetails());
630}
631
[email protected]d5f942ba2008-09-26 19:30:34632void TabContents::Activate() {
633 if (delegate_)
634 delegate_->ActivateContents(this);
635}
636
[email protected]96d185d2009-04-24 03:28:54637void TabContents::ShowContents() {
638 if (render_widget_host_view())
639 render_widget_host_view()->DidBecomeSelected();
[email protected]96d185d2009-04-24 03:28:54640}
641
642void TabContents::HideContents() {
643 // TODO(pkasting): http://b/1239839 Right now we purposefully don't call
644 // our superclass HideContents(), because some callers want to be very picky
645 // about the order in which these get called. In addition to making the code
646 // here practically impossible to understand, this also means we end up
647 // calling TabContents::WasHidden() twice if callers call both versions of
[email protected]57c6a652009-05-04 07:58:34648 // HideContents() on a TabContents.
[email protected]96d185d2009-04-24 03:28:54649 WasHidden();
650}
651
[email protected]c0588052008-10-27 23:01:50652void TabContents::OpenURL(const GURL& url, const GURL& referrer,
[email protected]d5f942ba2008-09-26 19:30:34653 WindowOpenDisposition disposition,
654 PageTransition::Type transition) {
655 if (delegate_)
[email protected]c0588052008-10-27 23:01:50656 delegate_->OpenURLFromTab(this, url, referrer, disposition, transition);
[email protected]d5f942ba2008-09-26 19:30:34657}
658
659bool TabContents::NavigateToPendingEntry(bool reload) {
[email protected]96d185d2009-04-24 03:28:54660 const NavigationEntry& entry = *controller_.pending_entry();
661
662 RenderViewHost* dest_render_view_host = render_manager_.Navigate(entry);
663 if (!dest_render_view_host)
664 return false; // Unable to create the desired render view host.
665
666 // Tell DevTools agent that it is attached prior to the navigation.
[email protected]d9f9b792009-06-24 13:17:12667 DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
[email protected]7e8e6b62009-05-08 11:28:32668 if (devtools_manager) { // NULL in unit tests.
[email protected]684b4ba22009-05-07 06:27:41669 devtools_manager->OnNavigatingToPendingEntry(
670 render_view_host(),
671 dest_render_view_host,
672 controller_.pending_entry()->url());
[email protected]7e8e6b62009-05-08 11:28:32673 }
[email protected]96d185d2009-04-24 03:28:54674
675 // Used for page load time metrics.
676 current_load_start_ = base::TimeTicks::Now();
677
678 // Navigate in the desired RenderViewHost.
[email protected]056de2d2009-06-26 16:41:34679 ViewMsg_Navigate_Params navigate_params;
680 MakeNavigateParams(entry, reload, &navigate_params);
681 dest_render_view_host->Navigate(navigate_params);
[email protected]96d185d2009-04-24 03:28:54682
683 if (entry.page_id() == -1) {
684 // HACK!! This code suppresses javascript: URLs from being added to
685 // session history, which is what we want to do for javascript: URLs that
686 // do not generate content. What we really need is a message from the
687 // renderer telling us that a new page was not created. The same message
688 // could be used for mailto: URLs and the like.
689 if (entry.url().SchemeIs(chrome::kJavaScriptScheme))
690 return false;
691 }
692
693 // Clear any provisional password saves - this stops password infobars
694 // showing up on pages the user navigates to while the right page is
695 // loading.
696 GetPasswordManager()->ClearProvisionalSave();
697
698 if (reload && !profile()->IsOffTheRecord()) {
699 HistoryService* history =
700 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
701 if (history)
702 history->SetFavIconOutOfDateForPage(entry.url());
703 }
704
[email protected]d5f942ba2008-09-26 19:30:34705 return true;
706}
707
[email protected]96d185d2009-04-24 03:28:54708void TabContents::Stop() {
709 render_manager_.Stop();
710 printing_.Stop();
711}
712
713void TabContents::Cut() {
714 render_view_host()->Cut();
715}
716
717void TabContents::Copy() {
718 render_view_host()->Copy();
719}
720
721void TabContents::Paste() {
722 render_view_host()->Paste();
723}
724
725void TabContents::DisassociateFromPopupCount() {
726 render_view_host()->DisassociateFromPopupCount();
727}
728
729TabContents* TabContents::Clone() {
730 // We create a new SiteInstance so that the new tab won't share processes
731 // with the old one. This can be changed in the future if we need it to share
732 // processes for some reason.
[email protected]420ae012009-04-24 05:16:32733 TabContents* tc = new TabContents(profile(),
[email protected]96d185d2009-04-24 03:28:54734 SiteInstance::CreateSiteInstance(profile()),
735 MSG_ROUTING_NONE, NULL);
736 tc->controller().CopyStateFrom(controller_);
737 return tc;
738}
739
[email protected]420ae012009-04-24 05:16:32740void TabContents::CreateShortcut() {
741 NavigationEntry* entry = controller_.GetLastCommittedEntry();
742 if (!entry)
743 return;
744
745 // We only allow one pending install request. By resetting the page id we
746 // effectively cancel the pending install request.
747 pending_install_.page_id = entry->page_id();
748 pending_install_.icon = GetFavIcon();
749 pending_install_.title = UTF16ToWideHack(GetTitle());
750 pending_install_.url = GetURL();
751 if (pending_install_.callback_functor) {
752 pending_install_.callback_functor->Cancel();
753 pending_install_.callback_functor = NULL;
754 }
755 DCHECK(!pending_install_.icon.isNull()) << "Menu item should be disabled.";
756 if (pending_install_.title.empty())
757 pending_install_.title = UTF8ToWide(GetURL().spec());
758
759 // Request the application info. When done OnDidGetApplicationInfo is invoked
760 // and we'll create the shortcut.
761 render_view_host()->GetApplicationInfo(pending_install_.page_id);
762}
763
[email protected]e8382172009-06-19 22:16:28764#if defined(OS_WIN) || defined(OS_LINUX)
initial.commit09911bf2008-07-26 23:55:29765ConstrainedWindow* TabContents::CreateConstrainedDialog(
[email protected]e8382172009-06-19 22:16:28766 ConstrainedWindowDelegate* delegate) {
initial.commit09911bf2008-07-26 23:55:29767 ConstrainedWindow* window =
[email protected]e8382172009-06-19 22:16:28768 ConstrainedWindow::CreateConstrainedDialog(this, delegate);
initial.commit09911bf2008-07-26 23:55:29769 child_windows_.push_back(window);
770 return window;
771}
[email protected]f3332e12009-03-23 15:28:57772#endif
initial.commit09911bf2008-07-26 23:55:29773
774void TabContents::AddNewContents(TabContents* new_contents,
775 WindowOpenDisposition disposition,
776 const gfx::Rect& initial_pos,
[email protected]c88a70fe2009-05-05 20:00:22777 bool user_gesture,
778 const GURL& creator_url) {
initial.commit09911bf2008-07-26 23:55:29779 if (!delegate_)
780 return;
781
[email protected]35f7d212009-04-29 21:19:27782 if ((disposition == NEW_POPUP) && !user_gesture &&
783 !CommandLine::ForCurrentProcess()->HasSwitch(
784 switches::kDisablePopupBlocking)) {
[email protected]2c4410d2009-05-06 23:46:22785 // Unrequested popups from normal pages are constrained unless they're in
[email protected]b6c874582009-05-08 19:38:31786 // the whitelist. The popup owner will handle checking this.
787 delegate_->GetConstrainingContents(this)->AddPopup(new_contents,
788 initial_pos,
789 creator_url.is_valid() ? creator_url.host() : std::string());
790 } else {
[email protected]0aa55312008-10-17 21:53:08791 new_contents->DisassociateFromPopupCount();
initial.commit09911bf2008-07-26 23:55:29792 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
793 user_gesture);
794 }
[email protected]b6c874582009-05-08 19:38:31795 PopupNotificationVisibilityChanged(ShowingBlockedPopupNotification());
initial.commit09911bf2008-07-26 23:55:29796}
797
initial.commit09911bf2008-07-26 23:55:29798void TabContents::CloseAllSuppressedPopups() {
[email protected]d6598c052008-11-05 19:03:25799 if (blocked_popups_)
[email protected]2c4410d2009-05-06 23:46:22800 blocked_popups_->CloseAll();
initial.commit09911bf2008-07-26 23:55:29801}
802
[email protected]96d185d2009-04-24 03:28:54803void TabContents::PopupNotificationVisibilityChanged(bool visible) {
804 render_view_host()->PopupNotificationVisibilityChanged(visible);
805}
806
807gfx::NativeView TabContents::GetContentNativeView() {
808 return view_->GetContentNativeView();
809}
810
811gfx::NativeView TabContents::GetNativeView() const {
812 return view_->GetNativeView();
813}
814
815void TabContents::GetContainerBounds(gfx::Rect *out) const {
816 view_->GetContainerBounds(out);
817}
818
819void TabContents::Focus() {
820 view_->Focus();
821}
822
[email protected]90daadb42009-06-08 21:27:28823void TabContents::FocusThroughTabTraversal(bool reverse) {
[email protected]7e383692009-06-12 19:14:54824 if (showing_interstitial_page()) {
825 render_manager_.interstitial_page()->FocusThroughTabTraversal(reverse);
826 return;
827 }
[email protected]96d185d2009-04-24 03:28:54828 render_view_host()->SetInitialFocus(reverse);
829}
830
831bool TabContents::FocusLocationBarByDefault() {
832 DOMUI* dom_ui = GetDOMUIForCurrentState();
833 if (dom_ui)
834 return dom_ui->focus_location_bar_by_default();
[email protected]3e3f0eb2009-06-22 18:33:43835 NavigationEntry* entry = controller_.GetActiveEntry();
836 if (entry && entry->url() == GURL("about:blank"))
837 return true;
[email protected]96d185d2009-04-24 03:28:54838 return false;
839}
840
[email protected]616ed5a2008-11-21 22:27:24841void TabContents::AddInfoBar(InfoBarDelegate* delegate) {
842 // Look through the existing InfoBarDelegates we have for a match. If we've
843 // already got one that matches, then we don't add the new one.
[email protected]f86a07022008-11-25 01:06:05844 for (int i = 0; i < infobar_delegate_count(); ++i) {
[email protected]616ed5a2008-11-21 22:27:24845 if (GetInfoBarDelegateAt(i)->EqualsDelegate(delegate))
846 return;
847 }
848
849 infobar_delegates_.push_back(delegate);
[email protected]bfd04a62009-02-01 18:16:56850 NotificationService::current()->Notify(
851 NotificationType::TAB_CONTENTS_INFOBAR_ADDED,
852 Source<TabContents>(this),
853 Details<InfoBarDelegate>(delegate));
[email protected]616ed5a2008-11-21 22:27:24854
855 // Add ourselves as an observer for navigations the first time a delegate is
856 // added. We use this notification to expire InfoBars that need to expire on
857 // page transitions.
858 if (infobar_delegates_.size() == 1) {
[email protected]bfd04a62009-02-01 18:16:56859 registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57860 Source<NavigationController>(&controller_));
[email protected]616ed5a2008-11-21 22:27:24861 }
862}
863
864void TabContents::RemoveInfoBar(InfoBarDelegate* delegate) {
865 std::vector<InfoBarDelegate*>::iterator it =
866 find(infobar_delegates_.begin(), infobar_delegates_.end(), delegate);
867 if (it != infobar_delegates_.end()) {
868 InfoBarDelegate* delegate = *it;
[email protected]bfd04a62009-02-01 18:16:56869 NotificationService::current()->Notify(
870 NotificationType::TAB_CONTENTS_INFOBAR_REMOVED,
871 Source<TabContents>(this),
872 Details<InfoBarDelegate>(delegate));
[email protected]f86a07022008-11-25 01:06:05873 infobar_delegates_.erase(it);
[email protected]616ed5a2008-11-21 22:27:24874
[email protected]6a02963e2009-01-06 16:58:03875 // Remove ourselves as an observer if we are tracking no more InfoBars.
876 if (infobar_delegates_.empty()) {
[email protected]bfd04a62009-02-01 18:16:56877 registrar_.Remove(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57878 Source<NavigationController>(&controller_));
[email protected]6a02963e2009-01-06 16:58:03879 }
[email protected]616ed5a2008-11-21 22:27:24880 }
881}
[email protected]3edd9522009-03-04 22:19:41882
[email protected]96d185d2009-04-24 03:28:54883bool TabContents::IsBookmarkBarAlwaysVisible() {
884 // See GetDOMUIForCurrentState() comment for more info. This case is very
885 // similar, but for non-first loads, we want to use the committed entry. This
886 // is so the bookmarks bar disappears at the same time the page does.
887 if (controller_.GetLastCommittedEntry()) {
888 // Not the first load, always use the committed DOM UI.
889 if (render_manager_.dom_ui())
890 return render_manager_.dom_ui()->force_bookmark_bar_visible();
891 return false; // Default.
892 }
893
894 // When it's the first load, we know either the pending one or the committed
895 // one will have the DOM UI in it (see GetDOMUIForCurrentState), and only one
896 // of them will be valid, so we can just check both.
897 if (render_manager_.pending_dom_ui())
898 return render_manager_.pending_dom_ui()->force_bookmark_bar_visible();
899 if (render_manager_.dom_ui())
900 return render_manager_.dom_ui()->force_bookmark_bar_visible();
901 return false; // Default.
902}
903
[email protected]3edd9522009-03-04 22:19:41904void TabContents::ToolbarSizeChanged(bool is_animating) {
905 TabContentsDelegate* d = delegate();
906 if (d)
907 d->ToolbarSizeChanged(this, is_animating);
908}
[email protected]616ed5a2008-11-21 22:27:24909
[email protected]d5f942ba2008-09-26 19:30:34910void TabContents::OnStartDownload(DownloadItem* download) {
911 DCHECK(download);
[email protected]d5f942ba2008-09-26 19:30:34912
913 // Download in a constrained popup is shown in the tab that opened it.
[email protected]b6c874582009-05-08 19:38:31914 TabContents* tab_contents = delegate()->GetConstrainingContents(this);
[email protected]d5f942ba2008-09-26 19:30:34915
[email protected]59560e0b2009-06-04 03:30:22916 if (tab_contents && tab_contents->delegate())
917 tab_contents->delegate()->OnStartDownload(download);
[email protected]3edd9522009-03-04 22:19:41918}
[email protected]3edd9522009-03-04 22:19:41919
[email protected]d5f942ba2008-09-26 19:30:34920void TabContents::WillClose(ConstrainedWindow* window) {
921 ConstrainedWindowList::iterator it =
922 find(child_windows_.begin(), child_windows_.end(), window);
923 if (it != child_windows_.end())
924 child_windows_.erase(it);
[email protected]66ba4932009-06-04 19:22:13925}
[email protected]d5f942ba2008-09-26 19:30:34926
[email protected]66ba4932009-06-04 19:22:13927void TabContents::WillCloseBlockedPopupContainer(
928 BlockedPopupContainer* container) {
929 DCHECK(blocked_popups_ == container);
930 blocked_popups_ = NULL;
[email protected]d5f942ba2008-09-26 19:30:34931}
932
[email protected]d5f942ba2008-09-26 19:30:34933void TabContents::DidMoveOrResize(ConstrainedWindow* window) {
[email protected]332af7732009-03-11 13:21:35934#if defined(OS_WIN)
[email protected]92edc472009-02-10 20:32:06935 UpdateWindow(GetNativeView());
[email protected]332af7732009-03-11 13:21:35936#endif
[email protected]d5f942ba2008-09-26 19:30:34937}
938
[email protected]e491f1c2009-05-22 20:28:12939void TabContents::StartFinding(string16 find_text,
940 bool forward_direction,
941 bool case_sensitive) {
[email protected]6e95706d2009-04-23 22:55:01942 // If find_text is empty, it means FindNext was pressed with a keyboard
943 // shortcut so unless we have something to search for we return early.
[email protected]e491f1c2009-05-22 20:28:12944 if (find_text.empty() && find_text_.empty()) {
945 if (last_search_prepopulate_text_->empty())
946 return;
947 // Try whatever we searched for last in any tab.
948 find_text = *last_search_prepopulate_text_;
949 }
[email protected]6e95706d2009-04-23 22:55:01950
951 // This is a FindNext operation if we are searching for the same text again,
952 // or if the passed in search text is empty (FindNext keyboard shortcut). The
953 // exception to this is if the Find was aborted (then we don't want FindNext
954 // because the highlighting has been cleared and we need it to reappear). We
955 // therefore treat FindNext after an aborted Find operation as a full fledged
956 // Find.
957 bool find_next = (find_text_ == find_text || find_text.empty()) &&
[email protected]e491f1c2009-05-22 20:28:12958 (last_search_case_sensitive_ == case_sensitive) &&
[email protected]6e95706d2009-04-23 22:55:01959 !find_op_aborted_;
960 if (!find_next)
961 current_find_request_id_ = find_request_id_counter_++;
962
963 if (!find_text.empty())
964 find_text_ = find_text;
[email protected]e491f1c2009-05-22 20:28:12965 last_search_case_sensitive_ = case_sensitive;
[email protected]6e95706d2009-04-23 22:55:01966
967 find_op_aborted_ = false;
968
969 // Keep track of what the last search was across the tabs.
[email protected]e491f1c2009-05-22 20:28:12970 *last_search_prepopulate_text_ = find_text;
[email protected]6e95706d2009-04-23 22:55:01971
972 render_view_host()->StartFinding(current_find_request_id_,
973 find_text_,
974 forward_direction,
[email protected]e491f1c2009-05-22 20:28:12975 case_sensitive,
[email protected]6e95706d2009-04-23 22:55:01976 find_next);
977}
978
979void TabContents::StopFinding(bool clear_selection) {
[email protected]2d2dffc2009-06-09 21:41:00980 // When |clear_selection| is true, it means the find string has been cleared
981 // by the user, but the UI has not been dismissed.
982 if (!clear_selection)
983 find_ui_active_ = false;
[email protected]6e95706d2009-04-23 22:55:01984 find_op_aborted_ = true;
[email protected]e491f1c2009-05-22 20:28:12985 last_search_result_ = FindNotificationDetails();
[email protected]6e95706d2009-04-23 22:55:01986 render_view_host()->StopFinding(clear_selection);
987}
988
[email protected]420ae012009-04-24 05:16:32989void TabContents::OnJavaScriptMessageBoxClosed(IPC::Message* reply_msg,
990 bool success,
991 const std::wstring& prompt) {
992 last_javascript_message_dismissal_ = base::TimeTicks::Now();
993 render_manager_.OnJavaScriptMessageBoxClosed(reply_msg, success, prompt);
994}
995
[email protected]571e31152009-05-15 19:34:02996void TabContents::OnJavaScriptMessageBoxWindowDestroyed() {
997 render_manager_.OnJavaScriptMessageBoxWindowDestroyed();
998}
999
[email protected]420ae012009-04-24 05:16:321000void TabContents::OnSavePage() {
1001 // If we can not save the page, try to download it.
1002 if (!SavePackage::IsSavableContents(contents_mime_type())) {
1003 DownloadManager* dlm = profile()->GetDownloadManager();
1004 const GURL& current_page_url = GetURL();
1005 if (dlm && current_page_url.is_valid())
[email protected]d82ed61e2009-06-16 02:46:221006 dlm->DownloadUrl(current_page_url, GURL(), "", this);
[email protected]420ae012009-04-24 05:16:321007 return;
1008 }
1009
1010 Stop();
1011
1012 // Create the save package and possibly prompt the user for the name to save
1013 // the page as. The user prompt is an asynchronous operation that runs on
1014 // another thread.
[email protected]d82ed61e2009-06-16 02:46:221015 save_package_ = new SavePackage(this);
[email protected]420ae012009-04-24 05:16:321016 save_package_->GetSaveInfo();
1017}
1018
1019// Used in automated testing to bypass prompting the user for file names.
1020// Instead, the names and paths are hard coded rather than running them through
1021// file name sanitation and extension / mime checking.
1022void TabContents::SavePage(const std::wstring& main_file,
1023 const std::wstring& dir_path,
1024 SavePackage::SavePackageType save_type) {
1025 // Stop the page from navigating.
1026 Stop();
1027
[email protected]d82ed61e2009-06-16 02:46:221028 save_package_ = new SavePackage(this, save_type,
[email protected]420ae012009-04-24 05:16:321029 FilePath::FromWStringHack(main_file),
1030 FilePath::FromWStringHack(dir_path));
1031 save_package_->Init();
1032}
1033
1034void TabContents::PrintPreview() {
1035 // We don't show the print preview yet, only the print dialog.
1036 PrintNow();
1037}
1038
1039bool TabContents::PrintNow() {
1040 // We can't print interstitial page for now.
1041 if (showing_interstitial_page())
1042 return false;
1043
1044 return render_view_host()->PrintPages();
1045}
1046
[email protected]82270452009-06-19 15:58:011047void TabContents::PrintingDone(int document_cookie, bool success) {
1048 render_view_host()->PrintingDone(document_cookie, success);
1049}
1050
[email protected]420ae012009-04-24 05:16:321051bool TabContents::IsActiveEntry(int32 page_id) {
1052 NavigationEntry* active_entry = controller_.GetActiveEntry();
1053 return (active_entry != NULL &&
1054 active_entry->site_instance() == GetSiteInstance() &&
1055 active_entry->page_id() == page_id);
1056}
1057
[email protected]96d185d2009-04-24 03:28:541058// Notifies the RenderWidgetHost instance about the fact that the page is
1059// loading, or done loading and calls the base implementation.
1060void TabContents::SetIsLoading(bool is_loading,
1061 LoadNotificationDetails* details) {
1062 if (is_loading == is_loading_)
1063 return;
1064
1065 if (!is_loading) {
1066 load_state_ = net::LOAD_STATE_IDLE;
1067 load_state_host_.clear();
1068 }
1069
1070 render_manager_.SetIsLoading(is_loading);
1071
1072 is_loading_ = is_loading;
1073 waiting_for_response_ = is_loading;
1074
1075 if (delegate_)
1076 delegate_->LoadingStateChanged(this);
[email protected]329581b2009-04-28 06:52:351077 NotifyNavigationStateChanged(INVALIDATE_LOAD);
[email protected]96d185d2009-04-24 03:28:541078
1079 NotificationType type = is_loading ? NotificationType::LOAD_START :
1080 NotificationType::LOAD_STOP;
[email protected]ce5c4502009-05-06 16:46:111081 NotificationDetails det = NotificationService::NoDetails();
[email protected]96d185d2009-04-24 03:28:541082 if (details)
1083 det = Details<LoadNotificationDetails>(details);
1084 NotificationService::current()->Notify(type,
1085 Source<NavigationController>(&controller_),
1086 det);
1087}
1088
[email protected]2c4410d2009-05-06 23:46:221089void TabContents::CreateBlockedPopupContainerIfNecessary() {
1090 if (blocked_popups_)
1091 return;
1092
[email protected]4d4c0b92009-06-08 23:13:011093 blocked_popups_ = BlockedPopupContainer::Create(this, profile());
[email protected]2c4410d2009-05-06 23:46:221094}
1095
[email protected]b6c874582009-05-08 19:38:311096void TabContents::AddPopup(TabContents* new_contents,
1097 const gfx::Rect& initial_pos,
1098 const std::string& host) {
[email protected]2c4410d2009-05-06 23:46:221099 CreateBlockedPopupContainerIfNecessary();
1100 blocked_popups_->AddTabContents(new_contents, initial_pos, host);
[email protected]2c4410d2009-05-06 23:46:221101}
1102
[email protected]e69bce3dd2009-04-20 22:05:121103// TODO(brettw) This should be on the TabContentsView.
[email protected]66ba4932009-06-04 19:22:131104void TabContents::RepositionSupressedPopupsToFit() {
[email protected]d6598c052008-11-05 19:03:251105 if (blocked_popups_)
[email protected]4d4c0b92009-06-08 23:13:011106 blocked_popups_->RepositionBlockedPopupContainer();
[email protected]d5f942ba2008-09-26 19:30:341107}
1108
[email protected]b9681312008-11-07 00:08:261109bool TabContents::ShowingBlockedPopupNotification() const {
1110 return blocked_popups_ != NULL &&
[email protected]2c4410d2009-05-06 23:46:221111 blocked_popups_->GetBlockedPopupCount() != 0;
[email protected]b9681312008-11-07 00:08:261112}
[email protected]616ed5a2008-11-21 22:27:241113
1114namespace {
1115bool TransitionIsReload(PageTransition::Type transition) {
1116 return PageTransition::StripQualifier(transition) == PageTransition::RELOAD;
1117}
1118}
1119
1120void TabContents::ExpireInfoBars(
1121 const NavigationController::LoadCommittedDetails& details) {
1122 // Only hide InfoBars when the user has done something that makes the main
1123 // frame load. We don't want various automatic or subframe navigations making
1124 // it disappear.
1125 if (!details.is_user_initiated_main_frame_load())
1126 return;
1127
[email protected]f86a07022008-11-25 01:06:051128 for (int i = infobar_delegate_count() - 1; i >= 0; --i) {
[email protected]616ed5a2008-11-21 22:27:241129 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
[email protected]f86a07022008-11-25 01:06:051130 if (delegate->ShouldExpire(details))
[email protected]616ed5a2008-11-21 22:27:241131 RemoveInfoBar(delegate);
[email protected]616ed5a2008-11-21 22:27:241132 }
1133}
[email protected]fdd61c62009-04-22 19:22:571134
1135void TabContents::OnGearsCreateShortcutDone(
1136 const GearsShortcutData2& shortcut_data, bool success) {
1137 NavigationEntry* current_entry = controller_.GetLastCommittedEntry();
1138 bool same_page =
1139 current_entry && pending_install_.page_id == current_entry->page_id();
1140
1141 if (success && same_page) {
1142 // Only switch to app mode if the user chose to create a shortcut and
1143 // we're still on the same page that it corresponded to.
1144 if (delegate())
1145 delegate()->ConvertContentsToApplication(this);
1146 }
1147
1148 // Reset the page id to indicate no requests are pending.
1149 pending_install_.page_id = 0;
1150 pending_install_.callback_functor = NULL;
1151}
[email protected]96d185d2009-04-24 03:28:541152
1153DOMUI* TabContents::GetDOMUIForCurrentState() {
1154 // When there is a pending navigation entry, we want to use the pending DOMUI
1155 // that goes along with it to control the basic flags. For example, we want to
1156 // show the pending URL in the URL bar, so we want the display_url flag to
1157 // be from the pending entry.
1158 //
1159 // The confusion comes because there are multiple possibilities for the
1160 // initial load in a tab as a side effect of the way the RenderViewHostManager
1161 // works.
1162 //
1163 // - For the very first tab the load looks "normal". The new tab DOM UI is
1164 // the pending one, and we want it to apply here.
1165 //
1166 // - For subsequent new tabs, they'll get a new SiteInstance which will then
1167 // get switched to the one previously associated with the new tab pages.
1168 // This switching will cause the manager to commit the RVH/DOMUI. So we'll
1169 // have a committed DOM UI in this case.
1170 //
1171 // This condition handles all of these cases:
1172 //
1173 // - First load in first tab: no committed nav entry + pending nav entry +
1174 // pending dom ui:
1175 // -> Use pending DOM UI if any.
1176 //
1177 // - First load in second tab: no committed nav entry + pending nav entry +
1178 // no pending DOM UI:
1179 // -> Use the committed DOM UI if any.
1180 //
1181 // - Second navigation in any tab: committed nav entry + pending nav entry:
1182 // -> Use pending DOM UI if any.
1183 //
1184 // - Normal state with no load: committed nav entry + no pending nav entry:
1185 // -> Use committed DOM UI.
1186 if (controller_.pending_entry() &&
1187 (controller_.GetLastCommittedEntry() ||
1188 render_manager_.pending_dom_ui()))
1189 return render_manager_.pending_dom_ui();
1190 return render_manager_.dom_ui();
1191}
[email protected]420ae012009-04-24 05:16:321192
1193void TabContents::DidNavigateMainFramePostCommit(
1194 const NavigationController::LoadCommittedDetails& details,
1195 const ViewHostMsg_FrameNavigate_Params& params) {
[email protected]420ae012009-04-24 05:16:321196 if (details.is_user_initiated_main_frame_load()) {
1197 // Clear the status bubble. This is a workaround for a bug where WebKit
1198 // doesn't let us know that the cursor left an element during a
1199 // transition (this is also why the mouse cursor remains as a hand after
1200 // clicking on a link); see bugs 1184641 and 980803. We don't want to
1201 // clear the bubble when a user navigates to a named anchor in the same
1202 // page.
1203 UpdateTargetURL(details.entry->page_id(), GURL());
1204
1205 // UpdateHelpersForDidNavigate will handle the case where the password_form
1206 // origin is valid.
1207 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1208 // cleaned up and covered by tests.
1209 if (!params.password_form.origin.is_valid())
1210 GetPasswordManager()->DidNavigate();
1211 }
1212
1213 // The keyword generator uses the navigation entries, so must be called after
1214 // the commit.
1215 GenerateKeywordIfNecessary(params);
1216
1217 // Allow the new page to set the title again.
1218 received_page_title_ = false;
1219
1220 // Get the favicon, either from history or request it from the net.
1221 fav_icon_helper_.FetchFavIcon(details.entry->url());
1222
[email protected]ce5c4502009-05-06 16:46:111223 // Disable all page actions.
1224 enabled_page_actions_.clear();
1225
[email protected]420ae012009-04-24 05:16:321226 // Close constrained popups if necessary.
1227 MaybeCloseChildWindows(details.previous_url, details.entry->url());
1228
1229 // Update the starred state.
1230 UpdateStarredStateForCurrentURL();
1231}
1232
1233void TabContents::DidNavigateAnyFramePostCommit(
1234 RenderViewHost* render_view_host,
1235 const NavigationController::LoadCommittedDetails& details,
1236 const ViewHostMsg_FrameNavigate_Params& params) {
1237 // If we navigate, start showing messages again. This does nothing to prevent
1238 // a malicious script from spamming messages, since the script could just
1239 // reload the page to stop blocking.
1240 suppress_javascript_messages_ = false;
1241
[email protected]420ae012009-04-24 05:16:321242 // Notify the password manager of the navigation or form submit.
1243 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1244 // cleaned up and covered by tests.
1245 if (params.password_form.origin.is_valid())
1246 GetPasswordManager()->ProvisionallySavePassword(params.password_form);
1247}
1248
1249void TabContents::MaybeCloseChildWindows(const GURL& previous_url,
1250 const GURL& current_url) {
1251 if (net::RegistryControlledDomainService::SameDomainOrHost(
1252 previous_url, current_url))
1253 return;
1254
1255 // Clear out any child windows since we are leaving this page entirely.
1256 // We use indices instead of iterators in case CloseWindow does something
1257 // that may invalidate an iterator.
1258 int size = static_cast<int>(child_windows_.size());
1259 for (int i = size - 1; i >= 0; --i) {
1260 ConstrainedWindow* window = child_windows_[i];
1261 if (window)
1262 window->CloseConstrainedWindow();
1263 }
1264}
1265
1266void TabContents::UpdateStarredStateForCurrentURL() {
1267 BookmarkModel* model = profile()->GetBookmarkModel();
1268 const bool old_state = is_starred_;
1269 is_starred_ = (model && model->IsBookmarked(GetURL()));
1270
1271 if (is_starred_ != old_state && delegate())
1272 delegate()->URLStarredChanged(this, is_starred_);
1273}
1274
1275void TabContents::UpdateAlternateErrorPageURL() {
1276 GURL url = GetAlternateErrorPageURL();
1277 render_view_host()->SetAlternateErrorPageURL(url);
1278}
1279
1280void TabContents::UpdateWebPreferences() {
1281 render_view_host()->UpdateWebPreferences(GetWebkitPrefs());
1282}
1283
1284void TabContents::UpdateMaxPageIDIfNecessary(SiteInstance* site_instance,
1285 RenderViewHost* rvh) {
1286 // If we are creating a RVH for a restored controller, then we might
1287 // have more page IDs than the SiteInstance's current max page ID. We must
1288 // make sure that the max page ID is larger than any restored page ID.
1289 // Note that it is ok for conflicting page IDs to exist in another tab
1290 // (i.e., NavigationController), but if any page ID is larger than the max,
1291 // the back/forward list will get confused.
1292 int max_restored_page_id = controller_.max_restored_page_id();
1293 if (max_restored_page_id > 0) {
1294 int curr_max_page_id = site_instance->max_page_id();
1295 if (max_restored_page_id > curr_max_page_id) {
1296 // Need to update the site instance immediately.
1297 site_instance->UpdateMaxPageID(max_restored_page_id);
1298
1299 // Also tell the renderer to update its internal representation. We
1300 // need to reserve enough IDs to make all restored page IDs less than
1301 // the max.
1302 if (curr_max_page_id < 0)
1303 curr_max_page_id = 0;
1304 rvh->ReservePageIDRange(max_restored_page_id - curr_max_page_id);
1305 }
1306 }
1307}
1308
1309void TabContents::UpdateHistoryForNavigation(
1310 const GURL& display_url,
[email protected]befd8d822009-07-01 04:51:471311 const NavigationController::LoadCommittedDetails& details,
[email protected]420ae012009-04-24 05:16:321312 const ViewHostMsg_FrameNavigate_Params& params) {
1313 if (profile()->IsOffTheRecord())
1314 return;
1315
1316 // Add to history service.
1317 HistoryService* hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1318 if (hs) {
1319 if (PageTransition::IsMainFrame(params.transition) &&
1320 display_url != params.url) {
1321 // Hack on the "display" URL so that it will appear in history. For some
1322 // types of URLs, we will display a magic URL that is different from where
1323 // the page is actually navigated. We want the user to see in history
1324 // what they saw in the URL bar, so we add the display URL as a redirect.
1325 // This only applies to the main frame, as the display URL doesn't apply
1326 // to sub-frames.
1327 std::vector<GURL> redirects = params.redirects;
1328 if (!redirects.empty())
1329 redirects.back() = display_url;
1330 hs->AddPage(display_url, this, params.page_id, params.referrer,
[email protected]befd8d822009-07-01 04:51:471331 params.transition, redirects, details.did_replace_entry);
[email protected]420ae012009-04-24 05:16:321332 } else {
1333 hs->AddPage(params.url, this, params.page_id, params.referrer,
[email protected]befd8d822009-07-01 04:51:471334 params.transition, params.redirects,
1335 details.did_replace_entry);
[email protected]420ae012009-04-24 05:16:321336 }
1337 }
1338}
1339
1340bool TabContents::UpdateTitleForEntry(NavigationEntry* entry,
1341 const std::wstring& title) {
1342 // For file URLs without a title, use the pathname instead. In the case of a
1343 // synthesized title, we don't want the update to count toward the "one set
1344 // per page of the title to history."
1345 std::wstring final_title;
1346 bool explicit_set;
1347 if (entry->url().SchemeIsFile() && title.empty()) {
1348 final_title = UTF8ToWide(entry->url().ExtractFileName());
1349 explicit_set = false; // Don't count synthetic titles toward the set limit.
1350 } else {
1351 TrimWhitespace(title, TRIM_ALL, &final_title);
1352 explicit_set = true;
1353 }
1354
1355 if (final_title == UTF16ToWideHack(entry->title()))
1356 return false; // Nothing changed, don't bother.
1357
1358 entry->set_title(WideToUTF16Hack(final_title));
1359
1360 // Update the history system for this page.
1361 if (!profile()->IsOffTheRecord() && !received_page_title_) {
1362 HistoryService* hs =
1363 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1364 if (hs)
1365 hs->SetPageTitle(entry->display_url(), final_title);
1366
1367 // Don't allow the title to be saved again for explicitly set ones.
1368 received_page_title_ = explicit_set;
1369 }
1370
1371 // Lastly, set the title for the view.
1372 view_->SetPageTitle(final_title);
1373
1374 return true;
1375}
1376
1377void TabContents::NotifySwapped() {
1378 // After sending out a swap notification, we need to send a disconnect
1379 // notification so that clients that pick up a pointer to |this| can NULL the
1380 // pointer. See Bug 1230284.
1381 notify_disconnection_ = true;
1382 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341383 NotificationType::TAB_CONTENTS_SWAPPED,
[email protected]d82ed61e2009-06-16 02:46:221384 Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321385 NotificationService::NoDetails());
1386}
1387
1388void TabContents::NotifyConnected() {
1389 notify_disconnection_ = true;
1390 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341391 NotificationType::TAB_CONTENTS_CONNECTED,
[email protected]d82ed61e2009-06-16 02:46:221392 Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321393 NotificationService::NoDetails());
1394}
1395
1396void TabContents::NotifyDisconnected() {
1397 if (!notify_disconnection_)
1398 return;
1399
1400 notify_disconnection_ = false;
1401 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341402 NotificationType::TAB_CONTENTS_DISCONNECTED,
[email protected]d82ed61e2009-06-16 02:46:221403 Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321404 NotificationService::NoDetails());
1405}
1406
1407void TabContents::GenerateKeywordIfNecessary(
1408 const ViewHostMsg_FrameNavigate_Params& params) {
1409 if (!params.searchable_form_url.is_valid())
1410 return;
1411
1412 if (profile()->IsOffTheRecord())
1413 return;
1414
1415 int last_index = controller_.last_committed_entry_index();
1416 // When there was no previous page, the last index will be 0. This is
1417 // normally due to a form submit that opened in a new tab.
1418 // TODO(brettw) bug 916126: we should support keywords when form submits
1419 // happen in new tabs.
1420 if (last_index <= 0)
1421 return;
1422 const NavigationEntry* previous_entry =
1423 controller_.GetEntryAtIndex(last_index - 1);
1424 if (IsFormSubmit(previous_entry)) {
1425 // Only generate a keyword if the previous page wasn't itself a form
1426 // submit.
1427 return;
1428 }
1429
1430 GURL keyword_url = previous_entry->user_typed_url().is_valid() ?
1431 previous_entry->user_typed_url() : previous_entry->url();
1432 std::wstring keyword =
1433 TemplateURLModel::GenerateKeyword(keyword_url, true); // autodetected
1434 if (keyword.empty())
1435 return;
1436
1437 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
1438 if (!url_model)
1439 return;
1440
1441 if (!url_model->loaded()) {
1442 url_model->Load();
1443 return;
1444 }
1445
1446 const TemplateURL* current_url;
1447 std::wstring url = UTF8ToWide(params.searchable_form_url.spec());
1448 if (!url_model->CanReplaceKeyword(keyword, url, &current_url))
1449 return;
1450
1451 if (current_url) {
1452 if (current_url->originating_url().is_valid()) {
1453 // The existing keyword was generated from an OpenSearch description
1454 // document, don't regenerate.
1455 return;
1456 }
1457 url_model->Remove(current_url);
1458 }
1459 TemplateURL* new_url = new TemplateURL();
1460 new_url->set_keyword(keyword);
1461 new_url->set_short_name(keyword);
1462 new_url->SetURL(url, 0, 0);
1463 new_url->add_input_encoding(params.searchable_form_encoding);
1464 DCHECK(controller_.GetLastCommittedEntry());
1465 const GURL& favicon_url =
1466 controller_.GetLastCommittedEntry()->favicon().url();
1467 if (favicon_url.is_valid()) {
1468 new_url->SetFavIconURL(favicon_url);
1469 } else {
1470 // The favicon url isn't valid. This means there really isn't a favicon,
1471 // or the favicon url wasn't obtained before the load started. This assumes
1472 // the later.
1473 // TODO(sky): Need a way to set the favicon that doesn't involve generating
1474 // its url.
1475 new_url->SetFavIconURL(TemplateURL::GenerateFaviconURL(params.referrer));
1476 }
1477 new_url->set_safe_for_autoreplace(true);
1478 url_model->Add(new_url);
1479}
1480
[email protected]bf5c2ff392009-07-08 16:24:331481void TabContents::OnUserGesture() {
1482 // See comment in RenderViewHostDelegate::OnUserGesture as to why we do this.
1483 DownloadRequestManager* drm = g_browser_process->download_request_manager();
1484 if (drm)
1485 drm->OnUserGesture(this);
1486 controller_.OnUserGesture();
1487}
1488
1489void TabContents::OnFindReply(int request_id,
1490 int number_of_matches,
1491 const gfx::Rect& selection_rect,
1492 int active_match_ordinal,
1493 bool final_update) {
1494 // Ignore responses for requests other than the one we have most recently
1495 // issued. That way we won't act on stale results when the user has
1496 // already typed in another query.
1497 if (request_id != current_find_request_id_)
1498 return;
1499
1500 if (number_of_matches == -1)
1501 number_of_matches = last_search_result_.number_of_matches();
1502 if (active_match_ordinal == -1)
1503 active_match_ordinal = last_search_result_.active_match_ordinal();
1504
1505 gfx::Rect selection = selection_rect;
1506 if (selection.IsEmpty())
1507 selection = last_search_result_.selection_rect();
1508
1509 // Notify the UI, automation and any other observers that a find result was
1510 // found.
1511 last_search_result_ = FindNotificationDetails(request_id, number_of_matches,
1512 selection, active_match_ordinal,
1513 final_update);
1514 NotificationService::current()->Notify(
1515 NotificationType::FIND_RESULT_AVAILABLE,
1516 Source<TabContents>(this),
1517 Details<FindNotificationDetails>(&last_search_result_));
1518}
1519
1520void TabContents::GoToEntryAtOffset(int offset) {
1521 controller_.GoToOffset(offset);
1522}
1523
1524void TabContents::GetHistoryListCount(int* back_list_count,
1525 int* forward_list_count) {
1526 int current_index = controller_.last_committed_entry_index();
1527 *back_list_count = current_index;
1528 *forward_list_count = controller_.entry_count() - current_index - 1;
1529}
1530
1531void TabContents::OnMissingPluginStatus(int status) {
1532#if defined(OS_WIN)
1533// TODO(PORT): pull in when plug-ins work
1534 GetPluginInstaller()->OnMissingPluginStatus(status);
1535#endif
1536}
1537
1538void TabContents::OnCrashedPlugin(const FilePath& plugin_path) {
1539#if defined(OS_WIN)
1540// TODO(PORT): pull in when plug-ins work
1541 DCHECK(!plugin_path.value().empty());
1542
1543 std::wstring plugin_name = plugin_path.ToWStringHack();
1544 scoped_ptr<FileVersionInfo> version_info(
1545 FileVersionInfo::CreateFileVersionInfo(plugin_path));
1546 if (version_info.get()) {
1547 const std::wstring& product_name = version_info->product_name();
1548 if (!product_name.empty())
1549 plugin_name = product_name;
1550 }
1551 AddInfoBar(new SimpleAlertInfoBarDelegate(
1552 this, l10n_util::GetStringF(IDS_PLUGIN_CRASHED_PROMPT, plugin_name),
1553 NULL));
1554#endif
1555}
1556
1557void TabContents::OnCrashedWorker() {
1558 AddInfoBar(new SimpleAlertInfoBarDelegate(
1559 this, l10n_util::GetString(IDS_WEBWORKER_CRASHED_PROMPT),
1560 NULL));
1561}
1562
1563void TabContents::OnDidGetApplicationInfo(
1564 int32 page_id,
1565 const webkit_glue::WebApplicationInfo& info) {
1566 if (pending_install_.page_id != page_id)
1567 return; // The user clicked create on a separate page. Ignore this.
1568
1569 pending_install_.callback_functor =
1570 new GearsCreateShortcutCallbackFunctor(this);
1571 GearsCreateShortcut(
1572 info, pending_install_.title, pending_install_.url, pending_install_.icon,
1573 NewCallback(pending_install_.callback_functor,
1574 &GearsCreateShortcutCallbackFunctor::Run));
1575}
1576
1577void TabContents::DidStartProvisionalLoadForFrame(
1578 RenderViewHost* render_view_host,
1579 bool is_main_frame,
1580 const GURL& url) {
1581 ProvisionalLoadDetails details(is_main_frame,
1582 controller_.IsURLInPageNavigation(url),
1583 url, std::string(), false);
1584 NotificationService::current()->Notify(
1585 NotificationType::FRAME_PROVISIONAL_LOAD_START,
1586 Source<NavigationController>(&controller_),
1587 Details<ProvisionalLoadDetails>(&details));
1588}
1589
1590void TabContents::DidStartReceivingResourceResponse(
1591 ResourceRequestDetails* details) {
1592 NotificationService::current()->Notify(
1593 NotificationType::RESOURCE_RESPONSE_STARTED,
1594 Source<NavigationController>(&controller()),
1595 Details<ResourceRequestDetails>(details));
1596}
1597
1598void TabContents::DidRedirectResource(ResourceRequestDetails* details) {
1599 NotificationService::current()->Notify(
1600 NotificationType::RESOURCE_RECEIVED_REDIRECT,
1601 Source<NavigationController>(&controller()),
1602 Details<ResourceRequestDetails>(details));
1603}
1604
1605void TabContents::DidLoadResourceFromMemoryCache(
1606 const GURL& url,
1607 const std::string& frame_origin,
1608 const std::string& main_frame_origin,
1609 const std::string& security_info) {
1610 // Send out a notification that we loaded a resource from our memory cache.
1611 int cert_id = 0, cert_status = 0, security_bits = 0;
1612 SSLManager::DeserializeSecurityInfo(security_info,
1613 &cert_id, &cert_status,
1614 &security_bits);
1615 LoadFromMemoryCacheDetails details(url, frame_origin, main_frame_origin,
1616 process()->pid(), cert_id, cert_status);
1617
1618 NotificationService::current()->Notify(
1619 NotificationType::LOAD_FROM_MEMORY_CACHE,
1620 Source<NavigationController>(&controller_),
1621 Details<LoadFromMemoryCacheDetails>(&details));
1622}
1623
1624void TabContents::DidFailProvisionalLoadWithError(
1625 RenderViewHost* render_view_host,
1626 bool is_main_frame,
1627 int error_code,
1628 const GURL& url,
1629 bool showing_repost_interstitial) {
1630 if (net::ERR_ABORTED == error_code) {
1631 // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
1632 // This means that the interstitial won't be torn down properly, which is
1633 // bad. But if we have an interstitial, go back to another tab type, and
1634 // then load the same interstitial again, we could end up getting the first
1635 // interstitial's "failed" message (as a result of the cancel) when we're on
1636 // the second one.
1637 //
1638 // We can't tell this apart, so we think we're tearing down the current page
1639 // which will cause a crash later one. There is also some code in
1640 // RenderViewHostManager::RendererAbortedProvisionalLoad that is commented
1641 // out because of this problem.
1642 //
1643 // http://code.google.com/p/chromium/issues/detail?id=2855
1644 // Because this will not tear down the interstitial properly, if "back" is
1645 // back to another tab type, the interstitial will still be somewhat alive
1646 // in the previous tab type. If you navigate somewhere that activates the
1647 // tab with the interstitial again, you'll see a flash before the new load
1648 // commits of the interstitial page.
1649 if (showing_interstitial_page()) {
1650 LOG(WARNING) << "Discarding message during interstitial.";
1651 return;
1652 }
1653
1654 // This will discard our pending entry if we cancelled the load (e.g., if we
1655 // decided to download the file instead of load it). Only discard the
1656 // pending entry if the URLs match, otherwise the user initiated a navigate
1657 // before the page loaded so that the discard would discard the wrong entry.
1658 NavigationEntry* pending_entry = controller_.pending_entry();
1659 if (pending_entry && pending_entry->url() == url) {
1660 controller_.DiscardNonCommittedEntries();
1661 // Update the URL display.
1662 NotifyNavigationStateChanged(TabContents::INVALIDATE_URL);
1663 }
1664
1665 render_manager_.RendererAbortedProvisionalLoad(render_view_host);
1666 }
1667
1668 // Send out a notification that we failed a provisional load with an error.
1669 ProvisionalLoadDetails details(is_main_frame,
1670 controller_.IsURLInPageNavigation(url),
1671 url, std::string(), false);
1672 details.set_error_code(error_code);
1673
1674 NotificationService::current()->Notify(
1675 NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR,
1676 Source<NavigationController>(&controller_),
1677 Details<ProvisionalLoadDetails>(&details));
1678}
1679
1680void TabContents::DocumentLoadedInFrame() {
1681 controller_.DocumentLoadedInFrame();
1682}
1683
[email protected]420ae012009-04-24 05:16:321684RenderViewHostDelegate::View* TabContents::GetViewDelegate() const {
1685 return view_.get();
1686}
1687
[email protected]bf5c2ff392009-07-08 16:24:331688RenderViewHostDelegate::BrowserIntegration*
1689 TabContents::GetBrowserIntegrationDelegate() const {
1690 return const_cast<TabContents*>(this);
1691}
1692
1693RenderViewHostDelegate::Resource* TabContents::GetResourceDelegate() const {
1694 return const_cast<TabContents*>(this);
1695}
1696
[email protected]420ae012009-04-24 05:16:321697RenderViewHostDelegate::Save* TabContents::GetSaveDelegate() const {
1698 return save_package_.get(); // May be NULL, but we can return NULL.
1699}
1700
[email protected]bf5c2ff392009-07-08 16:24:331701RenderViewHostDelegate::FavIcon* TabContents::GetFavIconDelegate() const {
1702 return &const_cast<TabContents*>(this)->fav_icon_helper_;
1703}
1704
[email protected]80d96fa2009-06-10 22:34:511705RendererPreferences TabContents::GetRendererPrefs() const {
1706 if (delegate())
1707 return delegate()->GetRendererPrefs();
1708 else
1709 return RendererPreferences();
1710}
1711
[email protected]57c6a652009-05-04 07:58:341712TabContents* TabContents::GetAsTabContents() {
1713 return this;
1714}
1715
[email protected]420ae012009-04-24 05:16:321716void TabContents::RenderViewCreated(RenderViewHost* render_view_host) {
[email protected]2e4633c2009-07-09 16:58:061717 NotificationService::current()->Notify(
1718 NotificationType::RENDER_VIEW_HOST_CREATED_FOR_TAB,
1719 Source<TabContents>(this),
1720 Details<RenderViewHost>(render_view_host));
1721
[email protected]420ae012009-04-24 05:16:321722 NavigationEntry* entry = controller_.GetActiveEntry();
1723 if (!entry)
1724 return;
1725
1726 // When we're creating views, we're still doing initial setup, so we always
1727 // use the pending DOM UI rather than any possibly existing committed one.
1728 if (render_manager_.pending_dom_ui()) {
1729 render_manager_.pending_dom_ui()->RenderViewCreated(render_view_host);
1730 }
1731
1732 if (entry->IsViewSourceMode()) {
1733 // Put the renderer in view source mode.
1734 render_view_host->Send(
1735 new ViewMsg_EnableViewSourceMode(render_view_host->routing_id()));
1736 }
[email protected]0666aef2009-05-13 19:48:081737
1738 view()->RenderViewCreated(render_view_host);
[email protected]420ae012009-04-24 05:16:321739}
1740
1741void TabContents::RenderViewReady(RenderViewHost* rvh) {
1742 if (rvh != render_view_host()) {
1743 // Don't notify the world, since this came from a renderer in the
1744 // background.
1745 return;
1746 }
1747
1748 NotifyConnected();
1749 SetIsCrashed(false);
1750}
1751
1752void TabContents::RenderViewGone(RenderViewHost* rvh) {
1753 // Ask the print preview if this renderer was valuable.
1754 if (!printing_.OnRenderViewGone(rvh))
1755 return;
1756 if (rvh != render_view_host()) {
1757 // The pending page's RenderViewHost is gone.
1758 return;
1759 }
1760
1761 SetIsLoading(false, NULL);
1762 NotifyDisconnected();
1763 SetIsCrashed(true);
1764
[email protected]8e537302009-06-10 21:19:581765 // Tell the view that we've crashed so it can prepare the sad tab page.
1766 view_->OnTabCrashed();
[email protected]420ae012009-04-24 05:16:321767
1768 // Hide any visible hung renderer warning for this web contents' process.
[email protected]d82ed61e2009-06-16 02:46:221769 HungRendererDialog::HideForTabContents(this);
[email protected]420ae012009-04-24 05:16:321770}
1771
[email protected]2e4633c2009-07-09 16:58:061772void TabContents::RenderViewDeleted(RenderViewHost* rvh) {
1773 NotificationService::current()->Notify(
1774 NotificationType::RENDER_VIEW_HOST_DELETED,
1775 Source<TabContents>(this),
1776 Details<RenderViewHost>(rvh));
1777}
1778
[email protected]420ae012009-04-24 05:16:321779void TabContents::DidNavigate(RenderViewHost* rvh,
1780 const ViewHostMsg_FrameNavigate_Params& params) {
1781 if (PageTransition::IsMainFrame(params.transition))
1782 render_manager_.DidNavigateMainFrame(rvh);
1783
1784 // Update the site of the SiteInstance if it doesn't have one yet.
1785 if (!GetSiteInstance()->has_site())
1786 GetSiteInstance()->SetSite(params.url);
1787
1788 // Need to update MIME type here because it's referred to in
1789 // UpdateNavigationCommands() called by RendererDidNavigate() to
1790 // determine whether or not to enable the encoding menu.
1791 // It's updated only for the main frame. For a subframe,
1792 // RenderView::UpdateURL does not set params.contents_mime_type.
1793 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
1794 // TODO(jungshik): Add a test for the encoding menu to avoid
1795 // regressing it again.
1796 if (PageTransition::IsMainFrame(params.transition))
1797 contents_mime_type_ = params.contents_mime_type;
1798
1799 NavigationController::LoadCommittedDetails details;
[email protected]3e90d4a2009-07-03 17:38:391800 bool did_navigate = controller_.RendererDidNavigate(params, &details);
1801
1802 // Update history. Note that this needs to happen after the entry is complete,
1803 // which WillNavigate[Main,Sub]Frame will do before this function is called.
1804 if (params.should_update_history) {
1805 // Most of the time, the displayURL matches the loaded URL, but for about:
1806 // URLs, we use a data: URL as the real value. We actually want to save
1807 // the about: URL to the history db and keep the data: URL hidden. This is
1808 // what the TabContents' URL getter does.
1809 UpdateHistoryForNavigation(GetURL(), details, params);
1810 }
1811
1812 if (!did_navigate)
1813 return; // No navigation happened.
[email protected]420ae012009-04-24 05:16:321814
1815 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
1816 // for the appropriate notification (best) or you can add it to
1817 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
1818 // necessary, please).
1819
1820 // Run post-commit tasks.
1821 if (details.is_main_frame)
1822 DidNavigateMainFramePostCommit(details, params);
1823 DidNavigateAnyFramePostCommit(rvh, details, params);
1824}
1825
1826void TabContents::UpdateState(RenderViewHost* rvh,
1827 int32 page_id,
1828 const std::string& state) {
1829 DCHECK(rvh == render_view_host());
1830
1831 // We must be prepared to handle state updates for any page, these occur
1832 // when the user is scrolling and entering form data, as well as when we're
1833 // leaving a page, in which case our state may have already been moved to
1834 // the next page. The navigation controller will look up the appropriate
1835 // NavigationEntry and update it when it is notified via the delegate.
1836
1837 int entry_index = controller_.GetEntryIndexWithPageID(
1838 GetSiteInstance(), page_id);
1839 if (entry_index < 0)
1840 return;
1841 NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
1842
1843 if (state == entry->content_state())
1844 return; // Nothing to update.
1845 entry->set_content_state(state);
1846 controller_.NotifyEntryChanged(entry, entry_index);
1847}
1848
1849void TabContents::UpdateTitle(RenderViewHost* rvh,
1850 int32 page_id, const std::wstring& title) {
1851 // If we have a title, that's a pretty good indication that we've started
1852 // getting useful data.
1853 SetNotWaitingForResponse();
1854
1855 DCHECK(rvh == render_view_host());
1856 NavigationEntry* entry = controller_.GetEntryWithPageID(GetSiteInstance(),
1857 page_id);
1858 if (!entry || !UpdateTitleForEntry(entry, title))
1859 return;
1860
1861 // Broadcast notifications when the UI should be updated.
1862 if (entry == controller_.GetEntryAtOffset(0))
[email protected]c9cd2222009-05-06 05:16:501863 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:321864}
1865
[email protected]420ae012009-04-24 05:16:321866void TabContents::UpdateEncoding(RenderViewHost* render_view_host,
1867 const std::wstring& encoding) {
1868 set_encoding(encoding);
1869}
1870
1871void TabContents::UpdateTargetURL(int32 page_id, const GURL& url) {
1872 if (delegate())
1873 delegate()->UpdateTargetURL(this, url);
1874}
1875
1876void TabContents::UpdateThumbnail(const GURL& url,
1877 const SkBitmap& bitmap,
1878 const ThumbnailScore& score) {
1879 // Tell History about this thumbnail
[email protected]449478302009-06-09 20:04:281880 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kThumbnailStore)) {
[email protected]32545632009-07-08 00:08:311881 profile()->GetThumbnailStore()->
1882 SetPageThumbnail(url, bitmap, score, !profile()->IsOffTheRecord());
[email protected]449478302009-06-09 20:04:281883 } else {
1884 HistoryService* hs;
1885 if (!profile()->IsOffTheRecord() &&
1886 (hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS))) {
1887 hs->SetPageThumbnail(url, bitmap, score);
1888 }
[email protected]420ae012009-04-24 05:16:321889 }
1890}
1891
[email protected]0df30122009-06-03 12:13:081892void TabContents::UpdateInspectorSettings(const std::wstring& raw_settings) {
1893 profile()->GetPrefs()->SetString(prefs::kWebKitInspectorSettings,
1894 raw_settings);
1895}
1896
[email protected]420ae012009-04-24 05:16:321897void TabContents::Close(RenderViewHost* rvh) {
1898 // Ignore this if it comes from a RenderViewHost that we aren't showing.
1899 if (delegate() && rvh == render_view_host())
1900 delegate()->CloseContents(this);
1901}
1902
1903void TabContents::RequestMove(const gfx::Rect& new_bounds) {
1904 if (delegate() && delegate()->IsPopup(this))
1905 delegate()->MoveContents(this, new_bounds);
1906}
1907
[email protected]329581b2009-04-28 06:52:351908void TabContents::DidStartLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321909 SetIsLoading(true, NULL);
1910}
1911
[email protected]329581b2009-04-28 06:52:351912void TabContents::DidStopLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321913 scoped_ptr<LoadNotificationDetails> details;
1914
1915 NavigationEntry* entry = controller_.GetActiveEntry();
1916 // An entry may not exist for a stop when loading an initial blank page or
1917 // if an iframe injected by script into a blank page finishes loading.
1918 if (entry) {
1919 scoped_ptr<base::ProcessMetrics> metrics(
1920 base::ProcessMetrics::CreateProcessMetrics(
1921 process()->process().handle()));
1922
1923 base::TimeDelta elapsed = base::TimeTicks::Now() - current_load_start_;
1924
1925 details.reset(new LoadNotificationDetails(
1926 entry->display_url(),
1927 entry->transition_type(),
1928 elapsed,
1929 &controller_,
1930 controller_.GetCurrentEntryIndex()));
1931 }
1932
1933 // Tell PasswordManager we've finished a page load, which serves as a
1934 // green light to save pending passwords and reset itself.
1935 GetPasswordManager()->DidStopLoading();
1936
1937 SetIsLoading(false, details.get());
1938}
1939
[email protected]420ae012009-04-24 05:16:321940void TabContents::DidRedirectProvisionalLoad(int32 page_id,
1941 const GURL& source_url,
1942 const GURL& target_url) {
1943 NavigationEntry* entry;
1944 if (page_id == -1)
1945 entry = controller_.pending_entry();
1946 else
1947 entry = controller_.GetEntryWithPageID(GetSiteInstance(), page_id);
1948 if (!entry || entry->url() != source_url)
1949 return;
1950 entry->set_url(target_url);
1951}
1952
[email protected]420ae012009-04-24 05:16:321953void TabContents::RequestOpenURL(const GURL& url, const GURL& referrer,
1954 WindowOpenDisposition disposition) {
1955 if (render_manager_.dom_ui()) {
1956 // When we're a DOM UI, it will provide a page transition type for us (this
1957 // is so the new tab page can specify AUTO_BOOKMARK for automatically
1958 // generated suggestions).
1959 //
1960 // Note also that we hide the referrer for DOM UI pages. We don't really
[email protected]60e448982009-05-06 04:21:161961 // want web sites to see a referrer of "chrome://blah" (and some
1962 // chrome: URLs might have search terms or other stuff we don't want to
[email protected]420ae012009-04-24 05:16:321963 // send to the site), so we send no referrer.
1964 OpenURL(url, GURL(), disposition,
1965 render_manager_.dom_ui()->link_transition_type());
1966 } else {
1967 OpenURL(url, referrer, disposition, PageTransition::LINK);
1968 }
1969}
1970
[email protected]1ee614862009-07-06 20:29:181971void TabContents::DomOperationResponse(const std::string& json_string,
1972 int automation_id) {
1973}
1974
[email protected]420ae012009-04-24 05:16:321975void TabContents::ProcessDOMUIMessage(const std::string& message,
[email protected]811bfe32009-07-01 08:46:251976 const std::string& content,
1977 int request_id,
1978 bool has_callback) {
[email protected]420ae012009-04-24 05:16:321979 if (!render_manager_.dom_ui()) {
1980 // We shouldn't get a DOM UI message when we haven't enabled the DOM UI.
1981 // Because the renderer might be owned and sending random messages, we need
1982 // to ignore these inproper ones.
1983 NOTREACHED();
1984 return;
1985 }
[email protected]811bfe32009-07-01 08:46:251986 render_manager_.dom_ui()->ProcessDOMUIMessage(message, content, request_id,
1987 has_callback);
[email protected]420ae012009-04-24 05:16:321988}
1989
1990void TabContents::ProcessExternalHostMessage(const std::string& message,
1991 const std::string& origin,
1992 const std::string& target) {
1993 if (delegate())
1994 delegate()->ForwardMessageToExternalHost(message, origin, target);
1995}
1996
[email protected]420ae012009-04-24 05:16:321997void TabContents::RunFileChooser(bool multiple_files,
1998 const string16& title,
1999 const FilePath& default_file) {
2000 if (!select_file_dialog_.get())
2001 select_file_dialog_ = SelectFileDialog::Create(this);
2002 SelectFileDialog::Type dialog_type =
2003 multiple_files ? SelectFileDialog::SELECT_OPEN_MULTI_FILE :
2004 SelectFileDialog::SELECT_OPEN_FILE;
2005 select_file_dialog_->SelectFile(dialog_type, title, default_file,
2006 NULL, 0, FILE_PATH_LITERAL(""),
2007 view_->GetTopLevelNativeWindow(), NULL);
2008}
2009
2010void TabContents::RunJavaScriptMessage(
2011 const std::wstring& message,
2012 const std::wstring& default_prompt,
2013 const GURL& frame_url,
2014 const int flags,
2015 IPC::Message* reply_msg,
2016 bool* did_suppress_message) {
2017 // Suppress javascript messages when requested and when inside a constrained
2018 // popup window (because that activates them and breaks them out of the
2019 // constrained window jail).
[email protected]91ed49a2009-07-07 21:29:552020 // Also suppress messages when showing an interstitial. The interstitial is
2021 // shown over the previous page, we don't want the hidden page dialogs to
2022 // interfere with the interstitial.
2023 bool suppress_this_message = suppress_javascript_messages_ ||
2024 showing_interstitial_page();
[email protected]420ae012009-04-24 05:16:322025 if (delegate())
2026 suppress_this_message |=
[email protected]b6c874582009-05-08 19:38:312027 (delegate()->GetConstrainingContents(this) != this);
[email protected]420ae012009-04-24 05:16:322028
2029 *did_suppress_message = suppress_this_message;
2030
2031 if (!suppress_this_message) {
2032 base::TimeDelta time_since_last_message(
2033 base::TimeTicks::Now() - last_javascript_message_dismissal_);
2034 bool show_suppress_checkbox = false;
2035 // Show a checkbox offering to suppress further messages if this message is
2036 // being displayed within kJavascriptMessageExpectedDelay of the last one.
2037 if (time_since_last_message <
2038 base::TimeDelta::FromMilliseconds(kJavascriptMessageExpectedDelay))
2039 show_suppress_checkbox = true;
2040
[email protected]d82ed61e2009-06-16 02:46:222041 RunJavascriptMessageBox(this, frame_url, flags, message, default_prompt,
[email protected]420ae012009-04-24 05:16:322042 show_suppress_checkbox, reply_msg);
2043 } else {
2044 // If we are suppressing messages, just reply as is if the user immediately
2045 // pressed "Cancel".
2046 OnJavaScriptMessageBoxClosed(reply_msg, false, std::wstring());
2047 }
2048}
2049
2050void TabContents::RunBeforeUnloadConfirm(const std::wstring& message,
2051 IPC::Message* reply_msg) {
[email protected]d82ed61e2009-06-16 02:46:222052 RunBeforeUnloadDialog(this, message, reply_msg);
[email protected]420ae012009-04-24 05:16:322053}
2054
2055void TabContents::ShowModalHTMLDialog(const GURL& url, int width, int height,
2056 const std::string& json_arguments,
2057 IPC::Message* reply_msg) {
2058 if (delegate()) {
2059 HtmlDialogUIDelegate* dialog_delegate =
2060 new ModalHtmlDialogDelegate(url, width, height, json_arguments,
[email protected]d82ed61e2009-06-16 02:46:222061 reply_msg, this);
[email protected]420ae012009-04-24 05:16:322062 delegate()->ShowHtmlDialog(dialog_delegate, NULL);
2063 }
2064}
2065
2066void TabContents::PasswordFormsSeen(
[email protected]ed3fb032009-06-16 19:50:562067 const std::vector<webkit_glue::PasswordForm>& forms) {
[email protected]420ae012009-04-24 05:16:322068 GetPasswordManager()->PasswordFormsSeen(forms);
2069}
2070
2071void TabContents::AutofillFormSubmitted(
[email protected]daa8c58e2009-06-15 17:21:102072 const webkit_glue::AutofillForm& form) {
[email protected]420ae012009-04-24 05:16:322073 GetAutofillManager()->AutofillFormSubmitted(form);
2074}
2075
2076void TabContents::GetAutofillSuggestions(const std::wstring& field_name,
2077 const std::wstring& user_text, int64 node_id, int request_id) {
2078 GetAutofillManager()->FetchValuesForName(field_name, user_text,
2079 kMaxAutofillMenuItems, node_id, request_id);
2080}
2081
2082void TabContents::RemoveAutofillEntry(const std::wstring& field_name,
2083 const std::wstring& value) {
2084 GetAutofillManager()->RemoveValueForName(field_name, value);
2085}
2086
2087// Checks to see if we should generate a keyword based on the OSDD, and if
2088// necessary uses TemplateURLFetcher to download the OSDD and create a keyword.
2089void TabContents::PageHasOSDD(RenderViewHost* render_view_host,
2090 int32 page_id, const GURL& url,
2091 bool autodetected) {
2092 // Make sure page_id is the current page, and the TemplateURLModel is loaded.
2093 DCHECK(url.is_valid());
2094 if (!IsActiveEntry(page_id))
2095 return;
2096 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
2097 if (!url_model)
2098 return;
2099 if (!url_model->loaded()) {
2100 url_model->Load();
2101 return;
2102 }
2103 if (!profile()->GetTemplateURLFetcher())
2104 return;
2105
2106 if (profile()->IsOffTheRecord())
2107 return;
2108
2109 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
2110 DCHECK(entry);
2111
2112 const NavigationEntry* base_entry = entry;
2113 if (IsFormSubmit(base_entry)) {
2114 // If the current page is a form submit, find the last page that was not
2115 // a form submit and use its url to generate the keyword from.
2116 int index = controller_.last_committed_entry_index() - 1;
2117 while (index >= 0 && IsFormSubmit(controller_.GetEntryAtIndex(index)))
2118 index--;
2119 if (index >= 0)
2120 base_entry = controller_.GetEntryAtIndex(index);
2121 else
2122 base_entry = NULL;
2123 }
2124
2125 // We want to use the user typed URL if available since that represents what
2126 // the user typed to get here, and fall back on the regular URL if not.
2127 if (!base_entry)
2128 return;
2129 GURL keyword_url = base_entry->user_typed_url().is_valid() ?
2130 base_entry->user_typed_url() : base_entry->url();
2131 if (!keyword_url.is_valid())
2132 return;
2133 std::wstring keyword = TemplateURLModel::GenerateKeyword(keyword_url,
2134 autodetected);
2135 if (keyword.empty())
2136 return;
2137 const TemplateURL* template_url =
2138 url_model->GetTemplateURLForKeyword(keyword);
2139 if (template_url && (!template_url->safe_for_autoreplace() ||
2140 template_url->originating_url() == url)) {
2141 // Either there is a user created TemplateURL for this keyword, or the
2142 // keyword has the same OSDD url and we've parsed it.
2143 return;
2144 }
2145
2146 // Download the OpenSearch description document. If this is successful a
2147 // new keyword will be created when done.
[email protected]420ae012009-04-24 05:16:322148 profile()->GetTemplateURLFetcher()->ScheduleDownload(
2149 keyword,
2150 url,
2151 base_entry->favicon().url(),
[email protected]d0cc9fb52009-06-23 02:26:162152 this,
[email protected]420ae012009-04-24 05:16:322153 autodetected);
2154}
2155
[email protected]420ae012009-04-24 05:16:322156void TabContents::DidGetPrintedPagesCount(int cookie, int number_pages) {
2157 printing_.DidGetPrintedPagesCount(cookie, number_pages);
2158}
2159
2160void TabContents::DidPrintPage(const ViewHostMsg_DidPrintPage_Params& params) {
2161 printing_.DidPrintPage(params);
2162}
2163
2164GURL TabContents::GetAlternateErrorPageURL() const {
2165 GURL url;
2166 // Disable alternate error pages when in OffTheRecord/Incognito mode.
2167 if (profile()->IsOffTheRecord())
2168 return url;
2169
2170 PrefService* prefs = profile()->GetPrefs();
2171 DCHECK(prefs);
2172 if (prefs->GetBoolean(prefs::kAlternateErrorPagesEnabled)) {
2173 url = google_util::AppendGoogleLocaleParam(GURL(kLinkDoctorBaseURL));
2174 url = google_util::AppendGoogleTLDParam(url);
2175 }
2176 return url;
2177}
2178
2179WebPreferences TabContents::GetWebkitPrefs() {
2180 PrefService* prefs = render_view_host()->process()->profile()->GetPrefs();
2181 bool isDomUI = false;
2182 return RenderViewHostDelegateHelper::GetWebkitPrefs(prefs, isDomUI);
2183}
2184
[email protected]420ae012009-04-24 05:16:322185void TabContents::OnJSOutOfMemory() {
2186 AddInfoBar(new SimpleAlertInfoBarDelegate(
2187 this, l10n_util::GetString(IDS_JS_OUT_OF_MEMORY_PROMPT), NULL));
2188}
2189
2190void TabContents::ShouldClosePage(bool proceed) {
2191 render_manager_.ShouldClosePage(proceed);
2192}
2193
2194void TabContents::OnCrossSiteResponse(int new_render_process_host_id,
2195 int new_request_id) {
[email protected]57c6a652009-05-04 07:58:342196 // Allows the TabContents to react when a cross-site response is ready to be
[email protected]420ae012009-04-24 05:16:322197 // delivered to a pending RenderViewHost. We must first run the onunload
2198 // handler of the old RenderViewHost before we can allow it to proceed.
2199 render_manager_.OnCrossSiteResponse(new_render_process_host_id,
2200 new_request_id);
2201}
2202
[email protected]1ee614862009-07-06 20:29:182203void TabContents::OnCrossSiteNavigationCanceled() {
2204 render_manager_.CrossSiteNavigationCanceled();
2205}
2206
[email protected]420ae012009-04-24 05:16:322207bool TabContents::CanBlur() const {
2208 return delegate() ? delegate()->CanBlur() : true;
2209}
2210
2211gfx::Rect TabContents::GetRootWindowResizerRect() const {
2212 if (delegate())
2213 return delegate()->GetRootWindowResizerRect();
2214 return gfx::Rect();
2215}
2216
2217void TabContents::RendererUnresponsive(RenderViewHost* rvh,
2218 bool is_during_unload) {
2219 if (is_during_unload) {
2220 // Hang occurred while firing the beforeunload/unload handler.
2221 // Pretend the handler fired so tab closing continues as if it had.
[email protected]829e7612009-04-25 01:15:112222 rvh->set_sudden_termination_allowed(true);
[email protected]420ae012009-04-24 05:16:322223
2224 if (!render_manager_.ShouldCloseTabOnUnresponsiveRenderer())
2225 return;
2226
2227 // If the tab hangs in the beforeunload/unload handler there's really
2228 // nothing we can do to recover. Pretend the unload listeners have
2229 // all fired and close the tab. If the hang is in the beforeunload handler
2230 // then the user will not have the option of cancelling the close.
2231 Close(rvh);
2232 return;
2233 }
2234
2235 if (render_view_host() && render_view_host()->IsRenderViewLive())
[email protected]d82ed61e2009-06-16 02:46:222236 HungRendererDialog::ShowForTabContents(this);
[email protected]420ae012009-04-24 05:16:322237}
2238
2239void TabContents::RendererResponsive(RenderViewHost* render_view_host) {
[email protected]d82ed61e2009-06-16 02:46:222240 HungRendererDialog::HideForTabContents(this);
[email protected]420ae012009-04-24 05:16:322241}
2242
2243void TabContents::LoadStateChanged(const GURL& url,
2244 net::LoadState load_state) {
2245 load_state_ = load_state;
[email protected]d686e812009-06-03 19:10:292246 std::wstring languages =
2247 profile()->GetPrefs()->GetString(prefs::kAcceptLanguages);
2248 load_state_host_.clear();
2249 std::string host = url.host();
2250 net::IDNToUnicode(host.c_str(), host.size(), languages, &load_state_host_);
[email protected]420ae012009-04-24 05:16:322251 if (load_state_ == net::LOAD_STATE_READING_RESPONSE)
2252 SetNotWaitingForResponse();
2253 if (is_loading())
[email protected]c9cd2222009-05-06 05:16:502254 NotifyNavigationStateChanged(INVALIDATE_LOAD | INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:322255}
2256
[email protected]1ee614862009-07-06 20:29:182257bool TabContents::IsExternalTabContainer() const {
2258 if (!delegate())
2259 return false;
2260
2261 return delegate()->IsExternalTabContainer();
2262}
2263
[email protected]1ee614862009-07-06 20:29:182264void TabContents::DidInsertCSS() {
2265 // This RVHDelegate function is used for extensions and not us.
[email protected]420ae012009-04-24 05:16:322266}
2267
2268void TabContents::FileSelected(const FilePath& path,
2269 int index, void* params) {
2270 render_view_host()->FileSelected(path);
2271}
2272
2273void TabContents::MultiFilesSelected(const std::vector<FilePath>& files,
2274 void* params) {
2275 render_view_host()->MultiFilesSelected(files);
2276}
2277
2278void TabContents::FileSelectionCanceled(void* params) {
2279 // If the user cancels choosing a file to upload we pass back an
2280 // empty vector.
2281 render_view_host()->MultiFilesSelected(std::vector<FilePath>());
2282}
2283
2284void TabContents::BeforeUnloadFiredFromRenderManager(
2285 bool proceed,
2286 bool* proceed_to_fire_unload) {
2287 if (delegate())
2288 delegate()->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
2289}
2290
2291void TabContents::UpdateRenderViewSizeForRenderManager() {
2292 // TODO(brettw) this is a hack. See TabContentsView::SizeContents.
2293 view_->SizeContents(view_->GetContainerSize());
2294}
2295
2296DOMUI* TabContents::CreateDOMUIForRenderManager(const GURL& url) {
[email protected]d82ed61e2009-06-16 02:46:222297 return DOMUIFactory::CreateDOMUIForURL(this, url);
[email protected]420ae012009-04-24 05:16:322298}
2299
2300NavigationEntry*
2301TabContents::GetLastCommittedNavigationEntryForRenderManager() {
2302 return controller_.GetLastCommittedEntry();
2303}
2304
2305bool TabContents::CreateRenderViewForRenderManager(
2306 RenderViewHost* render_view_host) {
[email protected]811bfe32009-07-01 08:46:252307 // If the pending navigation is to a DOMUI, tell the RenderView about any
2308 // bindings it will need enabled.
[email protected]420ae012009-04-24 05:16:322309 if (render_manager_.pending_dom_ui())
[email protected]811bfe32009-07-01 08:46:252310 render_view_host->AllowBindings(
2311 render_manager_.pending_dom_ui()->bindings());
[email protected]1adff062009-06-02 18:39:552312
[email protected]420ae012009-04-24 05:16:322313 RenderWidgetHostView* rwh_view = view_->CreateViewForWidget(render_view_host);
2314 if (!render_view_host->CreateRenderView())
2315 return false;
2316
2317 // Now that the RenderView has been created, we need to tell it its size.
2318 rwh_view->SetSize(view_->GetContainerSize());
2319
2320 UpdateMaxPageIDIfNecessary(render_view_host->site_instance(),
2321 render_view_host);
2322 return true;
2323}
2324
2325void TabContents::Observe(NotificationType type,
2326 const NotificationSource& source,
2327 const NotificationDetails& details) {
2328 switch (type.value) {
2329 case NotificationType::BOOKMARK_MODEL_LOADED:
2330 // BookmarkModel finished loading, fall through to update starred state.
2331 case NotificationType::URLS_STARRED: {
2332 // Somewhere, a URL has been starred.
2333 // Ignore notifications for profiles other than our current one.
2334 Profile* source_profile = Source<Profile>(source).ptr();
2335 if (!source_profile || !source_profile->IsSameProfile(profile()))
2336 return;
2337
2338 UpdateStarredStateForCurrentURL();
2339 break;
2340 }
2341 case NotificationType::PREF_CHANGED: {
2342 std::wstring* pref_name_in = Details<std::wstring>(details).ptr();
2343 DCHECK(Source<PrefService>(source).ptr() == profile()->GetPrefs());
2344 if (*pref_name_in == prefs::kAlternateErrorPagesEnabled) {
2345 UpdateAlternateErrorPageURL();
2346 } else if (*pref_name_in == prefs::kDefaultCharset ||
2347 StartsWithASCII(WideToUTF8(*pref_name_in), "webkit.webprefs.", true)
2348 ) {
2349 UpdateWebPreferences();
2350 } else {
2351 NOTREACHED() << "unexpected pref change notification" << *pref_name_in;
2352 }
2353 break;
2354 }
2355 case NotificationType::RENDER_WIDGET_HOST_DESTROYED:
2356 view_->RenderWidgetHostDestroyed(Source<RenderWidgetHost>(source).ptr());
2357 break;
2358
2359 case NotificationType::NAV_ENTRY_COMMITTED: {
2360 DCHECK(&controller_ == Source<NavigationController>(source).ptr());
2361
2362 NavigationController::LoadCommittedDetails& committed_details =
2363 *(Details<NavigationController::LoadCommittedDetails>(details).ptr());
2364 ExpireInfoBars(committed_details);
2365 break;
2366 }
2367
2368 default:
2369 NOTREACHED();
2370 }
2371}