blob: 001be5853849b9a96f6bf3f152a1c7e4a4d4fc29 [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]e8382172009-06-19 22:16:28754#if defined(OS_WIN) || defined(OS_LINUX)
initial.commit09911bf2008-07-26 23:55:29755ConstrainedWindow* TabContents::CreateConstrainedDialog(
[email protected]e8382172009-06-19 22:16:28756 ConstrainedWindowDelegate* delegate) {
initial.commit09911bf2008-07-26 23:55:29757 ConstrainedWindow* window =
[email protected]e8382172009-06-19 22:16:28758 ConstrainedWindow::CreateConstrainedDialog(this, delegate);
initial.commit09911bf2008-07-26 23:55:29759 child_windows_.push_back(window);
760 return window;
761}
[email protected]f3332e12009-03-23 15:28:57762#endif
initial.commit09911bf2008-07-26 23:55:29763
764void TabContents::AddNewContents(TabContents* new_contents,
765 WindowOpenDisposition disposition,
766 const gfx::Rect& initial_pos,
[email protected]c88a70fe2009-05-05 20:00:22767 bool user_gesture,
768 const GURL& creator_url) {
initial.commit09911bf2008-07-26 23:55:29769 if (!delegate_)
770 return;
771
[email protected]35f7d212009-04-29 21:19:27772 if ((disposition == NEW_POPUP) && !user_gesture &&
773 !CommandLine::ForCurrentProcess()->HasSwitch(
774 switches::kDisablePopupBlocking)) {
[email protected]2c4410d2009-05-06 23:46:22775 // Unrequested popups from normal pages are constrained unless they're in
[email protected]b6c874582009-05-08 19:38:31776 // the whitelist. The popup owner will handle checking this.
777 delegate_->GetConstrainingContents(this)->AddPopup(new_contents,
778 initial_pos,
779 creator_url.is_valid() ? creator_url.host() : std::string());
780 } else {
[email protected]0aa55312008-10-17 21:53:08781 new_contents->DisassociateFromPopupCount();
initial.commit09911bf2008-07-26 23:55:29782 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
783 user_gesture);
784 }
[email protected]b6c874582009-05-08 19:38:31785 PopupNotificationVisibilityChanged(ShowingBlockedPopupNotification());
initial.commit09911bf2008-07-26 23:55:29786}
787
initial.commit09911bf2008-07-26 23:55:29788void TabContents::CloseAllSuppressedPopups() {
[email protected]d6598c052008-11-05 19:03:25789 if (blocked_popups_)
[email protected]2c4410d2009-05-06 23:46:22790 blocked_popups_->CloseAll();
initial.commit09911bf2008-07-26 23:55:29791}
792
[email protected]96d185d2009-04-24 03:28:54793void TabContents::PopupNotificationVisibilityChanged(bool visible) {
794 render_view_host()->PopupNotificationVisibilityChanged(visible);
795}
796
797gfx::NativeView TabContents::GetContentNativeView() {
798 return view_->GetContentNativeView();
799}
800
801gfx::NativeView TabContents::GetNativeView() const {
802 return view_->GetNativeView();
803}
804
805void TabContents::GetContainerBounds(gfx::Rect *out) const {
806 view_->GetContainerBounds(out);
807}
808
809void TabContents::Focus() {
810 view_->Focus();
811}
812
[email protected]90daadb42009-06-08 21:27:28813void TabContents::FocusThroughTabTraversal(bool reverse) {
[email protected]7e383692009-06-12 19:14:54814 if (showing_interstitial_page()) {
815 render_manager_.interstitial_page()->FocusThroughTabTraversal(reverse);
816 return;
817 }
[email protected]96d185d2009-04-24 03:28:54818 render_view_host()->SetInitialFocus(reverse);
819}
820
821bool TabContents::FocusLocationBarByDefault() {
822 DOMUI* dom_ui = GetDOMUIForCurrentState();
823 if (dom_ui)
824 return dom_ui->focus_location_bar_by_default();
[email protected]3e3f0eb2009-06-22 18:33:43825 NavigationEntry* entry = controller_.GetActiveEntry();
826 if (entry && entry->url() == GURL("about:blank"))
827 return true;
[email protected]96d185d2009-04-24 03:28:54828 return false;
829}
830
[email protected]616ed5a2008-11-21 22:27:24831void TabContents::AddInfoBar(InfoBarDelegate* delegate) {
832 // Look through the existing InfoBarDelegates we have for a match. If we've
833 // already got one that matches, then we don't add the new one.
[email protected]f86a07022008-11-25 01:06:05834 for (int i = 0; i < infobar_delegate_count(); ++i) {
[email protected]616ed5a2008-11-21 22:27:24835 if (GetInfoBarDelegateAt(i)->EqualsDelegate(delegate))
836 return;
837 }
838
839 infobar_delegates_.push_back(delegate);
[email protected]bfd04a62009-02-01 18:16:56840 NotificationService::current()->Notify(
841 NotificationType::TAB_CONTENTS_INFOBAR_ADDED,
842 Source<TabContents>(this),
843 Details<InfoBarDelegate>(delegate));
[email protected]616ed5a2008-11-21 22:27:24844
845 // Add ourselves as an observer for navigations the first time a delegate is
846 // added. We use this notification to expire InfoBars that need to expire on
847 // page transitions.
848 if (infobar_delegates_.size() == 1) {
[email protected]bfd04a62009-02-01 18:16:56849 registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57850 Source<NavigationController>(&controller_));
[email protected]616ed5a2008-11-21 22:27:24851 }
852}
853
854void TabContents::RemoveInfoBar(InfoBarDelegate* delegate) {
855 std::vector<InfoBarDelegate*>::iterator it =
856 find(infobar_delegates_.begin(), infobar_delegates_.end(), delegate);
857 if (it != infobar_delegates_.end()) {
858 InfoBarDelegate* delegate = *it;
[email protected]bfd04a62009-02-01 18:16:56859 NotificationService::current()->Notify(
860 NotificationType::TAB_CONTENTS_INFOBAR_REMOVED,
861 Source<TabContents>(this),
862 Details<InfoBarDelegate>(delegate));
[email protected]f86a07022008-11-25 01:06:05863 infobar_delegates_.erase(it);
[email protected]616ed5a2008-11-21 22:27:24864
[email protected]6a02963e2009-01-06 16:58:03865 // Remove ourselves as an observer if we are tracking no more InfoBars.
866 if (infobar_delegates_.empty()) {
[email protected]bfd04a62009-02-01 18:16:56867 registrar_.Remove(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57868 Source<NavigationController>(&controller_));
[email protected]6a02963e2009-01-06 16:58:03869 }
[email protected]616ed5a2008-11-21 22:27:24870 }
871}
[email protected]3edd9522009-03-04 22:19:41872
[email protected]96d185d2009-04-24 03:28:54873bool TabContents::IsBookmarkBarAlwaysVisible() {
874 // See GetDOMUIForCurrentState() comment for more info. This case is very
875 // similar, but for non-first loads, we want to use the committed entry. This
876 // is so the bookmarks bar disappears at the same time the page does.
877 if (controller_.GetLastCommittedEntry()) {
878 // Not the first load, always use the committed DOM UI.
879 if (render_manager_.dom_ui())
880 return render_manager_.dom_ui()->force_bookmark_bar_visible();
881 return false; // Default.
882 }
883
884 // When it's the first load, we know either the pending one or the committed
885 // one will have the DOM UI in it (see GetDOMUIForCurrentState), and only one
886 // of them will be valid, so we can just check both.
887 if (render_manager_.pending_dom_ui())
888 return render_manager_.pending_dom_ui()->force_bookmark_bar_visible();
889 if (render_manager_.dom_ui())
890 return render_manager_.dom_ui()->force_bookmark_bar_visible();
891 return false; // Default.
892}
893
[email protected]3edd9522009-03-04 22:19:41894void TabContents::ToolbarSizeChanged(bool is_animating) {
895 TabContentsDelegate* d = delegate();
896 if (d)
897 d->ToolbarSizeChanged(this, is_animating);
898}
[email protected]616ed5a2008-11-21 22:27:24899
[email protected]d5f942ba2008-09-26 19:30:34900void TabContents::OnStartDownload(DownloadItem* download) {
901 DCHECK(download);
[email protected]d5f942ba2008-09-26 19:30:34902
903 // Download in a constrained popup is shown in the tab that opened it.
[email protected]b6c874582009-05-08 19:38:31904 TabContents* tab_contents = delegate()->GetConstrainingContents(this);
[email protected]d5f942ba2008-09-26 19:30:34905
[email protected]59560e0b2009-06-04 03:30:22906 if (tab_contents && tab_contents->delegate())
907 tab_contents->delegate()->OnStartDownload(download);
[email protected]3edd9522009-03-04 22:19:41908}
[email protected]3edd9522009-03-04 22:19:41909
[email protected]d5f942ba2008-09-26 19:30:34910void TabContents::WillClose(ConstrainedWindow* window) {
911 ConstrainedWindowList::iterator it =
912 find(child_windows_.begin(), child_windows_.end(), window);
913 if (it != child_windows_.end())
914 child_windows_.erase(it);
[email protected]66ba4932009-06-04 19:22:13915}
[email protected]d5f942ba2008-09-26 19:30:34916
[email protected]66ba4932009-06-04 19:22:13917void TabContents::WillCloseBlockedPopupContainer(
918 BlockedPopupContainer* container) {
919 DCHECK(blocked_popups_ == container);
920 blocked_popups_ = NULL;
[email protected]d5f942ba2008-09-26 19:30:34921}
922
[email protected]d5f942ba2008-09-26 19:30:34923void TabContents::DidMoveOrResize(ConstrainedWindow* window) {
[email protected]332af7732009-03-11 13:21:35924#if defined(OS_WIN)
[email protected]92edc472009-02-10 20:32:06925 UpdateWindow(GetNativeView());
[email protected]332af7732009-03-11 13:21:35926#endif
[email protected]d5f942ba2008-09-26 19:30:34927}
928
[email protected]e491f1c2009-05-22 20:28:12929void TabContents::StartFinding(string16 find_text,
930 bool forward_direction,
931 bool case_sensitive) {
[email protected]6e95706d2009-04-23 22:55:01932 // If find_text is empty, it means FindNext was pressed with a keyboard
933 // shortcut so unless we have something to search for we return early.
[email protected]e491f1c2009-05-22 20:28:12934 if (find_text.empty() && find_text_.empty()) {
935 if (last_search_prepopulate_text_->empty())
936 return;
937 // Try whatever we searched for last in any tab.
938 find_text = *last_search_prepopulate_text_;
939 }
[email protected]6e95706d2009-04-23 22:55:01940
941 // This is a FindNext operation if we are searching for the same text again,
942 // or if the passed in search text is empty (FindNext keyboard shortcut). The
943 // exception to this is if the Find was aborted (then we don't want FindNext
944 // because the highlighting has been cleared and we need it to reappear). We
945 // therefore treat FindNext after an aborted Find operation as a full fledged
946 // Find.
947 bool find_next = (find_text_ == find_text || find_text.empty()) &&
[email protected]e491f1c2009-05-22 20:28:12948 (last_search_case_sensitive_ == case_sensitive) &&
[email protected]6e95706d2009-04-23 22:55:01949 !find_op_aborted_;
950 if (!find_next)
951 current_find_request_id_ = find_request_id_counter_++;
952
953 if (!find_text.empty())
954 find_text_ = find_text;
[email protected]e491f1c2009-05-22 20:28:12955 last_search_case_sensitive_ = case_sensitive;
[email protected]6e95706d2009-04-23 22:55:01956
957 find_op_aborted_ = false;
958
959 // Keep track of what the last search was across the tabs.
[email protected]e491f1c2009-05-22 20:28:12960 *last_search_prepopulate_text_ = find_text;
[email protected]6e95706d2009-04-23 22:55:01961
962 render_view_host()->StartFinding(current_find_request_id_,
963 find_text_,
964 forward_direction,
[email protected]e491f1c2009-05-22 20:28:12965 case_sensitive,
[email protected]6e95706d2009-04-23 22:55:01966 find_next);
967}
968
969void TabContents::StopFinding(bool clear_selection) {
[email protected]2d2dffc2009-06-09 21:41:00970 // When |clear_selection| is true, it means the find string has been cleared
971 // by the user, but the UI has not been dismissed.
972 if (!clear_selection)
973 find_ui_active_ = false;
[email protected]6e95706d2009-04-23 22:55:01974 find_op_aborted_ = true;
[email protected]e491f1c2009-05-22 20:28:12975 last_search_result_ = FindNotificationDetails();
[email protected]6e95706d2009-04-23 22:55:01976 render_view_host()->StopFinding(clear_selection);
977}
978
[email protected]420ae012009-04-24 05:16:32979void TabContents::OnJavaScriptMessageBoxClosed(IPC::Message* reply_msg,
980 bool success,
981 const std::wstring& prompt) {
982 last_javascript_message_dismissal_ = base::TimeTicks::Now();
983 render_manager_.OnJavaScriptMessageBoxClosed(reply_msg, success, prompt);
984}
985
[email protected]571e31152009-05-15 19:34:02986void TabContents::OnJavaScriptMessageBoxWindowDestroyed() {
987 render_manager_.OnJavaScriptMessageBoxWindowDestroyed();
988}
989
[email protected]420ae012009-04-24 05:16:32990void TabContents::OnSavePage() {
991 // If we can not save the page, try to download it.
992 if (!SavePackage::IsSavableContents(contents_mime_type())) {
993 DownloadManager* dlm = profile()->GetDownloadManager();
994 const GURL& current_page_url = GetURL();
995 if (dlm && current_page_url.is_valid())
[email protected]d82ed61e2009-06-16 02:46:22996 dlm->DownloadUrl(current_page_url, GURL(), "", this);
[email protected]420ae012009-04-24 05:16:32997 return;
998 }
999
1000 Stop();
1001
1002 // Create the save package and possibly prompt the user for the name to save
1003 // the page as. The user prompt is an asynchronous operation that runs on
1004 // another thread.
[email protected]d82ed61e2009-06-16 02:46:221005 save_package_ = new SavePackage(this);
[email protected]420ae012009-04-24 05:16:321006 save_package_->GetSaveInfo();
1007}
1008
1009// Used in automated testing to bypass prompting the user for file names.
1010// Instead, the names and paths are hard coded rather than running them through
1011// file name sanitation and extension / mime checking.
1012void TabContents::SavePage(const std::wstring& main_file,
1013 const std::wstring& dir_path,
1014 SavePackage::SavePackageType save_type) {
1015 // Stop the page from navigating.
1016 Stop();
1017
[email protected]d82ed61e2009-06-16 02:46:221018 save_package_ = new SavePackage(this, save_type,
[email protected]420ae012009-04-24 05:16:321019 FilePath::FromWStringHack(main_file),
1020 FilePath::FromWStringHack(dir_path));
1021 save_package_->Init();
1022}
1023
1024void TabContents::PrintPreview() {
1025 // We don't show the print preview yet, only the print dialog.
1026 PrintNow();
1027}
1028
1029bool TabContents::PrintNow() {
1030 // We can't print interstitial page for now.
1031 if (showing_interstitial_page())
1032 return false;
1033
1034 return render_view_host()->PrintPages();
1035}
1036
[email protected]82270452009-06-19 15:58:011037void TabContents::PrintingDone(int document_cookie, bool success) {
1038 render_view_host()->PrintingDone(document_cookie, success);
1039}
1040
[email protected]420ae012009-04-24 05:16:321041bool TabContents::IsActiveEntry(int32 page_id) {
1042 NavigationEntry* active_entry = controller_.GetActiveEntry();
1043 return (active_entry != NULL &&
1044 active_entry->site_instance() == GetSiteInstance() &&
1045 active_entry->page_id() == page_id);
1046}
1047
[email protected]96d185d2009-04-24 03:28:541048// Notifies the RenderWidgetHost instance about the fact that the page is
1049// loading, or done loading and calls the base implementation.
1050void TabContents::SetIsLoading(bool is_loading,
1051 LoadNotificationDetails* details) {
1052 if (is_loading == is_loading_)
1053 return;
1054
1055 if (!is_loading) {
1056 load_state_ = net::LOAD_STATE_IDLE;
1057 load_state_host_.clear();
1058 }
1059
1060 render_manager_.SetIsLoading(is_loading);
1061
1062 is_loading_ = is_loading;
1063 waiting_for_response_ = is_loading;
1064
1065 if (delegate_)
1066 delegate_->LoadingStateChanged(this);
[email protected]329581b2009-04-28 06:52:351067 NotifyNavigationStateChanged(INVALIDATE_LOAD);
[email protected]96d185d2009-04-24 03:28:541068
1069 NotificationType type = is_loading ? NotificationType::LOAD_START :
1070 NotificationType::LOAD_STOP;
[email protected]ce5c4502009-05-06 16:46:111071 NotificationDetails det = NotificationService::NoDetails();
[email protected]96d185d2009-04-24 03:28:541072 if (details)
1073 det = Details<LoadNotificationDetails>(details);
1074 NotificationService::current()->Notify(type,
1075 Source<NavigationController>(&controller_),
1076 det);
1077}
1078
[email protected]2c4410d2009-05-06 23:46:221079void TabContents::CreateBlockedPopupContainerIfNecessary() {
1080 if (blocked_popups_)
1081 return;
1082
[email protected]4d4c0b92009-06-08 23:13:011083 blocked_popups_ = BlockedPopupContainer::Create(this, profile());
[email protected]2c4410d2009-05-06 23:46:221084}
1085
[email protected]b6c874582009-05-08 19:38:311086void TabContents::AddPopup(TabContents* new_contents,
1087 const gfx::Rect& initial_pos,
1088 const std::string& host) {
[email protected]2c4410d2009-05-06 23:46:221089 CreateBlockedPopupContainerIfNecessary();
1090 blocked_popups_->AddTabContents(new_contents, initial_pos, host);
[email protected]2c4410d2009-05-06 23:46:221091}
1092
[email protected]e69bce3dd2009-04-20 22:05:121093// TODO(brettw) This should be on the TabContentsView.
[email protected]66ba4932009-06-04 19:22:131094void TabContents::RepositionSupressedPopupsToFit() {
[email protected]d6598c052008-11-05 19:03:251095 if (blocked_popups_)
[email protected]4d4c0b92009-06-08 23:13:011096 blocked_popups_->RepositionBlockedPopupContainer();
[email protected]d5f942ba2008-09-26 19:30:341097}
1098
[email protected]b9681312008-11-07 00:08:261099bool TabContents::ShowingBlockedPopupNotification() const {
1100 return blocked_popups_ != NULL &&
[email protected]2c4410d2009-05-06 23:46:221101 blocked_popups_->GetBlockedPopupCount() != 0;
[email protected]b9681312008-11-07 00:08:261102}
[email protected]616ed5a2008-11-21 22:27:241103
1104namespace {
1105bool TransitionIsReload(PageTransition::Type transition) {
1106 return PageTransition::StripQualifier(transition) == PageTransition::RELOAD;
1107}
1108}
1109
1110void TabContents::ExpireInfoBars(
1111 const NavigationController::LoadCommittedDetails& details) {
1112 // Only hide InfoBars when the user has done something that makes the main
1113 // frame load. We don't want various automatic or subframe navigations making
1114 // it disappear.
1115 if (!details.is_user_initiated_main_frame_load())
1116 return;
1117
[email protected]f86a07022008-11-25 01:06:051118 for (int i = infobar_delegate_count() - 1; i >= 0; --i) {
[email protected]616ed5a2008-11-21 22:27:241119 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
[email protected]f86a07022008-11-25 01:06:051120 if (delegate->ShouldExpire(details))
[email protected]616ed5a2008-11-21 22:27:241121 RemoveInfoBar(delegate);
[email protected]616ed5a2008-11-21 22:27:241122 }
1123}
[email protected]fdd61c62009-04-22 19:22:571124
1125void TabContents::OnGearsCreateShortcutDone(
1126 const GearsShortcutData2& shortcut_data, bool success) {
1127 NavigationEntry* current_entry = controller_.GetLastCommittedEntry();
1128 bool same_page =
1129 current_entry && pending_install_.page_id == current_entry->page_id();
1130
1131 if (success && same_page) {
1132 // Only switch to app mode if the user chose to create a shortcut and
1133 // we're still on the same page that it corresponded to.
1134 if (delegate())
1135 delegate()->ConvertContentsToApplication(this);
1136 }
1137
1138 // Reset the page id to indicate no requests are pending.
1139 pending_install_.page_id = 0;
1140 pending_install_.callback_functor = NULL;
1141}
[email protected]96d185d2009-04-24 03:28:541142
1143DOMUI* TabContents::GetDOMUIForCurrentState() {
1144 // When there is a pending navigation entry, we want to use the pending DOMUI
1145 // that goes along with it to control the basic flags. For example, we want to
1146 // show the pending URL in the URL bar, so we want the display_url flag to
1147 // be from the pending entry.
1148 //
1149 // The confusion comes because there are multiple possibilities for the
1150 // initial load in a tab as a side effect of the way the RenderViewHostManager
1151 // works.
1152 //
1153 // - For the very first tab the load looks "normal". The new tab DOM UI is
1154 // the pending one, and we want it to apply here.
1155 //
1156 // - For subsequent new tabs, they'll get a new SiteInstance which will then
1157 // get switched to the one previously associated with the new tab pages.
1158 // This switching will cause the manager to commit the RVH/DOMUI. So we'll
1159 // have a committed DOM UI in this case.
1160 //
1161 // This condition handles all of these cases:
1162 //
1163 // - First load in first tab: no committed nav entry + pending nav entry +
1164 // pending dom ui:
1165 // -> Use pending DOM UI if any.
1166 //
1167 // - First load in second tab: no committed nav entry + pending nav entry +
1168 // no pending DOM UI:
1169 // -> Use the committed DOM UI if any.
1170 //
1171 // - Second navigation in any tab: committed nav entry + pending nav entry:
1172 // -> Use pending DOM UI if any.
1173 //
1174 // - Normal state with no load: committed nav entry + no pending nav entry:
1175 // -> Use committed DOM UI.
1176 if (controller_.pending_entry() &&
1177 (controller_.GetLastCommittedEntry() ||
1178 render_manager_.pending_dom_ui()))
1179 return render_manager_.pending_dom_ui();
1180 return render_manager_.dom_ui();
1181}
[email protected]420ae012009-04-24 05:16:321182
1183void TabContents::DidNavigateMainFramePostCommit(
1184 const NavigationController::LoadCommittedDetails& details,
1185 const ViewHostMsg_FrameNavigate_Params& params) {
[email protected]420ae012009-04-24 05:16:321186 if (details.is_user_initiated_main_frame_load()) {
1187 // Clear the status bubble. This is a workaround for a bug where WebKit
1188 // doesn't let us know that the cursor left an element during a
1189 // transition (this is also why the mouse cursor remains as a hand after
1190 // clicking on a link); see bugs 1184641 and 980803. We don't want to
1191 // clear the bubble when a user navigates to a named anchor in the same
1192 // page.
1193 UpdateTargetURL(details.entry->page_id(), GURL());
1194
1195 // UpdateHelpersForDidNavigate will handle the case where the password_form
1196 // origin is valid.
1197 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1198 // cleaned up and covered by tests.
1199 if (!params.password_form.origin.is_valid())
1200 GetPasswordManager()->DidNavigate();
1201 }
1202
1203 // The keyword generator uses the navigation entries, so must be called after
1204 // the commit.
1205 GenerateKeywordIfNecessary(params);
1206
1207 // Allow the new page to set the title again.
1208 received_page_title_ = false;
1209
1210 // Get the favicon, either from history or request it from the net.
1211 fav_icon_helper_.FetchFavIcon(details.entry->url());
1212
[email protected]ce5c4502009-05-06 16:46:111213 // Disable all page actions.
1214 enabled_page_actions_.clear();
1215
[email protected]420ae012009-04-24 05:16:321216 // Close constrained popups if necessary.
1217 MaybeCloseChildWindows(details.previous_url, details.entry->url());
1218
1219 // Update the starred state.
1220 UpdateStarredStateForCurrentURL();
1221}
1222
1223void TabContents::DidNavigateAnyFramePostCommit(
1224 RenderViewHost* render_view_host,
1225 const NavigationController::LoadCommittedDetails& details,
1226 const ViewHostMsg_FrameNavigate_Params& params) {
1227 // If we navigate, start showing messages again. This does nothing to prevent
1228 // a malicious script from spamming messages, since the script could just
1229 // reload the page to stop blocking.
1230 suppress_javascript_messages_ = false;
1231
[email protected]420ae012009-04-24 05:16:321232 // Notify the password manager of the navigation or form submit.
1233 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1234 // cleaned up and covered by tests.
1235 if (params.password_form.origin.is_valid())
1236 GetPasswordManager()->ProvisionallySavePassword(params.password_form);
1237}
1238
1239void TabContents::MaybeCloseChildWindows(const GURL& previous_url,
1240 const GURL& current_url) {
1241 if (net::RegistryControlledDomainService::SameDomainOrHost(
1242 previous_url, current_url))
1243 return;
1244
1245 // Clear out any child windows since we are leaving this page entirely.
1246 // We use indices instead of iterators in case CloseWindow does something
1247 // that may invalidate an iterator.
1248 int size = static_cast<int>(child_windows_.size());
1249 for (int i = size - 1; i >= 0; --i) {
1250 ConstrainedWindow* window = child_windows_[i];
1251 if (window)
1252 window->CloseConstrainedWindow();
1253 }
1254}
1255
1256void TabContents::UpdateStarredStateForCurrentURL() {
1257 BookmarkModel* model = profile()->GetBookmarkModel();
1258 const bool old_state = is_starred_;
1259 is_starred_ = (model && model->IsBookmarked(GetURL()));
1260
1261 if (is_starred_ != old_state && delegate())
1262 delegate()->URLStarredChanged(this, is_starred_);
1263}
1264
1265void TabContents::UpdateAlternateErrorPageURL() {
1266 GURL url = GetAlternateErrorPageURL();
1267 render_view_host()->SetAlternateErrorPageURL(url);
1268}
1269
1270void TabContents::UpdateWebPreferences() {
1271 render_view_host()->UpdateWebPreferences(GetWebkitPrefs());
1272}
1273
1274void TabContents::UpdateMaxPageIDIfNecessary(SiteInstance* site_instance,
1275 RenderViewHost* rvh) {
1276 // If we are creating a RVH for a restored controller, then we might
1277 // have more page IDs than the SiteInstance's current max page ID. We must
1278 // make sure that the max page ID is larger than any restored page ID.
1279 // Note that it is ok for conflicting page IDs to exist in another tab
1280 // (i.e., NavigationController), but if any page ID is larger than the max,
1281 // the back/forward list will get confused.
1282 int max_restored_page_id = controller_.max_restored_page_id();
1283 if (max_restored_page_id > 0) {
1284 int curr_max_page_id = site_instance->max_page_id();
1285 if (max_restored_page_id > curr_max_page_id) {
1286 // Need to update the site instance immediately.
1287 site_instance->UpdateMaxPageID(max_restored_page_id);
1288
1289 // Also tell the renderer to update its internal representation. We
1290 // need to reserve enough IDs to make all restored page IDs less than
1291 // the max.
1292 if (curr_max_page_id < 0)
1293 curr_max_page_id = 0;
1294 rvh->ReservePageIDRange(max_restored_page_id - curr_max_page_id);
1295 }
1296 }
1297}
1298
1299void TabContents::UpdateHistoryForNavigation(
1300 const GURL& display_url,
[email protected]befd8d822009-07-01 04:51:471301 const NavigationController::LoadCommittedDetails& details,
[email protected]420ae012009-04-24 05:16:321302 const ViewHostMsg_FrameNavigate_Params& params) {
1303 if (profile()->IsOffTheRecord())
1304 return;
1305
1306 // Add to history service.
1307 HistoryService* hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1308 if (hs) {
1309 if (PageTransition::IsMainFrame(params.transition) &&
1310 display_url != params.url) {
1311 // Hack on the "display" URL so that it will appear in history. For some
1312 // types of URLs, we will display a magic URL that is different from where
1313 // the page is actually navigated. We want the user to see in history
1314 // what they saw in the URL bar, so we add the display URL as a redirect.
1315 // This only applies to the main frame, as the display URL doesn't apply
1316 // to sub-frames.
1317 std::vector<GURL> redirects = params.redirects;
1318 if (!redirects.empty())
1319 redirects.back() = display_url;
1320 hs->AddPage(display_url, this, params.page_id, params.referrer,
[email protected]befd8d822009-07-01 04:51:471321 params.transition, redirects, details.did_replace_entry);
[email protected]420ae012009-04-24 05:16:321322 } else {
1323 hs->AddPage(params.url, this, params.page_id, params.referrer,
[email protected]befd8d822009-07-01 04:51:471324 params.transition, params.redirects,
1325 details.did_replace_entry);
[email protected]420ae012009-04-24 05:16:321326 }
1327 }
1328}
1329
1330bool TabContents::UpdateTitleForEntry(NavigationEntry* entry,
1331 const std::wstring& title) {
1332 // For file URLs without a title, use the pathname instead. In the case of a
1333 // synthesized title, we don't want the update to count toward the "one set
1334 // per page of the title to history."
1335 std::wstring final_title;
1336 bool explicit_set;
1337 if (entry->url().SchemeIsFile() && title.empty()) {
1338 final_title = UTF8ToWide(entry->url().ExtractFileName());
1339 explicit_set = false; // Don't count synthetic titles toward the set limit.
1340 } else {
1341 TrimWhitespace(title, TRIM_ALL, &final_title);
1342 explicit_set = true;
1343 }
1344
1345 if (final_title == UTF16ToWideHack(entry->title()))
1346 return false; // Nothing changed, don't bother.
1347
1348 entry->set_title(WideToUTF16Hack(final_title));
1349
1350 // Update the history system for this page.
1351 if (!profile()->IsOffTheRecord() && !received_page_title_) {
1352 HistoryService* hs =
1353 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1354 if (hs)
1355 hs->SetPageTitle(entry->display_url(), final_title);
1356
1357 // Don't allow the title to be saved again for explicitly set ones.
1358 received_page_title_ = explicit_set;
1359 }
1360
1361 // Lastly, set the title for the view.
1362 view_->SetPageTitle(final_title);
1363
1364 return true;
1365}
1366
1367void TabContents::NotifySwapped() {
1368 // After sending out a swap notification, we need to send a disconnect
1369 // notification so that clients that pick up a pointer to |this| can NULL the
1370 // pointer. See Bug 1230284.
1371 notify_disconnection_ = true;
1372 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341373 NotificationType::TAB_CONTENTS_SWAPPED,
[email protected]d82ed61e2009-06-16 02:46:221374 Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321375 NotificationService::NoDetails());
1376}
1377
1378void TabContents::NotifyConnected() {
1379 notify_disconnection_ = true;
1380 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341381 NotificationType::TAB_CONTENTS_CONNECTED,
[email protected]d82ed61e2009-06-16 02:46:221382 Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321383 NotificationService::NoDetails());
1384}
1385
1386void TabContents::NotifyDisconnected() {
1387 if (!notify_disconnection_)
1388 return;
1389
1390 notify_disconnection_ = false;
1391 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341392 NotificationType::TAB_CONTENTS_DISCONNECTED,
[email protected]d82ed61e2009-06-16 02:46:221393 Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321394 NotificationService::NoDetails());
1395}
1396
1397void TabContents::GenerateKeywordIfNecessary(
1398 const ViewHostMsg_FrameNavigate_Params& params) {
1399 if (!params.searchable_form_url.is_valid())
1400 return;
1401
1402 if (profile()->IsOffTheRecord())
1403 return;
1404
1405 int last_index = controller_.last_committed_entry_index();
1406 // When there was no previous page, the last index will be 0. This is
1407 // normally due to a form submit that opened in a new tab.
1408 // TODO(brettw) bug 916126: we should support keywords when form submits
1409 // happen in new tabs.
1410 if (last_index <= 0)
1411 return;
1412 const NavigationEntry* previous_entry =
1413 controller_.GetEntryAtIndex(last_index - 1);
1414 if (IsFormSubmit(previous_entry)) {
1415 // Only generate a keyword if the previous page wasn't itself a form
1416 // submit.
1417 return;
1418 }
1419
1420 GURL keyword_url = previous_entry->user_typed_url().is_valid() ?
1421 previous_entry->user_typed_url() : previous_entry->url();
1422 std::wstring keyword =
1423 TemplateURLModel::GenerateKeyword(keyword_url, true); // autodetected
1424 if (keyword.empty())
1425 return;
1426
1427 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
1428 if (!url_model)
1429 return;
1430
1431 if (!url_model->loaded()) {
1432 url_model->Load();
1433 return;
1434 }
1435
1436 const TemplateURL* current_url;
1437 std::wstring url = UTF8ToWide(params.searchable_form_url.spec());
1438 if (!url_model->CanReplaceKeyword(keyword, url, &current_url))
1439 return;
1440
1441 if (current_url) {
1442 if (current_url->originating_url().is_valid()) {
1443 // The existing keyword was generated from an OpenSearch description
1444 // document, don't regenerate.
1445 return;
1446 }
1447 url_model->Remove(current_url);
1448 }
1449 TemplateURL* new_url = new TemplateURL();
1450 new_url->set_keyword(keyword);
1451 new_url->set_short_name(keyword);
1452 new_url->SetURL(url, 0, 0);
1453 new_url->add_input_encoding(params.searchable_form_encoding);
1454 DCHECK(controller_.GetLastCommittedEntry());
1455 const GURL& favicon_url =
1456 controller_.GetLastCommittedEntry()->favicon().url();
1457 if (favicon_url.is_valid()) {
1458 new_url->SetFavIconURL(favicon_url);
1459 } else {
1460 // The favicon url isn't valid. This means there really isn't a favicon,
1461 // or the favicon url wasn't obtained before the load started. This assumes
1462 // the later.
1463 // TODO(sky): Need a way to set the favicon that doesn't involve generating
1464 // its url.
1465 new_url->SetFavIconURL(TemplateURL::GenerateFaviconURL(params.referrer));
1466 }
1467 new_url->set_safe_for_autoreplace(true);
1468 url_model->Add(new_url);
1469}
1470
[email protected]bf5c2ff392009-07-08 16:24:331471void TabContents::OnUserGesture() {
1472 // See comment in RenderViewHostDelegate::OnUserGesture as to why we do this.
1473 DownloadRequestManager* drm = g_browser_process->download_request_manager();
1474 if (drm)
1475 drm->OnUserGesture(this);
1476 controller_.OnUserGesture();
1477}
1478
1479void TabContents::OnFindReply(int request_id,
1480 int number_of_matches,
1481 const gfx::Rect& selection_rect,
1482 int active_match_ordinal,
1483 bool final_update) {
1484 // Ignore responses for requests other than the one we have most recently
1485 // issued. That way we won't act on stale results when the user has
1486 // already typed in another query.
1487 if (request_id != current_find_request_id_)
1488 return;
1489
1490 if (number_of_matches == -1)
1491 number_of_matches = last_search_result_.number_of_matches();
1492 if (active_match_ordinal == -1)
1493 active_match_ordinal = last_search_result_.active_match_ordinal();
1494
1495 gfx::Rect selection = selection_rect;
1496 if (selection.IsEmpty())
1497 selection = last_search_result_.selection_rect();
1498
1499 // Notify the UI, automation and any other observers that a find result was
1500 // found.
1501 last_search_result_ = FindNotificationDetails(request_id, number_of_matches,
1502 selection, active_match_ordinal,
1503 final_update);
1504 NotificationService::current()->Notify(
1505 NotificationType::FIND_RESULT_AVAILABLE,
1506 Source<TabContents>(this),
1507 Details<FindNotificationDetails>(&last_search_result_));
1508}
1509
1510void TabContents::GoToEntryAtOffset(int offset) {
1511 controller_.GoToOffset(offset);
1512}
1513
1514void TabContents::GetHistoryListCount(int* back_list_count,
1515 int* forward_list_count) {
1516 int current_index = controller_.last_committed_entry_index();
1517 *back_list_count = current_index;
1518 *forward_list_count = controller_.entry_count() - current_index - 1;
1519}
1520
1521void TabContents::OnMissingPluginStatus(int status) {
1522#if defined(OS_WIN)
1523// TODO(PORT): pull in when plug-ins work
1524 GetPluginInstaller()->OnMissingPluginStatus(status);
1525#endif
1526}
1527
1528void TabContents::OnCrashedPlugin(const FilePath& plugin_path) {
1529#if defined(OS_WIN)
1530// TODO(PORT): pull in when plug-ins work
1531 DCHECK(!plugin_path.value().empty());
1532
1533 std::wstring plugin_name = plugin_path.ToWStringHack();
1534 scoped_ptr<FileVersionInfo> version_info(
1535 FileVersionInfo::CreateFileVersionInfo(plugin_path));
1536 if (version_info.get()) {
1537 const std::wstring& product_name = version_info->product_name();
1538 if (!product_name.empty())
1539 plugin_name = product_name;
1540 }
1541 AddInfoBar(new SimpleAlertInfoBarDelegate(
1542 this, l10n_util::GetStringF(IDS_PLUGIN_CRASHED_PROMPT, plugin_name),
1543 NULL));
1544#endif
1545}
1546
1547void TabContents::OnCrashedWorker() {
1548 AddInfoBar(new SimpleAlertInfoBarDelegate(
1549 this, l10n_util::GetString(IDS_WEBWORKER_CRASHED_PROMPT),
1550 NULL));
1551}
1552
1553void TabContents::OnDidGetApplicationInfo(
1554 int32 page_id,
1555 const webkit_glue::WebApplicationInfo& info) {
1556 if (pending_install_.page_id != page_id)
1557 return; // The user clicked create on a separate page. Ignore this.
1558
1559 pending_install_.callback_functor =
1560 new GearsCreateShortcutCallbackFunctor(this);
1561 GearsCreateShortcut(
1562 info, pending_install_.title, pending_install_.url, pending_install_.icon,
1563 NewCallback(pending_install_.callback_functor,
1564 &GearsCreateShortcutCallbackFunctor::Run));
1565}
1566
1567void TabContents::DidStartProvisionalLoadForFrame(
1568 RenderViewHost* render_view_host,
1569 bool is_main_frame,
1570 const GURL& url) {
1571 ProvisionalLoadDetails details(is_main_frame,
1572 controller_.IsURLInPageNavigation(url),
1573 url, std::string(), false);
1574 NotificationService::current()->Notify(
1575 NotificationType::FRAME_PROVISIONAL_LOAD_START,
1576 Source<NavigationController>(&controller_),
1577 Details<ProvisionalLoadDetails>(&details));
1578}
1579
1580void TabContents::DidStartReceivingResourceResponse(
1581 ResourceRequestDetails* details) {
1582 NotificationService::current()->Notify(
1583 NotificationType::RESOURCE_RESPONSE_STARTED,
1584 Source<NavigationController>(&controller()),
1585 Details<ResourceRequestDetails>(details));
1586}
1587
1588void TabContents::DidRedirectResource(ResourceRequestDetails* details) {
1589 NotificationService::current()->Notify(
1590 NotificationType::RESOURCE_RECEIVED_REDIRECT,
1591 Source<NavigationController>(&controller()),
1592 Details<ResourceRequestDetails>(details));
1593}
1594
1595void TabContents::DidLoadResourceFromMemoryCache(
1596 const GURL& url,
1597 const std::string& frame_origin,
1598 const std::string& main_frame_origin,
1599 const std::string& security_info) {
1600 // Send out a notification that we loaded a resource from our memory cache.
1601 int cert_id = 0, cert_status = 0, security_bits = 0;
1602 SSLManager::DeserializeSecurityInfo(security_info,
1603 &cert_id, &cert_status,
1604 &security_bits);
1605 LoadFromMemoryCacheDetails details(url, frame_origin, main_frame_origin,
1606 process()->pid(), cert_id, cert_status);
1607
1608 NotificationService::current()->Notify(
1609 NotificationType::LOAD_FROM_MEMORY_CACHE,
1610 Source<NavigationController>(&controller_),
1611 Details<LoadFromMemoryCacheDetails>(&details));
1612}
1613
1614void TabContents::DidFailProvisionalLoadWithError(
1615 RenderViewHost* render_view_host,
1616 bool is_main_frame,
1617 int error_code,
1618 const GURL& url,
1619 bool showing_repost_interstitial) {
1620 if (net::ERR_ABORTED == error_code) {
1621 // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
1622 // This means that the interstitial won't be torn down properly, which is
1623 // bad. But if we have an interstitial, go back to another tab type, and
1624 // then load the same interstitial again, we could end up getting the first
1625 // interstitial's "failed" message (as a result of the cancel) when we're on
1626 // the second one.
1627 //
1628 // We can't tell this apart, so we think we're tearing down the current page
1629 // which will cause a crash later one. There is also some code in
1630 // RenderViewHostManager::RendererAbortedProvisionalLoad that is commented
1631 // out because of this problem.
1632 //
1633 // http://code.google.com/p/chromium/issues/detail?id=2855
1634 // Because this will not tear down the interstitial properly, if "back" is
1635 // back to another tab type, the interstitial will still be somewhat alive
1636 // in the previous tab type. If you navigate somewhere that activates the
1637 // tab with the interstitial again, you'll see a flash before the new load
1638 // commits of the interstitial page.
1639 if (showing_interstitial_page()) {
1640 LOG(WARNING) << "Discarding message during interstitial.";
1641 return;
1642 }
1643
1644 // This will discard our pending entry if we cancelled the load (e.g., if we
1645 // decided to download the file instead of load it). Only discard the
1646 // pending entry if the URLs match, otherwise the user initiated a navigate
1647 // before the page loaded so that the discard would discard the wrong entry.
1648 NavigationEntry* pending_entry = controller_.pending_entry();
1649 if (pending_entry && pending_entry->url() == url) {
1650 controller_.DiscardNonCommittedEntries();
1651 // Update the URL display.
1652 NotifyNavigationStateChanged(TabContents::INVALIDATE_URL);
1653 }
1654
1655 render_manager_.RendererAbortedProvisionalLoad(render_view_host);
1656 }
1657
1658 // Send out a notification that we failed a provisional load with an error.
1659 ProvisionalLoadDetails details(is_main_frame,
1660 controller_.IsURLInPageNavigation(url),
1661 url, std::string(), false);
1662 details.set_error_code(error_code);
1663
1664 NotificationService::current()->Notify(
1665 NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR,
1666 Source<NavigationController>(&controller_),
1667 Details<ProvisionalLoadDetails>(&details));
1668}
1669
1670void TabContents::DocumentLoadedInFrame() {
1671 controller_.DocumentLoadedInFrame();
1672}
1673
[email protected]8d3347f2009-07-09 22:00:211674RenderViewHostDelegate::View* TabContents::GetViewDelegate() {
[email protected]420ae012009-04-24 05:16:321675 return view_.get();
1676}
1677
[email protected]8d3347f2009-07-09 22:00:211678RenderViewHostDelegate::RendererManagement*
1679TabContents::GetRendererManagementDelegate() {
1680 return &render_manager_;
1681}
1682
[email protected]bf5c2ff392009-07-08 16:24:331683RenderViewHostDelegate::BrowserIntegration*
[email protected]8d3347f2009-07-09 22:00:211684 TabContents::GetBrowserIntegrationDelegate() {
1685 return this;
[email protected]bf5c2ff392009-07-08 16:24:331686}
1687
[email protected]8d3347f2009-07-09 22:00:211688RenderViewHostDelegate::Resource* TabContents::GetResourceDelegate() {
1689 return this;
[email protected]bf5c2ff392009-07-08 16:24:331690}
1691
[email protected]8d3347f2009-07-09 22:00:211692RenderViewHostDelegate::Save* TabContents::GetSaveDelegate() {
[email protected]420ae012009-04-24 05:16:321693 return save_package_.get(); // May be NULL, but we can return NULL.
1694}
1695
[email protected]8d3347f2009-07-09 22:00:211696RenderViewHostDelegate::Printing* TabContents::GetPrintingDelegate() {
1697 return &printing_;
1698}
1699
1700RenderViewHostDelegate::FavIcon* TabContents::GetFavIconDelegate() {
1701 return &fav_icon_helper_;
1702}
1703
1704RenderViewHostDelegate::Autofill* TabContents::GetAutofillDelegate() {
1705 if (autofill_manager_.get() == NULL)
1706 autofill_manager_.reset(new AutofillManager(this));
1707 return autofill_manager_.get();
[email protected]bf5c2ff392009-07-08 16:24:331708}
1709
[email protected]80d96fa2009-06-10 22:34:511710RendererPreferences TabContents::GetRendererPrefs() const {
1711 if (delegate())
1712 return delegate()->GetRendererPrefs();
1713 else
1714 return RendererPreferences();
1715}
1716
[email protected]57c6a652009-05-04 07:58:341717TabContents* TabContents::GetAsTabContents() {
1718 return this;
1719}
1720
[email protected]420ae012009-04-24 05:16:321721void TabContents::RenderViewCreated(RenderViewHost* render_view_host) {
[email protected]2e4633c2009-07-09 16:58:061722 NotificationService::current()->Notify(
1723 NotificationType::RENDER_VIEW_HOST_CREATED_FOR_TAB,
1724 Source<TabContents>(this),
1725 Details<RenderViewHost>(render_view_host));
1726
[email protected]420ae012009-04-24 05:16:321727 NavigationEntry* entry = controller_.GetActiveEntry();
1728 if (!entry)
1729 return;
1730
1731 // When we're creating views, we're still doing initial setup, so we always
1732 // use the pending DOM UI rather than any possibly existing committed one.
1733 if (render_manager_.pending_dom_ui()) {
1734 render_manager_.pending_dom_ui()->RenderViewCreated(render_view_host);
1735 }
1736
1737 if (entry->IsViewSourceMode()) {
1738 // Put the renderer in view source mode.
1739 render_view_host->Send(
1740 new ViewMsg_EnableViewSourceMode(render_view_host->routing_id()));
1741 }
[email protected]0666aef2009-05-13 19:48:081742
1743 view()->RenderViewCreated(render_view_host);
[email protected]420ae012009-04-24 05:16:321744}
1745
1746void TabContents::RenderViewReady(RenderViewHost* rvh) {
1747 if (rvh != render_view_host()) {
1748 // Don't notify the world, since this came from a renderer in the
1749 // background.
1750 return;
1751 }
1752
1753 NotifyConnected();
1754 SetIsCrashed(false);
1755}
1756
1757void TabContents::RenderViewGone(RenderViewHost* rvh) {
1758 // Ask the print preview if this renderer was valuable.
1759 if (!printing_.OnRenderViewGone(rvh))
1760 return;
1761 if (rvh != render_view_host()) {
1762 // The pending page's RenderViewHost is gone.
1763 return;
1764 }
1765
1766 SetIsLoading(false, NULL);
1767 NotifyDisconnected();
1768 SetIsCrashed(true);
1769
[email protected]8e537302009-06-10 21:19:581770 // Tell the view that we've crashed so it can prepare the sad tab page.
1771 view_->OnTabCrashed();
[email protected]420ae012009-04-24 05:16:321772
1773 // Hide any visible hung renderer warning for this web contents' process.
[email protected]d82ed61e2009-06-16 02:46:221774 HungRendererDialog::HideForTabContents(this);
[email protected]420ae012009-04-24 05:16:321775}
1776
[email protected]2e4633c2009-07-09 16:58:061777void TabContents::RenderViewDeleted(RenderViewHost* rvh) {
1778 NotificationService::current()->Notify(
1779 NotificationType::RENDER_VIEW_HOST_DELETED,
1780 Source<TabContents>(this),
1781 Details<RenderViewHost>(rvh));
1782}
1783
[email protected]420ae012009-04-24 05:16:321784void TabContents::DidNavigate(RenderViewHost* rvh,
1785 const ViewHostMsg_FrameNavigate_Params& params) {
1786 if (PageTransition::IsMainFrame(params.transition))
1787 render_manager_.DidNavigateMainFrame(rvh);
1788
1789 // Update the site of the SiteInstance if it doesn't have one yet.
1790 if (!GetSiteInstance()->has_site())
1791 GetSiteInstance()->SetSite(params.url);
1792
1793 // Need to update MIME type here because it's referred to in
1794 // UpdateNavigationCommands() called by RendererDidNavigate() to
1795 // determine whether or not to enable the encoding menu.
1796 // It's updated only for the main frame. For a subframe,
1797 // RenderView::UpdateURL does not set params.contents_mime_type.
1798 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
1799 // TODO(jungshik): Add a test for the encoding menu to avoid
1800 // regressing it again.
1801 if (PageTransition::IsMainFrame(params.transition))
1802 contents_mime_type_ = params.contents_mime_type;
1803
1804 NavigationController::LoadCommittedDetails details;
[email protected]3e90d4a2009-07-03 17:38:391805 bool did_navigate = controller_.RendererDidNavigate(params, &details);
1806
1807 // Update history. Note that this needs to happen after the entry is complete,
1808 // which WillNavigate[Main,Sub]Frame will do before this function is called.
1809 if (params.should_update_history) {
1810 // Most of the time, the displayURL matches the loaded URL, but for about:
1811 // URLs, we use a data: URL as the real value. We actually want to save
1812 // the about: URL to the history db and keep the data: URL hidden. This is
1813 // what the TabContents' URL getter does.
1814 UpdateHistoryForNavigation(GetURL(), details, params);
1815 }
1816
1817 if (!did_navigate)
1818 return; // No navigation happened.
[email protected]420ae012009-04-24 05:16:321819
1820 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
1821 // for the appropriate notification (best) or you can add it to
1822 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
1823 // necessary, please).
1824
1825 // Run post-commit tasks.
1826 if (details.is_main_frame)
1827 DidNavigateMainFramePostCommit(details, params);
1828 DidNavigateAnyFramePostCommit(rvh, details, params);
1829}
1830
1831void TabContents::UpdateState(RenderViewHost* rvh,
1832 int32 page_id,
1833 const std::string& state) {
1834 DCHECK(rvh == render_view_host());
1835
1836 // We must be prepared to handle state updates for any page, these occur
1837 // when the user is scrolling and entering form data, as well as when we're
1838 // leaving a page, in which case our state may have already been moved to
1839 // the next page. The navigation controller will look up the appropriate
1840 // NavigationEntry and update it when it is notified via the delegate.
1841
1842 int entry_index = controller_.GetEntryIndexWithPageID(
1843 GetSiteInstance(), page_id);
1844 if (entry_index < 0)
1845 return;
1846 NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
1847
1848 if (state == entry->content_state())
1849 return; // Nothing to update.
1850 entry->set_content_state(state);
1851 controller_.NotifyEntryChanged(entry, entry_index);
1852}
1853
1854void TabContents::UpdateTitle(RenderViewHost* rvh,
1855 int32 page_id, const std::wstring& title) {
1856 // If we have a title, that's a pretty good indication that we've started
1857 // getting useful data.
1858 SetNotWaitingForResponse();
1859
1860 DCHECK(rvh == render_view_host());
1861 NavigationEntry* entry = controller_.GetEntryWithPageID(GetSiteInstance(),
1862 page_id);
1863 if (!entry || !UpdateTitleForEntry(entry, title))
1864 return;
1865
1866 // Broadcast notifications when the UI should be updated.
1867 if (entry == controller_.GetEntryAtOffset(0))
[email protected]c9cd2222009-05-06 05:16:501868 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:321869}
1870
[email protected]420ae012009-04-24 05:16:321871void TabContents::UpdateEncoding(RenderViewHost* render_view_host,
1872 const std::wstring& encoding) {
1873 set_encoding(encoding);
1874}
1875
1876void TabContents::UpdateTargetURL(int32 page_id, const GURL& url) {
1877 if (delegate())
1878 delegate()->UpdateTargetURL(this, url);
1879}
1880
1881void TabContents::UpdateThumbnail(const GURL& url,
1882 const SkBitmap& bitmap,
1883 const ThumbnailScore& score) {
1884 // Tell History about this thumbnail
[email protected]449478302009-06-09 20:04:281885 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kThumbnailStore)) {
[email protected]72d0fc72009-07-09 17:30:491886 if (!profile()->IsOffTheRecord())
1887 profile()->GetThumbnailStore()->SetPageThumbnail(url, bitmap, score);
[email protected]449478302009-06-09 20:04:281888 } else {
1889 HistoryService* hs;
1890 if (!profile()->IsOffTheRecord() &&
1891 (hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS))) {
1892 hs->SetPageThumbnail(url, bitmap, score);
1893 }
[email protected]420ae012009-04-24 05:16:321894 }
1895}
1896
[email protected]0df30122009-06-03 12:13:081897void TabContents::UpdateInspectorSettings(const std::wstring& raw_settings) {
1898 profile()->GetPrefs()->SetString(prefs::kWebKitInspectorSettings,
1899 raw_settings);
1900}
1901
[email protected]420ae012009-04-24 05:16:321902void TabContents::Close(RenderViewHost* rvh) {
1903 // Ignore this if it comes from a RenderViewHost that we aren't showing.
1904 if (delegate() && rvh == render_view_host())
1905 delegate()->CloseContents(this);
1906}
1907
1908void TabContents::RequestMove(const gfx::Rect& new_bounds) {
1909 if (delegate() && delegate()->IsPopup(this))
1910 delegate()->MoveContents(this, new_bounds);
1911}
1912
[email protected]329581b2009-04-28 06:52:351913void TabContents::DidStartLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321914 SetIsLoading(true, NULL);
1915}
1916
[email protected]329581b2009-04-28 06:52:351917void TabContents::DidStopLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321918 scoped_ptr<LoadNotificationDetails> details;
1919
1920 NavigationEntry* entry = controller_.GetActiveEntry();
1921 // An entry may not exist for a stop when loading an initial blank page or
1922 // if an iframe injected by script into a blank page finishes loading.
1923 if (entry) {
1924 scoped_ptr<base::ProcessMetrics> metrics(
1925 base::ProcessMetrics::CreateProcessMetrics(
1926 process()->process().handle()));
1927
1928 base::TimeDelta elapsed = base::TimeTicks::Now() - current_load_start_;
1929
1930 details.reset(new LoadNotificationDetails(
1931 entry->display_url(),
1932 entry->transition_type(),
1933 elapsed,
1934 &controller_,
1935 controller_.GetCurrentEntryIndex()));
1936 }
1937
1938 // Tell PasswordManager we've finished a page load, which serves as a
1939 // green light to save pending passwords and reset itself.
1940 GetPasswordManager()->DidStopLoading();
1941
1942 SetIsLoading(false, details.get());
1943}
1944
[email protected]420ae012009-04-24 05:16:321945void TabContents::DidRedirectProvisionalLoad(int32 page_id,
1946 const GURL& source_url,
1947 const GURL& target_url) {
1948 NavigationEntry* entry;
1949 if (page_id == -1)
1950 entry = controller_.pending_entry();
1951 else
1952 entry = controller_.GetEntryWithPageID(GetSiteInstance(), page_id);
1953 if (!entry || entry->url() != source_url)
1954 return;
1955 entry->set_url(target_url);
1956}
1957
[email protected]420ae012009-04-24 05:16:321958void TabContents::RequestOpenURL(const GURL& url, const GURL& referrer,
1959 WindowOpenDisposition disposition) {
1960 if (render_manager_.dom_ui()) {
1961 // When we're a DOM UI, it will provide a page transition type for us (this
1962 // is so the new tab page can specify AUTO_BOOKMARK for automatically
1963 // generated suggestions).
1964 //
1965 // Note also that we hide the referrer for DOM UI pages. We don't really
[email protected]60e448982009-05-06 04:21:161966 // want web sites to see a referrer of "chrome://blah" (and some
1967 // chrome: URLs might have search terms or other stuff we don't want to
[email protected]420ae012009-04-24 05:16:321968 // send to the site), so we send no referrer.
1969 OpenURL(url, GURL(), disposition,
1970 render_manager_.dom_ui()->link_transition_type());
1971 } else {
1972 OpenURL(url, referrer, disposition, PageTransition::LINK);
1973 }
1974}
1975
[email protected]1ee614862009-07-06 20:29:181976void TabContents::DomOperationResponse(const std::string& json_string,
1977 int automation_id) {
1978}
1979
[email protected]420ae012009-04-24 05:16:321980void TabContents::ProcessDOMUIMessage(const std::string& message,
[email protected]811bfe32009-07-01 08:46:251981 const std::string& content,
1982 int request_id,
1983 bool has_callback) {
[email protected]420ae012009-04-24 05:16:321984 if (!render_manager_.dom_ui()) {
1985 // We shouldn't get a DOM UI message when we haven't enabled the DOM UI.
1986 // Because the renderer might be owned and sending random messages, we need
1987 // to ignore these inproper ones.
1988 NOTREACHED();
1989 return;
1990 }
[email protected]811bfe32009-07-01 08:46:251991 render_manager_.dom_ui()->ProcessDOMUIMessage(message, content, request_id,
1992 has_callback);
[email protected]420ae012009-04-24 05:16:321993}
1994
1995void TabContents::ProcessExternalHostMessage(const std::string& message,
1996 const std::string& origin,
1997 const std::string& target) {
1998 if (delegate())
1999 delegate()->ForwardMessageToExternalHost(message, origin, target);
2000}
2001
[email protected]420ae012009-04-24 05:16:322002void TabContents::RunFileChooser(bool multiple_files,
2003 const string16& title,
2004 const FilePath& default_file) {
2005 if (!select_file_dialog_.get())
2006 select_file_dialog_ = SelectFileDialog::Create(this);
2007 SelectFileDialog::Type dialog_type =
2008 multiple_files ? SelectFileDialog::SELECT_OPEN_MULTI_FILE :
2009 SelectFileDialog::SELECT_OPEN_FILE;
2010 select_file_dialog_->SelectFile(dialog_type, title, default_file,
2011 NULL, 0, FILE_PATH_LITERAL(""),
2012 view_->GetTopLevelNativeWindow(), NULL);
2013}
2014
2015void TabContents::RunJavaScriptMessage(
2016 const std::wstring& message,
2017 const std::wstring& default_prompt,
2018 const GURL& frame_url,
2019 const int flags,
2020 IPC::Message* reply_msg,
2021 bool* did_suppress_message) {
2022 // Suppress javascript messages when requested and when inside a constrained
2023 // popup window (because that activates them and breaks them out of the
2024 // constrained window jail).
[email protected]91ed49a2009-07-07 21:29:552025 // Also suppress messages when showing an interstitial. The interstitial is
2026 // shown over the previous page, we don't want the hidden page dialogs to
2027 // interfere with the interstitial.
2028 bool suppress_this_message = suppress_javascript_messages_ ||
2029 showing_interstitial_page();
[email protected]420ae012009-04-24 05:16:322030 if (delegate())
2031 suppress_this_message |=
[email protected]b6c874582009-05-08 19:38:312032 (delegate()->GetConstrainingContents(this) != this);
[email protected]420ae012009-04-24 05:16:322033
2034 *did_suppress_message = suppress_this_message;
2035
2036 if (!suppress_this_message) {
2037 base::TimeDelta time_since_last_message(
2038 base::TimeTicks::Now() - last_javascript_message_dismissal_);
2039 bool show_suppress_checkbox = false;
2040 // Show a checkbox offering to suppress further messages if this message is
2041 // being displayed within kJavascriptMessageExpectedDelay of the last one.
2042 if (time_since_last_message <
2043 base::TimeDelta::FromMilliseconds(kJavascriptMessageExpectedDelay))
2044 show_suppress_checkbox = true;
2045
[email protected]d82ed61e2009-06-16 02:46:222046 RunJavascriptMessageBox(this, frame_url, flags, message, default_prompt,
[email protected]420ae012009-04-24 05:16:322047 show_suppress_checkbox, reply_msg);
2048 } else {
2049 // If we are suppressing messages, just reply as is if the user immediately
2050 // pressed "Cancel".
2051 OnJavaScriptMessageBoxClosed(reply_msg, false, std::wstring());
2052 }
2053}
2054
2055void TabContents::RunBeforeUnloadConfirm(const std::wstring& message,
2056 IPC::Message* reply_msg) {
[email protected]d82ed61e2009-06-16 02:46:222057 RunBeforeUnloadDialog(this, message, reply_msg);
[email protected]420ae012009-04-24 05:16:322058}
2059
2060void TabContents::ShowModalHTMLDialog(const GURL& url, int width, int height,
2061 const std::string& json_arguments,
2062 IPC::Message* reply_msg) {
2063 if (delegate()) {
2064 HtmlDialogUIDelegate* dialog_delegate =
2065 new ModalHtmlDialogDelegate(url, width, height, json_arguments,
[email protected]d82ed61e2009-06-16 02:46:222066 reply_msg, this);
[email protected]420ae012009-04-24 05:16:322067 delegate()->ShowHtmlDialog(dialog_delegate, NULL);
2068 }
2069}
2070
2071void TabContents::PasswordFormsSeen(
[email protected]ed3fb032009-06-16 19:50:562072 const std::vector<webkit_glue::PasswordForm>& forms) {
[email protected]420ae012009-04-24 05:16:322073 GetPasswordManager()->PasswordFormsSeen(forms);
2074}
2075
[email protected]420ae012009-04-24 05:16:322076// Checks to see if we should generate a keyword based on the OSDD, and if
2077// necessary uses TemplateURLFetcher to download the OSDD and create a keyword.
2078void TabContents::PageHasOSDD(RenderViewHost* render_view_host,
2079 int32 page_id, const GURL& url,
2080 bool autodetected) {
2081 // Make sure page_id is the current page, and the TemplateURLModel is loaded.
2082 DCHECK(url.is_valid());
2083 if (!IsActiveEntry(page_id))
2084 return;
2085 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
2086 if (!url_model)
2087 return;
2088 if (!url_model->loaded()) {
2089 url_model->Load();
2090 return;
2091 }
2092 if (!profile()->GetTemplateURLFetcher())
2093 return;
2094
2095 if (profile()->IsOffTheRecord())
2096 return;
2097
2098 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
2099 DCHECK(entry);
2100
2101 const NavigationEntry* base_entry = entry;
2102 if (IsFormSubmit(base_entry)) {
2103 // If the current page is a form submit, find the last page that was not
2104 // a form submit and use its url to generate the keyword from.
2105 int index = controller_.last_committed_entry_index() - 1;
2106 while (index >= 0 && IsFormSubmit(controller_.GetEntryAtIndex(index)))
2107 index--;
2108 if (index >= 0)
2109 base_entry = controller_.GetEntryAtIndex(index);
2110 else
2111 base_entry = NULL;
2112 }
2113
2114 // We want to use the user typed URL if available since that represents what
2115 // the user typed to get here, and fall back on the regular URL if not.
2116 if (!base_entry)
2117 return;
2118 GURL keyword_url = base_entry->user_typed_url().is_valid() ?
2119 base_entry->user_typed_url() : base_entry->url();
2120 if (!keyword_url.is_valid())
2121 return;
2122 std::wstring keyword = TemplateURLModel::GenerateKeyword(keyword_url,
2123 autodetected);
2124 if (keyword.empty())
2125 return;
2126 const TemplateURL* template_url =
2127 url_model->GetTemplateURLForKeyword(keyword);
2128 if (template_url && (!template_url->safe_for_autoreplace() ||
2129 template_url->originating_url() == url)) {
2130 // Either there is a user created TemplateURL for this keyword, or the
2131 // keyword has the same OSDD url and we've parsed it.
2132 return;
2133 }
2134
2135 // Download the OpenSearch description document. If this is successful a
2136 // new keyword will be created when done.
[email protected]420ae012009-04-24 05:16:322137 profile()->GetTemplateURLFetcher()->ScheduleDownload(
2138 keyword,
2139 url,
2140 base_entry->favicon().url(),
[email protected]d0cc9fb52009-06-23 02:26:162141 this,
[email protected]420ae012009-04-24 05:16:322142 autodetected);
2143}
2144
[email protected]420ae012009-04-24 05:16:322145GURL TabContents::GetAlternateErrorPageURL() const {
2146 GURL url;
2147 // Disable alternate error pages when in OffTheRecord/Incognito mode.
2148 if (profile()->IsOffTheRecord())
2149 return url;
2150
2151 PrefService* prefs = profile()->GetPrefs();
2152 DCHECK(prefs);
2153 if (prefs->GetBoolean(prefs::kAlternateErrorPagesEnabled)) {
2154 url = google_util::AppendGoogleLocaleParam(GURL(kLinkDoctorBaseURL));
2155 url = google_util::AppendGoogleTLDParam(url);
2156 }
2157 return url;
2158}
2159
2160WebPreferences TabContents::GetWebkitPrefs() {
2161 PrefService* prefs = render_view_host()->process()->profile()->GetPrefs();
2162 bool isDomUI = false;
2163 return RenderViewHostDelegateHelper::GetWebkitPrefs(prefs, isDomUI);
2164}
2165
[email protected]420ae012009-04-24 05:16:322166void TabContents::OnJSOutOfMemory() {
2167 AddInfoBar(new SimpleAlertInfoBarDelegate(
2168 this, l10n_util::GetString(IDS_JS_OUT_OF_MEMORY_PROMPT), NULL));
2169}
2170
2171void TabContents::ShouldClosePage(bool proceed) {
2172 render_manager_.ShouldClosePage(proceed);
2173}
2174
2175void TabContents::OnCrossSiteResponse(int new_render_process_host_id,
2176 int new_request_id) {
[email protected]57c6a652009-05-04 07:58:342177 // Allows the TabContents to react when a cross-site response is ready to be
[email protected]420ae012009-04-24 05:16:322178 // delivered to a pending RenderViewHost. We must first run the onunload
2179 // handler of the old RenderViewHost before we can allow it to proceed.
2180 render_manager_.OnCrossSiteResponse(new_render_process_host_id,
2181 new_request_id);
2182}
2183
2184bool TabContents::CanBlur() const {
2185 return delegate() ? delegate()->CanBlur() : true;
2186}
2187
2188gfx::Rect TabContents::GetRootWindowResizerRect() const {
2189 if (delegate())
2190 return delegate()->GetRootWindowResizerRect();
2191 return gfx::Rect();
2192}
2193
2194void TabContents::RendererUnresponsive(RenderViewHost* rvh,
2195 bool is_during_unload) {
2196 if (is_during_unload) {
2197 // Hang occurred while firing the beforeunload/unload handler.
2198 // Pretend the handler fired so tab closing continues as if it had.
[email protected]829e7612009-04-25 01:15:112199 rvh->set_sudden_termination_allowed(true);
[email protected]420ae012009-04-24 05:16:322200
2201 if (!render_manager_.ShouldCloseTabOnUnresponsiveRenderer())
2202 return;
2203
2204 // If the tab hangs in the beforeunload/unload handler there's really
2205 // nothing we can do to recover. Pretend the unload listeners have
2206 // all fired and close the tab. If the hang is in the beforeunload handler
2207 // then the user will not have the option of cancelling the close.
2208 Close(rvh);
2209 return;
2210 }
2211
2212 if (render_view_host() && render_view_host()->IsRenderViewLive())
[email protected]d82ed61e2009-06-16 02:46:222213 HungRendererDialog::ShowForTabContents(this);
[email protected]420ae012009-04-24 05:16:322214}
2215
2216void TabContents::RendererResponsive(RenderViewHost* render_view_host) {
[email protected]d82ed61e2009-06-16 02:46:222217 HungRendererDialog::HideForTabContents(this);
[email protected]420ae012009-04-24 05:16:322218}
2219
2220void TabContents::LoadStateChanged(const GURL& url,
2221 net::LoadState load_state) {
2222 load_state_ = load_state;
[email protected]d686e812009-06-03 19:10:292223 std::wstring languages =
2224 profile()->GetPrefs()->GetString(prefs::kAcceptLanguages);
2225 load_state_host_.clear();
2226 std::string host = url.host();
2227 net::IDNToUnicode(host.c_str(), host.size(), languages, &load_state_host_);
[email protected]420ae012009-04-24 05:16:322228 if (load_state_ == net::LOAD_STATE_READING_RESPONSE)
2229 SetNotWaitingForResponse();
2230 if (is_loading())
[email protected]c9cd2222009-05-06 05:16:502231 NotifyNavigationStateChanged(INVALIDATE_LOAD | INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:322232}
2233
[email protected]1ee614862009-07-06 20:29:182234bool TabContents::IsExternalTabContainer() const {
2235 if (!delegate())
2236 return false;
2237
2238 return delegate()->IsExternalTabContainer();
2239}
2240
[email protected]1ee614862009-07-06 20:29:182241void TabContents::DidInsertCSS() {
2242 // This RVHDelegate function is used for extensions and not us.
[email protected]420ae012009-04-24 05:16:322243}
2244
2245void TabContents::FileSelected(const FilePath& path,
2246 int index, void* params) {
2247 render_view_host()->FileSelected(path);
2248}
2249
2250void TabContents::MultiFilesSelected(const std::vector<FilePath>& files,
2251 void* params) {
2252 render_view_host()->MultiFilesSelected(files);
2253}
2254
2255void TabContents::FileSelectionCanceled(void* params) {
2256 // If the user cancels choosing a file to upload we pass back an
2257 // empty vector.
2258 render_view_host()->MultiFilesSelected(std::vector<FilePath>());
2259}
2260
2261void TabContents::BeforeUnloadFiredFromRenderManager(
2262 bool proceed,
2263 bool* proceed_to_fire_unload) {
2264 if (delegate())
2265 delegate()->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
2266}
2267
2268void TabContents::UpdateRenderViewSizeForRenderManager() {
2269 // TODO(brettw) this is a hack. See TabContentsView::SizeContents.
2270 view_->SizeContents(view_->GetContainerSize());
2271}
2272
2273DOMUI* TabContents::CreateDOMUIForRenderManager(const GURL& url) {
[email protected]d82ed61e2009-06-16 02:46:222274 return DOMUIFactory::CreateDOMUIForURL(this, url);
[email protected]420ae012009-04-24 05:16:322275}
2276
2277NavigationEntry*
2278TabContents::GetLastCommittedNavigationEntryForRenderManager() {
2279 return controller_.GetLastCommittedEntry();
2280}
2281
2282bool TabContents::CreateRenderViewForRenderManager(
2283 RenderViewHost* render_view_host) {
[email protected]811bfe32009-07-01 08:46:252284 // If the pending navigation is to a DOMUI, tell the RenderView about any
2285 // bindings it will need enabled.
[email protected]420ae012009-04-24 05:16:322286 if (render_manager_.pending_dom_ui())
[email protected]811bfe32009-07-01 08:46:252287 render_view_host->AllowBindings(
2288 render_manager_.pending_dom_ui()->bindings());
[email protected]1adff062009-06-02 18:39:552289
[email protected]420ae012009-04-24 05:16:322290 RenderWidgetHostView* rwh_view = view_->CreateViewForWidget(render_view_host);
2291 if (!render_view_host->CreateRenderView())
2292 return false;
2293
2294 // Now that the RenderView has been created, we need to tell it its size.
2295 rwh_view->SetSize(view_->GetContainerSize());
2296
2297 UpdateMaxPageIDIfNecessary(render_view_host->site_instance(),
2298 render_view_host);
2299 return true;
2300}
2301
2302void TabContents::Observe(NotificationType type,
2303 const NotificationSource& source,
2304 const NotificationDetails& details) {
2305 switch (type.value) {
2306 case NotificationType::BOOKMARK_MODEL_LOADED:
2307 // BookmarkModel finished loading, fall through to update starred state.
2308 case NotificationType::URLS_STARRED: {
2309 // Somewhere, a URL has been starred.
2310 // Ignore notifications for profiles other than our current one.
2311 Profile* source_profile = Source<Profile>(source).ptr();
2312 if (!source_profile || !source_profile->IsSameProfile(profile()))
2313 return;
2314
2315 UpdateStarredStateForCurrentURL();
2316 break;
2317 }
2318 case NotificationType::PREF_CHANGED: {
2319 std::wstring* pref_name_in = Details<std::wstring>(details).ptr();
2320 DCHECK(Source<PrefService>(source).ptr() == profile()->GetPrefs());
2321 if (*pref_name_in == prefs::kAlternateErrorPagesEnabled) {
2322 UpdateAlternateErrorPageURL();
2323 } else if (*pref_name_in == prefs::kDefaultCharset ||
2324 StartsWithASCII(WideToUTF8(*pref_name_in), "webkit.webprefs.", true)
2325 ) {
2326 UpdateWebPreferences();
2327 } else {
2328 NOTREACHED() << "unexpected pref change notification" << *pref_name_in;
2329 }
2330 break;
2331 }
2332 case NotificationType::RENDER_WIDGET_HOST_DESTROYED:
2333 view_->RenderWidgetHostDestroyed(Source<RenderWidgetHost>(source).ptr());
2334 break;
2335
2336 case NotificationType::NAV_ENTRY_COMMITTED: {
2337 DCHECK(&controller_ == Source<NavigationController>(source).ptr());
2338
2339 NavigationController::LoadCommittedDetails& committed_details =
2340 *(Details<NavigationController::LoadCommittedDetails>(details).ptr());
2341 ExpireInfoBars(committed_details);
2342 break;
2343 }
2344
2345 default:
2346 NOTREACHED();
2347 }
2348}