blob: e0b57daa5e375bf4db2dfbdb56bfeff6ec926a22 [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
[email protected]420ae012009-04-24 05:16:32152// Returns true if the entry's transition type is FORM_SUBMIT.
153bool IsFormSubmit(const NavigationEntry* entry) {
154 return (PageTransition::StripQualifier(entry->transition_type()) ==
155 PageTransition::FORM_SUBMIT);
156}
157
158#if defined(OS_WIN)
159
160BOOL CALLBACK InvalidateWindow(HWND hwnd, LPARAM lparam) {
161 // Note: erase is required to properly paint some widgets borders. This can
162 // be seen with textfields.
163 InvalidateRect(hwnd, NULL, TRUE);
164 return TRUE;
165}
166#endif
167
[email protected]056de2d2009-06-26 16:41:34168void MakeNavigateParams(const NavigationEntry& entry, bool reload,
169 ViewMsg_Navigate_Params* params) {
170 params->page_id = entry.page_id();
171 params->url = entry.url();
172 params->referrer = entry.referrer();
173 params->transition = entry.transition_type();
174 params->state = entry.content_state();
175 params->reload = reload;
176 params->request_time = base::Time::Now();
177}
178
[email protected]420ae012009-04-24 05:16:32179} // namespace
180
181// -----------------------------------------------------------------------------
182
[email protected]fdd61c62009-04-22 19:22:57183// static
184int TabContents::find_request_id_counter_ = -1;
185
[email protected]420ae012009-04-24 05:16:32186class TabContents::GearsCreateShortcutCallbackFunctor {
187 public:
188 explicit GearsCreateShortcutCallbackFunctor(TabContents* contents)
189 : contents_(contents) {}
190
191 void Run(const GearsShortcutData2& shortcut_data, bool success) {
192 if (contents_)
193 contents_->OnGearsCreateShortcutDone(shortcut_data, success);
194 delete this;
195 }
196 void Cancel() {
197 contents_ = NULL;
198 }
199
200 private:
201 TabContents* contents_;
202};
203
[email protected]420ae012009-04-24 05:16:32204TabContents::TabContents(Profile* profile,
205 SiteInstance* site_instance,
206 int routing_id,
207 base::WaitableEvent* modal_dialog_event)
[email protected]b680ad22009-04-15 23:19:42208 : delegate_(NULL),
[email protected]66ba4932009-06-04 19:22:13209 ALLOW_THIS_IN_INITIALIZER_LIST(controller_(this, profile)),
210 ALLOW_THIS_IN_INITIALIZER_LIST(view_(
[email protected]d82ed61e2009-06-16 02:46:22211 TabContentsView::Create(this))),
212 ALLOW_THIS_IN_INITIALIZER_LIST(render_manager_(this, this)),
[email protected]fdd61c62009-04-22 19:22:57213 property_bag_(),
214 registrar_(),
[email protected]d82ed61e2009-06-16 02:46:22215 ALLOW_THIS_IN_INITIALIZER_LIST(printing_(*this)),
[email protected]fdd61c62009-04-22 19:22:57216 save_package_(),
217 cancelable_consumer_(),
218 autofill_manager_(),
219 password_manager_(),
220 plugin_installer_(),
[email protected]d82ed61e2009-06-16 02:46:22221 ALLOW_THIS_IN_INITIALIZER_LIST(fav_icon_helper_(this)),
[email protected]fdd61c62009-04-22 19:22:57222 select_file_dialog_(),
223 pending_install_(),
[email protected]d5f942ba2008-09-26 19:30:34224 is_loading_(false),
initial.commit09911bf2008-07-26 23:55:29225 is_crashed_(false),
[email protected]d5f942ba2008-09-26 19:30:34226 waiting_for_response_(false),
[email protected]d5f942ba2008-09-26 19:30:34227 max_page_id_(-1),
[email protected]fdd61c62009-04-22 19:22:57228 current_load_start_(),
229 load_state_(net::LOAD_STATE_IDLE),
230 load_state_host_(),
231 received_page_title_(false),
232 is_starred_(false),
233 contents_mime_type_(),
234 encoding_(),
[email protected]332af7732009-03-11 13:21:35235 blocked_popups_(NULL),
[email protected]fdd61c62009-04-22 19:22:57236 infobar_delegates_(),
[email protected]fdd61c62009-04-22 19:22:57237 find_ui_active_(false),
238 find_op_aborted_(false),
239 current_find_request_id_(find_request_id_counter_++),
240 find_text_(),
[email protected]e491f1c2009-05-22 20:28:12241 last_search_case_sensitive_(false),
242 last_search_prepopulate_text_(NULL),
243 last_search_result_(),
[email protected]fdd61c62009-04-22 19:22:57244 capturing_contents_(false),
245 is_being_destroyed_(false),
246 notify_disconnection_(false),
247 history_requests_(),
248#if defined(OS_WIN)
249 message_box_active_(CreateEvent(NULL, TRUE, FALSE, NULL)),
250#endif
251 last_javascript_message_dismissal_(),
252 suppress_javascript_messages_(false) {
[email protected]420ae012009-04-24 05:16:32253 pending_install_.page_id = 0;
254 pending_install_.callback_functor = NULL;
255
[email protected]16779842009-07-08 23:45:29256#if defined(OS_CHROMEOS)
[email protected]58dca552009-06-17 00:35:02257 // Make sure the thumbnailer is started before starting the render manager.
258 // The thumbnailer will want to listen for RVH creations, one of which will
259 // happen in RVHManager::Init.
260 ThumbnailGenerator* generator = g_browser_process->GetThumbnailGenerator();
261 if (generator)
262 generator->StartThumbnailing();
263#endif
264
[email protected]420ae012009-04-24 05:16:32265 render_manager_.Init(profile, site_instance, routing_id, modal_dialog_event);
266
267 view_->CreateView();
268
269 // Register for notifications about all interested prefs change.
270 PrefService* prefs = profile->GetPrefs();
271 if (prefs) {
272 for (int i = 0; i < kPrefsToObserveLength; ++i)
273 prefs->AddPrefObserver(kPrefsToObserve[i], this);
274 }
275
276 // Register for notifications about URL starredness changing on any profile.
277 registrar_.Add(this, NotificationType::URLS_STARRED,
278 NotificationService::AllSources());
279 registrar_.Add(this, NotificationType::BOOKMARK_MODEL_LOADED,
280 NotificationService::AllSources());
281 registrar_.Add(this, NotificationType::RENDER_WIDGET_HOST_DESTROYED,
282 NotificationService::AllSources());
283
284 // Keep a global copy of the previous search string (if any).
285 static string16 global_last_search = string16();
[email protected]e491f1c2009-05-22 20:28:12286 last_search_prepopulate_text_ = &global_last_search;
[email protected]332af7732009-03-11 13:21:35287}
initial.commit09911bf2008-07-26 23:55:29288
289TabContents::~TabContents() {
[email protected]420ae012009-04-24 05:16:32290 is_being_destroyed_ = true;
291
292 // We don't want any notifications while we're runnign our destructor.
293 registrar_.RemoveAll();
294
295 // Unregister the notifications of all observed prefs change.
296 PrefService* prefs = profile()->GetPrefs();
297 if (prefs) {
298 for (int i = 0; i < kPrefsToObserveLength; ++i)
299 prefs->RemovePrefObserver(kPrefsToObserve[i], this);
300 }
301
302 // Clean up subwindows like plugins and the find in page bar.
303 view_->OnContentsDestroy();
304
305 NotifyDisconnected();
[email protected]d82ed61e2009-06-16 02:46:22306 HungRendererDialog::HideForTabContents(this);
[email protected]420ae012009-04-24 05:16:32307
308 if (pending_install_.callback_functor)
309 pending_install_.callback_functor->Cancel();
310
311 // First cleanly close all child windows.
312 // TODO(mpcomplete): handle case if MaybeCloseChildWindows() already asked
313 // some of these to close. CloseWindows is async, so it might get called
314 // twice before it runs.
315 int size = static_cast<int>(child_windows_.size());
316 for (int i = size - 1; i >= 0; --i) {
317 ConstrainedWindow* window = child_windows_[i];
318 if (window)
319 window->CloseConstrainedWindow();
320 }
321
[email protected]66ba4932009-06-04 19:22:13322 if (blocked_popups_)
323 blocked_popups_->Destroy();
324
[email protected]420ae012009-04-24 05:16:32325 // Notify any observer that have a reference on this tab contents.
326 NotificationService::current()->Notify(
327 NotificationType::TAB_CONTENTS_DESTROYED,
328 Source<TabContents>(this),
329 NotificationService::NoDetails());
330
[email protected]1e5e74f2009-05-27 20:55:12331 // Notify any lasting InfobarDelegates that have not yet been removed that
332 // whatever infobar they were handling in this TabContents has closed,
333 // because the TabContents is going away entirely.
334 // This must happen after the TAB_CONTENTS_DESTROYED notification as the
335 // notification may trigger infobars calls that access their delegate. (and
336 // some implementations of InfoBarDelegate do delete themselves on
337 // InfoBarClosed()).
338 for (int i = 0; i < infobar_delegate_count(); ++i) {
339 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
340 delegate->InfoBarClosed();
341 }
342 infobar_delegates_.clear();
343
[email protected]420ae012009-04-24 05:16:32344 // TODO(brettw) this should be moved to the view.
345#if defined(OS_WIN)
346 // If we still have a window handle, destroy it. GetNativeView can return
347 // NULL if this contents was part of a window that closed.
348 if (GetNativeView())
349 ::DestroyWindow(GetNativeView());
350#endif
initial.commit09911bf2008-07-26 23:55:29351}
352
[email protected]d5f942ba2008-09-26 19:30:34353// static
354void TabContents::RegisterUserPrefs(PrefService* prefs) {
[email protected]420ae012009-04-24 05:16:32355 prefs->RegisterBooleanPref(prefs::kAlternateErrorPagesEnabled, true);
356
357 WebPreferences pref_defaults;
358 prefs->RegisterBooleanPref(prefs::kWebKitJavascriptEnabled,
359 pref_defaults.javascript_enabled);
360 prefs->RegisterBooleanPref(prefs::kWebKitWebSecurityEnabled,
361 pref_defaults.web_security_enabled);
362 prefs->RegisterBooleanPref(
363 prefs::kWebKitJavascriptCanOpenWindowsAutomatically, true);
364 prefs->RegisterBooleanPref(prefs::kWebKitLoadsImagesAutomatically,
365 pref_defaults.loads_images_automatically);
366 prefs->RegisterBooleanPref(prefs::kWebKitPluginsEnabled,
367 pref_defaults.plugins_enabled);
368 prefs->RegisterBooleanPref(prefs::kWebKitDomPasteEnabled,
369 pref_defaults.dom_paste_enabled);
370 prefs->RegisterBooleanPref(prefs::kWebKitShrinksStandaloneImagesToFit,
371 pref_defaults.shrinks_standalone_images_to_fit);
[email protected]0df30122009-06-03 12:13:08372 prefs->RegisterStringPref(prefs::kWebKitInspectorSettings,
373 pref_defaults.inspector_settings);
[email protected]420ae012009-04-24 05:16:32374 prefs->RegisterBooleanPref(prefs::kWebKitTextAreasAreResizable,
375 pref_defaults.text_areas_are_resizable);
376 prefs->RegisterBooleanPref(prefs::kWebKitJavaEnabled,
377 pref_defaults.java_enabled);
378
379 prefs->RegisterLocalizedStringPref(prefs::kAcceptLanguages,
380 IDS_ACCEPT_LANGUAGES);
381 prefs->RegisterLocalizedStringPref(prefs::kDefaultCharset,
382 IDS_DEFAULT_ENCODING);
383 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitStandardFontIsSerif,
384 IDS_STANDARD_FONT_IS_SERIF);
385 prefs->RegisterLocalizedStringPref(prefs::kWebKitFixedFontFamily,
386 IDS_FIXED_FONT_FAMILY);
387 prefs->RegisterLocalizedStringPref(prefs::kWebKitSerifFontFamily,
388 IDS_SERIF_FONT_FAMILY);
389 prefs->RegisterLocalizedStringPref(prefs::kWebKitSansSerifFontFamily,
390 IDS_SANS_SERIF_FONT_FAMILY);
391 prefs->RegisterLocalizedStringPref(prefs::kWebKitCursiveFontFamily,
392 IDS_CURSIVE_FONT_FAMILY);
393 prefs->RegisterLocalizedStringPref(prefs::kWebKitFantasyFontFamily,
394 IDS_FANTASY_FONT_FAMILY);
395 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFontSize,
396 IDS_DEFAULT_FONT_SIZE);
397 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFixedFontSize,
398 IDS_DEFAULT_FIXED_FONT_SIZE);
399 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumFontSize,
400 IDS_MINIMUM_FONT_SIZE);
401 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumLogicalFontSize,
402 IDS_MINIMUM_LOGICAL_FONT_SIZE);
403 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitUsesUniversalDetector,
404 IDS_USES_UNIVERSAL_DETECTOR);
405 prefs->RegisterLocalizedStringPref(prefs::kStaticEncodings,
406 IDS_STATIC_ENCODING_LIST);
initial.commit09911bf2008-07-26 23:55:29407}
408
[email protected]13367f72009-07-08 16:39:02409// Returns true if contains content rendered by an extension.
410bool TabContents::HostsExtension() const {
411 return GetURL().SchemeIs(chrome::kExtensionScheme);
[email protected]d5f942ba2008-09-26 19:30:34412}
413
[email protected]6e95706d2009-04-23 22:55:01414PasswordManager* TabContents::GetPasswordManager() {
415 if (password_manager_.get() == NULL)
416 password_manager_.reset(new PasswordManager(this));
417 return password_manager_.get();
418}
419
420PluginInstaller* TabContents::GetPluginInstaller() {
421 if (plugin_installer_.get() == NULL)
422 plugin_installer_.reset(new PluginInstaller(this));
423 return plugin_installer_.get();
424}
425
[email protected]d5f942ba2008-09-26 19:30:34426const GURL& TabContents::GetURL() const {
427 // We may not have a navigation entry yet
[email protected]ce3fa3c2009-04-20 19:55:57428 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34429 return entry ? entry->display_url() : GURL::EmptyGURL();
430}
431
[email protected]96d185d2009-04-24 03:28:54432const string16& TabContents::GetTitle() const {
[email protected]4c6092c5b2009-06-06 00:23:55433 // Transient entries take precedence. They are used for interstitial pages
434 // that are shown on top of existing pages.
435 NavigationEntry* entry = controller_.GetTransientEntry();
436 if (entry)
437 return entry->GetTitleForDisplay(&controller_);
438
[email protected]96d185d2009-04-24 03:28:54439 DOMUI* our_dom_ui = render_manager_.pending_dom_ui() ?
440 render_manager_.pending_dom_ui() : render_manager_.dom_ui();
441 if (our_dom_ui) {
442 // Don't override the title in view source mode.
[email protected]4c6092c5b2009-06-06 00:23:55443 entry = controller_.GetActiveEntry();
[email protected]96d185d2009-04-24 03:28:54444 if (!(entry && entry->IsViewSourceMode())) {
445 // Give the DOM UI the chance to override our title.
446 const string16& title = our_dom_ui->overridden_title();
447 if (!title.empty())
448 return title;
449 }
450 }
451
452 // We use the title for the last committed entry rather than a pending
453 // navigation entry. For example, when the user types in a URL, we want to
454 // keep the old page's title until the new load has committed and we get a new
455 // title.
[email protected]96d185d2009-04-24 03:28:54456 entry = controller_.GetLastCommittedEntry();
457 if (entry)
458 return entry->GetTitleForDisplay(&controller_);
459 else if (controller_.LoadingURLLazily())
460 return controller_.GetLazyTitle();
461 return EmptyString16();
462}
463
[email protected]d5f942ba2008-09-26 19:30:34464int32 TabContents::GetMaxPageID() {
465 if (GetSiteInstance())
466 return GetSiteInstance()->max_page_id();
467 else
468 return max_page_id_;
469}
470
471void TabContents::UpdateMaxPageID(int32 page_id) {
472 // Ensure both the SiteInstance and RenderProcessHost update their max page
[email protected]57c6a652009-05-04 07:58:34473 // IDs in sync. Only TabContents will also have site instances, except during
[email protected]d5f942ba2008-09-26 19:30:34474 // testing.
475 if (GetSiteInstance())
476 GetSiteInstance()->UpdateMaxPageID(page_id);
[email protected]57c6a652009-05-04 07:58:34477 process()->UpdateMaxPageID(page_id);
[email protected]d5f942ba2008-09-26 19:30:34478}
479
[email protected]96d185d2009-04-24 03:28:54480SiteInstance* TabContents::GetSiteInstance() const {
481 return render_manager_.current_host()->site_instance();
482}
483
[email protected]d5f942ba2008-09-26 19:30:34484const std::wstring TabContents::GetDefaultTitle() const {
485 return l10n_util::GetString(IDS_DEFAULT_TAB_TITLE);
486}
487
[email protected]96d185d2009-04-24 03:28:54488bool TabContents::ShouldDisplayURL() {
489 // Don't hide the url in view source mode.
490 NavigationEntry* entry = controller_.GetActiveEntry();
491 if (entry && entry->IsViewSourceMode())
492 return true;
[email protected]83e3895b2009-06-11 00:07:16493
[email protected]96d185d2009-04-24 03:28:54494 DOMUI* dom_ui = GetDOMUIForCurrentState();
495 if (dom_ui)
496 return !dom_ui->should_hide_url();
497 return true;
498}
499
[email protected]d5f942ba2008-09-26 19:30:34500SkBitmap TabContents::GetFavIcon() const {
501 // Like GetTitle(), we also want to use the favicon for the last committed
502 // entry rather than a pending navigation entry.
[email protected]ce3fa3c2009-04-20 19:55:57503 NavigationEntry* entry = controller_.GetTransientEntry();
[email protected]cbab76d2008-10-13 22:42:47504 if (entry)
505 return entry->favicon().bitmap();
506
[email protected]ce3fa3c2009-04-20 19:55:57507 entry = controller_.GetLastCommittedEntry();
[email protected]d5f942ba2008-09-26 19:30:34508 if (entry)
509 return entry->favicon().bitmap();
[email protected]ce3fa3c2009-04-20 19:55:57510 else if (controller_.LoadingURLLazily())
511 return controller_.GetLazyFavIcon();
[email protected]d5f942ba2008-09-26 19:30:34512 return SkBitmap();
513}
514
[email protected]96d185d2009-04-24 03:28:54515bool TabContents::ShouldDisplayFavIcon() {
516 // Always display a throbber during pending loads.
517 if (controller_.GetLastCommittedEntry() && controller_.pending_entry())
518 return true;
519
520 DOMUI* dom_ui = GetDOMUIForCurrentState();
521 if (dom_ui)
522 return !dom_ui->hide_favicon();
523 return true;
524}
525
[email protected]96d185d2009-04-24 03:28:54526std::wstring TabContents::GetStatusText() const {
527 if (!is_loading() || load_state_ == net::LOAD_STATE_IDLE)
528 return std::wstring();
529
530 switch (load_state_) {
531 case net::LOAD_STATE_WAITING_FOR_CACHE:
532 return l10n_util::GetString(IDS_LOAD_STATE_WAITING_FOR_CACHE);
533 case net::LOAD_STATE_RESOLVING_PROXY_FOR_URL:
534 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_PROXY_FOR_URL);
535 case net::LOAD_STATE_RESOLVING_HOST:
536 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_HOST);
537 case net::LOAD_STATE_CONNECTING:
538 return l10n_util::GetString(IDS_LOAD_STATE_CONNECTING);
539 case net::LOAD_STATE_SENDING_REQUEST:
540 return l10n_util::GetString(IDS_LOAD_STATE_SENDING_REQUEST);
541 case net::LOAD_STATE_WAITING_FOR_RESPONSE:
542 return l10n_util::GetStringF(IDS_LOAD_STATE_WAITING_FOR_RESPONSE,
543 load_state_host_);
544 // Ignore net::LOAD_STATE_READING_RESPONSE and net::LOAD_STATE_IDLE
545 case net::LOAD_STATE_IDLE:
546 case net::LOAD_STATE_READING_RESPONSE:
547 break;
548 }
549
550 return std::wstring();
551}
552
[email protected]d5f942ba2008-09-26 19:30:34553void TabContents::SetIsCrashed(bool state) {
554 if (state == is_crashed_)
555 return;
556
557 is_crashed_ = state;
[email protected]c9cd2222009-05-06 05:16:50558 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]d5f942ba2008-09-26 19:30:34559}
560
[email protected]f9b1a7b2009-06-22 17:26:38561void TabContents::SetPageActionEnabled(const PageAction* page_action,
[email protected]d7eaf572009-07-01 21:57:00562 bool enable,
563 const std::string& title,
564 int icon_id) {
[email protected]ce5c4502009-05-06 16:46:11565 DCHECK(page_action);
566
[email protected]d7eaf572009-07-01 21:57:00567 if (!enable &&
568 enabled_page_actions_.end() == enabled_page_actions_.find(page_action)) {
569 return; // Don't need to disable twice.
570 }
[email protected]ce5c4502009-05-06 16:46:11571
[email protected]d7eaf572009-07-01 21:57:00572 if (enable) {
573 enabled_page_actions_[page_action].reset(
574 new PageActionState(title, icon_id));
575 } else {
[email protected]f9b1a7b2009-06-22 17:26:38576 enabled_page_actions_.erase(page_action);
[email protected]d7eaf572009-07-01 21:57:00577 }
[email protected]ce5c4502009-05-06 16:46:11578}
579
[email protected]d7eaf572009-07-01 21:57:00580const PageActionState* TabContents::GetPageActionState(
581 const PageAction* page_action) {
582 if (enabled_page_actions_.end() == enabled_page_actions_.find(page_action))
583 return NULL;
[email protected]ce5c4502009-05-06 16:46:11584
[email protected]d7eaf572009-07-01 21:57:00585 return enabled_page_actions_[page_action].get();
586}
[email protected]ce5c4502009-05-06 16:46:11587
[email protected]d5f942ba2008-09-26 19:30:34588void TabContents::NotifyNavigationStateChanged(unsigned changed_flags) {
589 if (delegate_)
590 delegate_->NavigationStateChanged(this, changed_flags);
591}
592
[email protected]96d185d2009-04-24 03:28:54593void TabContents::DidBecomeSelected() {
594 controller_.SetActive(true);
595
596 if (render_widget_host_view())
597 render_widget_host_view()->DidBecomeSelected();
598
599 // If pid() is -1, that means the RenderProcessHost still hasn't been
600 // initialized. It'll register with CacheManagerHost when it is.
601 if (process()->pid() != -1)
602 WebCacheManager::GetInstance()->ObserveActivity(process()->pid());
603}
604
605void TabContents::WasHidden() {
606 if (!capturing_contents()) {
607 // |render_view_host()| can be NULL if the user middle clicks a link to open
608 // a tab in then background, then closes the tab before selecting it. This
609 // is because closing the tab calls TabContents::Destroy(), which removes
610 // the |render_view_host()|; then when we actually destroy the window,
611 // OnWindowPosChanged() notices and calls HideContents() (which calls us).
612 if (render_widget_host_view())
613 render_widget_host_view()->WasHidden();
[email protected]96d185d2009-04-24 03:28:54614 }
615
616 NotificationService::current()->Notify(
617 NotificationType::TAB_CONTENTS_HIDDEN,
618 Source<TabContents>(this),
619 NotificationService::NoDetails());
620}
621
[email protected]d5f942ba2008-09-26 19:30:34622void TabContents::Activate() {
623 if (delegate_)
624 delegate_->ActivateContents(this);
625}
626
[email protected]96d185d2009-04-24 03:28:54627void TabContents::ShowContents() {
628 if (render_widget_host_view())
629 render_widget_host_view()->DidBecomeSelected();
[email protected]96d185d2009-04-24 03:28:54630}
631
632void TabContents::HideContents() {
633 // TODO(pkasting): http://b/1239839 Right now we purposefully don't call
634 // our superclass HideContents(), because some callers want to be very picky
635 // about the order in which these get called. In addition to making the code
636 // here practically impossible to understand, this also means we end up
637 // calling TabContents::WasHidden() twice if callers call both versions of
[email protected]57c6a652009-05-04 07:58:34638 // HideContents() on a TabContents.
[email protected]96d185d2009-04-24 03:28:54639 WasHidden();
640}
641
[email protected]c0588052008-10-27 23:01:50642void TabContents::OpenURL(const GURL& url, const GURL& referrer,
[email protected]d5f942ba2008-09-26 19:30:34643 WindowOpenDisposition disposition,
644 PageTransition::Type transition) {
645 if (delegate_)
[email protected]c0588052008-10-27 23:01:50646 delegate_->OpenURLFromTab(this, url, referrer, disposition, transition);
[email protected]d5f942ba2008-09-26 19:30:34647}
648
649bool TabContents::NavigateToPendingEntry(bool reload) {
[email protected]96d185d2009-04-24 03:28:54650 const NavigationEntry& entry = *controller_.pending_entry();
651
652 RenderViewHost* dest_render_view_host = render_manager_.Navigate(entry);
653 if (!dest_render_view_host)
654 return false; // Unable to create the desired render view host.
655
656 // Tell DevTools agent that it is attached prior to the navigation.
[email protected]d9f9b792009-06-24 13:17:12657 DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
[email protected]7e8e6b62009-05-08 11:28:32658 if (devtools_manager) { // NULL in unit tests.
[email protected]684b4ba22009-05-07 06:27:41659 devtools_manager->OnNavigatingToPendingEntry(
660 render_view_host(),
661 dest_render_view_host,
662 controller_.pending_entry()->url());
[email protected]7e8e6b62009-05-08 11:28:32663 }
[email protected]96d185d2009-04-24 03:28:54664
665 // Used for page load time metrics.
666 current_load_start_ = base::TimeTicks::Now();
667
668 // Navigate in the desired RenderViewHost.
[email protected]056de2d2009-06-26 16:41:34669 ViewMsg_Navigate_Params navigate_params;
670 MakeNavigateParams(entry, reload, &navigate_params);
671 dest_render_view_host->Navigate(navigate_params);
[email protected]96d185d2009-04-24 03:28:54672
673 if (entry.page_id() == -1) {
674 // HACK!! This code suppresses javascript: URLs from being added to
675 // session history, which is what we want to do for javascript: URLs that
676 // do not generate content. What we really need is a message from the
677 // renderer telling us that a new page was not created. The same message
678 // could be used for mailto: URLs and the like.
679 if (entry.url().SchemeIs(chrome::kJavaScriptScheme))
680 return false;
681 }
682
683 // Clear any provisional password saves - this stops password infobars
684 // showing up on pages the user navigates to while the right page is
685 // loading.
686 GetPasswordManager()->ClearProvisionalSave();
687
688 if (reload && !profile()->IsOffTheRecord()) {
689 HistoryService* history =
690 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
691 if (history)
692 history->SetFavIconOutOfDateForPage(entry.url());
693 }
694
[email protected]d5f942ba2008-09-26 19:30:34695 return true;
696}
697
[email protected]96d185d2009-04-24 03:28:54698void TabContents::Stop() {
699 render_manager_.Stop();
700 printing_.Stop();
701}
702
703void TabContents::Cut() {
704 render_view_host()->Cut();
705}
706
707void TabContents::Copy() {
708 render_view_host()->Copy();
709}
710
711void TabContents::Paste() {
712 render_view_host()->Paste();
713}
714
715void TabContents::DisassociateFromPopupCount() {
716 render_view_host()->DisassociateFromPopupCount();
717}
718
719TabContents* TabContents::Clone() {
720 // We create a new SiteInstance so that the new tab won't share processes
721 // with the old one. This can be changed in the future if we need it to share
722 // processes for some reason.
[email protected]420ae012009-04-24 05:16:32723 TabContents* tc = new TabContents(profile(),
[email protected]96d185d2009-04-24 03:28:54724 SiteInstance::CreateSiteInstance(profile()),
725 MSG_ROUTING_NONE, NULL);
726 tc->controller().CopyStateFrom(controller_);
727 return tc;
728}
729
[email protected]420ae012009-04-24 05:16:32730void TabContents::CreateShortcut() {
731 NavigationEntry* entry = controller_.GetLastCommittedEntry();
732 if (!entry)
733 return;
734
735 // We only allow one pending install request. By resetting the page id we
736 // effectively cancel the pending install request.
737 pending_install_.page_id = entry->page_id();
738 pending_install_.icon = GetFavIcon();
739 pending_install_.title = UTF16ToWideHack(GetTitle());
740 pending_install_.url = GetURL();
741 if (pending_install_.callback_functor) {
742 pending_install_.callback_functor->Cancel();
743 pending_install_.callback_functor = NULL;
744 }
745 DCHECK(!pending_install_.icon.isNull()) << "Menu item should be disabled.";
746 if (pending_install_.title.empty())
747 pending_install_.title = UTF8ToWide(GetURL().spec());
748
749 // Request the application info. When done OnDidGetApplicationInfo is invoked
750 // and we'll create the shortcut.
751 render_view_host()->GetApplicationInfo(pending_install_.page_id);
752}
753
[email protected]4d677202009-07-19 07:37:12754void TabContents::ShowPageInfo(const GURL& url,
755 const NavigationEntry::SSLStatus& ssl,
756 bool show_history) {
757 if (!delegate_)
758 return;
759
[email protected]bb678332009-07-21 00:15:50760 delegate_->ShowPageInfo(profile(), url, ssl, show_history);
[email protected]4d677202009-07-19 07:37:12761}
762
[email protected]e8382172009-06-19 22:16:28763#if defined(OS_WIN) || defined(OS_LINUX)
initial.commit09911bf2008-07-26 23:55:29764ConstrainedWindow* TabContents::CreateConstrainedDialog(
[email protected]e8382172009-06-19 22:16:28765 ConstrainedWindowDelegate* delegate) {
initial.commit09911bf2008-07-26 23:55:29766 ConstrainedWindow* window =
[email protected]e8382172009-06-19 22:16:28767 ConstrainedWindow::CreateConstrainedDialog(this, delegate);
initial.commit09911bf2008-07-26 23:55:29768 child_windows_.push_back(window);
769 return window;
770}
[email protected]f3332e12009-03-23 15:28:57771#endif
initial.commit09911bf2008-07-26 23:55:29772
773void TabContents::AddNewContents(TabContents* new_contents,
774 WindowOpenDisposition disposition,
775 const gfx::Rect& initial_pos,
[email protected]c88a70fe2009-05-05 20:00:22776 bool user_gesture,
777 const GURL& creator_url) {
initial.commit09911bf2008-07-26 23:55:29778 if (!delegate_)
779 return;
780
[email protected]35f7d212009-04-29 21:19:27781 if ((disposition == NEW_POPUP) && !user_gesture &&
782 !CommandLine::ForCurrentProcess()->HasSwitch(
783 switches::kDisablePopupBlocking)) {
[email protected]2c4410d2009-05-06 23:46:22784 // Unrequested popups from normal pages are constrained unless they're in
[email protected]b6c874582009-05-08 19:38:31785 // the whitelist. The popup owner will handle checking this.
786 delegate_->GetConstrainingContents(this)->AddPopup(new_contents,
787 initial_pos,
788 creator_url.is_valid() ? creator_url.host() : std::string());
789 } else {
[email protected]0aa55312008-10-17 21:53:08790 new_contents->DisassociateFromPopupCount();
initial.commit09911bf2008-07-26 23:55:29791 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
792 user_gesture);
793 }
[email protected]b6c874582009-05-08 19:38:31794 PopupNotificationVisibilityChanged(ShowingBlockedPopupNotification());
initial.commit09911bf2008-07-26 23:55:29795}
796
initial.commit09911bf2008-07-26 23:55:29797void TabContents::CloseAllSuppressedPopups() {
[email protected]d6598c052008-11-05 19:03:25798 if (blocked_popups_)
[email protected]2c4410d2009-05-06 23:46:22799 blocked_popups_->CloseAll();
initial.commit09911bf2008-07-26 23:55:29800}
801
[email protected]96d185d2009-04-24 03:28:54802void TabContents::PopupNotificationVisibilityChanged(bool visible) {
803 render_view_host()->PopupNotificationVisibilityChanged(visible);
804}
805
806gfx::NativeView TabContents::GetContentNativeView() {
807 return view_->GetContentNativeView();
808}
809
810gfx::NativeView TabContents::GetNativeView() const {
811 return view_->GetNativeView();
812}
813
814void TabContents::GetContainerBounds(gfx::Rect *out) const {
815 view_->GetContainerBounds(out);
816}
817
818void TabContents::Focus() {
819 view_->Focus();
820}
821
[email protected]90daadb42009-06-08 21:27:28822void TabContents::FocusThroughTabTraversal(bool reverse) {
[email protected]7e383692009-06-12 19:14:54823 if (showing_interstitial_page()) {
824 render_manager_.interstitial_page()->FocusThroughTabTraversal(reverse);
825 return;
826 }
[email protected]96d185d2009-04-24 03:28:54827 render_view_host()->SetInitialFocus(reverse);
828}
829
830bool TabContents::FocusLocationBarByDefault() {
831 DOMUI* dom_ui = GetDOMUIForCurrentState();
832 if (dom_ui)
833 return dom_ui->focus_location_bar_by_default();
[email protected]3e3f0eb2009-06-22 18:33:43834 NavigationEntry* entry = controller_.GetActiveEntry();
835 if (entry && entry->url() == GURL("about:blank"))
836 return true;
[email protected]96d185d2009-04-24 03:28:54837 return false;
838}
839
[email protected]616ed5a2008-11-21 22:27:24840void TabContents::AddInfoBar(InfoBarDelegate* delegate) {
841 // Look through the existing InfoBarDelegates we have for a match. If we've
842 // already got one that matches, then we don't add the new one.
[email protected]f86a07022008-11-25 01:06:05843 for (int i = 0; i < infobar_delegate_count(); ++i) {
[email protected]616ed5a2008-11-21 22:27:24844 if (GetInfoBarDelegateAt(i)->EqualsDelegate(delegate))
845 return;
846 }
847
848 infobar_delegates_.push_back(delegate);
[email protected]bfd04a62009-02-01 18:16:56849 NotificationService::current()->Notify(
850 NotificationType::TAB_CONTENTS_INFOBAR_ADDED,
851 Source<TabContents>(this),
852 Details<InfoBarDelegate>(delegate));
[email protected]616ed5a2008-11-21 22:27:24853
854 // Add ourselves as an observer for navigations the first time a delegate is
855 // added. We use this notification to expire InfoBars that need to expire on
856 // page transitions.
857 if (infobar_delegates_.size() == 1) {
[email protected]bfd04a62009-02-01 18:16:56858 registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57859 Source<NavigationController>(&controller_));
[email protected]616ed5a2008-11-21 22:27:24860 }
861}
862
863void TabContents::RemoveInfoBar(InfoBarDelegate* delegate) {
864 std::vector<InfoBarDelegate*>::iterator it =
865 find(infobar_delegates_.begin(), infobar_delegates_.end(), delegate);
866 if (it != infobar_delegates_.end()) {
867 InfoBarDelegate* delegate = *it;
[email protected]bfd04a62009-02-01 18:16:56868 NotificationService::current()->Notify(
869 NotificationType::TAB_CONTENTS_INFOBAR_REMOVED,
870 Source<TabContents>(this),
871 Details<InfoBarDelegate>(delegate));
[email protected]f86a07022008-11-25 01:06:05872 infobar_delegates_.erase(it);
[email protected]616ed5a2008-11-21 22:27:24873
[email protected]6a02963e2009-01-06 16:58:03874 // Remove ourselves as an observer if we are tracking no more InfoBars.
875 if (infobar_delegates_.empty()) {
[email protected]bfd04a62009-02-01 18:16:56876 registrar_.Remove(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57877 Source<NavigationController>(&controller_));
[email protected]6a02963e2009-01-06 16:58:03878 }
[email protected]616ed5a2008-11-21 22:27:24879 }
880}
[email protected]3edd9522009-03-04 22:19:41881
[email protected]96d185d2009-04-24 03:28:54882bool TabContents::IsBookmarkBarAlwaysVisible() {
883 // See GetDOMUIForCurrentState() comment for more info. This case is very
884 // similar, but for non-first loads, we want to use the committed entry. This
885 // is so the bookmarks bar disappears at the same time the page does.
886 if (controller_.GetLastCommittedEntry()) {
887 // Not the first load, always use the committed DOM UI.
888 if (render_manager_.dom_ui())
889 return render_manager_.dom_ui()->force_bookmark_bar_visible();
890 return false; // Default.
891 }
892
893 // When it's the first load, we know either the pending one or the committed
894 // one will have the DOM UI in it (see GetDOMUIForCurrentState), and only one
895 // of them will be valid, so we can just check both.
896 if (render_manager_.pending_dom_ui())
897 return render_manager_.pending_dom_ui()->force_bookmark_bar_visible();
898 if (render_manager_.dom_ui())
899 return render_manager_.dom_ui()->force_bookmark_bar_visible();
900 return false; // Default.
901}
902
[email protected]3edd9522009-03-04 22:19:41903void TabContents::ToolbarSizeChanged(bool is_animating) {
904 TabContentsDelegate* d = delegate();
905 if (d)
906 d->ToolbarSizeChanged(this, is_animating);
907}
[email protected]616ed5a2008-11-21 22:27:24908
[email protected]d5f942ba2008-09-26 19:30:34909void TabContents::OnStartDownload(DownloadItem* download) {
910 DCHECK(download);
[email protected]d5f942ba2008-09-26 19:30:34911
912 // Download in a constrained popup is shown in the tab that opened it.
[email protected]b6c874582009-05-08 19:38:31913 TabContents* tab_contents = delegate()->GetConstrainingContents(this);
[email protected]d5f942ba2008-09-26 19:30:34914
[email protected]59560e0b2009-06-04 03:30:22915 if (tab_contents && tab_contents->delegate())
916 tab_contents->delegate()->OnStartDownload(download);
[email protected]3edd9522009-03-04 22:19:41917}
[email protected]3edd9522009-03-04 22:19:41918
[email protected]d5f942ba2008-09-26 19:30:34919void TabContents::WillClose(ConstrainedWindow* window) {
920 ConstrainedWindowList::iterator it =
921 find(child_windows_.begin(), child_windows_.end(), window);
922 if (it != child_windows_.end())
923 child_windows_.erase(it);
[email protected]66ba4932009-06-04 19:22:13924}
[email protected]d5f942ba2008-09-26 19:30:34925
[email protected]66ba4932009-06-04 19:22:13926void TabContents::WillCloseBlockedPopupContainer(
927 BlockedPopupContainer* container) {
928 DCHECK(blocked_popups_ == container);
929 blocked_popups_ = NULL;
[email protected]d5f942ba2008-09-26 19:30:34930}
931
[email protected]d5f942ba2008-09-26 19:30:34932void TabContents::DidMoveOrResize(ConstrainedWindow* window) {
[email protected]332af7732009-03-11 13:21:35933#if defined(OS_WIN)
[email protected]92edc472009-02-10 20:32:06934 UpdateWindow(GetNativeView());
[email protected]332af7732009-03-11 13:21:35935#endif
[email protected]d5f942ba2008-09-26 19:30:34936}
937
[email protected]e491f1c2009-05-22 20:28:12938void TabContents::StartFinding(string16 find_text,
939 bool forward_direction,
940 bool case_sensitive) {
[email protected]6e95706d2009-04-23 22:55:01941 // If find_text is empty, it means FindNext was pressed with a keyboard
942 // shortcut so unless we have something to search for we return early.
[email protected]e491f1c2009-05-22 20:28:12943 if (find_text.empty() && find_text_.empty()) {
944 if (last_search_prepopulate_text_->empty())
945 return;
946 // Try whatever we searched for last in any tab.
947 find_text = *last_search_prepopulate_text_;
948 }
[email protected]6e95706d2009-04-23 22:55:01949
950 // This is a FindNext operation if we are searching for the same text again,
951 // or if the passed in search text is empty (FindNext keyboard shortcut). The
952 // exception to this is if the Find was aborted (then we don't want FindNext
953 // because the highlighting has been cleared and we need it to reappear). We
954 // therefore treat FindNext after an aborted Find operation as a full fledged
955 // Find.
956 bool find_next = (find_text_ == find_text || find_text.empty()) &&
[email protected]e491f1c2009-05-22 20:28:12957 (last_search_case_sensitive_ == case_sensitive) &&
[email protected]6e95706d2009-04-23 22:55:01958 !find_op_aborted_;
959 if (!find_next)
960 current_find_request_id_ = find_request_id_counter_++;
961
962 if (!find_text.empty())
963 find_text_ = find_text;
[email protected]e491f1c2009-05-22 20:28:12964 last_search_case_sensitive_ = case_sensitive;
[email protected]6e95706d2009-04-23 22:55:01965
966 find_op_aborted_ = false;
967
968 // Keep track of what the last search was across the tabs.
[email protected]e491f1c2009-05-22 20:28:12969 *last_search_prepopulate_text_ = find_text;
[email protected]6e95706d2009-04-23 22:55:01970
971 render_view_host()->StartFinding(current_find_request_id_,
972 find_text_,
973 forward_direction,
[email protected]e491f1c2009-05-22 20:28:12974 case_sensitive,
[email protected]6e95706d2009-04-23 22:55:01975 find_next);
976}
977
978void TabContents::StopFinding(bool clear_selection) {
[email protected]2d2dffc2009-06-09 21:41:00979 // When |clear_selection| is true, it means the find string has been cleared
980 // by the user, but the UI has not been dismissed.
981 if (!clear_selection)
982 find_ui_active_ = false;
[email protected]6e95706d2009-04-23 22:55:01983 find_op_aborted_ = true;
[email protected]e491f1c2009-05-22 20:28:12984 last_search_result_ = FindNotificationDetails();
[email protected]6e95706d2009-04-23 22:55:01985 render_view_host()->StopFinding(clear_selection);
986}
987
[email protected]5c4266922009-07-10 16:41:27988void TabContents::GetPageLanguage() {
989 render_view_host()->GetPageLanguage();
990}
991
[email protected]420ae012009-04-24 05:16:32992void TabContents::OnJavaScriptMessageBoxClosed(IPC::Message* reply_msg,
993 bool success,
994 const std::wstring& prompt) {
995 last_javascript_message_dismissal_ = base::TimeTicks::Now();
996 render_manager_.OnJavaScriptMessageBoxClosed(reply_msg, success, prompt);
997}
998
[email protected]571e31152009-05-15 19:34:02999void TabContents::OnJavaScriptMessageBoxWindowDestroyed() {
1000 render_manager_.OnJavaScriptMessageBoxWindowDestroyed();
1001}
1002
[email protected]420ae012009-04-24 05:16:321003void TabContents::OnSavePage() {
1004 // If we can not save the page, try to download it.
1005 if (!SavePackage::IsSavableContents(contents_mime_type())) {
1006 DownloadManager* dlm = profile()->GetDownloadManager();
1007 const GURL& current_page_url = GetURL();
1008 if (dlm && current_page_url.is_valid())
[email protected]d82ed61e2009-06-16 02:46:221009 dlm->DownloadUrl(current_page_url, GURL(), "", this);
[email protected]420ae012009-04-24 05:16:321010 return;
1011 }
1012
1013 Stop();
1014
1015 // Create the save package and possibly prompt the user for the name to save
1016 // the page as. The user prompt is an asynchronous operation that runs on
1017 // another thread.
[email protected]d82ed61e2009-06-16 02:46:221018 save_package_ = new SavePackage(this);
[email protected]420ae012009-04-24 05:16:321019 save_package_->GetSaveInfo();
1020}
1021
1022// Used in automated testing to bypass prompting the user for file names.
1023// Instead, the names and paths are hard coded rather than running them through
1024// file name sanitation and extension / mime checking.
1025void TabContents::SavePage(const std::wstring& main_file,
1026 const std::wstring& dir_path,
1027 SavePackage::SavePackageType save_type) {
1028 // Stop the page from navigating.
1029 Stop();
1030
[email protected]d82ed61e2009-06-16 02:46:221031 save_package_ = new SavePackage(this, save_type,
[email protected]420ae012009-04-24 05:16:321032 FilePath::FromWStringHack(main_file),
1033 FilePath::FromWStringHack(dir_path));
1034 save_package_->Init();
1035}
1036
1037void TabContents::PrintPreview() {
1038 // We don't show the print preview yet, only the print dialog.
1039 PrintNow();
1040}
1041
1042bool TabContents::PrintNow() {
1043 // We can't print interstitial page for now.
1044 if (showing_interstitial_page())
1045 return false;
1046
1047 return render_view_host()->PrintPages();
1048}
1049
[email protected]82270452009-06-19 15:58:011050void TabContents::PrintingDone(int document_cookie, bool success) {
1051 render_view_host()->PrintingDone(document_cookie, success);
1052}
1053
[email protected]420ae012009-04-24 05:16:321054bool TabContents::IsActiveEntry(int32 page_id) {
1055 NavigationEntry* active_entry = controller_.GetActiveEntry();
1056 return (active_entry != NULL &&
1057 active_entry->site_instance() == GetSiteInstance() &&
1058 active_entry->page_id() == page_id);
1059}
1060
[email protected]96d185d2009-04-24 03:28:541061// Notifies the RenderWidgetHost instance about the fact that the page is
1062// loading, or done loading and calls the base implementation.
1063void TabContents::SetIsLoading(bool is_loading,
1064 LoadNotificationDetails* details) {
1065 if (is_loading == is_loading_)
1066 return;
1067
1068 if (!is_loading) {
1069 load_state_ = net::LOAD_STATE_IDLE;
1070 load_state_host_.clear();
1071 }
1072
1073 render_manager_.SetIsLoading(is_loading);
1074
1075 is_loading_ = is_loading;
1076 waiting_for_response_ = is_loading;
1077
1078 if (delegate_)
1079 delegate_->LoadingStateChanged(this);
[email protected]329581b2009-04-28 06:52:351080 NotifyNavigationStateChanged(INVALIDATE_LOAD);
[email protected]96d185d2009-04-24 03:28:541081
1082 NotificationType type = is_loading ? NotificationType::LOAD_START :
1083 NotificationType::LOAD_STOP;
[email protected]ce5c4502009-05-06 16:46:111084 NotificationDetails det = NotificationService::NoDetails();
[email protected]96d185d2009-04-24 03:28:541085 if (details)
1086 det = Details<LoadNotificationDetails>(details);
1087 NotificationService::current()->Notify(type,
1088 Source<NavigationController>(&controller_),
1089 det);
1090}
1091
[email protected]2c4410d2009-05-06 23:46:221092void TabContents::CreateBlockedPopupContainerIfNecessary() {
1093 if (blocked_popups_)
1094 return;
1095
[email protected]4d4c0b92009-06-08 23:13:011096 blocked_popups_ = BlockedPopupContainer::Create(this, profile());
[email protected]2c4410d2009-05-06 23:46:221097}
1098
[email protected]b6c874582009-05-08 19:38:311099void TabContents::AddPopup(TabContents* new_contents,
1100 const gfx::Rect& initial_pos,
1101 const std::string& host) {
[email protected]2c4410d2009-05-06 23:46:221102 CreateBlockedPopupContainerIfNecessary();
1103 blocked_popups_->AddTabContents(new_contents, initial_pos, host);
[email protected]2c4410d2009-05-06 23:46:221104}
1105
[email protected]e69bce3dd2009-04-20 22:05:121106// TODO(brettw) This should be on the TabContentsView.
[email protected]66ba4932009-06-04 19:22:131107void TabContents::RepositionSupressedPopupsToFit() {
[email protected]d6598c052008-11-05 19:03:251108 if (blocked_popups_)
[email protected]4d4c0b92009-06-08 23:13:011109 blocked_popups_->RepositionBlockedPopupContainer();
[email protected]d5f942ba2008-09-26 19:30:341110}
1111
[email protected]b9681312008-11-07 00:08:261112bool TabContents::ShowingBlockedPopupNotification() const {
1113 return blocked_popups_ != NULL &&
[email protected]2c4410d2009-05-06 23:46:221114 blocked_popups_->GetBlockedPopupCount() != 0;
[email protected]b9681312008-11-07 00:08:261115}
[email protected]616ed5a2008-11-21 22:27:241116
1117namespace {
1118bool TransitionIsReload(PageTransition::Type transition) {
1119 return PageTransition::StripQualifier(transition) == PageTransition::RELOAD;
1120}
1121}
1122
1123void TabContents::ExpireInfoBars(
1124 const NavigationController::LoadCommittedDetails& details) {
1125 // Only hide InfoBars when the user has done something that makes the main
1126 // frame load. We don't want various automatic or subframe navigations making
1127 // it disappear.
1128 if (!details.is_user_initiated_main_frame_load())
1129 return;
1130
[email protected]f86a07022008-11-25 01:06:051131 for (int i = infobar_delegate_count() - 1; i >= 0; --i) {
[email protected]616ed5a2008-11-21 22:27:241132 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
[email protected]f86a07022008-11-25 01:06:051133 if (delegate->ShouldExpire(details))
[email protected]616ed5a2008-11-21 22:27:241134 RemoveInfoBar(delegate);
[email protected]616ed5a2008-11-21 22:27:241135 }
1136}
[email protected]fdd61c62009-04-22 19:22:571137
1138void TabContents::OnGearsCreateShortcutDone(
1139 const GearsShortcutData2& shortcut_data, bool success) {
1140 NavigationEntry* current_entry = controller_.GetLastCommittedEntry();
1141 bool same_page =
1142 current_entry && pending_install_.page_id == current_entry->page_id();
1143
1144 if (success && same_page) {
1145 // Only switch to app mode if the user chose to create a shortcut and
1146 // we're still on the same page that it corresponded to.
1147 if (delegate())
1148 delegate()->ConvertContentsToApplication(this);
1149 }
1150
1151 // Reset the page id to indicate no requests are pending.
1152 pending_install_.page_id = 0;
1153 pending_install_.callback_functor = NULL;
1154}
[email protected]96d185d2009-04-24 03:28:541155
1156DOMUI* TabContents::GetDOMUIForCurrentState() {
1157 // When there is a pending navigation entry, we want to use the pending DOMUI
1158 // that goes along with it to control the basic flags. For example, we want to
1159 // show the pending URL in the URL bar, so we want the display_url flag to
1160 // be from the pending entry.
1161 //
1162 // The confusion comes because there are multiple possibilities for the
1163 // initial load in a tab as a side effect of the way the RenderViewHostManager
1164 // works.
1165 //
1166 // - For the very first tab the load looks "normal". The new tab DOM UI is
1167 // the pending one, and we want it to apply here.
1168 //
1169 // - For subsequent new tabs, they'll get a new SiteInstance which will then
1170 // get switched to the one previously associated with the new tab pages.
1171 // This switching will cause the manager to commit the RVH/DOMUI. So we'll
1172 // have a committed DOM UI in this case.
1173 //
1174 // This condition handles all of these cases:
1175 //
1176 // - First load in first tab: no committed nav entry + pending nav entry +
1177 // pending dom ui:
1178 // -> Use pending DOM UI if any.
1179 //
1180 // - First load in second tab: no committed nav entry + pending nav entry +
1181 // no pending DOM UI:
1182 // -> Use the committed DOM UI if any.
1183 //
1184 // - Second navigation in any tab: committed nav entry + pending nav entry:
1185 // -> Use pending DOM UI if any.
1186 //
1187 // - Normal state with no load: committed nav entry + no pending nav entry:
1188 // -> Use committed DOM UI.
1189 if (controller_.pending_entry() &&
1190 (controller_.GetLastCommittedEntry() ||
1191 render_manager_.pending_dom_ui()))
1192 return render_manager_.pending_dom_ui();
1193 return render_manager_.dom_ui();
1194}
[email protected]420ae012009-04-24 05:16:321195
1196void TabContents::DidNavigateMainFramePostCommit(
1197 const NavigationController::LoadCommittedDetails& details,
1198 const ViewHostMsg_FrameNavigate_Params& params) {
[email protected]420ae012009-04-24 05:16:321199 if (details.is_user_initiated_main_frame_load()) {
1200 // Clear the status bubble. This is a workaround for a bug where WebKit
1201 // doesn't let us know that the cursor left an element during a
1202 // transition (this is also why the mouse cursor remains as a hand after
1203 // clicking on a link); see bugs 1184641 and 980803. We don't want to
1204 // clear the bubble when a user navigates to a named anchor in the same
1205 // page.
1206 UpdateTargetURL(details.entry->page_id(), GURL());
1207
1208 // UpdateHelpersForDidNavigate will handle the case where the password_form
1209 // origin is valid.
1210 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1211 // cleaned up and covered by tests.
1212 if (!params.password_form.origin.is_valid())
1213 GetPasswordManager()->DidNavigate();
1214 }
1215
1216 // The keyword generator uses the navigation entries, so must be called after
1217 // the commit.
1218 GenerateKeywordIfNecessary(params);
1219
1220 // Allow the new page to set the title again.
1221 received_page_title_ = false;
1222
1223 // Get the favicon, either from history or request it from the net.
1224 fav_icon_helper_.FetchFavIcon(details.entry->url());
1225
[email protected]ce5c4502009-05-06 16:46:111226 // Disable all page actions.
1227 enabled_page_actions_.clear();
1228
[email protected]420ae012009-04-24 05:16:321229 // Close constrained popups if necessary.
1230 MaybeCloseChildWindows(details.previous_url, details.entry->url());
1231
1232 // Update the starred state.
1233 UpdateStarredStateForCurrentURL();
1234}
1235
1236void TabContents::DidNavigateAnyFramePostCommit(
1237 RenderViewHost* render_view_host,
1238 const NavigationController::LoadCommittedDetails& details,
1239 const ViewHostMsg_FrameNavigate_Params& params) {
1240 // If we navigate, start showing messages again. This does nothing to prevent
1241 // a malicious script from spamming messages, since the script could just
1242 // reload the page to stop blocking.
1243 suppress_javascript_messages_ = false;
1244
[email protected]420ae012009-04-24 05:16:321245 // Notify the password manager of the navigation or form submit.
1246 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1247 // cleaned up and covered by tests.
1248 if (params.password_form.origin.is_valid())
1249 GetPasswordManager()->ProvisionallySavePassword(params.password_form);
1250}
1251
1252void TabContents::MaybeCloseChildWindows(const GURL& previous_url,
1253 const GURL& current_url) {
1254 if (net::RegistryControlledDomainService::SameDomainOrHost(
1255 previous_url, current_url))
1256 return;
1257
1258 // Clear out any child windows since we are leaving this page entirely.
1259 // We use indices instead of iterators in case CloseWindow does something
1260 // that may invalidate an iterator.
1261 int size = static_cast<int>(child_windows_.size());
1262 for (int i = size - 1; i >= 0; --i) {
1263 ConstrainedWindow* window = child_windows_[i];
1264 if (window)
1265 window->CloseConstrainedWindow();
1266 }
1267}
1268
1269void TabContents::UpdateStarredStateForCurrentURL() {
1270 BookmarkModel* model = profile()->GetBookmarkModel();
1271 const bool old_state = is_starred_;
1272 is_starred_ = (model && model->IsBookmarked(GetURL()));
1273
1274 if (is_starred_ != old_state && delegate())
1275 delegate()->URLStarredChanged(this, is_starred_);
1276}
1277
1278void TabContents::UpdateAlternateErrorPageURL() {
1279 GURL url = GetAlternateErrorPageURL();
1280 render_view_host()->SetAlternateErrorPageURL(url);
1281}
1282
1283void TabContents::UpdateWebPreferences() {
1284 render_view_host()->UpdateWebPreferences(GetWebkitPrefs());
1285}
1286
1287void TabContents::UpdateMaxPageIDIfNecessary(SiteInstance* site_instance,
1288 RenderViewHost* rvh) {
1289 // If we are creating a RVH for a restored controller, then we might
1290 // have more page IDs than the SiteInstance's current max page ID. We must
1291 // make sure that the max page ID is larger than any restored page ID.
1292 // Note that it is ok for conflicting page IDs to exist in another tab
1293 // (i.e., NavigationController), but if any page ID is larger than the max,
1294 // the back/forward list will get confused.
1295 int max_restored_page_id = controller_.max_restored_page_id();
1296 if (max_restored_page_id > 0) {
1297 int curr_max_page_id = site_instance->max_page_id();
1298 if (max_restored_page_id > curr_max_page_id) {
1299 // Need to update the site instance immediately.
1300 site_instance->UpdateMaxPageID(max_restored_page_id);
1301
1302 // Also tell the renderer to update its internal representation. We
1303 // need to reserve enough IDs to make all restored page IDs less than
1304 // the max.
1305 if (curr_max_page_id < 0)
1306 curr_max_page_id = 0;
1307 rvh->ReservePageIDRange(max_restored_page_id - curr_max_page_id);
1308 }
1309 }
1310}
1311
1312void TabContents::UpdateHistoryForNavigation(
1313 const GURL& display_url,
[email protected]befd8d822009-07-01 04:51:471314 const NavigationController::LoadCommittedDetails& details,
[email protected]420ae012009-04-24 05:16:321315 const ViewHostMsg_FrameNavigate_Params& params) {
1316 if (profile()->IsOffTheRecord())
1317 return;
1318
1319 // Add to history service.
1320 HistoryService* hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1321 if (hs) {
1322 if (PageTransition::IsMainFrame(params.transition) &&
1323 display_url != params.url) {
1324 // Hack on the "display" URL so that it will appear in history. For some
1325 // types of URLs, we will display a magic URL that is different from where
1326 // the page is actually navigated. We want the user to see in history
1327 // what they saw in the URL bar, so we add the display URL as a redirect.
1328 // This only applies to the main frame, as the display URL doesn't apply
1329 // to sub-frames.
1330 std::vector<GURL> redirects = params.redirects;
1331 if (!redirects.empty())
1332 redirects.back() = display_url;
1333 hs->AddPage(display_url, this, params.page_id, params.referrer,
[email protected]befd8d822009-07-01 04:51:471334 params.transition, redirects, details.did_replace_entry);
[email protected]420ae012009-04-24 05:16:321335 } else {
1336 hs->AddPage(params.url, this, params.page_id, params.referrer,
[email protected]befd8d822009-07-01 04:51:471337 params.transition, params.redirects,
1338 details.did_replace_entry);
[email protected]420ae012009-04-24 05:16:321339 }
1340 }
1341}
1342
1343bool TabContents::UpdateTitleForEntry(NavigationEntry* entry,
1344 const std::wstring& title) {
1345 // For file URLs without a title, use the pathname instead. In the case of a
1346 // synthesized title, we don't want the update to count toward the "one set
1347 // per page of the title to history."
1348 std::wstring final_title;
1349 bool explicit_set;
1350 if (entry->url().SchemeIsFile() && title.empty()) {
1351 final_title = UTF8ToWide(entry->url().ExtractFileName());
1352 explicit_set = false; // Don't count synthetic titles toward the set limit.
1353 } else {
1354 TrimWhitespace(title, TRIM_ALL, &final_title);
1355 explicit_set = true;
1356 }
1357
1358 if (final_title == UTF16ToWideHack(entry->title()))
1359 return false; // Nothing changed, don't bother.
1360
1361 entry->set_title(WideToUTF16Hack(final_title));
1362
1363 // Update the history system for this page.
1364 if (!profile()->IsOffTheRecord() && !received_page_title_) {
1365 HistoryService* hs =
1366 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1367 if (hs)
1368 hs->SetPageTitle(entry->display_url(), final_title);
1369
1370 // Don't allow the title to be saved again for explicitly set ones.
1371 received_page_title_ = explicit_set;
1372 }
1373
1374 // Lastly, set the title for the view.
1375 view_->SetPageTitle(final_title);
1376
1377 return true;
1378}
1379
1380void TabContents::NotifySwapped() {
1381 // After sending out a swap notification, we need to send a disconnect
1382 // notification so that clients that pick up a pointer to |this| can NULL the
1383 // pointer. See Bug 1230284.
1384 notify_disconnection_ = true;
1385 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341386 NotificationType::TAB_CONTENTS_SWAPPED,
[email protected]d82ed61e2009-06-16 02:46:221387 Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321388 NotificationService::NoDetails());
1389}
1390
1391void TabContents::NotifyConnected() {
1392 notify_disconnection_ = true;
1393 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341394 NotificationType::TAB_CONTENTS_CONNECTED,
[email protected]d82ed61e2009-06-16 02:46:221395 Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321396 NotificationService::NoDetails());
1397}
1398
1399void TabContents::NotifyDisconnected() {
1400 if (!notify_disconnection_)
1401 return;
1402
1403 notify_disconnection_ = false;
1404 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341405 NotificationType::TAB_CONTENTS_DISCONNECTED,
[email protected]d82ed61e2009-06-16 02:46:221406 Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321407 NotificationService::NoDetails());
1408}
1409
1410void TabContents::GenerateKeywordIfNecessary(
1411 const ViewHostMsg_FrameNavigate_Params& params) {
1412 if (!params.searchable_form_url.is_valid())
1413 return;
1414
1415 if (profile()->IsOffTheRecord())
1416 return;
1417
1418 int last_index = controller_.last_committed_entry_index();
1419 // When there was no previous page, the last index will be 0. This is
1420 // normally due to a form submit that opened in a new tab.
1421 // TODO(brettw) bug 916126: we should support keywords when form submits
1422 // happen in new tabs.
1423 if (last_index <= 0)
1424 return;
1425 const NavigationEntry* previous_entry =
1426 controller_.GetEntryAtIndex(last_index - 1);
1427 if (IsFormSubmit(previous_entry)) {
1428 // Only generate a keyword if the previous page wasn't itself a form
1429 // submit.
1430 return;
1431 }
1432
1433 GURL keyword_url = previous_entry->user_typed_url().is_valid() ?
1434 previous_entry->user_typed_url() : previous_entry->url();
1435 std::wstring keyword =
1436 TemplateURLModel::GenerateKeyword(keyword_url, true); // autodetected
1437 if (keyword.empty())
1438 return;
1439
1440 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
1441 if (!url_model)
1442 return;
1443
1444 if (!url_model->loaded()) {
1445 url_model->Load();
1446 return;
1447 }
1448
1449 const TemplateURL* current_url;
1450 std::wstring url = UTF8ToWide(params.searchable_form_url.spec());
1451 if (!url_model->CanReplaceKeyword(keyword, url, &current_url))
1452 return;
1453
1454 if (current_url) {
1455 if (current_url->originating_url().is_valid()) {
1456 // The existing keyword was generated from an OpenSearch description
1457 // document, don't regenerate.
1458 return;
1459 }
1460 url_model->Remove(current_url);
1461 }
1462 TemplateURL* new_url = new TemplateURL();
1463 new_url->set_keyword(keyword);
1464 new_url->set_short_name(keyword);
1465 new_url->SetURL(url, 0, 0);
1466 new_url->add_input_encoding(params.searchable_form_encoding);
1467 DCHECK(controller_.GetLastCommittedEntry());
1468 const GURL& favicon_url =
1469 controller_.GetLastCommittedEntry()->favicon().url();
1470 if (favicon_url.is_valid()) {
1471 new_url->SetFavIconURL(favicon_url);
1472 } else {
1473 // The favicon url isn't valid. This means there really isn't a favicon,
1474 // or the favicon url wasn't obtained before the load started. This assumes
1475 // the later.
1476 // TODO(sky): Need a way to set the favicon that doesn't involve generating
1477 // its url.
1478 new_url->SetFavIconURL(TemplateURL::GenerateFaviconURL(params.referrer));
1479 }
1480 new_url->set_safe_for_autoreplace(true);
1481 url_model->Add(new_url);
1482}
1483
[email protected]bf5c2ff392009-07-08 16:24:331484void TabContents::OnUserGesture() {
1485 // See comment in RenderViewHostDelegate::OnUserGesture as to why we do this.
1486 DownloadRequestManager* drm = g_browser_process->download_request_manager();
1487 if (drm)
1488 drm->OnUserGesture(this);
1489 controller_.OnUserGesture();
1490}
1491
1492void TabContents::OnFindReply(int request_id,
1493 int number_of_matches,
1494 const gfx::Rect& selection_rect,
1495 int active_match_ordinal,
1496 bool final_update) {
1497 // Ignore responses for requests other than the one we have most recently
1498 // issued. That way we won't act on stale results when the user has
1499 // already typed in another query.
1500 if (request_id != current_find_request_id_)
1501 return;
1502
1503 if (number_of_matches == -1)
1504 number_of_matches = last_search_result_.number_of_matches();
1505 if (active_match_ordinal == -1)
1506 active_match_ordinal = last_search_result_.active_match_ordinal();
1507
1508 gfx::Rect selection = selection_rect;
1509 if (selection.IsEmpty())
1510 selection = last_search_result_.selection_rect();
1511
1512 // Notify the UI, automation and any other observers that a find result was
1513 // found.
1514 last_search_result_ = FindNotificationDetails(request_id, number_of_matches,
1515 selection, active_match_ordinal,
1516 final_update);
1517 NotificationService::current()->Notify(
1518 NotificationType::FIND_RESULT_AVAILABLE,
1519 Source<TabContents>(this),
1520 Details<FindNotificationDetails>(&last_search_result_));
1521}
1522
1523void TabContents::GoToEntryAtOffset(int offset) {
1524 controller_.GoToOffset(offset);
1525}
1526
1527void TabContents::GetHistoryListCount(int* back_list_count,
1528 int* forward_list_count) {
1529 int current_index = controller_.last_committed_entry_index();
1530 *back_list_count = current_index;
1531 *forward_list_count = controller_.entry_count() - current_index - 1;
1532}
1533
1534void TabContents::OnMissingPluginStatus(int status) {
1535#if defined(OS_WIN)
1536// TODO(PORT): pull in when plug-ins work
1537 GetPluginInstaller()->OnMissingPluginStatus(status);
1538#endif
1539}
1540
1541void TabContents::OnCrashedPlugin(const FilePath& plugin_path) {
[email protected]bf5c2ff392009-07-08 16:24:331542 DCHECK(!plugin_path.value().empty());
1543
1544 std::wstring plugin_name = plugin_path.ToWStringHack();
[email protected]4a560ed2009-07-13 23:35:261545#if defined(OS_WIN)
[email protected]bf5c2ff392009-07-08 16:24:331546 scoped_ptr<FileVersionInfo> version_info(
1547 FileVersionInfo::CreateFileVersionInfo(plugin_path));
1548 if (version_info.get()) {
1549 const std::wstring& product_name = version_info->product_name();
1550 if (!product_name.empty())
1551 plugin_name = product_name;
1552 }
[email protected]4a560ed2009-07-13 23:35:261553#else
1554 NOTIMPLEMENTED() << " convert plugin path to plugin name";
1555#endif
[email protected]bf5c2ff392009-07-08 16:24:331556 AddInfoBar(new SimpleAlertInfoBarDelegate(
1557 this, l10n_util::GetStringF(IDS_PLUGIN_CRASHED_PROMPT, plugin_name),
1558 NULL));
[email protected]bf5c2ff392009-07-08 16:24:331559}
1560
1561void TabContents::OnCrashedWorker() {
1562 AddInfoBar(new SimpleAlertInfoBarDelegate(
1563 this, l10n_util::GetString(IDS_WEBWORKER_CRASHED_PROMPT),
1564 NULL));
1565}
1566
1567void TabContents::OnDidGetApplicationInfo(
1568 int32 page_id,
1569 const webkit_glue::WebApplicationInfo& info) {
1570 if (pending_install_.page_id != page_id)
1571 return; // The user clicked create on a separate page. Ignore this.
1572
1573 pending_install_.callback_functor =
1574 new GearsCreateShortcutCallbackFunctor(this);
1575 GearsCreateShortcut(
1576 info, pending_install_.title, pending_install_.url, pending_install_.icon,
1577 NewCallback(pending_install_.callback_functor,
1578 &GearsCreateShortcutCallbackFunctor::Run));
1579}
1580
1581void TabContents::DidStartProvisionalLoadForFrame(
1582 RenderViewHost* render_view_host,
1583 bool is_main_frame,
1584 const GURL& url) {
1585 ProvisionalLoadDetails details(is_main_frame,
1586 controller_.IsURLInPageNavigation(url),
1587 url, std::string(), false);
1588 NotificationService::current()->Notify(
1589 NotificationType::FRAME_PROVISIONAL_LOAD_START,
1590 Source<NavigationController>(&controller_),
1591 Details<ProvisionalLoadDetails>(&details));
1592}
1593
1594void TabContents::DidStartReceivingResourceResponse(
1595 ResourceRequestDetails* details) {
1596 NotificationService::current()->Notify(
1597 NotificationType::RESOURCE_RESPONSE_STARTED,
1598 Source<NavigationController>(&controller()),
1599 Details<ResourceRequestDetails>(details));
1600}
1601
1602void TabContents::DidRedirectResource(ResourceRequestDetails* details) {
1603 NotificationService::current()->Notify(
1604 NotificationType::RESOURCE_RECEIVED_REDIRECT,
1605 Source<NavigationController>(&controller()),
1606 Details<ResourceRequestDetails>(details));
1607}
1608
1609void TabContents::DidLoadResourceFromMemoryCache(
1610 const GURL& url,
1611 const std::string& frame_origin,
1612 const std::string& main_frame_origin,
1613 const std::string& security_info) {
1614 // Send out a notification that we loaded a resource from our memory cache.
1615 int cert_id = 0, cert_status = 0, security_bits = 0;
1616 SSLManager::DeserializeSecurityInfo(security_info,
1617 &cert_id, &cert_status,
1618 &security_bits);
1619 LoadFromMemoryCacheDetails details(url, frame_origin, main_frame_origin,
1620 process()->pid(), cert_id, cert_status);
1621
1622 NotificationService::current()->Notify(
1623 NotificationType::LOAD_FROM_MEMORY_CACHE,
1624 Source<NavigationController>(&controller_),
1625 Details<LoadFromMemoryCacheDetails>(&details));
1626}
1627
1628void TabContents::DidFailProvisionalLoadWithError(
1629 RenderViewHost* render_view_host,
1630 bool is_main_frame,
1631 int error_code,
1632 const GURL& url,
1633 bool showing_repost_interstitial) {
1634 if (net::ERR_ABORTED == error_code) {
1635 // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
1636 // This means that the interstitial won't be torn down properly, which is
1637 // bad. But if we have an interstitial, go back to another tab type, and
1638 // then load the same interstitial again, we could end up getting the first
1639 // interstitial's "failed" message (as a result of the cancel) when we're on
1640 // the second one.
1641 //
1642 // We can't tell this apart, so we think we're tearing down the current page
1643 // which will cause a crash later one. There is also some code in
1644 // RenderViewHostManager::RendererAbortedProvisionalLoad that is commented
1645 // out because of this problem.
1646 //
1647 // http://code.google.com/p/chromium/issues/detail?id=2855
1648 // Because this will not tear down the interstitial properly, if "back" is
1649 // back to another tab type, the interstitial will still be somewhat alive
1650 // in the previous tab type. If you navigate somewhere that activates the
1651 // tab with the interstitial again, you'll see a flash before the new load
1652 // commits of the interstitial page.
1653 if (showing_interstitial_page()) {
1654 LOG(WARNING) << "Discarding message during interstitial.";
1655 return;
1656 }
1657
1658 // This will discard our pending entry if we cancelled the load (e.g., if we
1659 // decided to download the file instead of load it). Only discard the
1660 // pending entry if the URLs match, otherwise the user initiated a navigate
1661 // before the page loaded so that the discard would discard the wrong entry.
1662 NavigationEntry* pending_entry = controller_.pending_entry();
1663 if (pending_entry && pending_entry->url() == url) {
1664 controller_.DiscardNonCommittedEntries();
1665 // Update the URL display.
1666 NotifyNavigationStateChanged(TabContents::INVALIDATE_URL);
1667 }
1668
1669 render_manager_.RendererAbortedProvisionalLoad(render_view_host);
1670 }
1671
1672 // Send out a notification that we failed a provisional load with an error.
1673 ProvisionalLoadDetails details(is_main_frame,
1674 controller_.IsURLInPageNavigation(url),
1675 url, std::string(), false);
1676 details.set_error_code(error_code);
1677
1678 NotificationService::current()->Notify(
1679 NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR,
1680 Source<NavigationController>(&controller_),
1681 Details<ProvisionalLoadDetails>(&details));
1682}
1683
1684void TabContents::DocumentLoadedInFrame() {
1685 controller_.DocumentLoadedInFrame();
1686}
1687
[email protected]8d3347f2009-07-09 22:00:211688RenderViewHostDelegate::View* TabContents::GetViewDelegate() {
[email protected]420ae012009-04-24 05:16:321689 return view_.get();
1690}
1691
[email protected]8d3347f2009-07-09 22:00:211692RenderViewHostDelegate::RendererManagement*
1693TabContents::GetRendererManagementDelegate() {
1694 return &render_manager_;
1695}
1696
[email protected]bf5c2ff392009-07-08 16:24:331697RenderViewHostDelegate::BrowserIntegration*
[email protected]8d3347f2009-07-09 22:00:211698 TabContents::GetBrowserIntegrationDelegate() {
1699 return this;
[email protected]bf5c2ff392009-07-08 16:24:331700}
1701
[email protected]8d3347f2009-07-09 22:00:211702RenderViewHostDelegate::Resource* TabContents::GetResourceDelegate() {
1703 return this;
[email protected]bf5c2ff392009-07-08 16:24:331704}
1705
[email protected]8d3347f2009-07-09 22:00:211706RenderViewHostDelegate::Save* TabContents::GetSaveDelegate() {
[email protected]420ae012009-04-24 05:16:321707 return save_package_.get(); // May be NULL, but we can return NULL.
1708}
1709
[email protected]8d3347f2009-07-09 22:00:211710RenderViewHostDelegate::Printing* TabContents::GetPrintingDelegate() {
1711 return &printing_;
1712}
1713
1714RenderViewHostDelegate::FavIcon* TabContents::GetFavIconDelegate() {
1715 return &fav_icon_helper_;
1716}
1717
1718RenderViewHostDelegate::Autofill* TabContents::GetAutofillDelegate() {
1719 if (autofill_manager_.get() == NULL)
1720 autofill_manager_.reset(new AutofillManager(this));
1721 return autofill_manager_.get();
[email protected]bf5c2ff392009-07-08 16:24:331722}
1723
[email protected]80d96fa2009-06-10 22:34:511724RendererPreferences TabContents::GetRendererPrefs() const {
1725 if (delegate())
1726 return delegate()->GetRendererPrefs();
1727 else
1728 return RendererPreferences();
1729}
1730
[email protected]57c6a652009-05-04 07:58:341731TabContents* TabContents::GetAsTabContents() {
1732 return this;
1733}
1734
[email protected]420ae012009-04-24 05:16:321735void TabContents::RenderViewCreated(RenderViewHost* render_view_host) {
[email protected]2e4633c2009-07-09 16:58:061736 NotificationService::current()->Notify(
1737 NotificationType::RENDER_VIEW_HOST_CREATED_FOR_TAB,
1738 Source<TabContents>(this),
1739 Details<RenderViewHost>(render_view_host));
1740
[email protected]420ae012009-04-24 05:16:321741 NavigationEntry* entry = controller_.GetActiveEntry();
1742 if (!entry)
1743 return;
1744
1745 // When we're creating views, we're still doing initial setup, so we always
1746 // use the pending DOM UI rather than any possibly existing committed one.
1747 if (render_manager_.pending_dom_ui()) {
1748 render_manager_.pending_dom_ui()->RenderViewCreated(render_view_host);
1749 }
1750
1751 if (entry->IsViewSourceMode()) {
1752 // Put the renderer in view source mode.
1753 render_view_host->Send(
1754 new ViewMsg_EnableViewSourceMode(render_view_host->routing_id()));
1755 }
[email protected]0666aef2009-05-13 19:48:081756
1757 view()->RenderViewCreated(render_view_host);
[email protected]420ae012009-04-24 05:16:321758}
1759
1760void TabContents::RenderViewReady(RenderViewHost* rvh) {
1761 if (rvh != render_view_host()) {
1762 // Don't notify the world, since this came from a renderer in the
1763 // background.
1764 return;
1765 }
1766
1767 NotifyConnected();
1768 SetIsCrashed(false);
1769}
1770
1771void TabContents::RenderViewGone(RenderViewHost* rvh) {
1772 // Ask the print preview if this renderer was valuable.
1773 if (!printing_.OnRenderViewGone(rvh))
1774 return;
1775 if (rvh != render_view_host()) {
1776 // The pending page's RenderViewHost is gone.
1777 return;
1778 }
1779
1780 SetIsLoading(false, NULL);
1781 NotifyDisconnected();
1782 SetIsCrashed(true);
1783
[email protected]8e537302009-06-10 21:19:581784 // Tell the view that we've crashed so it can prepare the sad tab page.
1785 view_->OnTabCrashed();
[email protected]420ae012009-04-24 05:16:321786
1787 // Hide any visible hung renderer warning for this web contents' process.
[email protected]d82ed61e2009-06-16 02:46:221788 HungRendererDialog::HideForTabContents(this);
[email protected]420ae012009-04-24 05:16:321789}
1790
[email protected]2e4633c2009-07-09 16:58:061791void TabContents::RenderViewDeleted(RenderViewHost* rvh) {
1792 NotificationService::current()->Notify(
1793 NotificationType::RENDER_VIEW_HOST_DELETED,
1794 Source<TabContents>(this),
1795 Details<RenderViewHost>(rvh));
1796}
1797
[email protected]420ae012009-04-24 05:16:321798void TabContents::DidNavigate(RenderViewHost* rvh,
1799 const ViewHostMsg_FrameNavigate_Params& params) {
1800 if (PageTransition::IsMainFrame(params.transition))
1801 render_manager_.DidNavigateMainFrame(rvh);
1802
1803 // Update the site of the SiteInstance if it doesn't have one yet.
1804 if (!GetSiteInstance()->has_site())
1805 GetSiteInstance()->SetSite(params.url);
1806
1807 // Need to update MIME type here because it's referred to in
1808 // UpdateNavigationCommands() called by RendererDidNavigate() to
1809 // determine whether or not to enable the encoding menu.
1810 // It's updated only for the main frame. For a subframe,
1811 // RenderView::UpdateURL does not set params.contents_mime_type.
1812 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
1813 // TODO(jungshik): Add a test for the encoding menu to avoid
1814 // regressing it again.
1815 if (PageTransition::IsMainFrame(params.transition))
1816 contents_mime_type_ = params.contents_mime_type;
1817
1818 NavigationController::LoadCommittedDetails details;
[email protected]3e90d4a2009-07-03 17:38:391819 bool did_navigate = controller_.RendererDidNavigate(params, &details);
1820
1821 // Update history. Note that this needs to happen after the entry is complete,
1822 // which WillNavigate[Main,Sub]Frame will do before this function is called.
1823 if (params.should_update_history) {
1824 // Most of the time, the displayURL matches the loaded URL, but for about:
1825 // URLs, we use a data: URL as the real value. We actually want to save
1826 // the about: URL to the history db and keep the data: URL hidden. This is
1827 // what the TabContents' URL getter does.
1828 UpdateHistoryForNavigation(GetURL(), details, params);
1829 }
1830
1831 if (!did_navigate)
1832 return; // No navigation happened.
[email protected]420ae012009-04-24 05:16:321833
1834 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
1835 // for the appropriate notification (best) or you can add it to
1836 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
1837 // necessary, please).
1838
1839 // Run post-commit tasks.
1840 if (details.is_main_frame)
1841 DidNavigateMainFramePostCommit(details, params);
1842 DidNavigateAnyFramePostCommit(rvh, details, params);
1843}
1844
1845void TabContents::UpdateState(RenderViewHost* rvh,
1846 int32 page_id,
1847 const std::string& state) {
1848 DCHECK(rvh == render_view_host());
1849
1850 // We must be prepared to handle state updates for any page, these occur
1851 // when the user is scrolling and entering form data, as well as when we're
1852 // leaving a page, in which case our state may have already been moved to
1853 // the next page. The navigation controller will look up the appropriate
1854 // NavigationEntry and update it when it is notified via the delegate.
1855
1856 int entry_index = controller_.GetEntryIndexWithPageID(
1857 GetSiteInstance(), page_id);
1858 if (entry_index < 0)
1859 return;
1860 NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
1861
1862 if (state == entry->content_state())
1863 return; // Nothing to update.
1864 entry->set_content_state(state);
1865 controller_.NotifyEntryChanged(entry, entry_index);
1866}
1867
1868void TabContents::UpdateTitle(RenderViewHost* rvh,
1869 int32 page_id, const std::wstring& title) {
1870 // If we have a title, that's a pretty good indication that we've started
1871 // getting useful data.
1872 SetNotWaitingForResponse();
1873
1874 DCHECK(rvh == render_view_host());
1875 NavigationEntry* entry = controller_.GetEntryWithPageID(GetSiteInstance(),
1876 page_id);
1877 if (!entry || !UpdateTitleForEntry(entry, title))
1878 return;
1879
1880 // Broadcast notifications when the UI should be updated.
1881 if (entry == controller_.GetEntryAtOffset(0))
[email protected]c9cd2222009-05-06 05:16:501882 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:321883}
1884
[email protected]420ae012009-04-24 05:16:321885void TabContents::UpdateEncoding(RenderViewHost* render_view_host,
1886 const std::wstring& encoding) {
1887 set_encoding(encoding);
1888}
1889
1890void TabContents::UpdateTargetURL(int32 page_id, const GURL& url) {
1891 if (delegate())
1892 delegate()->UpdateTargetURL(this, url);
1893}
1894
1895void TabContents::UpdateThumbnail(const GURL& url,
1896 const SkBitmap& bitmap,
1897 const ThumbnailScore& score) {
1898 // Tell History about this thumbnail
[email protected]449478302009-06-09 20:04:281899 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kThumbnailStore)) {
[email protected]72d0fc72009-07-09 17:30:491900 if (!profile()->IsOffTheRecord())
[email protected]42339402009-07-17 17:27:191901 profile()->GetThumbnailStore()->SetPageThumbnail(url, bitmap,
1902 score, true);
[email protected]449478302009-06-09 20:04:281903 } else {
1904 HistoryService* hs;
1905 if (!profile()->IsOffTheRecord() &&
1906 (hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS))) {
1907 hs->SetPageThumbnail(url, bitmap, score);
1908 }
[email protected]420ae012009-04-24 05:16:321909 }
1910}
1911
[email protected]0df30122009-06-03 12:13:081912void TabContents::UpdateInspectorSettings(const std::wstring& raw_settings) {
1913 profile()->GetPrefs()->SetString(prefs::kWebKitInspectorSettings,
1914 raw_settings);
1915}
1916
[email protected]420ae012009-04-24 05:16:321917void TabContents::Close(RenderViewHost* rvh) {
[email protected]24a4d1062009-07-10 23:10:421918 // If we close the tab while we're in the middle of a drag, we'll crash.
1919 // Instead, cancel the drag and close it as soon as the drag ends.
1920 if (view()->IsDoingDrag()) {
1921 view()->CancelDragAndCloseTab();
1922 return;
1923 }
1924
[email protected]420ae012009-04-24 05:16:321925 // Ignore this if it comes from a RenderViewHost that we aren't showing.
1926 if (delegate() && rvh == render_view_host())
1927 delegate()->CloseContents(this);
1928}
1929
1930void TabContents::RequestMove(const gfx::Rect& new_bounds) {
1931 if (delegate() && delegate()->IsPopup(this))
1932 delegate()->MoveContents(this, new_bounds);
1933}
1934
[email protected]329581b2009-04-28 06:52:351935void TabContents::DidStartLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321936 SetIsLoading(true, NULL);
1937}
1938
[email protected]329581b2009-04-28 06:52:351939void TabContents::DidStopLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321940 scoped_ptr<LoadNotificationDetails> details;
1941
1942 NavigationEntry* entry = controller_.GetActiveEntry();
1943 // An entry may not exist for a stop when loading an initial blank page or
1944 // if an iframe injected by script into a blank page finishes loading.
1945 if (entry) {
1946 scoped_ptr<base::ProcessMetrics> metrics(
1947 base::ProcessMetrics::CreateProcessMetrics(
1948 process()->process().handle()));
1949
1950 base::TimeDelta elapsed = base::TimeTicks::Now() - current_load_start_;
1951
1952 details.reset(new LoadNotificationDetails(
1953 entry->display_url(),
1954 entry->transition_type(),
1955 elapsed,
1956 &controller_,
1957 controller_.GetCurrentEntryIndex()));
1958 }
1959
1960 // Tell PasswordManager we've finished a page load, which serves as a
1961 // green light to save pending passwords and reset itself.
1962 GetPasswordManager()->DidStopLoading();
1963
1964 SetIsLoading(false, details.get());
1965}
1966
[email protected]420ae012009-04-24 05:16:321967void TabContents::DidRedirectProvisionalLoad(int32 page_id,
1968 const GURL& source_url,
1969 const GURL& target_url) {
1970 NavigationEntry* entry;
1971 if (page_id == -1)
1972 entry = controller_.pending_entry();
1973 else
1974 entry = controller_.GetEntryWithPageID(GetSiteInstance(), page_id);
1975 if (!entry || entry->url() != source_url)
1976 return;
1977 entry->set_url(target_url);
1978}
1979
[email protected]420ae012009-04-24 05:16:321980void TabContents::RequestOpenURL(const GURL& url, const GURL& referrer,
1981 WindowOpenDisposition disposition) {
1982 if (render_manager_.dom_ui()) {
1983 // When we're a DOM UI, it will provide a page transition type for us (this
1984 // is so the new tab page can specify AUTO_BOOKMARK for automatically
1985 // generated suggestions).
1986 //
1987 // Note also that we hide the referrer for DOM UI pages. We don't really
[email protected]60e448982009-05-06 04:21:161988 // want web sites to see a referrer of "chrome://blah" (and some
1989 // chrome: URLs might have search terms or other stuff we don't want to
[email protected]420ae012009-04-24 05:16:321990 // send to the site), so we send no referrer.
1991 OpenURL(url, GURL(), disposition,
1992 render_manager_.dom_ui()->link_transition_type());
1993 } else {
1994 OpenURL(url, referrer, disposition, PageTransition::LINK);
1995 }
1996}
1997
[email protected]1ee614862009-07-06 20:29:181998void TabContents::DomOperationResponse(const std::string& json_string,
1999 int automation_id) {
2000}
2001
[email protected]420ae012009-04-24 05:16:322002void TabContents::ProcessDOMUIMessage(const std::string& message,
[email protected]811bfe32009-07-01 08:46:252003 const std::string& content,
2004 int request_id,
2005 bool has_callback) {
[email protected]420ae012009-04-24 05:16:322006 if (!render_manager_.dom_ui()) {
2007 // We shouldn't get a DOM UI message when we haven't enabled the DOM UI.
2008 // Because the renderer might be owned and sending random messages, we need
2009 // to ignore these inproper ones.
2010 NOTREACHED();
2011 return;
2012 }
[email protected]811bfe32009-07-01 08:46:252013 render_manager_.dom_ui()->ProcessDOMUIMessage(message, content, request_id,
2014 has_callback);
[email protected]420ae012009-04-24 05:16:322015}
2016
2017void TabContents::ProcessExternalHostMessage(const std::string& message,
2018 const std::string& origin,
2019 const std::string& target) {
2020 if (delegate())
2021 delegate()->ForwardMessageToExternalHost(message, origin, target);
2022}
2023
[email protected]420ae012009-04-24 05:16:322024void TabContents::RunFileChooser(bool multiple_files,
2025 const string16& title,
2026 const FilePath& default_file) {
2027 if (!select_file_dialog_.get())
2028 select_file_dialog_ = SelectFileDialog::Create(this);
2029 SelectFileDialog::Type dialog_type =
2030 multiple_files ? SelectFileDialog::SELECT_OPEN_MULTI_FILE :
2031 SelectFileDialog::SELECT_OPEN_FILE;
2032 select_file_dialog_->SelectFile(dialog_type, title, default_file,
2033 NULL, 0, FILE_PATH_LITERAL(""),
2034 view_->GetTopLevelNativeWindow(), NULL);
2035}
2036
2037void TabContents::RunJavaScriptMessage(
2038 const std::wstring& message,
2039 const std::wstring& default_prompt,
2040 const GURL& frame_url,
2041 const int flags,
2042 IPC::Message* reply_msg,
2043 bool* did_suppress_message) {
2044 // Suppress javascript messages when requested and when inside a constrained
2045 // popup window (because that activates them and breaks them out of the
2046 // constrained window jail).
[email protected]91ed49a2009-07-07 21:29:552047 // Also suppress messages when showing an interstitial. The interstitial is
2048 // shown over the previous page, we don't want the hidden page dialogs to
2049 // interfere with the interstitial.
2050 bool suppress_this_message = suppress_javascript_messages_ ||
2051 showing_interstitial_page();
[email protected]420ae012009-04-24 05:16:322052 if (delegate())
2053 suppress_this_message |=
[email protected]b6c874582009-05-08 19:38:312054 (delegate()->GetConstrainingContents(this) != this);
[email protected]420ae012009-04-24 05:16:322055
2056 *did_suppress_message = suppress_this_message;
2057
2058 if (!suppress_this_message) {
2059 base::TimeDelta time_since_last_message(
2060 base::TimeTicks::Now() - last_javascript_message_dismissal_);
2061 bool show_suppress_checkbox = false;
2062 // Show a checkbox offering to suppress further messages if this message is
2063 // being displayed within kJavascriptMessageExpectedDelay of the last one.
2064 if (time_since_last_message <
2065 base::TimeDelta::FromMilliseconds(kJavascriptMessageExpectedDelay))
2066 show_suppress_checkbox = true;
2067
[email protected]d82ed61e2009-06-16 02:46:222068 RunJavascriptMessageBox(this, frame_url, flags, message, default_prompt,
[email protected]420ae012009-04-24 05:16:322069 show_suppress_checkbox, reply_msg);
2070 } else {
2071 // If we are suppressing messages, just reply as is if the user immediately
2072 // pressed "Cancel".
2073 OnJavaScriptMessageBoxClosed(reply_msg, false, std::wstring());
2074 }
2075}
2076
2077void TabContents::RunBeforeUnloadConfirm(const std::wstring& message,
2078 IPC::Message* reply_msg) {
[email protected]d82ed61e2009-06-16 02:46:222079 RunBeforeUnloadDialog(this, message, reply_msg);
[email protected]420ae012009-04-24 05:16:322080}
2081
2082void TabContents::ShowModalHTMLDialog(const GURL& url, int width, int height,
2083 const std::string& json_arguments,
2084 IPC::Message* reply_msg) {
2085 if (delegate()) {
2086 HtmlDialogUIDelegate* dialog_delegate =
2087 new ModalHtmlDialogDelegate(url, width, height, json_arguments,
[email protected]d82ed61e2009-06-16 02:46:222088 reply_msg, this);
[email protected]420ae012009-04-24 05:16:322089 delegate()->ShowHtmlDialog(dialog_delegate, NULL);
2090 }
2091}
2092
2093void TabContents::PasswordFormsSeen(
[email protected]ed3fb032009-06-16 19:50:562094 const std::vector<webkit_glue::PasswordForm>& forms) {
[email protected]420ae012009-04-24 05:16:322095 GetPasswordManager()->PasswordFormsSeen(forms);
2096}
2097
[email protected]420ae012009-04-24 05:16:322098// Checks to see if we should generate a keyword based on the OSDD, and if
2099// necessary uses TemplateURLFetcher to download the OSDD and create a keyword.
2100void TabContents::PageHasOSDD(RenderViewHost* render_view_host,
2101 int32 page_id, const GURL& url,
2102 bool autodetected) {
2103 // Make sure page_id is the current page, and the TemplateURLModel is loaded.
2104 DCHECK(url.is_valid());
2105 if (!IsActiveEntry(page_id))
2106 return;
2107 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
2108 if (!url_model)
2109 return;
2110 if (!url_model->loaded()) {
2111 url_model->Load();
2112 return;
2113 }
2114 if (!profile()->GetTemplateURLFetcher())
2115 return;
2116
2117 if (profile()->IsOffTheRecord())
2118 return;
2119
2120 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
2121 DCHECK(entry);
2122
2123 const NavigationEntry* base_entry = entry;
2124 if (IsFormSubmit(base_entry)) {
2125 // If the current page is a form submit, find the last page that was not
2126 // a form submit and use its url to generate the keyword from.
2127 int index = controller_.last_committed_entry_index() - 1;
2128 while (index >= 0 && IsFormSubmit(controller_.GetEntryAtIndex(index)))
2129 index--;
2130 if (index >= 0)
2131 base_entry = controller_.GetEntryAtIndex(index);
2132 else
2133 base_entry = NULL;
2134 }
2135
2136 // We want to use the user typed URL if available since that represents what
2137 // the user typed to get here, and fall back on the regular URL if not.
2138 if (!base_entry)
2139 return;
2140 GURL keyword_url = base_entry->user_typed_url().is_valid() ?
2141 base_entry->user_typed_url() : base_entry->url();
2142 if (!keyword_url.is_valid())
2143 return;
2144 std::wstring keyword = TemplateURLModel::GenerateKeyword(keyword_url,
2145 autodetected);
2146 if (keyword.empty())
2147 return;
2148 const TemplateURL* template_url =
2149 url_model->GetTemplateURLForKeyword(keyword);
2150 if (template_url && (!template_url->safe_for_autoreplace() ||
2151 template_url->originating_url() == url)) {
2152 // Either there is a user created TemplateURL for this keyword, or the
2153 // keyword has the same OSDD url and we've parsed it.
2154 return;
2155 }
2156
2157 // Download the OpenSearch description document. If this is successful a
2158 // new keyword will be created when done.
[email protected]420ae012009-04-24 05:16:322159 profile()->GetTemplateURLFetcher()->ScheduleDownload(
2160 keyword,
2161 url,
2162 base_entry->favicon().url(),
[email protected]d0cc9fb52009-06-23 02:26:162163 this,
[email protected]420ae012009-04-24 05:16:322164 autodetected);
2165}
2166
[email protected]420ae012009-04-24 05:16:322167GURL TabContents::GetAlternateErrorPageURL() const {
2168 GURL url;
2169 // Disable alternate error pages when in OffTheRecord/Incognito mode.
2170 if (profile()->IsOffTheRecord())
2171 return url;
2172
2173 PrefService* prefs = profile()->GetPrefs();
2174 DCHECK(prefs);
2175 if (prefs->GetBoolean(prefs::kAlternateErrorPagesEnabled)) {
2176 url = google_util::AppendGoogleLocaleParam(GURL(kLinkDoctorBaseURL));
2177 url = google_util::AppendGoogleTLDParam(url);
2178 }
2179 return url;
2180}
2181
2182WebPreferences TabContents::GetWebkitPrefs() {
2183 PrefService* prefs = render_view_host()->process()->profile()->GetPrefs();
2184 bool isDomUI = false;
2185 return RenderViewHostDelegateHelper::GetWebkitPrefs(prefs, isDomUI);
2186}
2187
[email protected]420ae012009-04-24 05:16:322188void TabContents::OnJSOutOfMemory() {
2189 AddInfoBar(new SimpleAlertInfoBarDelegate(
2190 this, l10n_util::GetString(IDS_JS_OUT_OF_MEMORY_PROMPT), NULL));
2191}
2192
2193void TabContents::ShouldClosePage(bool proceed) {
2194 render_manager_.ShouldClosePage(proceed);
2195}
2196
2197void TabContents::OnCrossSiteResponse(int new_render_process_host_id,
2198 int new_request_id) {
[email protected]57c6a652009-05-04 07:58:342199 // Allows the TabContents to react when a cross-site response is ready to be
[email protected]420ae012009-04-24 05:16:322200 // delivered to a pending RenderViewHost. We must first run the onunload
2201 // handler of the old RenderViewHost before we can allow it to proceed.
2202 render_manager_.OnCrossSiteResponse(new_render_process_host_id,
2203 new_request_id);
2204}
2205
2206bool TabContents::CanBlur() const {
2207 return delegate() ? delegate()->CanBlur() : true;
2208}
2209
2210gfx::Rect TabContents::GetRootWindowResizerRect() const {
2211 if (delegate())
2212 return delegate()->GetRootWindowResizerRect();
2213 return gfx::Rect();
2214}
2215
2216void TabContents::RendererUnresponsive(RenderViewHost* rvh,
2217 bool is_during_unload) {
2218 if (is_during_unload) {
2219 // Hang occurred while firing the beforeunload/unload handler.
2220 // Pretend the handler fired so tab closing continues as if it had.
[email protected]829e7612009-04-25 01:15:112221 rvh->set_sudden_termination_allowed(true);
[email protected]420ae012009-04-24 05:16:322222
2223 if (!render_manager_.ShouldCloseTabOnUnresponsiveRenderer())
2224 return;
2225
2226 // If the tab hangs in the beforeunload/unload handler there's really
2227 // nothing we can do to recover. Pretend the unload listeners have
2228 // all fired and close the tab. If the hang is in the beforeunload handler
2229 // then the user will not have the option of cancelling the close.
2230 Close(rvh);
2231 return;
2232 }
2233
2234 if (render_view_host() && render_view_host()->IsRenderViewLive())
[email protected]d82ed61e2009-06-16 02:46:222235 HungRendererDialog::ShowForTabContents(this);
[email protected]420ae012009-04-24 05:16:322236}
2237
2238void TabContents::RendererResponsive(RenderViewHost* render_view_host) {
[email protected]d82ed61e2009-06-16 02:46:222239 HungRendererDialog::HideForTabContents(this);
[email protected]420ae012009-04-24 05:16:322240}
2241
2242void TabContents::LoadStateChanged(const GURL& url,
2243 net::LoadState load_state) {
2244 load_state_ = load_state;
[email protected]d686e812009-06-03 19:10:292245 std::wstring languages =
2246 profile()->GetPrefs()->GetString(prefs::kAcceptLanguages);
2247 load_state_host_.clear();
2248 std::string host = url.host();
2249 net::IDNToUnicode(host.c_str(), host.size(), languages, &load_state_host_);
[email protected]420ae012009-04-24 05:16:322250 if (load_state_ == net::LOAD_STATE_READING_RESPONSE)
2251 SetNotWaitingForResponse();
2252 if (is_loading())
[email protected]c9cd2222009-05-06 05:16:502253 NotifyNavigationStateChanged(INVALIDATE_LOAD | INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:322254}
2255
[email protected]1ee614862009-07-06 20:29:182256bool TabContents::IsExternalTabContainer() const {
2257 if (!delegate())
2258 return false;
2259
2260 return delegate()->IsExternalTabContainer();
2261}
2262
[email protected]1ee614862009-07-06 20:29:182263void TabContents::DidInsertCSS() {
2264 // This RVHDelegate function is used for extensions and not us.
[email protected]420ae012009-04-24 05:16:322265}
2266
2267void TabContents::FileSelected(const FilePath& path,
2268 int index, void* params) {
2269 render_view_host()->FileSelected(path);
2270}
2271
2272void TabContents::MultiFilesSelected(const std::vector<FilePath>& files,
2273 void* params) {
2274 render_view_host()->MultiFilesSelected(files);
2275}
2276
2277void TabContents::FileSelectionCanceled(void* params) {
2278 // If the user cancels choosing a file to upload we pass back an
2279 // empty vector.
2280 render_view_host()->MultiFilesSelected(std::vector<FilePath>());
2281}
2282
2283void TabContents::BeforeUnloadFiredFromRenderManager(
2284 bool proceed,
2285 bool* proceed_to_fire_unload) {
2286 if (delegate())
2287 delegate()->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
2288}
2289
2290void TabContents::UpdateRenderViewSizeForRenderManager() {
2291 // TODO(brettw) this is a hack. See TabContentsView::SizeContents.
2292 view_->SizeContents(view_->GetContainerSize());
2293}
2294
2295DOMUI* TabContents::CreateDOMUIForRenderManager(const GURL& url) {
[email protected]d82ed61e2009-06-16 02:46:222296 return DOMUIFactory::CreateDOMUIForURL(this, url);
[email protected]420ae012009-04-24 05:16:322297}
2298
2299NavigationEntry*
2300TabContents::GetLastCommittedNavigationEntryForRenderManager() {
2301 return controller_.GetLastCommittedEntry();
2302}
2303
2304bool TabContents::CreateRenderViewForRenderManager(
2305 RenderViewHost* render_view_host) {
[email protected]811bfe32009-07-01 08:46:252306 // If the pending navigation is to a DOMUI, tell the RenderView about any
2307 // bindings it will need enabled.
[email protected]420ae012009-04-24 05:16:322308 if (render_manager_.pending_dom_ui())
[email protected]811bfe32009-07-01 08:46:252309 render_view_host->AllowBindings(
2310 render_manager_.pending_dom_ui()->bindings());
[email protected]1adff062009-06-02 18:39:552311
[email protected]420ae012009-04-24 05:16:322312 RenderWidgetHostView* rwh_view = view_->CreateViewForWidget(render_view_host);
2313 if (!render_view_host->CreateRenderView())
2314 return false;
2315
2316 // Now that the RenderView has been created, we need to tell it its size.
2317 rwh_view->SetSize(view_->GetContainerSize());
2318
2319 UpdateMaxPageIDIfNecessary(render_view_host->site_instance(),
2320 render_view_host);
2321 return true;
2322}
2323
2324void TabContents::Observe(NotificationType type,
2325 const NotificationSource& source,
2326 const NotificationDetails& details) {
2327 switch (type.value) {
2328 case NotificationType::BOOKMARK_MODEL_LOADED:
2329 // BookmarkModel finished loading, fall through to update starred state.
2330 case NotificationType::URLS_STARRED: {
2331 // Somewhere, a URL has been starred.
2332 // Ignore notifications for profiles other than our current one.
2333 Profile* source_profile = Source<Profile>(source).ptr();
2334 if (!source_profile || !source_profile->IsSameProfile(profile()))
2335 return;
2336
2337 UpdateStarredStateForCurrentURL();
2338 break;
2339 }
2340 case NotificationType::PREF_CHANGED: {
2341 std::wstring* pref_name_in = Details<std::wstring>(details).ptr();
2342 DCHECK(Source<PrefService>(source).ptr() == profile()->GetPrefs());
2343 if (*pref_name_in == prefs::kAlternateErrorPagesEnabled) {
2344 UpdateAlternateErrorPageURL();
2345 } else if (*pref_name_in == prefs::kDefaultCharset ||
2346 StartsWithASCII(WideToUTF8(*pref_name_in), "webkit.webprefs.", true)
2347 ) {
2348 UpdateWebPreferences();
2349 } else {
2350 NOTREACHED() << "unexpected pref change notification" << *pref_name_in;
2351 }
2352 break;
2353 }
2354 case NotificationType::RENDER_WIDGET_HOST_DESTROYED:
2355 view_->RenderWidgetHostDestroyed(Source<RenderWidgetHost>(source).ptr());
2356 break;
2357
2358 case NotificationType::NAV_ENTRY_COMMITTED: {
2359 DCHECK(&controller_ == Source<NavigationController>(source).ptr());
2360
2361 NavigationController::LoadCommittedDetails& committed_details =
2362 *(Details<NavigationController::LoadCommittedDetails>(details).ptr());
2363 ExpireInfoBars(committed_details);
2364 break;
2365 }
2366
2367 default:
2368 NOTREACHED();
2369 }
2370}