blob: 4508d34ddbc695531fd609bb0345dc025d4477bf [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]96d185d2009-04-24 03:28:5453#include "chrome/common/url_constants.h"
[email protected]8897c382009-05-06 17:53:2654#include "grit/generated_resources.h"
[email protected]420ae012009-04-24 05:16:3255#include "grit/locale_settings.h"
56#include "net/base/mime_util.h"
57#include "net/base/net_errors.h"
[email protected]d686e812009-06-03 19:10:2958#include "net/base/net_util.h"
[email protected]420ae012009-04-24 05:16:3259#include "net/base/registry_controlled_domain.h"
[email protected]3e45ba92009-02-20 21:09:0060
61#if defined(OS_WIN)
[email protected]66ba4932009-06-04 19:22:1362// For CRect
[email protected]9041a302009-06-04 19:36:3363#include <atlbase.h>
[email protected]326f7112009-06-04 19:30:2964#include <atlapp.h>
[email protected]66ba4932009-06-04 19:22:1365#include <atlmisc.h>
[email protected]3e45ba92009-02-20 21:09:0066// TODO(port): some of these headers should be ported.
[email protected]420ae012009-04-24 05:16:3267#include "chrome/browser/modal_html_dialog_delegate.h"
[email protected]2362e4f2009-05-08 00:34:0568#include "views/controls/scrollbar/native_scroll_bar.h"
[email protected]3e45ba92009-02-20 21:09:0069#endif
initial.commit09911bf2008-07-26 23:55:2970
[email protected]420ae012009-04-24 05:16:3271// Cross-Site Navigations
72//
73// If a TabContents is told to navigate to a different web site (as determined
74// by SiteInstance), it will replace its current RenderViewHost with a new
75// RenderViewHost dedicated to the new SiteInstance. This works as follows:
76//
77// - Navigate determines whether the destination is cross-site, and if so,
78// it creates a pending_render_view_host_ and moves into the PENDING
79// RendererState.
80// - The pending RVH is "suspended," so that no navigation messages are sent to
81// its renderer until the onbeforeunload JavaScript handler has a chance to
82// run in the current RVH.
83// - The pending RVH tells CrossSiteRequestManager (a thread-safe singleton)
84// that it has a pending cross-site request. ResourceDispatcherHost will
85// check for this when the response arrives.
86// - The current RVH runs its onbeforeunload handler. If it returns false, we
87// cancel all the pending logic and go back to NORMAL. Otherwise we allow
88// the pending RVH to send the navigation request to its renderer.
89// - ResourceDispatcherHost receives a ResourceRequest on the IO thread. It
90// checks CrossSiteRequestManager to see that the RVH responsible has a
91// pending cross-site request, and then installs a CrossSiteEventHandler.
92// - When RDH receives a response, the BufferedEventHandler determines whether
93// it is a download. If so, it sends a message to the new renderer causing
94// it to cancel the request, and the download proceeds in the download
95// thread. For now, we stay in a PENDING state (with a pending RVH) until
[email protected]57c6a652009-05-04 07:58:3496// the next DidNavigate event for this TabContents. This isn't ideal, but it
[email protected]420ae012009-04-24 05:16:3297// doesn't affect any functionality.
98// - After RDH receives a response and determines that it is safe and not a
99// download, it pauses the response to first run the old page's onunload
100// handler. It does this by asynchronously calling the OnCrossSiteResponse
[email protected]57c6a652009-05-04 07:58:34101// method of TabContents on the UI thread, which sends a ClosePage message
[email protected]420ae012009-04-24 05:16:32102// to the current RVH.
103// - Once the onunload handler is finished, a ClosePage_ACK message is sent to
104// the ResourceDispatcherHost, who unpauses the response. Data is then sent
105// to the pending RVH.
106// - The pending renderer sends a FrameNavigate message that invokes the
107// DidNavigate method. This replaces the current RVH with the
108// pending RVH and goes back to the NORMAL RendererState.
109
110namespace {
111
112// Amount of time we wait between when a key event is received and the renderer
113// is queried for its state and pushed to the NavigationEntry.
114const int kQueryStateDelay = 5000;
115
116const int kSyncWaitDelay = 40;
117
118// If another javascript message box is displayed within
119// kJavascriptMessageExpectedDelay of a previous javascript message box being
120// dismissed, display an option to suppress future message boxes from this
121// contents.
122const int kJavascriptMessageExpectedDelay = 1000;
123
[email protected]420ae012009-04-24 05:16:32124const char kLinkDoctorBaseURL[] =
125 "http://linkhelp.clients.google.com/tbproxy/lh/fixurl";
126
[email protected]420ae012009-04-24 05:16:32127// The list of prefs we want to observe.
128const wchar_t* kPrefsToObserve[] = {
129 prefs::kAlternateErrorPagesEnabled,
130 prefs::kWebKitJavaEnabled,
131 prefs::kWebKitJavascriptEnabled,
132 prefs::kWebKitLoadsImagesAutomatically,
133 prefs::kWebKitPluginsEnabled,
134 prefs::kWebKitUsesUniversalDetector,
135 prefs::kWebKitSerifFontFamily,
136 prefs::kWebKitSansSerifFontFamily,
137 prefs::kWebKitFixedFontFamily,
138 prefs::kWebKitDefaultFontSize,
139 prefs::kWebKitDefaultFixedFontSize,
140 prefs::kDefaultCharset
141 // kWebKitStandardFontIsSerif needs to be added
142 // if we let users pick which font to use, serif or sans-serif when
143 // no font is specified or a CSS generic family (serif or sans-serif)
144 // is not specified.
145};
146
147const int kPrefsToObserveLength = arraysize(kPrefsToObserve);
148
149// Limit on the number of suggestions to appear in the pop-up menu under an
150// text input element in a form.
151const int kMaxAutofillMenuItems = 6;
152
153// Returns true if the entry's transition type is FORM_SUBMIT.
154bool IsFormSubmit(const NavigationEntry* entry) {
155 return (PageTransition::StripQualifier(entry->transition_type()) ==
156 PageTransition::FORM_SUBMIT);
157}
158
159#if defined(OS_WIN)
160
161BOOL CALLBACK InvalidateWindow(HWND hwnd, LPARAM lparam) {
162 // Note: erase is required to properly paint some widgets borders. This can
163 // be seen with textfields.
164 InvalidateRect(hwnd, NULL, TRUE);
165 return TRUE;
166}
167#endif
168
[email protected]056de2d2009-06-26 16:41:34169void MakeNavigateParams(const NavigationEntry& entry, bool reload,
170 ViewMsg_Navigate_Params* params) {
171 params->page_id = entry.page_id();
172 params->url = entry.url();
173 params->referrer = entry.referrer();
174 params->transition = entry.transition_type();
175 params->state = entry.content_state();
176 params->reload = reload;
177 params->request_time = base::Time::Now();
178}
179
[email protected]420ae012009-04-24 05:16:32180} // namespace
181
182// -----------------------------------------------------------------------------
183
[email protected]fdd61c62009-04-22 19:22:57184// static
185int TabContents::find_request_id_counter_ = -1;
186
[email protected]420ae012009-04-24 05:16:32187class TabContents::GearsCreateShortcutCallbackFunctor {
188 public:
189 explicit GearsCreateShortcutCallbackFunctor(TabContents* contents)
190 : contents_(contents) {}
191
192 void Run(const GearsShortcutData2& shortcut_data, bool success) {
193 if (contents_)
194 contents_->OnGearsCreateShortcutDone(shortcut_data, success);
195 delete this;
196 }
197 void Cancel() {
198 contents_ = NULL;
199 }
200
201 private:
202 TabContents* contents_;
203};
204
[email protected]420ae012009-04-24 05:16:32205TabContents::TabContents(Profile* profile,
206 SiteInstance* site_instance,
207 int routing_id,
208 base::WaitableEvent* modal_dialog_event)
[email protected]b680ad22009-04-15 23:19:42209 : delegate_(NULL),
[email protected]66ba4932009-06-04 19:22:13210 ALLOW_THIS_IN_INITIALIZER_LIST(controller_(this, profile)),
211 ALLOW_THIS_IN_INITIALIZER_LIST(view_(
[email protected]d82ed61e2009-06-16 02:46:22212 TabContentsView::Create(this))),
213 ALLOW_THIS_IN_INITIALIZER_LIST(render_manager_(this, this)),
[email protected]fdd61c62009-04-22 19:22:57214 property_bag_(),
215 registrar_(),
[email protected]d82ed61e2009-06-16 02:46:22216 ALLOW_THIS_IN_INITIALIZER_LIST(printing_(*this)),
[email protected]fdd61c62009-04-22 19:22:57217 save_package_(),
218 cancelable_consumer_(),
219 autofill_manager_(),
220 password_manager_(),
221 plugin_installer_(),
[email protected]d82ed61e2009-06-16 02:46:22222 ALLOW_THIS_IN_INITIALIZER_LIST(fav_icon_helper_(this)),
[email protected]fdd61c62009-04-22 19:22:57223 select_file_dialog_(),
224 pending_install_(),
[email protected]d5f942ba2008-09-26 19:30:34225 is_loading_(false),
initial.commit09911bf2008-07-26 23:55:29226 is_crashed_(false),
[email protected]d5f942ba2008-09-26 19:30:34227 waiting_for_response_(false),
[email protected]d5f942ba2008-09-26 19:30:34228 max_page_id_(-1),
[email protected]fdd61c62009-04-22 19:22:57229 current_load_start_(),
230 load_state_(net::LOAD_STATE_IDLE),
231 load_state_host_(),
232 received_page_title_(false),
233 is_starred_(false),
234 contents_mime_type_(),
235 encoding_(),
[email protected]332af7732009-03-11 13:21:35236 blocked_popups_(NULL),
[email protected]fdd61c62009-04-22 19:22:57237 infobar_delegates_(),
[email protected]fdd61c62009-04-22 19:22:57238 find_ui_active_(false),
239 find_op_aborted_(false),
240 current_find_request_id_(find_request_id_counter_++),
241 find_text_(),
[email protected]e491f1c2009-05-22 20:28:12242 last_search_case_sensitive_(false),
243 last_search_prepopulate_text_(NULL),
244 last_search_result_(),
[email protected]fdd61c62009-04-22 19:22:57245 capturing_contents_(false),
246 is_being_destroyed_(false),
247 notify_disconnection_(false),
248 history_requests_(),
249#if defined(OS_WIN)
250 message_box_active_(CreateEvent(NULL, TRUE, FALSE, NULL)),
251#endif
252 last_javascript_message_dismissal_(),
253 suppress_javascript_messages_(false) {
[email protected]420ae012009-04-24 05:16:32254 pending_install_.page_id = 0;
255 pending_install_.callback_functor = NULL;
256
[email protected]58dca552009-06-17 00:35:02257#if defined(LINUX2)
258 // Make sure the thumbnailer is started before starting the render manager.
259 // The thumbnailer will want to listen for RVH creations, one of which will
260 // happen in RVHManager::Init.
261 ThumbnailGenerator* generator = g_browser_process->GetThumbnailGenerator();
262 if (generator)
263 generator->StartThumbnailing();
264#endif
265
[email protected]420ae012009-04-24 05:16:32266 render_manager_.Init(profile, site_instance, routing_id, modal_dialog_event);
267
268 view_->CreateView();
269
270 // Register for notifications about all interested prefs change.
271 PrefService* prefs = profile->GetPrefs();
272 if (prefs) {
273 for (int i = 0; i < kPrefsToObserveLength; ++i)
274 prefs->AddPrefObserver(kPrefsToObserve[i], this);
275 }
276
277 // Register for notifications about URL starredness changing on any profile.
278 registrar_.Add(this, NotificationType::URLS_STARRED,
279 NotificationService::AllSources());
280 registrar_.Add(this, NotificationType::BOOKMARK_MODEL_LOADED,
281 NotificationService::AllSources());
282 registrar_.Add(this, NotificationType::RENDER_WIDGET_HOST_DESTROYED,
283 NotificationService::AllSources());
284
285 // Keep a global copy of the previous search string (if any).
286 static string16 global_last_search = string16();
[email protected]e491f1c2009-05-22 20:28:12287 last_search_prepopulate_text_ = &global_last_search;
[email protected]332af7732009-03-11 13:21:35288}
initial.commit09911bf2008-07-26 23:55:29289
290TabContents::~TabContents() {
[email protected]420ae012009-04-24 05:16:32291 is_being_destroyed_ = true;
292
293 // We don't want any notifications while we're runnign our destructor.
294 registrar_.RemoveAll();
295
296 // Unregister the notifications of all observed prefs change.
297 PrefService* prefs = profile()->GetPrefs();
298 if (prefs) {
299 for (int i = 0; i < kPrefsToObserveLength; ++i)
300 prefs->RemovePrefObserver(kPrefsToObserve[i], this);
301 }
302
303 // Clean up subwindows like plugins and the find in page bar.
304 view_->OnContentsDestroy();
305
306 NotifyDisconnected();
[email protected]d82ed61e2009-06-16 02:46:22307 HungRendererDialog::HideForTabContents(this);
[email protected]420ae012009-04-24 05:16:32308
309 if (pending_install_.callback_functor)
310 pending_install_.callback_functor->Cancel();
311
312 // First cleanly close all child windows.
313 // TODO(mpcomplete): handle case if MaybeCloseChildWindows() already asked
314 // some of these to close. CloseWindows is async, so it might get called
315 // twice before it runs.
316 int size = static_cast<int>(child_windows_.size());
317 for (int i = size - 1; i >= 0; --i) {
318 ConstrainedWindow* window = child_windows_[i];
319 if (window)
320 window->CloseConstrainedWindow();
321 }
322
[email protected]66ba4932009-06-04 19:22:13323 if (blocked_popups_)
324 blocked_popups_->Destroy();
325
[email protected]420ae012009-04-24 05:16:32326 // Notify any observer that have a reference on this tab contents.
327 NotificationService::current()->Notify(
328 NotificationType::TAB_CONTENTS_DESTROYED,
329 Source<TabContents>(this),
330 NotificationService::NoDetails());
331
[email protected]1e5e74f2009-05-27 20:55:12332 // Notify any lasting InfobarDelegates that have not yet been removed that
333 // whatever infobar they were handling in this TabContents has closed,
334 // because the TabContents is going away entirely.
335 // This must happen after the TAB_CONTENTS_DESTROYED notification as the
336 // notification may trigger infobars calls that access their delegate. (and
337 // some implementations of InfoBarDelegate do delete themselves on
338 // InfoBarClosed()).
339 for (int i = 0; i < infobar_delegate_count(); ++i) {
340 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
341 delegate->InfoBarClosed();
342 }
343 infobar_delegates_.clear();
344
[email protected]420ae012009-04-24 05:16:32345 // TODO(brettw) this should be moved to the view.
346#if defined(OS_WIN)
347 // If we still have a window handle, destroy it. GetNativeView can return
348 // NULL if this contents was part of a window that closed.
349 if (GetNativeView())
350 ::DestroyWindow(GetNativeView());
351#endif
initial.commit09911bf2008-07-26 23:55:29352}
353
[email protected]d5f942ba2008-09-26 19:30:34354// static
355void TabContents::RegisterUserPrefs(PrefService* prefs) {
[email protected]420ae012009-04-24 05:16:32356 prefs->RegisterBooleanPref(prefs::kAlternateErrorPagesEnabled, true);
357
358 WebPreferences pref_defaults;
359 prefs->RegisterBooleanPref(prefs::kWebKitJavascriptEnabled,
360 pref_defaults.javascript_enabled);
361 prefs->RegisterBooleanPref(prefs::kWebKitWebSecurityEnabled,
362 pref_defaults.web_security_enabled);
363 prefs->RegisterBooleanPref(
364 prefs::kWebKitJavascriptCanOpenWindowsAutomatically, true);
365 prefs->RegisterBooleanPref(prefs::kWebKitLoadsImagesAutomatically,
366 pref_defaults.loads_images_automatically);
367 prefs->RegisterBooleanPref(prefs::kWebKitPluginsEnabled,
368 pref_defaults.plugins_enabled);
369 prefs->RegisterBooleanPref(prefs::kWebKitDomPasteEnabled,
370 pref_defaults.dom_paste_enabled);
371 prefs->RegisterBooleanPref(prefs::kWebKitShrinksStandaloneImagesToFit,
372 pref_defaults.shrinks_standalone_images_to_fit);
[email protected]0df30122009-06-03 12:13:08373 prefs->RegisterStringPref(prefs::kWebKitInspectorSettings,
374 pref_defaults.inspector_settings);
[email protected]420ae012009-04-24 05:16:32375 prefs->RegisterBooleanPref(prefs::kWebKitTextAreasAreResizable,
376 pref_defaults.text_areas_are_resizable);
377 prefs->RegisterBooleanPref(prefs::kWebKitJavaEnabled,
378 pref_defaults.java_enabled);
379
380 prefs->RegisterLocalizedStringPref(prefs::kAcceptLanguages,
381 IDS_ACCEPT_LANGUAGES);
382 prefs->RegisterLocalizedStringPref(prefs::kDefaultCharset,
383 IDS_DEFAULT_ENCODING);
384 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitStandardFontIsSerif,
385 IDS_STANDARD_FONT_IS_SERIF);
386 prefs->RegisterLocalizedStringPref(prefs::kWebKitFixedFontFamily,
387 IDS_FIXED_FONT_FAMILY);
388 prefs->RegisterLocalizedStringPref(prefs::kWebKitSerifFontFamily,
389 IDS_SERIF_FONT_FAMILY);
390 prefs->RegisterLocalizedStringPref(prefs::kWebKitSansSerifFontFamily,
391 IDS_SANS_SERIF_FONT_FAMILY);
392 prefs->RegisterLocalizedStringPref(prefs::kWebKitCursiveFontFamily,
393 IDS_CURSIVE_FONT_FAMILY);
394 prefs->RegisterLocalizedStringPref(prefs::kWebKitFantasyFontFamily,
395 IDS_FANTASY_FONT_FAMILY);
396 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFontSize,
397 IDS_DEFAULT_FONT_SIZE);
398 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFixedFontSize,
399 IDS_DEFAULT_FIXED_FONT_SIZE);
400 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumFontSize,
401 IDS_MINIMUM_FONT_SIZE);
402 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumLogicalFontSize,
403 IDS_MINIMUM_LOGICAL_FONT_SIZE);
404 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitUsesUniversalDetector,
405 IDS_USES_UNIVERSAL_DETECTOR);
406 prefs->RegisterLocalizedStringPref(prefs::kStaticEncodings,
407 IDS_STATIC_ENCODING_LIST);
initial.commit09911bf2008-07-26 23:55:29408}
409
[email protected]d5f942ba2008-09-26 19:30:34410bool TabContents::SupportsURL(GURL* url) {
[email protected]6e95706d2009-04-23 22:55:01411 // TODO(brettw) remove this function.
[email protected]9423d9412009-04-14 22:13:55412 return true;
[email protected]d5f942ba2008-09-26 19:30:34413}
414
[email protected]6e95706d2009-04-23 22:55:01415AutofillManager* TabContents::GetAutofillManager() {
416 if (autofill_manager_.get() == NULL)
417 autofill_manager_.reset(new AutofillManager(this));
418 return autofill_manager_.get();
419}
420
421PasswordManager* TabContents::GetPasswordManager() {
422 if (password_manager_.get() == NULL)
423 password_manager_.reset(new PasswordManager(this));
424 return password_manager_.get();
425}
426
427PluginInstaller* TabContents::GetPluginInstaller() {
428 if (plugin_installer_.get() == NULL)
429 plugin_installer_.reset(new PluginInstaller(this));
430 return plugin_installer_.get();
431}
432
[email protected]d5f942ba2008-09-26 19:30:34433const GURL& TabContents::GetURL() const {
434 // We may not have a navigation entry yet
[email protected]ce3fa3c2009-04-20 19:55:57435 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34436 return entry ? entry->display_url() : GURL::EmptyGURL();
437}
438
[email protected]96d185d2009-04-24 03:28:54439const string16& TabContents::GetTitle() const {
[email protected]4c6092c5b2009-06-06 00:23:55440 // Transient entries take precedence. They are used for interstitial pages
441 // that are shown on top of existing pages.
442 NavigationEntry* entry = controller_.GetTransientEntry();
443 if (entry)
444 return entry->GetTitleForDisplay(&controller_);
445
[email protected]96d185d2009-04-24 03:28:54446 DOMUI* our_dom_ui = render_manager_.pending_dom_ui() ?
447 render_manager_.pending_dom_ui() : render_manager_.dom_ui();
448 if (our_dom_ui) {
449 // Don't override the title in view source mode.
[email protected]4c6092c5b2009-06-06 00:23:55450 entry = controller_.GetActiveEntry();
[email protected]96d185d2009-04-24 03:28:54451 if (!(entry && entry->IsViewSourceMode())) {
452 // Give the DOM UI the chance to override our title.
453 const string16& title = our_dom_ui->overridden_title();
454 if (!title.empty())
455 return title;
456 }
457 }
458
459 // We use the title for the last committed entry rather than a pending
460 // navigation entry. For example, when the user types in a URL, we want to
461 // keep the old page's title until the new load has committed and we get a new
462 // title.
[email protected]96d185d2009-04-24 03:28:54463 entry = controller_.GetLastCommittedEntry();
464 if (entry)
465 return entry->GetTitleForDisplay(&controller_);
466 else if (controller_.LoadingURLLazily())
467 return controller_.GetLazyTitle();
468 return EmptyString16();
469}
470
[email protected]d5f942ba2008-09-26 19:30:34471int32 TabContents::GetMaxPageID() {
472 if (GetSiteInstance())
473 return GetSiteInstance()->max_page_id();
474 else
475 return max_page_id_;
476}
477
478void TabContents::UpdateMaxPageID(int32 page_id) {
479 // Ensure both the SiteInstance and RenderProcessHost update their max page
[email protected]57c6a652009-05-04 07:58:34480 // IDs in sync. Only TabContents will also have site instances, except during
[email protected]d5f942ba2008-09-26 19:30:34481 // testing.
482 if (GetSiteInstance())
483 GetSiteInstance()->UpdateMaxPageID(page_id);
[email protected]57c6a652009-05-04 07:58:34484 process()->UpdateMaxPageID(page_id);
[email protected]d5f942ba2008-09-26 19:30:34485}
486
[email protected]96d185d2009-04-24 03:28:54487SiteInstance* TabContents::GetSiteInstance() const {
488 return render_manager_.current_host()->site_instance();
489}
490
[email protected]d5f942ba2008-09-26 19:30:34491const std::wstring TabContents::GetDefaultTitle() const {
492 return l10n_util::GetString(IDS_DEFAULT_TAB_TITLE);
493}
494
[email protected]96d185d2009-04-24 03:28:54495bool TabContents::ShouldDisplayURL() {
496 // Don't hide the url in view source mode.
497 NavigationEntry* entry = controller_.GetActiveEntry();
498 if (entry && entry->IsViewSourceMode())
499 return true;
[email protected]83e3895b2009-06-11 00:07:16500
[email protected]96d185d2009-04-24 03:28:54501 DOMUI* dom_ui = GetDOMUIForCurrentState();
502 if (dom_ui)
503 return !dom_ui->should_hide_url();
504 return true;
505}
506
[email protected]d5f942ba2008-09-26 19:30:34507SkBitmap TabContents::GetFavIcon() const {
508 // Like GetTitle(), we also want to use the favicon for the last committed
509 // entry rather than a pending navigation entry.
[email protected]ce3fa3c2009-04-20 19:55:57510 NavigationEntry* entry = controller_.GetTransientEntry();
[email protected]cbab76d2008-10-13 22:42:47511 if (entry)
512 return entry->favicon().bitmap();
513
[email protected]ce3fa3c2009-04-20 19:55:57514 entry = controller_.GetLastCommittedEntry();
[email protected]d5f942ba2008-09-26 19:30:34515 if (entry)
516 return entry->favicon().bitmap();
[email protected]ce3fa3c2009-04-20 19:55:57517 else if (controller_.LoadingURLLazily())
518 return controller_.GetLazyFavIcon();
[email protected]d5f942ba2008-09-26 19:30:34519 return SkBitmap();
520}
521
[email protected]96d185d2009-04-24 03:28:54522bool TabContents::ShouldDisplayFavIcon() {
523 // Always display a throbber during pending loads.
524 if (controller_.GetLastCommittedEntry() && controller_.pending_entry())
525 return true;
526
527 DOMUI* dom_ui = GetDOMUIForCurrentState();
528 if (dom_ui)
529 return !dom_ui->hide_favicon();
530 return true;
531}
532
[email protected]96d185d2009-04-24 03:28:54533std::wstring TabContents::GetStatusText() const {
534 if (!is_loading() || load_state_ == net::LOAD_STATE_IDLE)
535 return std::wstring();
536
537 switch (load_state_) {
538 case net::LOAD_STATE_WAITING_FOR_CACHE:
539 return l10n_util::GetString(IDS_LOAD_STATE_WAITING_FOR_CACHE);
540 case net::LOAD_STATE_RESOLVING_PROXY_FOR_URL:
541 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_PROXY_FOR_URL);
542 case net::LOAD_STATE_RESOLVING_HOST:
543 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_HOST);
544 case net::LOAD_STATE_CONNECTING:
545 return l10n_util::GetString(IDS_LOAD_STATE_CONNECTING);
546 case net::LOAD_STATE_SENDING_REQUEST:
547 return l10n_util::GetString(IDS_LOAD_STATE_SENDING_REQUEST);
548 case net::LOAD_STATE_WAITING_FOR_RESPONSE:
549 return l10n_util::GetStringF(IDS_LOAD_STATE_WAITING_FOR_RESPONSE,
550 load_state_host_);
551 // Ignore net::LOAD_STATE_READING_RESPONSE and net::LOAD_STATE_IDLE
552 case net::LOAD_STATE_IDLE:
553 case net::LOAD_STATE_READING_RESPONSE:
554 break;
555 }
556
557 return std::wstring();
558}
559
[email protected]d5f942ba2008-09-26 19:30:34560void TabContents::SetIsCrashed(bool state) {
561 if (state == is_crashed_)
562 return;
563
564 is_crashed_ = state;
[email protected]c9cd2222009-05-06 05:16:50565 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]d5f942ba2008-09-26 19:30:34566}
567
[email protected]f9b1a7b2009-06-22 17:26:38568void TabContents::SetPageActionEnabled(const PageAction* page_action,
[email protected]d7eaf572009-07-01 21:57:00569 bool enable,
570 const std::string& title,
571 int icon_id) {
[email protected]ce5c4502009-05-06 16:46:11572 DCHECK(page_action);
573
[email protected]d7eaf572009-07-01 21:57:00574 if (!enable &&
575 enabled_page_actions_.end() == enabled_page_actions_.find(page_action)) {
576 return; // Don't need to disable twice.
577 }
[email protected]ce5c4502009-05-06 16:46:11578
[email protected]d7eaf572009-07-01 21:57:00579 if (enable) {
580 enabled_page_actions_[page_action].reset(
581 new PageActionState(title, icon_id));
582 } else {
[email protected]f9b1a7b2009-06-22 17:26:38583 enabled_page_actions_.erase(page_action);
[email protected]d7eaf572009-07-01 21:57:00584 }
[email protected]ce5c4502009-05-06 16:46:11585}
586
[email protected]d7eaf572009-07-01 21:57:00587const PageActionState* TabContents::GetPageActionState(
588 const PageAction* page_action) {
589 if (enabled_page_actions_.end() == enabled_page_actions_.find(page_action))
590 return NULL;
[email protected]ce5c4502009-05-06 16:46:11591
[email protected]d7eaf572009-07-01 21:57:00592 return enabled_page_actions_[page_action].get();
593}
[email protected]ce5c4502009-05-06 16:46:11594
[email protected]d5f942ba2008-09-26 19:30:34595void TabContents::NotifyNavigationStateChanged(unsigned changed_flags) {
596 if (delegate_)
597 delegate_->NavigationStateChanged(this, changed_flags);
598}
599
[email protected]96d185d2009-04-24 03:28:54600void TabContents::DidBecomeSelected() {
601 controller_.SetActive(true);
602
603 if (render_widget_host_view())
604 render_widget_host_view()->DidBecomeSelected();
605
606 // If pid() is -1, that means the RenderProcessHost still hasn't been
607 // initialized. It'll register with CacheManagerHost when it is.
608 if (process()->pid() != -1)
609 WebCacheManager::GetInstance()->ObserveActivity(process()->pid());
610}
611
612void TabContents::WasHidden() {
613 if (!capturing_contents()) {
614 // |render_view_host()| can be NULL if the user middle clicks a link to open
615 // a tab in then background, then closes the tab before selecting it. This
616 // is because closing the tab calls TabContents::Destroy(), which removes
617 // the |render_view_host()|; then when we actually destroy the window,
618 // OnWindowPosChanged() notices and calls HideContents() (which calls us).
619 if (render_widget_host_view())
620 render_widget_host_view()->WasHidden();
[email protected]96d185d2009-04-24 03:28:54621 }
622
623 NotificationService::current()->Notify(
624 NotificationType::TAB_CONTENTS_HIDDEN,
625 Source<TabContents>(this),
626 NotificationService::NoDetails());
627}
628
[email protected]d5f942ba2008-09-26 19:30:34629void TabContents::Activate() {
630 if (delegate_)
631 delegate_->ActivateContents(this);
632}
633
[email protected]96d185d2009-04-24 03:28:54634void TabContents::ShowContents() {
635 if (render_widget_host_view())
636 render_widget_host_view()->DidBecomeSelected();
[email protected]96d185d2009-04-24 03:28:54637}
638
639void TabContents::HideContents() {
640 // TODO(pkasting): http://b/1239839 Right now we purposefully don't call
641 // our superclass HideContents(), because some callers want to be very picky
642 // about the order in which these get called. In addition to making the code
643 // here practically impossible to understand, this also means we end up
644 // calling TabContents::WasHidden() twice if callers call both versions of
[email protected]57c6a652009-05-04 07:58:34645 // HideContents() on a TabContents.
[email protected]96d185d2009-04-24 03:28:54646 WasHidden();
647}
648
[email protected]c0588052008-10-27 23:01:50649void TabContents::OpenURL(const GURL& url, const GURL& referrer,
[email protected]d5f942ba2008-09-26 19:30:34650 WindowOpenDisposition disposition,
651 PageTransition::Type transition) {
652 if (delegate_)
[email protected]c0588052008-10-27 23:01:50653 delegate_->OpenURLFromTab(this, url, referrer, disposition, transition);
[email protected]d5f942ba2008-09-26 19:30:34654}
655
656bool TabContents::NavigateToPendingEntry(bool reload) {
[email protected]96d185d2009-04-24 03:28:54657 const NavigationEntry& entry = *controller_.pending_entry();
658
659 RenderViewHost* dest_render_view_host = render_manager_.Navigate(entry);
660 if (!dest_render_view_host)
661 return false; // Unable to create the desired render view host.
662
663 // Tell DevTools agent that it is attached prior to the navigation.
[email protected]d9f9b792009-06-24 13:17:12664 DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
[email protected]7e8e6b62009-05-08 11:28:32665 if (devtools_manager) { // NULL in unit tests.
[email protected]684b4ba22009-05-07 06:27:41666 devtools_manager->OnNavigatingToPendingEntry(
667 render_view_host(),
668 dest_render_view_host,
669 controller_.pending_entry()->url());
[email protected]7e8e6b62009-05-08 11:28:32670 }
[email protected]96d185d2009-04-24 03:28:54671
672 // Used for page load time metrics.
673 current_load_start_ = base::TimeTicks::Now();
674
675 // Navigate in the desired RenderViewHost.
[email protected]056de2d2009-06-26 16:41:34676 ViewMsg_Navigate_Params navigate_params;
677 MakeNavigateParams(entry, reload, &navigate_params);
678 dest_render_view_host->Navigate(navigate_params);
[email protected]96d185d2009-04-24 03:28:54679
680 if (entry.page_id() == -1) {
681 // HACK!! This code suppresses javascript: URLs from being added to
682 // session history, which is what we want to do for javascript: URLs that
683 // do not generate content. What we really need is a message from the
684 // renderer telling us that a new page was not created. The same message
685 // could be used for mailto: URLs and the like.
686 if (entry.url().SchemeIs(chrome::kJavaScriptScheme))
687 return false;
688 }
689
690 // Clear any provisional password saves - this stops password infobars
691 // showing up on pages the user navigates to while the right page is
692 // loading.
693 GetPasswordManager()->ClearProvisionalSave();
694
695 if (reload && !profile()->IsOffTheRecord()) {
696 HistoryService* history =
697 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
698 if (history)
699 history->SetFavIconOutOfDateForPage(entry.url());
700 }
701
[email protected]d5f942ba2008-09-26 19:30:34702 return true;
703}
704
[email protected]96d185d2009-04-24 03:28:54705void TabContents::Stop() {
706 render_manager_.Stop();
707 printing_.Stop();
708}
709
710void TabContents::Cut() {
711 render_view_host()->Cut();
712}
713
714void TabContents::Copy() {
715 render_view_host()->Copy();
716}
717
718void TabContents::Paste() {
719 render_view_host()->Paste();
720}
721
722void TabContents::DisassociateFromPopupCount() {
723 render_view_host()->DisassociateFromPopupCount();
724}
725
726TabContents* TabContents::Clone() {
727 // We create a new SiteInstance so that the new tab won't share processes
728 // with the old one. This can be changed in the future if we need it to share
729 // processes for some reason.
[email protected]420ae012009-04-24 05:16:32730 TabContents* tc = new TabContents(profile(),
[email protected]96d185d2009-04-24 03:28:54731 SiteInstance::CreateSiteInstance(profile()),
732 MSG_ROUTING_NONE, NULL);
733 tc->controller().CopyStateFrom(controller_);
734 return tc;
735}
736
[email protected]420ae012009-04-24 05:16:32737void TabContents::CreateShortcut() {
738 NavigationEntry* entry = controller_.GetLastCommittedEntry();
739 if (!entry)
740 return;
741
742 // We only allow one pending install request. By resetting the page id we
743 // effectively cancel the pending install request.
744 pending_install_.page_id = entry->page_id();
745 pending_install_.icon = GetFavIcon();
746 pending_install_.title = UTF16ToWideHack(GetTitle());
747 pending_install_.url = GetURL();
748 if (pending_install_.callback_functor) {
749 pending_install_.callback_functor->Cancel();
750 pending_install_.callback_functor = NULL;
751 }
752 DCHECK(!pending_install_.icon.isNull()) << "Menu item should be disabled.";
753 if (pending_install_.title.empty())
754 pending_install_.title = UTF8ToWide(GetURL().spec());
755
756 // Request the application info. When done OnDidGetApplicationInfo is invoked
757 // and we'll create the shortcut.
758 render_view_host()->GetApplicationInfo(pending_install_.page_id);
759}
760
[email protected]e8382172009-06-19 22:16:28761#if defined(OS_WIN) || defined(OS_LINUX)
initial.commit09911bf2008-07-26 23:55:29762ConstrainedWindow* TabContents::CreateConstrainedDialog(
[email protected]e8382172009-06-19 22:16:28763 ConstrainedWindowDelegate* delegate) {
initial.commit09911bf2008-07-26 23:55:29764 ConstrainedWindow* window =
[email protected]e8382172009-06-19 22:16:28765 ConstrainedWindow::CreateConstrainedDialog(this, delegate);
initial.commit09911bf2008-07-26 23:55:29766 child_windows_.push_back(window);
767 return window;
768}
[email protected]f3332e12009-03-23 15:28:57769#endif
initial.commit09911bf2008-07-26 23:55:29770
771void TabContents::AddNewContents(TabContents* new_contents,
772 WindowOpenDisposition disposition,
773 const gfx::Rect& initial_pos,
[email protected]c88a70fe2009-05-05 20:00:22774 bool user_gesture,
775 const GURL& creator_url) {
initial.commit09911bf2008-07-26 23:55:29776 if (!delegate_)
777 return;
778
[email protected]35f7d212009-04-29 21:19:27779 if ((disposition == NEW_POPUP) && !user_gesture &&
780 !CommandLine::ForCurrentProcess()->HasSwitch(
781 switches::kDisablePopupBlocking)) {
[email protected]2c4410d2009-05-06 23:46:22782 // Unrequested popups from normal pages are constrained unless they're in
[email protected]b6c874582009-05-08 19:38:31783 // the whitelist. The popup owner will handle checking this.
784 delegate_->GetConstrainingContents(this)->AddPopup(new_contents,
785 initial_pos,
786 creator_url.is_valid() ? creator_url.host() : std::string());
787 } else {
[email protected]0aa55312008-10-17 21:53:08788 new_contents->DisassociateFromPopupCount();
initial.commit09911bf2008-07-26 23:55:29789 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
790 user_gesture);
791 }
[email protected]b6c874582009-05-08 19:38:31792 PopupNotificationVisibilityChanged(ShowingBlockedPopupNotification());
initial.commit09911bf2008-07-26 23:55:29793}
794
initial.commit09911bf2008-07-26 23:55:29795void TabContents::CloseAllSuppressedPopups() {
[email protected]d6598c052008-11-05 19:03:25796 if (blocked_popups_)
[email protected]2c4410d2009-05-06 23:46:22797 blocked_popups_->CloseAll();
initial.commit09911bf2008-07-26 23:55:29798}
799
[email protected]96d185d2009-04-24 03:28:54800void TabContents::PopupNotificationVisibilityChanged(bool visible) {
801 render_view_host()->PopupNotificationVisibilityChanged(visible);
802}
803
804gfx::NativeView TabContents::GetContentNativeView() {
805 return view_->GetContentNativeView();
806}
807
808gfx::NativeView TabContents::GetNativeView() const {
809 return view_->GetNativeView();
810}
811
812void TabContents::GetContainerBounds(gfx::Rect *out) const {
813 view_->GetContainerBounds(out);
814}
815
816void TabContents::Focus() {
817 view_->Focus();
818}
819
[email protected]90daadb42009-06-08 21:27:28820void TabContents::FocusThroughTabTraversal(bool reverse) {
[email protected]7e383692009-06-12 19:14:54821 if (showing_interstitial_page()) {
822 render_manager_.interstitial_page()->FocusThroughTabTraversal(reverse);
823 return;
824 }
[email protected]96d185d2009-04-24 03:28:54825 render_view_host()->SetInitialFocus(reverse);
826}
827
828bool TabContents::FocusLocationBarByDefault() {
829 DOMUI* dom_ui = GetDOMUIForCurrentState();
830 if (dom_ui)
831 return dom_ui->focus_location_bar_by_default();
[email protected]3e3f0eb2009-06-22 18:33:43832 NavigationEntry* entry = controller_.GetActiveEntry();
833 if (entry && entry->url() == GURL("about:blank"))
834 return true;
[email protected]96d185d2009-04-24 03:28:54835 return false;
836}
837
[email protected]616ed5a2008-11-21 22:27:24838void TabContents::AddInfoBar(InfoBarDelegate* delegate) {
839 // Look through the existing InfoBarDelegates we have for a match. If we've
840 // already got one that matches, then we don't add the new one.
[email protected]f86a07022008-11-25 01:06:05841 for (int i = 0; i < infobar_delegate_count(); ++i) {
[email protected]616ed5a2008-11-21 22:27:24842 if (GetInfoBarDelegateAt(i)->EqualsDelegate(delegate))
843 return;
844 }
845
846 infobar_delegates_.push_back(delegate);
[email protected]bfd04a62009-02-01 18:16:56847 NotificationService::current()->Notify(
848 NotificationType::TAB_CONTENTS_INFOBAR_ADDED,
849 Source<TabContents>(this),
850 Details<InfoBarDelegate>(delegate));
[email protected]616ed5a2008-11-21 22:27:24851
852 // Add ourselves as an observer for navigations the first time a delegate is
853 // added. We use this notification to expire InfoBars that need to expire on
854 // page transitions.
855 if (infobar_delegates_.size() == 1) {
[email protected]bfd04a62009-02-01 18:16:56856 registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57857 Source<NavigationController>(&controller_));
[email protected]616ed5a2008-11-21 22:27:24858 }
859}
860
861void TabContents::RemoveInfoBar(InfoBarDelegate* delegate) {
862 std::vector<InfoBarDelegate*>::iterator it =
863 find(infobar_delegates_.begin(), infobar_delegates_.end(), delegate);
864 if (it != infobar_delegates_.end()) {
865 InfoBarDelegate* delegate = *it;
[email protected]bfd04a62009-02-01 18:16:56866 NotificationService::current()->Notify(
867 NotificationType::TAB_CONTENTS_INFOBAR_REMOVED,
868 Source<TabContents>(this),
869 Details<InfoBarDelegate>(delegate));
[email protected]f86a07022008-11-25 01:06:05870 infobar_delegates_.erase(it);
[email protected]616ed5a2008-11-21 22:27:24871
[email protected]6a02963e2009-01-06 16:58:03872 // Remove ourselves as an observer if we are tracking no more InfoBars.
873 if (infobar_delegates_.empty()) {
[email protected]bfd04a62009-02-01 18:16:56874 registrar_.Remove(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57875 Source<NavigationController>(&controller_));
[email protected]6a02963e2009-01-06 16:58:03876 }
[email protected]616ed5a2008-11-21 22:27:24877 }
878}
[email protected]3edd9522009-03-04 22:19:41879
[email protected]96d185d2009-04-24 03:28:54880bool TabContents::IsBookmarkBarAlwaysVisible() {
881 // See GetDOMUIForCurrentState() comment for more info. This case is very
882 // similar, but for non-first loads, we want to use the committed entry. This
883 // is so the bookmarks bar disappears at the same time the page does.
884 if (controller_.GetLastCommittedEntry()) {
885 // Not the first load, always use the committed DOM UI.
886 if (render_manager_.dom_ui())
887 return render_manager_.dom_ui()->force_bookmark_bar_visible();
888 return false; // Default.
889 }
890
891 // When it's the first load, we know either the pending one or the committed
892 // one will have the DOM UI in it (see GetDOMUIForCurrentState), and only one
893 // of them will be valid, so we can just check both.
894 if (render_manager_.pending_dom_ui())
895 return render_manager_.pending_dom_ui()->force_bookmark_bar_visible();
896 if (render_manager_.dom_ui())
897 return render_manager_.dom_ui()->force_bookmark_bar_visible();
898 return false; // Default.
899}
900
[email protected]3edd9522009-03-04 22:19:41901void TabContents::ToolbarSizeChanged(bool is_animating) {
902 TabContentsDelegate* d = delegate();
903 if (d)
904 d->ToolbarSizeChanged(this, is_animating);
905}
[email protected]616ed5a2008-11-21 22:27:24906
[email protected]d5f942ba2008-09-26 19:30:34907void TabContents::OnStartDownload(DownloadItem* download) {
908 DCHECK(download);
[email protected]d5f942ba2008-09-26 19:30:34909
910 // Download in a constrained popup is shown in the tab that opened it.
[email protected]b6c874582009-05-08 19:38:31911 TabContents* tab_contents = delegate()->GetConstrainingContents(this);
[email protected]d5f942ba2008-09-26 19:30:34912
[email protected]59560e0b2009-06-04 03:30:22913 if (tab_contents && tab_contents->delegate())
914 tab_contents->delegate()->OnStartDownload(download);
[email protected]3edd9522009-03-04 22:19:41915}
[email protected]3edd9522009-03-04 22:19:41916
[email protected]d5f942ba2008-09-26 19:30:34917void TabContents::WillClose(ConstrainedWindow* window) {
918 ConstrainedWindowList::iterator it =
919 find(child_windows_.begin(), child_windows_.end(), window);
920 if (it != child_windows_.end())
921 child_windows_.erase(it);
[email protected]66ba4932009-06-04 19:22:13922}
[email protected]d5f942ba2008-09-26 19:30:34923
[email protected]66ba4932009-06-04 19:22:13924void TabContents::WillCloseBlockedPopupContainer(
925 BlockedPopupContainer* container) {
926 DCHECK(blocked_popups_ == container);
927 blocked_popups_ = NULL;
[email protected]d5f942ba2008-09-26 19:30:34928}
929
[email protected]d5f942ba2008-09-26 19:30:34930void TabContents::DidMoveOrResize(ConstrainedWindow* window) {
[email protected]332af7732009-03-11 13:21:35931#if defined(OS_WIN)
[email protected]92edc472009-02-10 20:32:06932 UpdateWindow(GetNativeView());
[email protected]332af7732009-03-11 13:21:35933#endif
[email protected]d5f942ba2008-09-26 19:30:34934}
935
[email protected]e491f1c2009-05-22 20:28:12936void TabContents::StartFinding(string16 find_text,
937 bool forward_direction,
938 bool case_sensitive) {
[email protected]6e95706d2009-04-23 22:55:01939 // If find_text is empty, it means FindNext was pressed with a keyboard
940 // shortcut so unless we have something to search for we return early.
[email protected]e491f1c2009-05-22 20:28:12941 if (find_text.empty() && find_text_.empty()) {
942 if (last_search_prepopulate_text_->empty())
943 return;
944 // Try whatever we searched for last in any tab.
945 find_text = *last_search_prepopulate_text_;
946 }
[email protected]6e95706d2009-04-23 22:55:01947
948 // This is a FindNext operation if we are searching for the same text again,
949 // or if the passed in search text is empty (FindNext keyboard shortcut). The
950 // exception to this is if the Find was aborted (then we don't want FindNext
951 // because the highlighting has been cleared and we need it to reappear). We
952 // therefore treat FindNext after an aborted Find operation as a full fledged
953 // Find.
954 bool find_next = (find_text_ == find_text || find_text.empty()) &&
[email protected]e491f1c2009-05-22 20:28:12955 (last_search_case_sensitive_ == case_sensitive) &&
[email protected]6e95706d2009-04-23 22:55:01956 !find_op_aborted_;
957 if (!find_next)
958 current_find_request_id_ = find_request_id_counter_++;
959
960 if (!find_text.empty())
961 find_text_ = find_text;
[email protected]e491f1c2009-05-22 20:28:12962 last_search_case_sensitive_ = case_sensitive;
[email protected]6e95706d2009-04-23 22:55:01963
964 find_op_aborted_ = false;
965
966 // Keep track of what the last search was across the tabs.
[email protected]e491f1c2009-05-22 20:28:12967 *last_search_prepopulate_text_ = find_text;
[email protected]6e95706d2009-04-23 22:55:01968
969 render_view_host()->StartFinding(current_find_request_id_,
970 find_text_,
971 forward_direction,
[email protected]e491f1c2009-05-22 20:28:12972 case_sensitive,
[email protected]6e95706d2009-04-23 22:55:01973 find_next);
974}
975
976void TabContents::StopFinding(bool clear_selection) {
[email protected]2d2dffc2009-06-09 21:41:00977 // When |clear_selection| is true, it means the find string has been cleared
978 // by the user, but the UI has not been dismissed.
979 if (!clear_selection)
980 find_ui_active_ = false;
[email protected]6e95706d2009-04-23 22:55:01981 find_op_aborted_ = true;
[email protected]e491f1c2009-05-22 20:28:12982 last_search_result_ = FindNotificationDetails();
[email protected]6e95706d2009-04-23 22:55:01983 render_view_host()->StopFinding(clear_selection);
984}
985
[email protected]420ae012009-04-24 05:16:32986void TabContents::OnJavaScriptMessageBoxClosed(IPC::Message* reply_msg,
987 bool success,
988 const std::wstring& prompt) {
989 last_javascript_message_dismissal_ = base::TimeTicks::Now();
990 render_manager_.OnJavaScriptMessageBoxClosed(reply_msg, success, prompt);
991}
992
[email protected]571e31152009-05-15 19:34:02993void TabContents::OnJavaScriptMessageBoxWindowDestroyed() {
994 render_manager_.OnJavaScriptMessageBoxWindowDestroyed();
995}
996
[email protected]420ae012009-04-24 05:16:32997void TabContents::OnSavePage() {
998 // If we can not save the page, try to download it.
999 if (!SavePackage::IsSavableContents(contents_mime_type())) {
1000 DownloadManager* dlm = profile()->GetDownloadManager();
1001 const GURL& current_page_url = GetURL();
1002 if (dlm && current_page_url.is_valid())
[email protected]d82ed61e2009-06-16 02:46:221003 dlm->DownloadUrl(current_page_url, GURL(), "", this);
[email protected]420ae012009-04-24 05:16:321004 return;
1005 }
1006
1007 Stop();
1008
1009 // Create the save package and possibly prompt the user for the name to save
1010 // the page as. The user prompt is an asynchronous operation that runs on
1011 // another thread.
[email protected]d82ed61e2009-06-16 02:46:221012 save_package_ = new SavePackage(this);
[email protected]420ae012009-04-24 05:16:321013 save_package_->GetSaveInfo();
1014}
1015
1016// Used in automated testing to bypass prompting the user for file names.
1017// Instead, the names and paths are hard coded rather than running them through
1018// file name sanitation and extension / mime checking.
1019void TabContents::SavePage(const std::wstring& main_file,
1020 const std::wstring& dir_path,
1021 SavePackage::SavePackageType save_type) {
1022 // Stop the page from navigating.
1023 Stop();
1024
[email protected]d82ed61e2009-06-16 02:46:221025 save_package_ = new SavePackage(this, save_type,
[email protected]420ae012009-04-24 05:16:321026 FilePath::FromWStringHack(main_file),
1027 FilePath::FromWStringHack(dir_path));
1028 save_package_->Init();
1029}
1030
1031void TabContents::PrintPreview() {
1032 // We don't show the print preview yet, only the print dialog.
1033 PrintNow();
1034}
1035
1036bool TabContents::PrintNow() {
1037 // We can't print interstitial page for now.
1038 if (showing_interstitial_page())
1039 return false;
1040
1041 return render_view_host()->PrintPages();
1042}
1043
[email protected]82270452009-06-19 15:58:011044void TabContents::PrintingDone(int document_cookie, bool success) {
1045 render_view_host()->PrintingDone(document_cookie, success);
1046}
1047
[email protected]420ae012009-04-24 05:16:321048bool TabContents::IsActiveEntry(int32 page_id) {
1049 NavigationEntry* active_entry = controller_.GetActiveEntry();
1050 return (active_entry != NULL &&
1051 active_entry->site_instance() == GetSiteInstance() &&
1052 active_entry->page_id() == page_id);
1053}
1054
[email protected]96d185d2009-04-24 03:28:541055// Notifies the RenderWidgetHost instance about the fact that the page is
1056// loading, or done loading and calls the base implementation.
1057void TabContents::SetIsLoading(bool is_loading,
1058 LoadNotificationDetails* details) {
1059 if (is_loading == is_loading_)
1060 return;
1061
1062 if (!is_loading) {
1063 load_state_ = net::LOAD_STATE_IDLE;
1064 load_state_host_.clear();
1065 }
1066
1067 render_manager_.SetIsLoading(is_loading);
1068
1069 is_loading_ = is_loading;
1070 waiting_for_response_ = is_loading;
1071
1072 if (delegate_)
1073 delegate_->LoadingStateChanged(this);
[email protected]329581b2009-04-28 06:52:351074 NotifyNavigationStateChanged(INVALIDATE_LOAD);
[email protected]96d185d2009-04-24 03:28:541075
1076 NotificationType type = is_loading ? NotificationType::LOAD_START :
1077 NotificationType::LOAD_STOP;
[email protected]ce5c4502009-05-06 16:46:111078 NotificationDetails det = NotificationService::NoDetails();
[email protected]96d185d2009-04-24 03:28:541079 if (details)
1080 det = Details<LoadNotificationDetails>(details);
1081 NotificationService::current()->Notify(type,
1082 Source<NavigationController>(&controller_),
1083 det);
1084}
1085
[email protected]2c4410d2009-05-06 23:46:221086void TabContents::CreateBlockedPopupContainerIfNecessary() {
1087 if (blocked_popups_)
1088 return;
1089
[email protected]4d4c0b92009-06-08 23:13:011090 blocked_popups_ = BlockedPopupContainer::Create(this, profile());
[email protected]2c4410d2009-05-06 23:46:221091}
1092
[email protected]b6c874582009-05-08 19:38:311093void TabContents::AddPopup(TabContents* new_contents,
1094 const gfx::Rect& initial_pos,
1095 const std::string& host) {
[email protected]2c4410d2009-05-06 23:46:221096 CreateBlockedPopupContainerIfNecessary();
1097 blocked_popups_->AddTabContents(new_contents, initial_pos, host);
[email protected]2c4410d2009-05-06 23:46:221098}
1099
[email protected]e69bce3dd2009-04-20 22:05:121100// TODO(brettw) This should be on the TabContentsView.
[email protected]66ba4932009-06-04 19:22:131101void TabContents::RepositionSupressedPopupsToFit() {
[email protected]d6598c052008-11-05 19:03:251102 if (blocked_popups_)
[email protected]4d4c0b92009-06-08 23:13:011103 blocked_popups_->RepositionBlockedPopupContainer();
[email protected]d5f942ba2008-09-26 19:30:341104}
1105
[email protected]b9681312008-11-07 00:08:261106bool TabContents::ShowingBlockedPopupNotification() const {
1107 return blocked_popups_ != NULL &&
[email protected]2c4410d2009-05-06 23:46:221108 blocked_popups_->GetBlockedPopupCount() != 0;
[email protected]b9681312008-11-07 00:08:261109}
[email protected]616ed5a2008-11-21 22:27:241110
1111namespace {
1112bool TransitionIsReload(PageTransition::Type transition) {
1113 return PageTransition::StripQualifier(transition) == PageTransition::RELOAD;
1114}
1115}
1116
1117void TabContents::ExpireInfoBars(
1118 const NavigationController::LoadCommittedDetails& details) {
1119 // Only hide InfoBars when the user has done something that makes the main
1120 // frame load. We don't want various automatic or subframe navigations making
1121 // it disappear.
1122 if (!details.is_user_initiated_main_frame_load())
1123 return;
1124
[email protected]f86a07022008-11-25 01:06:051125 for (int i = infobar_delegate_count() - 1; i >= 0; --i) {
[email protected]616ed5a2008-11-21 22:27:241126 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
[email protected]f86a07022008-11-25 01:06:051127 if (delegate->ShouldExpire(details))
[email protected]616ed5a2008-11-21 22:27:241128 RemoveInfoBar(delegate);
[email protected]616ed5a2008-11-21 22:27:241129 }
1130}
[email protected]fdd61c62009-04-22 19:22:571131
1132void TabContents::OnGearsCreateShortcutDone(
1133 const GearsShortcutData2& shortcut_data, bool success) {
1134 NavigationEntry* current_entry = controller_.GetLastCommittedEntry();
1135 bool same_page =
1136 current_entry && pending_install_.page_id == current_entry->page_id();
1137
1138 if (success && same_page) {
1139 // Only switch to app mode if the user chose to create a shortcut and
1140 // we're still on the same page that it corresponded to.
1141 if (delegate())
1142 delegate()->ConvertContentsToApplication(this);
1143 }
1144
1145 // Reset the page id to indicate no requests are pending.
1146 pending_install_.page_id = 0;
1147 pending_install_.callback_functor = NULL;
1148}
[email protected]96d185d2009-04-24 03:28:541149
1150DOMUI* TabContents::GetDOMUIForCurrentState() {
1151 // When there is a pending navigation entry, we want to use the pending DOMUI
1152 // that goes along with it to control the basic flags. For example, we want to
1153 // show the pending URL in the URL bar, so we want the display_url flag to
1154 // be from the pending entry.
1155 //
1156 // The confusion comes because there are multiple possibilities for the
1157 // initial load in a tab as a side effect of the way the RenderViewHostManager
1158 // works.
1159 //
1160 // - For the very first tab the load looks "normal". The new tab DOM UI is
1161 // the pending one, and we want it to apply here.
1162 //
1163 // - For subsequent new tabs, they'll get a new SiteInstance which will then
1164 // get switched to the one previously associated with the new tab pages.
1165 // This switching will cause the manager to commit the RVH/DOMUI. So we'll
1166 // have a committed DOM UI in this case.
1167 //
1168 // This condition handles all of these cases:
1169 //
1170 // - First load in first tab: no committed nav entry + pending nav entry +
1171 // pending dom ui:
1172 // -> Use pending DOM UI if any.
1173 //
1174 // - First load in second tab: no committed nav entry + pending nav entry +
1175 // no pending DOM UI:
1176 // -> Use the committed DOM UI if any.
1177 //
1178 // - Second navigation in any tab: committed nav entry + pending nav entry:
1179 // -> Use pending DOM UI if any.
1180 //
1181 // - Normal state with no load: committed nav entry + no pending nav entry:
1182 // -> Use committed DOM UI.
1183 if (controller_.pending_entry() &&
1184 (controller_.GetLastCommittedEntry() ||
1185 render_manager_.pending_dom_ui()))
1186 return render_manager_.pending_dom_ui();
1187 return render_manager_.dom_ui();
1188}
[email protected]420ae012009-04-24 05:16:321189
1190void TabContents::DidNavigateMainFramePostCommit(
1191 const NavigationController::LoadCommittedDetails& details,
1192 const ViewHostMsg_FrameNavigate_Params& params) {
[email protected]420ae012009-04-24 05:16:321193 if (details.is_user_initiated_main_frame_load()) {
1194 // Clear the status bubble. This is a workaround for a bug where WebKit
1195 // doesn't let us know that the cursor left an element during a
1196 // transition (this is also why the mouse cursor remains as a hand after
1197 // clicking on a link); see bugs 1184641 and 980803. We don't want to
1198 // clear the bubble when a user navigates to a named anchor in the same
1199 // page.
1200 UpdateTargetURL(details.entry->page_id(), GURL());
1201
1202 // UpdateHelpersForDidNavigate will handle the case where the password_form
1203 // origin is valid.
1204 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1205 // cleaned up and covered by tests.
1206 if (!params.password_form.origin.is_valid())
1207 GetPasswordManager()->DidNavigate();
1208 }
1209
1210 // The keyword generator uses the navigation entries, so must be called after
1211 // the commit.
1212 GenerateKeywordIfNecessary(params);
1213
1214 // Allow the new page to set the title again.
1215 received_page_title_ = false;
1216
1217 // Get the favicon, either from history or request it from the net.
1218 fav_icon_helper_.FetchFavIcon(details.entry->url());
1219
[email protected]ce5c4502009-05-06 16:46:111220 // Disable all page actions.
1221 enabled_page_actions_.clear();
1222
[email protected]420ae012009-04-24 05:16:321223 // Close constrained popups if necessary.
1224 MaybeCloseChildWindows(details.previous_url, details.entry->url());
1225
1226 // Update the starred state.
1227 UpdateStarredStateForCurrentURL();
1228}
1229
1230void TabContents::DidNavigateAnyFramePostCommit(
1231 RenderViewHost* render_view_host,
1232 const NavigationController::LoadCommittedDetails& details,
1233 const ViewHostMsg_FrameNavigate_Params& params) {
1234 // If we navigate, start showing messages again. This does nothing to prevent
1235 // a malicious script from spamming messages, since the script could just
1236 // reload the page to stop blocking.
1237 suppress_javascript_messages_ = false;
1238
1239 // Update history. Note that this needs to happen after the entry is complete,
1240 // which WillNavigate[Main,Sub]Frame will do before this function is called.
1241 if (params.should_update_history) {
1242 // Most of the time, the displayURL matches the loaded URL, but for about:
1243 // URLs, we use a data: URL as the real value. We actually want to save
1244 // the about: URL to the history db and keep the data: URL hidden. This is
1245 // what the TabContents' URL getter does.
[email protected]befd8d822009-07-01 04:51:471246 UpdateHistoryForNavigation(GetURL(), details, params);
[email protected]420ae012009-04-24 05:16:321247 }
1248
1249 // Notify the password manager of the navigation or form submit.
1250 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1251 // cleaned up and covered by tests.
1252 if (params.password_form.origin.is_valid())
1253 GetPasswordManager()->ProvisionallySavePassword(params.password_form);
1254}
1255
1256void TabContents::MaybeCloseChildWindows(const GURL& previous_url,
1257 const GURL& current_url) {
1258 if (net::RegistryControlledDomainService::SameDomainOrHost(
1259 previous_url, current_url))
1260 return;
1261
1262 // Clear out any child windows since we are leaving this page entirely.
1263 // We use indices instead of iterators in case CloseWindow does something
1264 // that may invalidate an iterator.
1265 int size = static_cast<int>(child_windows_.size());
1266 for (int i = size - 1; i >= 0; --i) {
1267 ConstrainedWindow* window = child_windows_[i];
1268 if (window)
1269 window->CloseConstrainedWindow();
1270 }
1271}
1272
1273void TabContents::UpdateStarredStateForCurrentURL() {
1274 BookmarkModel* model = profile()->GetBookmarkModel();
1275 const bool old_state = is_starred_;
1276 is_starred_ = (model && model->IsBookmarked(GetURL()));
1277
1278 if (is_starred_ != old_state && delegate())
1279 delegate()->URLStarredChanged(this, is_starred_);
1280}
1281
1282void TabContents::UpdateAlternateErrorPageURL() {
1283 GURL url = GetAlternateErrorPageURL();
1284 render_view_host()->SetAlternateErrorPageURL(url);
1285}
1286
1287void TabContents::UpdateWebPreferences() {
1288 render_view_host()->UpdateWebPreferences(GetWebkitPrefs());
1289}
1290
1291void TabContents::UpdateMaxPageIDIfNecessary(SiteInstance* site_instance,
1292 RenderViewHost* rvh) {
1293 // If we are creating a RVH for a restored controller, then we might
1294 // have more page IDs than the SiteInstance's current max page ID. We must
1295 // make sure that the max page ID is larger than any restored page ID.
1296 // Note that it is ok for conflicting page IDs to exist in another tab
1297 // (i.e., NavigationController), but if any page ID is larger than the max,
1298 // the back/forward list will get confused.
1299 int max_restored_page_id = controller_.max_restored_page_id();
1300 if (max_restored_page_id > 0) {
1301 int curr_max_page_id = site_instance->max_page_id();
1302 if (max_restored_page_id > curr_max_page_id) {
1303 // Need to update the site instance immediately.
1304 site_instance->UpdateMaxPageID(max_restored_page_id);
1305
1306 // Also tell the renderer to update its internal representation. We
1307 // need to reserve enough IDs to make all restored page IDs less than
1308 // the max.
1309 if (curr_max_page_id < 0)
1310 curr_max_page_id = 0;
1311 rvh->ReservePageIDRange(max_restored_page_id - curr_max_page_id);
1312 }
1313 }
1314}
1315
1316void TabContents::UpdateHistoryForNavigation(
1317 const GURL& display_url,
[email protected]befd8d822009-07-01 04:51:471318 const NavigationController::LoadCommittedDetails& details,
[email protected]420ae012009-04-24 05:16:321319 const ViewHostMsg_FrameNavigate_Params& params) {
1320 if (profile()->IsOffTheRecord())
1321 return;
1322
1323 // Add to history service.
1324 HistoryService* hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1325 if (hs) {
1326 if (PageTransition::IsMainFrame(params.transition) &&
1327 display_url != params.url) {
1328 // Hack on the "display" URL so that it will appear in history. For some
1329 // types of URLs, we will display a magic URL that is different from where
1330 // the page is actually navigated. We want the user to see in history
1331 // what they saw in the URL bar, so we add the display URL as a redirect.
1332 // This only applies to the main frame, as the display URL doesn't apply
1333 // to sub-frames.
1334 std::vector<GURL> redirects = params.redirects;
1335 if (!redirects.empty())
1336 redirects.back() = display_url;
1337 hs->AddPage(display_url, this, params.page_id, params.referrer,
[email protected]befd8d822009-07-01 04:51:471338 params.transition, redirects, details.did_replace_entry);
[email protected]420ae012009-04-24 05:16:321339 } else {
1340 hs->AddPage(params.url, this, params.page_id, params.referrer,
[email protected]befd8d822009-07-01 04:51:471341 params.transition, params.redirects,
1342 details.did_replace_entry);
[email protected]420ae012009-04-24 05:16:321343 }
1344 }
1345}
1346
1347bool TabContents::UpdateTitleForEntry(NavigationEntry* entry,
1348 const std::wstring& title) {
1349 // For file URLs without a title, use the pathname instead. In the case of a
1350 // synthesized title, we don't want the update to count toward the "one set
1351 // per page of the title to history."
1352 std::wstring final_title;
1353 bool explicit_set;
1354 if (entry->url().SchemeIsFile() && title.empty()) {
1355 final_title = UTF8ToWide(entry->url().ExtractFileName());
1356 explicit_set = false; // Don't count synthetic titles toward the set limit.
1357 } else {
1358 TrimWhitespace(title, TRIM_ALL, &final_title);
1359 explicit_set = true;
1360 }
1361
1362 if (final_title == UTF16ToWideHack(entry->title()))
1363 return false; // Nothing changed, don't bother.
1364
1365 entry->set_title(WideToUTF16Hack(final_title));
1366
1367 // Update the history system for this page.
1368 if (!profile()->IsOffTheRecord() && !received_page_title_) {
1369 HistoryService* hs =
1370 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1371 if (hs)
1372 hs->SetPageTitle(entry->display_url(), final_title);
1373
1374 // Don't allow the title to be saved again for explicitly set ones.
1375 received_page_title_ = explicit_set;
1376 }
1377
1378 // Lastly, set the title for the view.
1379 view_->SetPageTitle(final_title);
1380
1381 return true;
1382}
1383
1384void TabContents::NotifySwapped() {
1385 // After sending out a swap notification, we need to send a disconnect
1386 // notification so that clients that pick up a pointer to |this| can NULL the
1387 // pointer. See Bug 1230284.
1388 notify_disconnection_ = true;
1389 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341390 NotificationType::TAB_CONTENTS_SWAPPED,
[email protected]d82ed61e2009-06-16 02:46:221391 Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321392 NotificationService::NoDetails());
1393}
1394
1395void TabContents::NotifyConnected() {
1396 notify_disconnection_ = true;
1397 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341398 NotificationType::TAB_CONTENTS_CONNECTED,
[email protected]d82ed61e2009-06-16 02:46:221399 Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321400 NotificationService::NoDetails());
1401}
1402
1403void TabContents::NotifyDisconnected() {
1404 if (!notify_disconnection_)
1405 return;
1406
1407 notify_disconnection_ = false;
1408 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341409 NotificationType::TAB_CONTENTS_DISCONNECTED,
[email protected]d82ed61e2009-06-16 02:46:221410 Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321411 NotificationService::NoDetails());
1412}
1413
1414void TabContents::GenerateKeywordIfNecessary(
1415 const ViewHostMsg_FrameNavigate_Params& params) {
1416 if (!params.searchable_form_url.is_valid())
1417 return;
1418
1419 if (profile()->IsOffTheRecord())
1420 return;
1421
1422 int last_index = controller_.last_committed_entry_index();
1423 // When there was no previous page, the last index will be 0. This is
1424 // normally due to a form submit that opened in a new tab.
1425 // TODO(brettw) bug 916126: we should support keywords when form submits
1426 // happen in new tabs.
1427 if (last_index <= 0)
1428 return;
1429 const NavigationEntry* previous_entry =
1430 controller_.GetEntryAtIndex(last_index - 1);
1431 if (IsFormSubmit(previous_entry)) {
1432 // Only generate a keyword if the previous page wasn't itself a form
1433 // submit.
1434 return;
1435 }
1436
1437 GURL keyword_url = previous_entry->user_typed_url().is_valid() ?
1438 previous_entry->user_typed_url() : previous_entry->url();
1439 std::wstring keyword =
1440 TemplateURLModel::GenerateKeyword(keyword_url, true); // autodetected
1441 if (keyword.empty())
1442 return;
1443
1444 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
1445 if (!url_model)
1446 return;
1447
1448 if (!url_model->loaded()) {
1449 url_model->Load();
1450 return;
1451 }
1452
1453 const TemplateURL* current_url;
1454 std::wstring url = UTF8ToWide(params.searchable_form_url.spec());
1455 if (!url_model->CanReplaceKeyword(keyword, url, &current_url))
1456 return;
1457
1458 if (current_url) {
1459 if (current_url->originating_url().is_valid()) {
1460 // The existing keyword was generated from an OpenSearch description
1461 // document, don't regenerate.
1462 return;
1463 }
1464 url_model->Remove(current_url);
1465 }
1466 TemplateURL* new_url = new TemplateURL();
1467 new_url->set_keyword(keyword);
1468 new_url->set_short_name(keyword);
1469 new_url->SetURL(url, 0, 0);
1470 new_url->add_input_encoding(params.searchable_form_encoding);
1471 DCHECK(controller_.GetLastCommittedEntry());
1472 const GURL& favicon_url =
1473 controller_.GetLastCommittedEntry()->favicon().url();
1474 if (favicon_url.is_valid()) {
1475 new_url->SetFavIconURL(favicon_url);
1476 } else {
1477 // The favicon url isn't valid. This means there really isn't a favicon,
1478 // or the favicon url wasn't obtained before the load started. This assumes
1479 // the later.
1480 // TODO(sky): Need a way to set the favicon that doesn't involve generating
1481 // its url.
1482 new_url->SetFavIconURL(TemplateURL::GenerateFaviconURL(params.referrer));
1483 }
1484 new_url->set_safe_for_autoreplace(true);
1485 url_model->Add(new_url);
1486}
1487
1488RenderViewHostDelegate::View* TabContents::GetViewDelegate() const {
1489 return view_.get();
1490}
1491
1492RenderViewHostDelegate::Save* TabContents::GetSaveDelegate() const {
1493 return save_package_.get(); // May be NULL, but we can return NULL.
1494}
1495
[email protected]80d96fa2009-06-10 22:34:511496RendererPreferences TabContents::GetRendererPrefs() const {
1497 if (delegate())
1498 return delegate()->GetRendererPrefs();
1499 else
1500 return RendererPreferences();
1501}
1502
[email protected]57c6a652009-05-04 07:58:341503TabContents* TabContents::GetAsTabContents() {
1504 return this;
1505}
1506
[email protected]420ae012009-04-24 05:16:321507void TabContents::RenderViewCreated(RenderViewHost* render_view_host) {
1508 NavigationEntry* entry = controller_.GetActiveEntry();
1509 if (!entry)
1510 return;
1511
1512 // When we're creating views, we're still doing initial setup, so we always
1513 // use the pending DOM UI rather than any possibly existing committed one.
1514 if (render_manager_.pending_dom_ui()) {
1515 render_manager_.pending_dom_ui()->RenderViewCreated(render_view_host);
1516 }
1517
1518 if (entry->IsViewSourceMode()) {
1519 // Put the renderer in view source mode.
1520 render_view_host->Send(
1521 new ViewMsg_EnableViewSourceMode(render_view_host->routing_id()));
1522 }
[email protected]0666aef2009-05-13 19:48:081523
1524 view()->RenderViewCreated(render_view_host);
[email protected]420ae012009-04-24 05:16:321525}
1526
1527void TabContents::RenderViewReady(RenderViewHost* rvh) {
1528 if (rvh != render_view_host()) {
1529 // Don't notify the world, since this came from a renderer in the
1530 // background.
1531 return;
1532 }
1533
1534 NotifyConnected();
1535 SetIsCrashed(false);
1536}
1537
1538void TabContents::RenderViewGone(RenderViewHost* rvh) {
1539 // Ask the print preview if this renderer was valuable.
1540 if (!printing_.OnRenderViewGone(rvh))
1541 return;
1542 if (rvh != render_view_host()) {
1543 // The pending page's RenderViewHost is gone.
1544 return;
1545 }
1546
1547 SetIsLoading(false, NULL);
1548 NotifyDisconnected();
1549 SetIsCrashed(true);
1550
[email protected]8e537302009-06-10 21:19:581551 // Tell the view that we've crashed so it can prepare the sad tab page.
1552 view_->OnTabCrashed();
[email protected]420ae012009-04-24 05:16:321553
1554 // Hide any visible hung renderer warning for this web contents' process.
[email protected]d82ed61e2009-06-16 02:46:221555 HungRendererDialog::HideForTabContents(this);
[email protected]420ae012009-04-24 05:16:321556}
1557
1558void TabContents::DidNavigate(RenderViewHost* rvh,
1559 const ViewHostMsg_FrameNavigate_Params& params) {
1560 if (PageTransition::IsMainFrame(params.transition))
1561 render_manager_.DidNavigateMainFrame(rvh);
1562
1563 // Update the site of the SiteInstance if it doesn't have one yet.
1564 if (!GetSiteInstance()->has_site())
1565 GetSiteInstance()->SetSite(params.url);
1566
1567 // Need to update MIME type here because it's referred to in
1568 // UpdateNavigationCommands() called by RendererDidNavigate() to
1569 // determine whether or not to enable the encoding menu.
1570 // It's updated only for the main frame. For a subframe,
1571 // RenderView::UpdateURL does not set params.contents_mime_type.
1572 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
1573 // TODO(jungshik): Add a test for the encoding menu to avoid
1574 // regressing it again.
1575 if (PageTransition::IsMainFrame(params.transition))
1576 contents_mime_type_ = params.contents_mime_type;
1577
1578 NavigationController::LoadCommittedDetails details;
1579 if (!controller_.RendererDidNavigate(params, &details))
1580 return; // No navigation happened.
1581
1582 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
1583 // for the appropriate notification (best) or you can add it to
1584 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
1585 // necessary, please).
1586
1587 // Run post-commit tasks.
1588 if (details.is_main_frame)
1589 DidNavigateMainFramePostCommit(details, params);
1590 DidNavigateAnyFramePostCommit(rvh, details, params);
1591}
1592
1593void TabContents::UpdateState(RenderViewHost* rvh,
1594 int32 page_id,
1595 const std::string& state) {
1596 DCHECK(rvh == render_view_host());
1597
1598 // We must be prepared to handle state updates for any page, these occur
1599 // when the user is scrolling and entering form data, as well as when we're
1600 // leaving a page, in which case our state may have already been moved to
1601 // the next page. The navigation controller will look up the appropriate
1602 // NavigationEntry and update it when it is notified via the delegate.
1603
1604 int entry_index = controller_.GetEntryIndexWithPageID(
1605 GetSiteInstance(), page_id);
1606 if (entry_index < 0)
1607 return;
1608 NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
1609
1610 if (state == entry->content_state())
1611 return; // Nothing to update.
1612 entry->set_content_state(state);
1613 controller_.NotifyEntryChanged(entry, entry_index);
1614}
1615
1616void TabContents::UpdateTitle(RenderViewHost* rvh,
1617 int32 page_id, const std::wstring& title) {
1618 // If we have a title, that's a pretty good indication that we've started
1619 // getting useful data.
1620 SetNotWaitingForResponse();
1621
1622 DCHECK(rvh == render_view_host());
1623 NavigationEntry* entry = controller_.GetEntryWithPageID(GetSiteInstance(),
1624 page_id);
1625 if (!entry || !UpdateTitleForEntry(entry, title))
1626 return;
1627
1628 // Broadcast notifications when the UI should be updated.
1629 if (entry == controller_.GetEntryAtOffset(0))
[email protected]c9cd2222009-05-06 05:16:501630 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:321631}
1632
[email protected]420ae012009-04-24 05:16:321633void TabContents::UpdateEncoding(RenderViewHost* render_view_host,
1634 const std::wstring& encoding) {
1635 set_encoding(encoding);
1636}
1637
1638void TabContents::UpdateTargetURL(int32 page_id, const GURL& url) {
1639 if (delegate())
1640 delegate()->UpdateTargetURL(this, url);
1641}
1642
1643void TabContents::UpdateThumbnail(const GURL& url,
1644 const SkBitmap& bitmap,
1645 const ThumbnailScore& score) {
1646 // Tell History about this thumbnail
[email protected]449478302009-06-09 20:04:281647 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kThumbnailStore)) {
1648 profile()->GetThumbnailStore()->
1649 SetPageThumbnail(url, bitmap, score, !profile()->IsOffTheRecord());
1650 } else {
1651 HistoryService* hs;
1652 if (!profile()->IsOffTheRecord() &&
1653 (hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS))) {
1654 hs->SetPageThumbnail(url, bitmap, score);
1655 }
[email protected]420ae012009-04-24 05:16:321656 }
1657}
1658
[email protected]0df30122009-06-03 12:13:081659void TabContents::UpdateInspectorSettings(const std::wstring& raw_settings) {
1660 profile()->GetPrefs()->SetString(prefs::kWebKitInspectorSettings,
1661 raw_settings);
1662}
1663
[email protected]420ae012009-04-24 05:16:321664void TabContents::Close(RenderViewHost* rvh) {
1665 // Ignore this if it comes from a RenderViewHost that we aren't showing.
1666 if (delegate() && rvh == render_view_host())
1667 delegate()->CloseContents(this);
1668}
1669
1670void TabContents::RequestMove(const gfx::Rect& new_bounds) {
1671 if (delegate() && delegate()->IsPopup(this))
1672 delegate()->MoveContents(this, new_bounds);
1673}
1674
[email protected]329581b2009-04-28 06:52:351675void TabContents::DidStartLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321676 SetIsLoading(true, NULL);
1677}
1678
[email protected]329581b2009-04-28 06:52:351679void TabContents::DidStopLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321680 scoped_ptr<LoadNotificationDetails> details;
1681
1682 NavigationEntry* entry = controller_.GetActiveEntry();
1683 // An entry may not exist for a stop when loading an initial blank page or
1684 // if an iframe injected by script into a blank page finishes loading.
1685 if (entry) {
1686 scoped_ptr<base::ProcessMetrics> metrics(
1687 base::ProcessMetrics::CreateProcessMetrics(
1688 process()->process().handle()));
1689
1690 base::TimeDelta elapsed = base::TimeTicks::Now() - current_load_start_;
1691
1692 details.reset(new LoadNotificationDetails(
1693 entry->display_url(),
1694 entry->transition_type(),
1695 elapsed,
1696 &controller_,
1697 controller_.GetCurrentEntryIndex()));
1698 }
1699
1700 // Tell PasswordManager we've finished a page load, which serves as a
1701 // green light to save pending passwords and reset itself.
1702 GetPasswordManager()->DidStopLoading();
1703
1704 SetIsLoading(false, details.get());
1705}
1706
1707void TabContents::DidStartProvisionalLoadForFrame(
1708 RenderViewHost* render_view_host,
1709 bool is_main_frame,
1710 const GURL& url) {
1711 ProvisionalLoadDetails details(is_main_frame,
1712 controller_.IsURLInPageNavigation(url),
1713 url, std::string(), false);
1714 NotificationService::current()->Notify(
1715 NotificationType::FRAME_PROVISIONAL_LOAD_START,
1716 Source<NavigationController>(&controller_),
1717 Details<ProvisionalLoadDetails>(&details));
1718}
1719
[email protected]fd694982009-07-03 17:32:371720void TabContents::DidStartReceivingResourceResponse(
1721 ResourceRequestDetails* details) {
1722 NotificationService::current()->Notify(
1723 NotificationType::RESOURCE_RESPONSE_STARTED,
1724 Source<NavigationController>(&controller()),
1725 Details<ResourceRequestDetails>(details));
1726}
1727
[email protected]420ae012009-04-24 05:16:321728void TabContents::DidRedirectProvisionalLoad(int32 page_id,
1729 const GURL& source_url,
1730 const GURL& target_url) {
1731 NavigationEntry* entry;
1732 if (page_id == -1)
1733 entry = controller_.pending_entry();
1734 else
1735 entry = controller_.GetEntryWithPageID(GetSiteInstance(), page_id);
1736 if (!entry || entry->url() != source_url)
1737 return;
1738 entry->set_url(target_url);
1739}
1740
[email protected]fd694982009-07-03 17:32:371741void TabContents::DidRedirectResource(ResourceRequestDetails* details) {
1742 NotificationService::current()->Notify(
1743 NotificationType::RESOURCE_RECEIVED_REDIRECT,
1744 Source<NavigationController>(&controller()),
1745 Details<ResourceRequestDetails>(details));
1746}
1747
[email protected]420ae012009-04-24 05:16:321748void TabContents::DidLoadResourceFromMemoryCache(
1749 const GURL& url,
1750 const std::string& frame_origin,
1751 const std::string& main_frame_origin,
1752 const std::string& security_info) {
1753 // Send out a notification that we loaded a resource from our memory cache.
1754 int cert_id = 0, cert_status = 0, security_bits = 0;
1755 SSLManager::DeserializeSecurityInfo(security_info,
1756 &cert_id, &cert_status,
1757 &security_bits);
1758 LoadFromMemoryCacheDetails details(url, frame_origin, main_frame_origin,
[email protected]9ae66cbf2009-05-12 16:21:031759 process()->pid(), cert_id, cert_status);
[email protected]420ae012009-04-24 05:16:321760
1761 NotificationService::current()->Notify(
1762 NotificationType::LOAD_FROM_MEMORY_CACHE,
1763 Source<NavigationController>(&controller_),
1764 Details<LoadFromMemoryCacheDetails>(&details));
1765}
1766
1767void TabContents::DidFailProvisionalLoadWithError(
1768 RenderViewHost* render_view_host,
1769 bool is_main_frame,
1770 int error_code,
1771 const GURL& url,
1772 bool showing_repost_interstitial) {
1773 if (net::ERR_ABORTED == error_code) {
1774 // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
1775 // This means that the interstitial won't be torn down properly, which is
1776 // bad. But if we have an interstitial, go back to another tab type, and
1777 // then load the same interstitial again, we could end up getting the first
1778 // interstitial's "failed" message (as a result of the cancel) when we're on
1779 // the second one.
1780 //
1781 // We can't tell this apart, so we think we're tearing down the current page
1782 // which will cause a crash later one. There is also some code in
1783 // RenderViewHostManager::RendererAbortedProvisionalLoad that is commented
1784 // out because of this problem.
1785 //
1786 // http://code.google.com/p/chromium/issues/detail?id=2855
1787 // Because this will not tear down the interstitial properly, if "back" is
1788 // back to another tab type, the interstitial will still be somewhat alive
1789 // in the previous tab type. If you navigate somewhere that activates the
1790 // tab with the interstitial again, you'll see a flash before the new load
1791 // commits of the interstitial page.
1792 if (showing_interstitial_page()) {
1793 LOG(WARNING) << "Discarding message during interstitial.";
1794 return;
1795 }
1796
1797 // This will discard our pending entry if we cancelled the load (e.g., if we
1798 // decided to download the file instead of load it). Only discard the
1799 // pending entry if the URLs match, otherwise the user initiated a navigate
1800 // before the page loaded so that the discard would discard the wrong entry.
1801 NavigationEntry* pending_entry = controller_.pending_entry();
[email protected]e684a312009-06-24 02:30:591802 if (pending_entry && pending_entry->url() == url) {
[email protected]420ae012009-04-24 05:16:321803 controller_.DiscardNonCommittedEntries();
[email protected]e684a312009-06-24 02:30:591804 // Update the URL display.
1805 NotifyNavigationStateChanged(TabContents::INVALIDATE_URL);
1806 }
[email protected]420ae012009-04-24 05:16:321807
1808 render_manager_.RendererAbortedProvisionalLoad(render_view_host);
1809 }
1810
1811 // Send out a notification that we failed a provisional load with an error.
1812 ProvisionalLoadDetails details(is_main_frame,
1813 controller_.IsURLInPageNavigation(url),
1814 url, std::string(), false);
1815 details.set_error_code(error_code);
1816
1817 NotificationService::current()->Notify(
1818 NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR,
1819 Source<NavigationController>(&controller_),
1820 Details<ProvisionalLoadDetails>(&details));
1821}
1822
1823void TabContents::UpdateFavIconURL(RenderViewHost* render_view_host,
1824 int32 page_id,
1825 const GURL& icon_url) {
1826 fav_icon_helper_.SetFavIconURL(icon_url);
1827}
1828
1829void TabContents::DidDownloadImage(
1830 RenderViewHost* render_view_host,
1831 int id,
1832 const GURL& image_url,
1833 bool errored,
1834 const SkBitmap& image) {
1835 // A notification for downloading would be more flexible, but for now I'm
1836 // forwarding to the two places that could possibly have initiated the
1837 // request. If we end up with another place invoking DownloadImage, probably
1838 // best to refactor out into notification service, or something similar.
1839 if (errored)
1840 fav_icon_helper_.FavIconDownloadFailed(id);
1841 else
1842 fav_icon_helper_.SetFavIcon(id, image_url, image);
1843}
1844
1845void TabContents::RequestOpenURL(const GURL& url, const GURL& referrer,
1846 WindowOpenDisposition disposition) {
1847 if (render_manager_.dom_ui()) {
1848 // When we're a DOM UI, it will provide a page transition type for us (this
1849 // is so the new tab page can specify AUTO_BOOKMARK for automatically
1850 // generated suggestions).
1851 //
1852 // Note also that we hide the referrer for DOM UI pages. We don't really
[email protected]60e448982009-05-06 04:21:161853 // want web sites to see a referrer of "chrome://blah" (and some
1854 // chrome: URLs might have search terms or other stuff we don't want to
[email protected]420ae012009-04-24 05:16:321855 // send to the site), so we send no referrer.
1856 OpenURL(url, GURL(), disposition,
1857 render_manager_.dom_ui()->link_transition_type());
1858 } else {
1859 OpenURL(url, referrer, disposition, PageTransition::LINK);
1860 }
1861}
1862
1863void TabContents::DomOperationResponse(const std::string& json_string,
1864 int automation_id) {
1865 DomOperationNotificationDetails details(json_string, automation_id);
1866 NotificationService::current()->Notify(
[email protected]d82ed61e2009-06-16 02:46:221867 NotificationType::DOM_OPERATION_RESPONSE, Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321868 Details<DomOperationNotificationDetails>(&details));
1869}
1870
1871void TabContents::ProcessDOMUIMessage(const std::string& message,
[email protected]811bfe32009-07-01 08:46:251872 const std::string& content,
1873 int request_id,
1874 bool has_callback) {
[email protected]420ae012009-04-24 05:16:321875 if (!render_manager_.dom_ui()) {
1876 // We shouldn't get a DOM UI message when we haven't enabled the DOM UI.
1877 // Because the renderer might be owned and sending random messages, we need
1878 // to ignore these inproper ones.
1879 NOTREACHED();
1880 return;
1881 }
[email protected]811bfe32009-07-01 08:46:251882 render_manager_.dom_ui()->ProcessDOMUIMessage(message, content, request_id,
1883 has_callback);
[email protected]420ae012009-04-24 05:16:321884}
1885
[email protected]09b8f82f2009-06-16 20:22:111886void TabContents::DocumentLoadedInFrame() {
1887 controller_.DocumentLoadedInFrame();
1888}
1889
[email protected]420ae012009-04-24 05:16:321890void TabContents::ProcessExternalHostMessage(const std::string& message,
1891 const std::string& origin,
1892 const std::string& target) {
1893 if (delegate())
1894 delegate()->ForwardMessageToExternalHost(message, origin, target);
1895}
1896
1897void TabContents::GoToEntryAtOffset(int offset) {
1898 controller_.GoToOffset(offset);
1899}
1900
1901void TabContents::GetHistoryListCount(int* back_list_count,
1902 int* forward_list_count) {
1903 int current_index = controller_.last_committed_entry_index();
1904 *back_list_count = current_index;
1905 *forward_list_count = controller_.entry_count() - current_index - 1;
1906}
1907
1908void TabContents::RunFileChooser(bool multiple_files,
1909 const string16& title,
1910 const FilePath& default_file) {
1911 if (!select_file_dialog_.get())
1912 select_file_dialog_ = SelectFileDialog::Create(this);
1913 SelectFileDialog::Type dialog_type =
1914 multiple_files ? SelectFileDialog::SELECT_OPEN_MULTI_FILE :
1915 SelectFileDialog::SELECT_OPEN_FILE;
1916 select_file_dialog_->SelectFile(dialog_type, title, default_file,
1917 NULL, 0, FILE_PATH_LITERAL(""),
1918 view_->GetTopLevelNativeWindow(), NULL);
1919}
1920
1921void TabContents::RunJavaScriptMessage(
1922 const std::wstring& message,
1923 const std::wstring& default_prompt,
1924 const GURL& frame_url,
1925 const int flags,
1926 IPC::Message* reply_msg,
1927 bool* did_suppress_message) {
1928 // Suppress javascript messages when requested and when inside a constrained
1929 // popup window (because that activates them and breaks them out of the
1930 // constrained window jail).
1931 bool suppress_this_message = suppress_javascript_messages_;
1932 if (delegate())
1933 suppress_this_message |=
[email protected]b6c874582009-05-08 19:38:311934 (delegate()->GetConstrainingContents(this) != this);
[email protected]420ae012009-04-24 05:16:321935
1936 *did_suppress_message = suppress_this_message;
1937
1938 if (!suppress_this_message) {
1939 base::TimeDelta time_since_last_message(
1940 base::TimeTicks::Now() - last_javascript_message_dismissal_);
1941 bool show_suppress_checkbox = false;
1942 // Show a checkbox offering to suppress further messages if this message is
1943 // being displayed within kJavascriptMessageExpectedDelay of the last one.
1944 if (time_since_last_message <
1945 base::TimeDelta::FromMilliseconds(kJavascriptMessageExpectedDelay))
1946 show_suppress_checkbox = true;
1947
[email protected]d82ed61e2009-06-16 02:46:221948 RunJavascriptMessageBox(this, frame_url, flags, message, default_prompt,
[email protected]420ae012009-04-24 05:16:321949 show_suppress_checkbox, reply_msg);
1950 } else {
1951 // If we are suppressing messages, just reply as is if the user immediately
1952 // pressed "Cancel".
1953 OnJavaScriptMessageBoxClosed(reply_msg, false, std::wstring());
1954 }
1955}
1956
1957void TabContents::RunBeforeUnloadConfirm(const std::wstring& message,
1958 IPC::Message* reply_msg) {
[email protected]d82ed61e2009-06-16 02:46:221959 RunBeforeUnloadDialog(this, message, reply_msg);
[email protected]420ae012009-04-24 05:16:321960}
1961
1962void TabContents::ShowModalHTMLDialog(const GURL& url, int width, int height,
1963 const std::string& json_arguments,
1964 IPC::Message* reply_msg) {
1965 if (delegate()) {
1966 HtmlDialogUIDelegate* dialog_delegate =
1967 new ModalHtmlDialogDelegate(url, width, height, json_arguments,
[email protected]d82ed61e2009-06-16 02:46:221968 reply_msg, this);
[email protected]420ae012009-04-24 05:16:321969 delegate()->ShowHtmlDialog(dialog_delegate, NULL);
1970 }
1971}
1972
1973void TabContents::PasswordFormsSeen(
[email protected]ed3fb032009-06-16 19:50:561974 const std::vector<webkit_glue::PasswordForm>& forms) {
[email protected]420ae012009-04-24 05:16:321975 GetPasswordManager()->PasswordFormsSeen(forms);
1976}
1977
1978void TabContents::AutofillFormSubmitted(
[email protected]daa8c58e2009-06-15 17:21:101979 const webkit_glue::AutofillForm& form) {
[email protected]420ae012009-04-24 05:16:321980 GetAutofillManager()->AutofillFormSubmitted(form);
1981}
1982
1983void TabContents::GetAutofillSuggestions(const std::wstring& field_name,
1984 const std::wstring& user_text, int64 node_id, int request_id) {
1985 GetAutofillManager()->FetchValuesForName(field_name, user_text,
1986 kMaxAutofillMenuItems, node_id, request_id);
1987}
1988
1989void TabContents::RemoveAutofillEntry(const std::wstring& field_name,
1990 const std::wstring& value) {
1991 GetAutofillManager()->RemoveValueForName(field_name, value);
1992}
1993
1994// Checks to see if we should generate a keyword based on the OSDD, and if
1995// necessary uses TemplateURLFetcher to download the OSDD and create a keyword.
1996void TabContents::PageHasOSDD(RenderViewHost* render_view_host,
1997 int32 page_id, const GURL& url,
1998 bool autodetected) {
1999 // Make sure page_id is the current page, and the TemplateURLModel is loaded.
2000 DCHECK(url.is_valid());
2001 if (!IsActiveEntry(page_id))
2002 return;
2003 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
2004 if (!url_model)
2005 return;
2006 if (!url_model->loaded()) {
2007 url_model->Load();
2008 return;
2009 }
2010 if (!profile()->GetTemplateURLFetcher())
2011 return;
2012
2013 if (profile()->IsOffTheRecord())
2014 return;
2015
2016 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
2017 DCHECK(entry);
2018
2019 const NavigationEntry* base_entry = entry;
2020 if (IsFormSubmit(base_entry)) {
2021 // If the current page is a form submit, find the last page that was not
2022 // a form submit and use its url to generate the keyword from.
2023 int index = controller_.last_committed_entry_index() - 1;
2024 while (index >= 0 && IsFormSubmit(controller_.GetEntryAtIndex(index)))
2025 index--;
2026 if (index >= 0)
2027 base_entry = controller_.GetEntryAtIndex(index);
2028 else
2029 base_entry = NULL;
2030 }
2031
2032 // We want to use the user typed URL if available since that represents what
2033 // the user typed to get here, and fall back on the regular URL if not.
2034 if (!base_entry)
2035 return;
2036 GURL keyword_url = base_entry->user_typed_url().is_valid() ?
2037 base_entry->user_typed_url() : base_entry->url();
2038 if (!keyword_url.is_valid())
2039 return;
2040 std::wstring keyword = TemplateURLModel::GenerateKeyword(keyword_url,
2041 autodetected);
2042 if (keyword.empty())
2043 return;
2044 const TemplateURL* template_url =
2045 url_model->GetTemplateURLForKeyword(keyword);
2046 if (template_url && (!template_url->safe_for_autoreplace() ||
2047 template_url->originating_url() == url)) {
2048 // Either there is a user created TemplateURL for this keyword, or the
2049 // keyword has the same OSDD url and we've parsed it.
2050 return;
2051 }
2052
2053 // Download the OpenSearch description document. If this is successful a
2054 // new keyword will be created when done.
[email protected]420ae012009-04-24 05:16:322055 profile()->GetTemplateURLFetcher()->ScheduleDownload(
2056 keyword,
2057 url,
2058 base_entry->favicon().url(),
[email protected]d0cc9fb52009-06-23 02:26:162059 this,
[email protected]420ae012009-04-24 05:16:322060 autodetected);
2061}
2062
[email protected]420ae012009-04-24 05:16:322063void TabContents::DidGetPrintedPagesCount(int cookie, int number_pages) {
2064 printing_.DidGetPrintedPagesCount(cookie, number_pages);
2065}
2066
2067void TabContents::DidPrintPage(const ViewHostMsg_DidPrintPage_Params& params) {
2068 printing_.DidPrintPage(params);
2069}
2070
2071GURL TabContents::GetAlternateErrorPageURL() const {
2072 GURL url;
2073 // Disable alternate error pages when in OffTheRecord/Incognito mode.
2074 if (profile()->IsOffTheRecord())
2075 return url;
2076
2077 PrefService* prefs = profile()->GetPrefs();
2078 DCHECK(prefs);
2079 if (prefs->GetBoolean(prefs::kAlternateErrorPagesEnabled)) {
2080 url = google_util::AppendGoogleLocaleParam(GURL(kLinkDoctorBaseURL));
2081 url = google_util::AppendGoogleTLDParam(url);
2082 }
2083 return url;
2084}
2085
2086WebPreferences TabContents::GetWebkitPrefs() {
2087 PrefService* prefs = render_view_host()->process()->profile()->GetPrefs();
2088 bool isDomUI = false;
2089 return RenderViewHostDelegateHelper::GetWebkitPrefs(prefs, isDomUI);
2090}
2091
2092void TabContents::OnMissingPluginStatus(int status) {
2093#if defined(OS_WIN)
2094// TODO(PORT): pull in when plug-ins work
2095 GetPluginInstaller()->OnMissingPluginStatus(status);
2096#endif
2097}
2098
2099void TabContents::OnCrashedPlugin(const FilePath& plugin_path) {
2100#if defined(OS_WIN)
2101// TODO(PORT): pull in when plug-ins work
2102 DCHECK(!plugin_path.value().empty());
2103
2104 std::wstring plugin_name = plugin_path.ToWStringHack();
2105 scoped_ptr<FileVersionInfo> version_info(
2106 FileVersionInfo::CreateFileVersionInfo(plugin_path));
2107 if (version_info.get()) {
2108 const std::wstring& product_name = version_info->product_name();
2109 if (!product_name.empty())
2110 plugin_name = product_name;
2111 }
2112 AddInfoBar(new SimpleAlertInfoBarDelegate(
2113 this, l10n_util::GetStringF(IDS_PLUGIN_CRASHED_PROMPT, plugin_name),
2114 NULL));
2115#endif
2116}
2117
2118void TabContents::OnCrashedWorker() {
2119 AddInfoBar(new SimpleAlertInfoBarDelegate(
2120 this, l10n_util::GetString(IDS_WEBWORKER_CRASHED_PROMPT),
2121 NULL));
2122}
2123
2124void TabContents::OnJSOutOfMemory() {
2125 AddInfoBar(new SimpleAlertInfoBarDelegate(
2126 this, l10n_util::GetString(IDS_JS_OUT_OF_MEMORY_PROMPT), NULL));
2127}
2128
2129void TabContents::ShouldClosePage(bool proceed) {
2130 render_manager_.ShouldClosePage(proceed);
2131}
2132
2133void TabContents::OnCrossSiteResponse(int new_render_process_host_id,
2134 int new_request_id) {
[email protected]57c6a652009-05-04 07:58:342135 // Allows the TabContents to react when a cross-site response is ready to be
[email protected]420ae012009-04-24 05:16:322136 // delivered to a pending RenderViewHost. We must first run the onunload
2137 // handler of the old RenderViewHost before we can allow it to proceed.
2138 render_manager_.OnCrossSiteResponse(new_render_process_host_id,
2139 new_request_id);
2140}
2141
2142bool TabContents::CanBlur() const {
2143 return delegate() ? delegate()->CanBlur() : true;
2144}
2145
2146gfx::Rect TabContents::GetRootWindowResizerRect() const {
2147 if (delegate())
2148 return delegate()->GetRootWindowResizerRect();
2149 return gfx::Rect();
2150}
2151
2152void TabContents::RendererUnresponsive(RenderViewHost* rvh,
2153 bool is_during_unload) {
2154 if (is_during_unload) {
2155 // Hang occurred while firing the beforeunload/unload handler.
2156 // Pretend the handler fired so tab closing continues as if it had.
[email protected]829e7612009-04-25 01:15:112157 rvh->set_sudden_termination_allowed(true);
[email protected]420ae012009-04-24 05:16:322158
2159 if (!render_manager_.ShouldCloseTabOnUnresponsiveRenderer())
2160 return;
2161
2162 // If the tab hangs in the beforeunload/unload handler there's really
2163 // nothing we can do to recover. Pretend the unload listeners have
2164 // all fired and close the tab. If the hang is in the beforeunload handler
2165 // then the user will not have the option of cancelling the close.
2166 Close(rvh);
2167 return;
2168 }
2169
2170 if (render_view_host() && render_view_host()->IsRenderViewLive())
[email protected]d82ed61e2009-06-16 02:46:222171 HungRendererDialog::ShowForTabContents(this);
[email protected]420ae012009-04-24 05:16:322172}
2173
2174void TabContents::RendererResponsive(RenderViewHost* render_view_host) {
[email protected]d82ed61e2009-06-16 02:46:222175 HungRendererDialog::HideForTabContents(this);
[email protected]420ae012009-04-24 05:16:322176}
2177
2178void TabContents::LoadStateChanged(const GURL& url,
2179 net::LoadState load_state) {
2180 load_state_ = load_state;
[email protected]d686e812009-06-03 19:10:292181 std::wstring languages =
2182 profile()->GetPrefs()->GetString(prefs::kAcceptLanguages);
2183 load_state_host_.clear();
2184 std::string host = url.host();
2185 net::IDNToUnicode(host.c_str(), host.size(), languages, &load_state_host_);
[email protected]420ae012009-04-24 05:16:322186 if (load_state_ == net::LOAD_STATE_READING_RESPONSE)
2187 SetNotWaitingForResponse();
2188 if (is_loading())
[email protected]c9cd2222009-05-06 05:16:502189 NotifyNavigationStateChanged(INVALIDATE_LOAD | INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:322190}
2191
2192void TabContents::OnDidGetApplicationInfo(
2193 int32 page_id,
2194 const webkit_glue::WebApplicationInfo& info) {
2195 if (pending_install_.page_id != page_id)
2196 return; // The user clicked create on a separate page. Ignore this.
2197
2198 pending_install_.callback_functor =
2199 new GearsCreateShortcutCallbackFunctor(this);
2200 GearsCreateShortcut(
2201 info, pending_install_.title, pending_install_.url, pending_install_.icon,
2202 NewCallback(pending_install_.callback_functor,
2203 &GearsCreateShortcutCallbackFunctor::Run));
2204}
2205
[email protected]14ce83f2009-05-28 18:35:242206void TabContents::OnUserGesture() {
2207 // See comment in RenderViewHostDelegate::OnUserGesture as to why we do this.
[email protected]420ae012009-04-24 05:16:322208 DownloadRequestManager* drm = g_browser_process->download_request_manager();
2209 if (drm)
2210 drm->OnUserGesture(this);
[email protected]09b8f82f2009-06-16 20:22:112211 controller_.OnUserGesture();
[email protected]420ae012009-04-24 05:16:322212}
2213
2214void TabContents::OnFindReply(int request_id,
2215 int number_of_matches,
2216 const gfx::Rect& selection_rect,
2217 int active_match_ordinal,
2218 bool final_update) {
2219 // Ignore responses for requests other than the one we have most recently
2220 // issued. That way we won't act on stale results when the user has
2221 // already typed in another query.
2222 if (request_id != current_find_request_id_)
2223 return;
2224
2225 if (number_of_matches == -1)
[email protected]e491f1c2009-05-22 20:28:122226 number_of_matches = last_search_result_.number_of_matches();
[email protected]420ae012009-04-24 05:16:322227 if (active_match_ordinal == -1)
[email protected]e491f1c2009-05-22 20:28:122228 active_match_ordinal = last_search_result_.active_match_ordinal();
[email protected]420ae012009-04-24 05:16:322229
[email protected]2c355c282009-05-21 23:24:432230 gfx::Rect selection = selection_rect;
2231 if (selection.IsEmpty())
[email protected]e491f1c2009-05-22 20:28:122232 selection = last_search_result_.selection_rect();
[email protected]2c355c282009-05-21 23:24:432233
[email protected]420ae012009-04-24 05:16:322234 // Notify the UI, automation and any other observers that a find result was
2235 // found.
[email protected]e491f1c2009-05-22 20:28:122236 last_search_result_ = FindNotificationDetails(request_id, number_of_matches,
2237 selection, active_match_ordinal,
2238 final_update);
[email protected]420ae012009-04-24 05:16:322239 NotificationService::current()->Notify(
2240 NotificationType::FIND_RESULT_AVAILABLE,
2241 Source<TabContents>(this),
[email protected]e491f1c2009-05-22 20:28:122242 Details<FindNotificationDetails>(&last_search_result_));
[email protected]420ae012009-04-24 05:16:322243}
2244
[email protected]829e7612009-04-25 01:15:112245bool TabContents::IsExternalTabContainer() const {
[email protected]420ae012009-04-24 05:16:322246 if (!delegate())
[email protected]829e7612009-04-25 01:15:112247 return false;
[email protected]420ae012009-04-24 05:16:322248
[email protected]829e7612009-04-25 01:15:112249 return delegate()->IsExternalTabContainer();
[email protected]420ae012009-04-24 05:16:322250}
2251
2252void TabContents::FileSelected(const FilePath& path,
2253 int index, void* params) {
2254 render_view_host()->FileSelected(path);
2255}
2256
2257void TabContents::MultiFilesSelected(const std::vector<FilePath>& files,
2258 void* params) {
2259 render_view_host()->MultiFilesSelected(files);
2260}
2261
2262void TabContents::FileSelectionCanceled(void* params) {
2263 // If the user cancels choosing a file to upload we pass back an
2264 // empty vector.
2265 render_view_host()->MultiFilesSelected(std::vector<FilePath>());
2266}
2267
2268void TabContents::BeforeUnloadFiredFromRenderManager(
2269 bool proceed,
2270 bool* proceed_to_fire_unload) {
2271 if (delegate())
2272 delegate()->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
2273}
2274
2275void TabContents::UpdateRenderViewSizeForRenderManager() {
2276 // TODO(brettw) this is a hack. See TabContentsView::SizeContents.
2277 view_->SizeContents(view_->GetContainerSize());
2278}
2279
2280DOMUI* TabContents::CreateDOMUIForRenderManager(const GURL& url) {
[email protected]d82ed61e2009-06-16 02:46:222281 return DOMUIFactory::CreateDOMUIForURL(this, url);
[email protected]420ae012009-04-24 05:16:322282}
2283
2284NavigationEntry*
2285TabContents::GetLastCommittedNavigationEntryForRenderManager() {
2286 return controller_.GetLastCommittedEntry();
2287}
2288
2289bool TabContents::CreateRenderViewForRenderManager(
2290 RenderViewHost* render_view_host) {
[email protected]811bfe32009-07-01 08:46:252291 // If the pending navigation is to a DOMUI, tell the RenderView about any
2292 // bindings it will need enabled.
[email protected]420ae012009-04-24 05:16:322293 if (render_manager_.pending_dom_ui())
[email protected]811bfe32009-07-01 08:46:252294 render_view_host->AllowBindings(
2295 render_manager_.pending_dom_ui()->bindings());
[email protected]1adff062009-06-02 18:39:552296
[email protected]420ae012009-04-24 05:16:322297 RenderWidgetHostView* rwh_view = view_->CreateViewForWidget(render_view_host);
2298 if (!render_view_host->CreateRenderView())
2299 return false;
2300
2301 // Now that the RenderView has been created, we need to tell it its size.
2302 rwh_view->SetSize(view_->GetContainerSize());
2303
2304 UpdateMaxPageIDIfNecessary(render_view_host->site_instance(),
2305 render_view_host);
2306 return true;
2307}
2308
2309void TabContents::Observe(NotificationType type,
2310 const NotificationSource& source,
2311 const NotificationDetails& details) {
2312 switch (type.value) {
2313 case NotificationType::BOOKMARK_MODEL_LOADED:
2314 // BookmarkModel finished loading, fall through to update starred state.
2315 case NotificationType::URLS_STARRED: {
2316 // Somewhere, a URL has been starred.
2317 // Ignore notifications for profiles other than our current one.
2318 Profile* source_profile = Source<Profile>(source).ptr();
2319 if (!source_profile || !source_profile->IsSameProfile(profile()))
2320 return;
2321
2322 UpdateStarredStateForCurrentURL();
2323 break;
2324 }
2325 case NotificationType::PREF_CHANGED: {
2326 std::wstring* pref_name_in = Details<std::wstring>(details).ptr();
2327 DCHECK(Source<PrefService>(source).ptr() == profile()->GetPrefs());
2328 if (*pref_name_in == prefs::kAlternateErrorPagesEnabled) {
2329 UpdateAlternateErrorPageURL();
2330 } else if (*pref_name_in == prefs::kDefaultCharset ||
2331 StartsWithASCII(WideToUTF8(*pref_name_in), "webkit.webprefs.", true)
2332 ) {
2333 UpdateWebPreferences();
2334 } else {
2335 NOTREACHED() << "unexpected pref change notification" << *pref_name_in;
2336 }
2337 break;
2338 }
2339 case NotificationType::RENDER_WIDGET_HOST_DESTROYED:
2340 view_->RenderWidgetHostDestroyed(Source<RenderWidgetHost>(source).ptr());
2341 break;
2342
2343 case NotificationType::NAV_ENTRY_COMMITTED: {
2344 DCHECK(&controller_ == Source<NavigationController>(source).ptr());
2345
2346 NavigationController::LoadCommittedDetails& committed_details =
2347 *(Details<NavigationController::LoadCommittedDetails>(details).ptr());
2348 ExpireInfoBars(committed_details);
2349 break;
2350 }
2351
2352 default:
2353 NOTREACHED();
2354 }
2355}