blob: bd4e803a62bcde05c8b37c8f469812eed62a6e66 [file] [log] [blame]
[email protected]ce5c4502009-05-06 16:46:111// Copyright (c) 2009 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
[email protected]f3ec7742009-01-15 00:59:165#include "chrome/browser/tab_contents/tab_contents.h"
initial.commit09911bf2008-07-26 23:55:296
[email protected]a92b8642009-05-05 23:38:567#include "app/l10n_util.h"
[email protected]9929da92009-05-05 02:05:118#include "app/resource_bundle.h"
[email protected]420ae012009-04-24 05:16:329#include "base/file_version_info.h"
10#include "base/process_util.h"
[email protected]96d185d2009-04-24 03:28:5411#include "base/string16.h"
12#include "base/time.h"
[email protected]fdd61c62009-04-22 19:22:5713#include "chrome/browser/autofill_manager.h"
[email protected]66ba4932009-06-04 19:22:1314#include "chrome/browser/blocked_popup_container.h"
[email protected]420ae012009-04-24 05:16:3215#include "chrome/browser/bookmarks/bookmark_model.h"
[email protected]96d185d2009-04-24 03:28:5416#include "chrome/browser/browser_process.h"
initial.commit09911bf2008-07-26 23:55:2917#include "chrome/browser/cert_store.h"
[email protected]96d185d2009-04-24 03:28:5418#include "chrome/browser/debugger/devtools_manager.h"
[email protected]420ae012009-04-24 05:16:3219#include "chrome/browser/dom_operation_notification_details.h"
[email protected]96d185d2009-04-24 03:28:5420#include "chrome/browser/dom_ui/dom_ui.h"
21#include "chrome/browser/dom_ui/dom_ui_factory.h"
[email protected]bcef0dc02009-02-28 00:35:0222#include "chrome/browser/download/download_item_model.h"
[email protected]420ae012009-04-24 05:16:3223#include "chrome/browser/download/download_manager.h"
24#include "chrome/browser/download/download_request_manager.h"
[email protected]420ae012009-04-24 05:16:3225#include "chrome/browser/gears_integration.h"
26#include "chrome/browser/google_util.h"
[email protected]8897c382009-05-06 17:53:2627#include "chrome/browser/hung_renderer_dialog.h"
[email protected]420ae012009-04-24 05:16:3228#include "chrome/browser/jsmessage_box_handler.h"
29#include "chrome/browser/load_from_memory_cache_details.h"
30#include "chrome/browser/load_notification_details.h"
[email protected]fdd61c62009-04-22 19:22:5731#include "chrome/browser/password_manager/password_manager.h"
32#include "chrome/browser/plugin_installer.h"
[email protected]ce560f82009-06-03 09:39:4433#include "chrome/browser/profile.h"
[email protected]96d185d2009-04-24 03:28:5434#include "chrome/browser/renderer_host/render_widget_host_view.h"
35#include "chrome/browser/renderer_host/web_cache_manager.h"
[email protected]bd1ad682009-05-15 22:19:1736#include "chrome/browser/tab_contents/infobar_delegate.h"
[email protected]7e383692009-06-12 19:14:5437#include "chrome/browser/tab_contents/interstitial_page.h"
[email protected]f3ec7742009-01-15 00:59:1638#include "chrome/browser/tab_contents/navigation_entry.h"
39#include "chrome/browser/tab_contents/tab_contents_delegate.h"
[email protected]fdd61c62009-04-22 19:22:5740#include "chrome/browser/tab_contents/tab_contents_view.h"
[email protected]58dca552009-06-17 00:35:0241#include "chrome/browser/tab_contents/thumbnail_generator.h"
[email protected]449478302009-06-09 20:04:2842#include "chrome/browser/thumbnail_store.h"
[email protected]420ae012009-04-24 05:16:3243#include "chrome/browser/search_engines/template_url_fetcher.h"
44#include "chrome/browser/search_engines/template_url_model.h"
[email protected]35f7d212009-04-29 21:19:2745#include "chrome/common/chrome_switches.h"
[email protected]bfd04a62009-02-01 18:16:5646#include "chrome/common/notification_service.h"
[email protected]ce5c4502009-05-06 16:46:1147#include "chrome/common/page_action.h"
initial.commit09911bf2008-07-26 23:55:2948#include "chrome/common/pref_names.h"
[email protected]1eb89e82008-08-15 12:27:0349#include "chrome/common/pref_service.h"
[email protected]420ae012009-04-24 05:16:3250#include "chrome/common/render_messages.h"
[email protected]96d185d2009-04-24 03:28:5451#include "chrome/common/url_constants.h"
[email protected]8897c382009-05-06 17:53:2652#include "grit/generated_resources.h"
[email protected]420ae012009-04-24 05:16:3253#include "grit/locale_settings.h"
54#include "net/base/mime_util.h"
55#include "net/base/net_errors.h"
[email protected]d686e812009-06-03 19:10:2956#include "net/base/net_util.h"
[email protected]420ae012009-04-24 05:16:3257#include "net/base/registry_controlled_domain.h"
[email protected]3e45ba92009-02-20 21:09:0058
59#if defined(OS_WIN)
[email protected]66ba4932009-06-04 19:22:1360// For CRect
[email protected]9041a302009-06-04 19:36:3361#include <atlbase.h>
[email protected]326f7112009-06-04 19:30:2962#include <atlapp.h>
[email protected]66ba4932009-06-04 19:22:1363#include <atlmisc.h>
[email protected]3e45ba92009-02-20 21:09:0064// TODO(port): some of these headers should be ported.
[email protected]420ae012009-04-24 05:16:3265#include "chrome/browser/modal_html_dialog_delegate.h"
[email protected]2362e4f2009-05-08 00:34:0566#include "views/controls/scrollbar/native_scroll_bar.h"
[email protected]3e45ba92009-02-20 21:09:0067#endif
initial.commit09911bf2008-07-26 23:55:2968
[email protected]420ae012009-04-24 05:16:3269// Cross-Site Navigations
70//
71// If a TabContents is told to navigate to a different web site (as determined
72// by SiteInstance), it will replace its current RenderViewHost with a new
73// RenderViewHost dedicated to the new SiteInstance. This works as follows:
74//
75// - Navigate determines whether the destination is cross-site, and if so,
76// it creates a pending_render_view_host_ and moves into the PENDING
77// RendererState.
78// - The pending RVH is "suspended," so that no navigation messages are sent to
79// its renderer until the onbeforeunload JavaScript handler has a chance to
80// run in the current RVH.
81// - The pending RVH tells CrossSiteRequestManager (a thread-safe singleton)
82// that it has a pending cross-site request. ResourceDispatcherHost will
83// check for this when the response arrives.
84// - The current RVH runs its onbeforeunload handler. If it returns false, we
85// cancel all the pending logic and go back to NORMAL. Otherwise we allow
86// the pending RVH to send the navigation request to its renderer.
87// - ResourceDispatcherHost receives a ResourceRequest on the IO thread. It
88// checks CrossSiteRequestManager to see that the RVH responsible has a
89// pending cross-site request, and then installs a CrossSiteEventHandler.
90// - When RDH receives a response, the BufferedEventHandler determines whether
91// it is a download. If so, it sends a message to the new renderer causing
92// it to cancel the request, and the download proceeds in the download
93// thread. For now, we stay in a PENDING state (with a pending RVH) until
[email protected]57c6a652009-05-04 07:58:3494// the next DidNavigate event for this TabContents. This isn't ideal, but it
[email protected]420ae012009-04-24 05:16:3295// doesn't affect any functionality.
96// - After RDH receives a response and determines that it is safe and not a
97// download, it pauses the response to first run the old page's onunload
98// handler. It does this by asynchronously calling the OnCrossSiteResponse
[email protected]57c6a652009-05-04 07:58:3499// method of TabContents on the UI thread, which sends a ClosePage message
[email protected]420ae012009-04-24 05:16:32100// to the current RVH.
101// - Once the onunload handler is finished, a ClosePage_ACK message is sent to
102// the ResourceDispatcherHost, who unpauses the response. Data is then sent
103// to the pending RVH.
104// - The pending renderer sends a FrameNavigate message that invokes the
105// DidNavigate method. This replaces the current RVH with the
106// pending RVH and goes back to the NORMAL RendererState.
107
108namespace {
109
110// Amount of time we wait between when a key event is received and the renderer
111// is queried for its state and pushed to the NavigationEntry.
112const int kQueryStateDelay = 5000;
113
114const int kSyncWaitDelay = 40;
115
116// If another javascript message box is displayed within
117// kJavascriptMessageExpectedDelay of a previous javascript message box being
118// dismissed, display an option to suppress future message boxes from this
119// contents.
120const int kJavascriptMessageExpectedDelay = 1000;
121
[email protected]420ae012009-04-24 05:16:32122const char kLinkDoctorBaseURL[] =
123 "http://linkhelp.clients.google.com/tbproxy/lh/fixurl";
124
125// The printer icon in shell32.dll. That's a standard icon user will quickly
126// recognize.
127const int kShell32PrinterIcon = 17;
128
129// The list of prefs we want to observe.
130const wchar_t* kPrefsToObserve[] = {
131 prefs::kAlternateErrorPagesEnabled,
132 prefs::kWebKitJavaEnabled,
133 prefs::kWebKitJavascriptEnabled,
134 prefs::kWebKitLoadsImagesAutomatically,
135 prefs::kWebKitPluginsEnabled,
136 prefs::kWebKitUsesUniversalDetector,
137 prefs::kWebKitSerifFontFamily,
138 prefs::kWebKitSansSerifFontFamily,
139 prefs::kWebKitFixedFontFamily,
140 prefs::kWebKitDefaultFontSize,
141 prefs::kWebKitDefaultFixedFontSize,
142 prefs::kDefaultCharset
143 // kWebKitStandardFontIsSerif needs to be added
144 // if we let users pick which font to use, serif or sans-serif when
145 // no font is specified or a CSS generic family (serif or sans-serif)
146 // is not specified.
147};
148
149const int kPrefsToObserveLength = arraysize(kPrefsToObserve);
150
151// Limit on the number of suggestions to appear in the pop-up menu under an
152// text input element in a form.
153const int kMaxAutofillMenuItems = 6;
154
155// Returns true if the entry's transition type is FORM_SUBMIT.
156bool IsFormSubmit(const NavigationEntry* entry) {
157 return (PageTransition::StripQualifier(entry->transition_type()) ==
158 PageTransition::FORM_SUBMIT);
159}
160
161#if defined(OS_WIN)
162
163BOOL CALLBACK InvalidateWindow(HWND hwnd, LPARAM lparam) {
164 // Note: erase is required to properly paint some widgets borders. This can
165 // be seen with textfields.
166 InvalidateRect(hwnd, NULL, TRUE);
167 return TRUE;
168}
169#endif
170
[email protected]420ae012009-04-24 05:16:32171} // namespace
172
173// -----------------------------------------------------------------------------
174
[email protected]fdd61c62009-04-22 19:22:57175// static
176int TabContents::find_request_id_counter_ = -1;
177
[email protected]420ae012009-04-24 05:16:32178class TabContents::GearsCreateShortcutCallbackFunctor {
179 public:
180 explicit GearsCreateShortcutCallbackFunctor(TabContents* contents)
181 : contents_(contents) {}
182
183 void Run(const GearsShortcutData2& shortcut_data, bool success) {
184 if (contents_)
185 contents_->OnGearsCreateShortcutDone(shortcut_data, success);
186 delete this;
187 }
188 void Cancel() {
189 contents_ = NULL;
190 }
191
192 private:
193 TabContents* contents_;
194};
195
[email protected]420ae012009-04-24 05:16:32196TabContents::TabContents(Profile* profile,
197 SiteInstance* site_instance,
198 int routing_id,
199 base::WaitableEvent* modal_dialog_event)
[email protected]b680ad22009-04-15 23:19:42200 : delegate_(NULL),
[email protected]66ba4932009-06-04 19:22:13201 ALLOW_THIS_IN_INITIALIZER_LIST(controller_(this, profile)),
202 ALLOW_THIS_IN_INITIALIZER_LIST(view_(
[email protected]d82ed61e2009-06-16 02:46:22203 TabContentsView::Create(this))),
204 ALLOW_THIS_IN_INITIALIZER_LIST(render_manager_(this, this)),
[email protected]fdd61c62009-04-22 19:22:57205 property_bag_(),
206 registrar_(),
[email protected]d82ed61e2009-06-16 02:46:22207 ALLOW_THIS_IN_INITIALIZER_LIST(printing_(*this)),
[email protected]fdd61c62009-04-22 19:22:57208 save_package_(),
209 cancelable_consumer_(),
210 autofill_manager_(),
211 password_manager_(),
212 plugin_installer_(),
[email protected]d82ed61e2009-06-16 02:46:22213 ALLOW_THIS_IN_INITIALIZER_LIST(fav_icon_helper_(this)),
[email protected]fdd61c62009-04-22 19:22:57214 select_file_dialog_(),
215 pending_install_(),
[email protected]d5f942ba2008-09-26 19:30:34216 is_loading_(false),
initial.commit09911bf2008-07-26 23:55:29217 is_crashed_(false),
[email protected]d5f942ba2008-09-26 19:30:34218 waiting_for_response_(false),
[email protected]d5f942ba2008-09-26 19:30:34219 max_page_id_(-1),
[email protected]fdd61c62009-04-22 19:22:57220 current_load_start_(),
221 load_state_(net::LOAD_STATE_IDLE),
222 load_state_host_(),
223 received_page_title_(false),
224 is_starred_(false),
225 contents_mime_type_(),
226 encoding_(),
[email protected]332af7732009-03-11 13:21:35227 blocked_popups_(NULL),
[email protected]fdd61c62009-04-22 19:22:57228 infobar_delegates_(),
[email protected]fdd61c62009-04-22 19:22:57229 find_ui_active_(false),
230 find_op_aborted_(false),
231 current_find_request_id_(find_request_id_counter_++),
232 find_text_(),
[email protected]e491f1c2009-05-22 20:28:12233 last_search_case_sensitive_(false),
234 last_search_prepopulate_text_(NULL),
235 last_search_result_(),
[email protected]fdd61c62009-04-22 19:22:57236 capturing_contents_(false),
237 is_being_destroyed_(false),
238 notify_disconnection_(false),
239 history_requests_(),
240#if defined(OS_WIN)
241 message_box_active_(CreateEvent(NULL, TRUE, FALSE, NULL)),
242#endif
243 last_javascript_message_dismissal_(),
244 suppress_javascript_messages_(false) {
[email protected]420ae012009-04-24 05:16:32245 pending_install_.page_id = 0;
246 pending_install_.callback_functor = NULL;
247
[email protected]58dca552009-06-17 00:35:02248#if defined(LINUX2)
249 // Make sure the thumbnailer is started before starting the render manager.
250 // The thumbnailer will want to listen for RVH creations, one of which will
251 // happen in RVHManager::Init.
252 ThumbnailGenerator* generator = g_browser_process->GetThumbnailGenerator();
253 if (generator)
254 generator->StartThumbnailing();
255#endif
256
[email protected]420ae012009-04-24 05:16:32257 render_manager_.Init(profile, site_instance, routing_id, modal_dialog_event);
258
259 view_->CreateView();
260
261 // Register for notifications about all interested prefs change.
262 PrefService* prefs = profile->GetPrefs();
263 if (prefs) {
264 for (int i = 0; i < kPrefsToObserveLength; ++i)
265 prefs->AddPrefObserver(kPrefsToObserve[i], this);
266 }
267
268 // Register for notifications about URL starredness changing on any profile.
269 registrar_.Add(this, NotificationType::URLS_STARRED,
270 NotificationService::AllSources());
271 registrar_.Add(this, NotificationType::BOOKMARK_MODEL_LOADED,
272 NotificationService::AllSources());
273 registrar_.Add(this, NotificationType::RENDER_WIDGET_HOST_DESTROYED,
274 NotificationService::AllSources());
275
276 // Keep a global copy of the previous search string (if any).
277 static string16 global_last_search = string16();
[email protected]e491f1c2009-05-22 20:28:12278 last_search_prepopulate_text_ = &global_last_search;
[email protected]332af7732009-03-11 13:21:35279}
initial.commit09911bf2008-07-26 23:55:29280
281TabContents::~TabContents() {
[email protected]420ae012009-04-24 05:16:32282 is_being_destroyed_ = true;
283
284 // We don't want any notifications while we're runnign our destructor.
285 registrar_.RemoveAll();
286
287 // Unregister the notifications of all observed prefs change.
288 PrefService* prefs = profile()->GetPrefs();
289 if (prefs) {
290 for (int i = 0; i < kPrefsToObserveLength; ++i)
291 prefs->RemovePrefObserver(kPrefsToObserve[i], this);
292 }
293
294 // Clean up subwindows like plugins and the find in page bar.
295 view_->OnContentsDestroy();
296
297 NotifyDisconnected();
[email protected]d82ed61e2009-06-16 02:46:22298 HungRendererDialog::HideForTabContents(this);
[email protected]420ae012009-04-24 05:16:32299
300 if (pending_install_.callback_functor)
301 pending_install_.callback_functor->Cancel();
302
303 // First cleanly close all child windows.
304 // TODO(mpcomplete): handle case if MaybeCloseChildWindows() already asked
305 // some of these to close. CloseWindows is async, so it might get called
306 // twice before it runs.
307 int size = static_cast<int>(child_windows_.size());
308 for (int i = size - 1; i >= 0; --i) {
309 ConstrainedWindow* window = child_windows_[i];
310 if (window)
311 window->CloseConstrainedWindow();
312 }
313
[email protected]66ba4932009-06-04 19:22:13314 if (blocked_popups_)
315 blocked_popups_->Destroy();
316
[email protected]420ae012009-04-24 05:16:32317 // Notify any observer that have a reference on this tab contents.
318 NotificationService::current()->Notify(
319 NotificationType::TAB_CONTENTS_DESTROYED,
320 Source<TabContents>(this),
321 NotificationService::NoDetails());
322
[email protected]1e5e74f2009-05-27 20:55:12323 // Notify any lasting InfobarDelegates that have not yet been removed that
324 // whatever infobar they were handling in this TabContents has closed,
325 // because the TabContents is going away entirely.
326 // This must happen after the TAB_CONTENTS_DESTROYED notification as the
327 // notification may trigger infobars calls that access their delegate. (and
328 // some implementations of InfoBarDelegate do delete themselves on
329 // InfoBarClosed()).
330 for (int i = 0; i < infobar_delegate_count(); ++i) {
331 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
332 delegate->InfoBarClosed();
333 }
334 infobar_delegates_.clear();
335
[email protected]420ae012009-04-24 05:16:32336 // TODO(brettw) this should be moved to the view.
337#if defined(OS_WIN)
338 // If we still have a window handle, destroy it. GetNativeView can return
339 // NULL if this contents was part of a window that closed.
340 if (GetNativeView())
341 ::DestroyWindow(GetNativeView());
342#endif
initial.commit09911bf2008-07-26 23:55:29343}
344
[email protected]d5f942ba2008-09-26 19:30:34345// static
346void TabContents::RegisterUserPrefs(PrefService* prefs) {
[email protected]420ae012009-04-24 05:16:32347 prefs->RegisterBooleanPref(prefs::kAlternateErrorPagesEnabled, true);
348
349 WebPreferences pref_defaults;
350 prefs->RegisterBooleanPref(prefs::kWebKitJavascriptEnabled,
351 pref_defaults.javascript_enabled);
352 prefs->RegisterBooleanPref(prefs::kWebKitWebSecurityEnabled,
353 pref_defaults.web_security_enabled);
354 prefs->RegisterBooleanPref(
355 prefs::kWebKitJavascriptCanOpenWindowsAutomatically, true);
356 prefs->RegisterBooleanPref(prefs::kWebKitLoadsImagesAutomatically,
357 pref_defaults.loads_images_automatically);
358 prefs->RegisterBooleanPref(prefs::kWebKitPluginsEnabled,
359 pref_defaults.plugins_enabled);
360 prefs->RegisterBooleanPref(prefs::kWebKitDomPasteEnabled,
361 pref_defaults.dom_paste_enabled);
362 prefs->RegisterBooleanPref(prefs::kWebKitShrinksStandaloneImagesToFit,
363 pref_defaults.shrinks_standalone_images_to_fit);
[email protected]0df30122009-06-03 12:13:08364 prefs->RegisterStringPref(prefs::kWebKitInspectorSettings,
365 pref_defaults.inspector_settings);
[email protected]420ae012009-04-24 05:16:32366 prefs->RegisterBooleanPref(prefs::kWebKitTextAreasAreResizable,
367 pref_defaults.text_areas_are_resizable);
368 prefs->RegisterBooleanPref(prefs::kWebKitJavaEnabled,
369 pref_defaults.java_enabled);
370
371 prefs->RegisterLocalizedStringPref(prefs::kAcceptLanguages,
372 IDS_ACCEPT_LANGUAGES);
373 prefs->RegisterLocalizedStringPref(prefs::kDefaultCharset,
374 IDS_DEFAULT_ENCODING);
375 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitStandardFontIsSerif,
376 IDS_STANDARD_FONT_IS_SERIF);
377 prefs->RegisterLocalizedStringPref(prefs::kWebKitFixedFontFamily,
378 IDS_FIXED_FONT_FAMILY);
379 prefs->RegisterLocalizedStringPref(prefs::kWebKitSerifFontFamily,
380 IDS_SERIF_FONT_FAMILY);
381 prefs->RegisterLocalizedStringPref(prefs::kWebKitSansSerifFontFamily,
382 IDS_SANS_SERIF_FONT_FAMILY);
383 prefs->RegisterLocalizedStringPref(prefs::kWebKitCursiveFontFamily,
384 IDS_CURSIVE_FONT_FAMILY);
385 prefs->RegisterLocalizedStringPref(prefs::kWebKitFantasyFontFamily,
386 IDS_FANTASY_FONT_FAMILY);
387 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFontSize,
388 IDS_DEFAULT_FONT_SIZE);
389 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFixedFontSize,
390 IDS_DEFAULT_FIXED_FONT_SIZE);
391 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumFontSize,
392 IDS_MINIMUM_FONT_SIZE);
393 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumLogicalFontSize,
394 IDS_MINIMUM_LOGICAL_FONT_SIZE);
395 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitUsesUniversalDetector,
396 IDS_USES_UNIVERSAL_DETECTOR);
397 prefs->RegisterLocalizedStringPref(prefs::kStaticEncodings,
398 IDS_STATIC_ENCODING_LIST);
initial.commit09911bf2008-07-26 23:55:29399}
400
[email protected]d5f942ba2008-09-26 19:30:34401bool TabContents::SupportsURL(GURL* url) {
[email protected]6e95706d2009-04-23 22:55:01402 // TODO(brettw) remove this function.
[email protected]9423d9412009-04-14 22:13:55403 return true;
[email protected]d5f942ba2008-09-26 19:30:34404}
405
[email protected]6e95706d2009-04-23 22:55:01406AutofillManager* TabContents::GetAutofillManager() {
407 if (autofill_manager_.get() == NULL)
408 autofill_manager_.reset(new AutofillManager(this));
409 return autofill_manager_.get();
410}
411
412PasswordManager* TabContents::GetPasswordManager() {
413 if (password_manager_.get() == NULL)
414 password_manager_.reset(new PasswordManager(this));
415 return password_manager_.get();
416}
417
418PluginInstaller* TabContents::GetPluginInstaller() {
419 if (plugin_installer_.get() == NULL)
420 plugin_installer_.reset(new PluginInstaller(this));
421 return plugin_installer_.get();
422}
423
[email protected]d5f942ba2008-09-26 19:30:34424const GURL& TabContents::GetURL() const {
425 // We may not have a navigation entry yet
[email protected]ce3fa3c2009-04-20 19:55:57426 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34427 return entry ? entry->display_url() : GURL::EmptyGURL();
428}
429
[email protected]96d185d2009-04-24 03:28:54430const string16& TabContents::GetTitle() const {
[email protected]4c6092c5b2009-06-06 00:23:55431 // Transient entries take precedence. They are used for interstitial pages
432 // that are shown on top of existing pages.
433 NavigationEntry* entry = controller_.GetTransientEntry();
434 if (entry)
435 return entry->GetTitleForDisplay(&controller_);
436
[email protected]96d185d2009-04-24 03:28:54437 DOMUI* our_dom_ui = render_manager_.pending_dom_ui() ?
438 render_manager_.pending_dom_ui() : render_manager_.dom_ui();
439 if (our_dom_ui) {
440 // Don't override the title in view source mode.
[email protected]4c6092c5b2009-06-06 00:23:55441 entry = controller_.GetActiveEntry();
[email protected]96d185d2009-04-24 03:28:54442 if (!(entry && entry->IsViewSourceMode())) {
443 // Give the DOM UI the chance to override our title.
444 const string16& title = our_dom_ui->overridden_title();
445 if (!title.empty())
446 return title;
447 }
448 }
449
450 // We use the title for the last committed entry rather than a pending
451 // navigation entry. For example, when the user types in a URL, we want to
452 // keep the old page's title until the new load has committed and we get a new
453 // title.
[email protected]96d185d2009-04-24 03:28:54454 entry = controller_.GetLastCommittedEntry();
455 if (entry)
456 return entry->GetTitleForDisplay(&controller_);
457 else if (controller_.LoadingURLLazily())
458 return controller_.GetLazyTitle();
459 return EmptyString16();
460}
461
[email protected]d5f942ba2008-09-26 19:30:34462int32 TabContents::GetMaxPageID() {
463 if (GetSiteInstance())
464 return GetSiteInstance()->max_page_id();
465 else
466 return max_page_id_;
467}
468
469void TabContents::UpdateMaxPageID(int32 page_id) {
470 // Ensure both the SiteInstance and RenderProcessHost update their max page
[email protected]57c6a652009-05-04 07:58:34471 // IDs in sync. Only TabContents will also have site instances, except during
[email protected]d5f942ba2008-09-26 19:30:34472 // testing.
473 if (GetSiteInstance())
474 GetSiteInstance()->UpdateMaxPageID(page_id);
[email protected]57c6a652009-05-04 07:58:34475 process()->UpdateMaxPageID(page_id);
[email protected]d5f942ba2008-09-26 19:30:34476}
477
[email protected]96d185d2009-04-24 03:28:54478SiteInstance* TabContents::GetSiteInstance() const {
479 return render_manager_.current_host()->site_instance();
480}
481
[email protected]d5f942ba2008-09-26 19:30:34482const std::wstring TabContents::GetDefaultTitle() const {
483 return l10n_util::GetString(IDS_DEFAULT_TAB_TITLE);
484}
485
[email protected]96d185d2009-04-24 03:28:54486bool TabContents::ShouldDisplayURL() {
487 // Don't hide the url in view source mode.
488 NavigationEntry* entry = controller_.GetActiveEntry();
489 if (entry && entry->IsViewSourceMode())
490 return true;
[email protected]83e3895b2009-06-11 00:07:16491
492 // Hide the URL in chrome-extension://.
493 if (GetURL().SchemeIs(chrome::kExtensionScheme))
494 return false;
495
[email protected]96d185d2009-04-24 03:28:54496 DOMUI* dom_ui = GetDOMUIForCurrentState();
497 if (dom_ui)
498 return !dom_ui->should_hide_url();
499 return true;
500}
501
[email protected]d5f942ba2008-09-26 19:30:34502SkBitmap TabContents::GetFavIcon() const {
503 // Like GetTitle(), we also want to use the favicon for the last committed
504 // entry rather than a pending navigation entry.
[email protected]ce3fa3c2009-04-20 19:55:57505 NavigationEntry* entry = controller_.GetTransientEntry();
[email protected]cbab76d2008-10-13 22:42:47506 if (entry)
507 return entry->favicon().bitmap();
508
[email protected]ce3fa3c2009-04-20 19:55:57509 entry = controller_.GetLastCommittedEntry();
[email protected]d5f942ba2008-09-26 19:30:34510 if (entry)
511 return entry->favicon().bitmap();
[email protected]ce3fa3c2009-04-20 19:55:57512 else if (controller_.LoadingURLLazily())
513 return controller_.GetLazyFavIcon();
[email protected]d5f942ba2008-09-26 19:30:34514 return SkBitmap();
515}
516
[email protected]96d185d2009-04-24 03:28:54517bool TabContents::ShouldDisplayFavIcon() {
518 // Always display a throbber during pending loads.
519 if (controller_.GetLastCommittedEntry() && controller_.pending_entry())
520 return true;
521
522 DOMUI* dom_ui = GetDOMUIForCurrentState();
523 if (dom_ui)
524 return !dom_ui->hide_favicon();
525 return true;
526}
527
[email protected]96d185d2009-04-24 03:28:54528std::wstring TabContents::GetStatusText() const {
529 if (!is_loading() || load_state_ == net::LOAD_STATE_IDLE)
530 return std::wstring();
531
532 switch (load_state_) {
533 case net::LOAD_STATE_WAITING_FOR_CACHE:
534 return l10n_util::GetString(IDS_LOAD_STATE_WAITING_FOR_CACHE);
535 case net::LOAD_STATE_RESOLVING_PROXY_FOR_URL:
536 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_PROXY_FOR_URL);
537 case net::LOAD_STATE_RESOLVING_HOST:
538 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_HOST);
539 case net::LOAD_STATE_CONNECTING:
540 return l10n_util::GetString(IDS_LOAD_STATE_CONNECTING);
541 case net::LOAD_STATE_SENDING_REQUEST:
542 return l10n_util::GetString(IDS_LOAD_STATE_SENDING_REQUEST);
543 case net::LOAD_STATE_WAITING_FOR_RESPONSE:
544 return l10n_util::GetStringF(IDS_LOAD_STATE_WAITING_FOR_RESPONSE,
545 load_state_host_);
546 // Ignore net::LOAD_STATE_READING_RESPONSE and net::LOAD_STATE_IDLE
547 case net::LOAD_STATE_IDLE:
548 case net::LOAD_STATE_READING_RESPONSE:
549 break;
550 }
551
552 return std::wstring();
553}
554
[email protected]d5f942ba2008-09-26 19:30:34555void TabContents::SetIsCrashed(bool state) {
556 if (state == is_crashed_)
557 return;
558
559 is_crashed_ = state;
[email protected]c9cd2222009-05-06 05:16:50560 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]d5f942ba2008-09-26 19:30:34561}
562
[email protected]ce5c4502009-05-06 16:46:11563void TabContents::EnablePageAction(const PageAction* page_action) {
564 DCHECK(page_action);
565
566 if (IsPageActionEnabled(page_action))
567 return; // Already enabled.
568
569 enabled_page_actions_.insert(page_action);
570}
571
572bool TabContents::IsPageActionEnabled(const PageAction* page_action) {
573 DCHECK(page_action);
574 return enabled_page_actions_.end() != enabled_page_actions_.find(page_action);
575}
576
577
[email protected]d5f942ba2008-09-26 19:30:34578void TabContents::NotifyNavigationStateChanged(unsigned changed_flags) {
579 if (delegate_)
580 delegate_->NavigationStateChanged(this, changed_flags);
581}
582
[email protected]96d185d2009-04-24 03:28:54583void TabContents::DidBecomeSelected() {
584 controller_.SetActive(true);
585
586 if (render_widget_host_view())
587 render_widget_host_view()->DidBecomeSelected();
588
589 // If pid() is -1, that means the RenderProcessHost still hasn't been
590 // initialized. It'll register with CacheManagerHost when it is.
591 if (process()->pid() != -1)
592 WebCacheManager::GetInstance()->ObserveActivity(process()->pid());
593}
594
595void TabContents::WasHidden() {
596 if (!capturing_contents()) {
597 // |render_view_host()| can be NULL if the user middle clicks a link to open
598 // a tab in then background, then closes the tab before selecting it. This
599 // is because closing the tab calls TabContents::Destroy(), which removes
600 // the |render_view_host()|; then when we actually destroy the window,
601 // OnWindowPosChanged() notices and calls HideContents() (which calls us).
602 if (render_widget_host_view())
603 render_widget_host_view()->WasHidden();
[email protected]96d185d2009-04-24 03:28:54604 }
605
606 NotificationService::current()->Notify(
607 NotificationType::TAB_CONTENTS_HIDDEN,
608 Source<TabContents>(this),
609 NotificationService::NoDetails());
610}
611
[email protected]d5f942ba2008-09-26 19:30:34612void TabContents::Activate() {
613 if (delegate_)
614 delegate_->ActivateContents(this);
615}
616
[email protected]96d185d2009-04-24 03:28:54617void TabContents::ShowContents() {
618 if (render_widget_host_view())
619 render_widget_host_view()->DidBecomeSelected();
[email protected]96d185d2009-04-24 03:28:54620}
621
622void TabContents::HideContents() {
623 // TODO(pkasting): http://b/1239839 Right now we purposefully don't call
624 // our superclass HideContents(), because some callers want to be very picky
625 // about the order in which these get called. In addition to making the code
626 // here practically impossible to understand, this also means we end up
627 // calling TabContents::WasHidden() twice if callers call both versions of
[email protected]57c6a652009-05-04 07:58:34628 // HideContents() on a TabContents.
[email protected]96d185d2009-04-24 03:28:54629 WasHidden();
630}
631
[email protected]c0588052008-10-27 23:01:50632void TabContents::OpenURL(const GURL& url, const GURL& referrer,
[email protected]d5f942ba2008-09-26 19:30:34633 WindowOpenDisposition disposition,
634 PageTransition::Type transition) {
635 if (delegate_)
[email protected]c0588052008-10-27 23:01:50636 delegate_->OpenURLFromTab(this, url, referrer, disposition, transition);
[email protected]d5f942ba2008-09-26 19:30:34637}
638
639bool TabContents::NavigateToPendingEntry(bool reload) {
[email protected]96d185d2009-04-24 03:28:54640 const NavigationEntry& entry = *controller_.pending_entry();
641
642 RenderViewHost* dest_render_view_host = render_manager_.Navigate(entry);
643 if (!dest_render_view_host)
644 return false; // Unable to create the desired render view host.
645
646 // Tell DevTools agent that it is attached prior to the navigation.
[email protected]684b4ba22009-05-07 06:27:41647 DevToolsManager* devtools_manager = g_browser_process->devtools_manager();
[email protected]7e8e6b62009-05-08 11:28:32648 if (devtools_manager) { // NULL in unit tests.
[email protected]684b4ba22009-05-07 06:27:41649 devtools_manager->OnNavigatingToPendingEntry(
650 render_view_host(),
651 dest_render_view_host,
652 controller_.pending_entry()->url());
[email protected]7e8e6b62009-05-08 11:28:32653 }
[email protected]96d185d2009-04-24 03:28:54654
655 // Used for page load time metrics.
656 current_load_start_ = base::TimeTicks::Now();
657
658 // Navigate in the desired RenderViewHost.
659 dest_render_view_host->NavigateToEntry(entry, reload);
660
661 if (entry.page_id() == -1) {
662 // HACK!! This code suppresses javascript: URLs from being added to
663 // session history, which is what we want to do for javascript: URLs that
664 // do not generate content. What we really need is a message from the
665 // renderer telling us that a new page was not created. The same message
666 // could be used for mailto: URLs and the like.
667 if (entry.url().SchemeIs(chrome::kJavaScriptScheme))
668 return false;
669 }
670
671 // Clear any provisional password saves - this stops password infobars
672 // showing up on pages the user navigates to while the right page is
673 // loading.
674 GetPasswordManager()->ClearProvisionalSave();
675
676 if (reload && !profile()->IsOffTheRecord()) {
677 HistoryService* history =
678 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
679 if (history)
680 history->SetFavIconOutOfDateForPage(entry.url());
681 }
682
[email protected]d5f942ba2008-09-26 19:30:34683 return true;
684}
685
[email protected]96d185d2009-04-24 03:28:54686void TabContents::Stop() {
687 render_manager_.Stop();
688 printing_.Stop();
689}
690
691void TabContents::Cut() {
692 render_view_host()->Cut();
693}
694
695void TabContents::Copy() {
696 render_view_host()->Copy();
697}
698
699void TabContents::Paste() {
700 render_view_host()->Paste();
701}
702
703void TabContents::DisassociateFromPopupCount() {
704 render_view_host()->DisassociateFromPopupCount();
705}
706
707TabContents* TabContents::Clone() {
708 // We create a new SiteInstance so that the new tab won't share processes
709 // with the old one. This can be changed in the future if we need it to share
710 // processes for some reason.
[email protected]420ae012009-04-24 05:16:32711 TabContents* tc = new TabContents(profile(),
[email protected]96d185d2009-04-24 03:28:54712 SiteInstance::CreateSiteInstance(profile()),
713 MSG_ROUTING_NONE, NULL);
714 tc->controller().CopyStateFrom(controller_);
715 return tc;
716}
717
[email protected]420ae012009-04-24 05:16:32718void TabContents::CreateShortcut() {
719 NavigationEntry* entry = controller_.GetLastCommittedEntry();
720 if (!entry)
721 return;
722
723 // We only allow one pending install request. By resetting the page id we
724 // effectively cancel the pending install request.
725 pending_install_.page_id = entry->page_id();
726 pending_install_.icon = GetFavIcon();
727 pending_install_.title = UTF16ToWideHack(GetTitle());
728 pending_install_.url = GetURL();
729 if (pending_install_.callback_functor) {
730 pending_install_.callback_functor->Cancel();
731 pending_install_.callback_functor = NULL;
732 }
733 DCHECK(!pending_install_.icon.isNull()) << "Menu item should be disabled.";
734 if (pending_install_.title.empty())
735 pending_install_.title = UTF8ToWide(GetURL().spec());
736
737 // Request the application info. When done OnDidGetApplicationInfo is invoked
738 // and we'll create the shortcut.
739 render_view_host()->GetApplicationInfo(pending_install_.page_id);
740}
741
[email protected]76f68dc2009-03-10 20:31:32742#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29743ConstrainedWindow* TabContents::CreateConstrainedDialog(
[email protected]c2dacc92008-10-16 23:51:38744 views::WindowDelegate* window_delegate,
745 views::View* contents_view) {
initial.commit09911bf2008-07-26 23:55:29746 ConstrainedWindow* window =
747 ConstrainedWindow::CreateConstrainedDialog(
748 this, gfx::Rect(), contents_view, window_delegate);
749 child_windows_.push_back(window);
750 return window;
751}
[email protected]f3332e12009-03-23 15:28:57752#endif
initial.commit09911bf2008-07-26 23:55:29753
754void TabContents::AddNewContents(TabContents* new_contents,
755 WindowOpenDisposition disposition,
756 const gfx::Rect& initial_pos,
[email protected]c88a70fe2009-05-05 20:00:22757 bool user_gesture,
758 const GURL& creator_url) {
initial.commit09911bf2008-07-26 23:55:29759 if (!delegate_)
760 return;
761
[email protected]ce494a312009-06-10 23:54:20762#if defined(OS_WIN) || defined(OS_LINUX)
[email protected]35f7d212009-04-29 21:19:27763 if ((disposition == NEW_POPUP) && !user_gesture &&
764 !CommandLine::ForCurrentProcess()->HasSwitch(
765 switches::kDisablePopupBlocking)) {
[email protected]2c4410d2009-05-06 23:46:22766 // Unrequested popups from normal pages are constrained unless they're in
[email protected]b6c874582009-05-08 19:38:31767 // the whitelist. The popup owner will handle checking this.
768 delegate_->GetConstrainingContents(this)->AddPopup(new_contents,
769 initial_pos,
770 creator_url.is_valid() ? creator_url.host() : std::string());
771 } else {
[email protected]0aa55312008-10-17 21:53:08772 new_contents->DisassociateFromPopupCount();
initial.commit09911bf2008-07-26 23:55:29773 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
774 user_gesture);
775 }
[email protected]b6c874582009-05-08 19:38:31776 PopupNotificationVisibilityChanged(ShowingBlockedPopupNotification());
[email protected]f3332e12009-03-23 15:28:57777#else
778 // TODO(port): implement the popup blocker stuff
779 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
780 user_gesture);
781#endif
initial.commit09911bf2008-07-26 23:55:29782}
783
initial.commit09911bf2008-07-26 23:55:29784void TabContents::CloseAllSuppressedPopups() {
[email protected]d6598c052008-11-05 19:03:25785 if (blocked_popups_)
[email protected]2c4410d2009-05-06 23:46:22786 blocked_popups_->CloseAll();
initial.commit09911bf2008-07-26 23:55:29787}
788
[email protected]96d185d2009-04-24 03:28:54789void TabContents::PopupNotificationVisibilityChanged(bool visible) {
790 render_view_host()->PopupNotificationVisibilityChanged(visible);
791}
792
793gfx::NativeView TabContents::GetContentNativeView() {
794 return view_->GetContentNativeView();
795}
796
797gfx::NativeView TabContents::GetNativeView() const {
798 return view_->GetNativeView();
799}
800
801void TabContents::GetContainerBounds(gfx::Rect *out) const {
802 view_->GetContainerBounds(out);
803}
804
805void TabContents::Focus() {
806 view_->Focus();
807}
808
[email protected]90daadb42009-06-08 21:27:28809void TabContents::FocusThroughTabTraversal(bool reverse) {
[email protected]7e383692009-06-12 19:14:54810 if (showing_interstitial_page()) {
811 render_manager_.interstitial_page()->FocusThroughTabTraversal(reverse);
812 return;
813 }
[email protected]96d185d2009-04-24 03:28:54814 render_view_host()->SetInitialFocus(reverse);
815}
816
817bool TabContents::FocusLocationBarByDefault() {
818 DOMUI* dom_ui = GetDOMUIForCurrentState();
819 if (dom_ui)
820 return dom_ui->focus_location_bar_by_default();
821 return false;
822}
823
[email protected]616ed5a2008-11-21 22:27:24824void TabContents::AddInfoBar(InfoBarDelegate* delegate) {
825 // Look through the existing InfoBarDelegates we have for a match. If we've
826 // already got one that matches, then we don't add the new one.
[email protected]f86a07022008-11-25 01:06:05827 for (int i = 0; i < infobar_delegate_count(); ++i) {
[email protected]616ed5a2008-11-21 22:27:24828 if (GetInfoBarDelegateAt(i)->EqualsDelegate(delegate))
829 return;
830 }
831
832 infobar_delegates_.push_back(delegate);
[email protected]bfd04a62009-02-01 18:16:56833 NotificationService::current()->Notify(
834 NotificationType::TAB_CONTENTS_INFOBAR_ADDED,
835 Source<TabContents>(this),
836 Details<InfoBarDelegate>(delegate));
[email protected]616ed5a2008-11-21 22:27:24837
838 // Add ourselves as an observer for navigations the first time a delegate is
839 // added. We use this notification to expire InfoBars that need to expire on
840 // page transitions.
841 if (infobar_delegates_.size() == 1) {
[email protected]bfd04a62009-02-01 18:16:56842 registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57843 Source<NavigationController>(&controller_));
[email protected]616ed5a2008-11-21 22:27:24844 }
845}
846
847void TabContents::RemoveInfoBar(InfoBarDelegate* delegate) {
848 std::vector<InfoBarDelegate*>::iterator it =
849 find(infobar_delegates_.begin(), infobar_delegates_.end(), delegate);
850 if (it != infobar_delegates_.end()) {
851 InfoBarDelegate* delegate = *it;
[email protected]bfd04a62009-02-01 18:16:56852 NotificationService::current()->Notify(
853 NotificationType::TAB_CONTENTS_INFOBAR_REMOVED,
854 Source<TabContents>(this),
855 Details<InfoBarDelegate>(delegate));
[email protected]f86a07022008-11-25 01:06:05856 infobar_delegates_.erase(it);
[email protected]616ed5a2008-11-21 22:27:24857
[email protected]6a02963e2009-01-06 16:58:03858 // Remove ourselves as an observer if we are tracking no more InfoBars.
859 if (infobar_delegates_.empty()) {
[email protected]bfd04a62009-02-01 18:16:56860 registrar_.Remove(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57861 Source<NavigationController>(&controller_));
[email protected]6a02963e2009-01-06 16:58:03862 }
[email protected]616ed5a2008-11-21 22:27:24863 }
864}
[email protected]3edd9522009-03-04 22:19:41865
[email protected]96d185d2009-04-24 03:28:54866bool TabContents::IsBookmarkBarAlwaysVisible() {
867 // See GetDOMUIForCurrentState() comment for more info. This case is very
868 // similar, but for non-first loads, we want to use the committed entry. This
869 // is so the bookmarks bar disappears at the same time the page does.
870 if (controller_.GetLastCommittedEntry()) {
871 // Not the first load, always use the committed DOM UI.
872 if (render_manager_.dom_ui())
873 return render_manager_.dom_ui()->force_bookmark_bar_visible();
874 return false; // Default.
875 }
876
877 // When it's the first load, we know either the pending one or the committed
878 // one will have the DOM UI in it (see GetDOMUIForCurrentState), and only one
879 // of them will be valid, so we can just check both.
880 if (render_manager_.pending_dom_ui())
881 return render_manager_.pending_dom_ui()->force_bookmark_bar_visible();
882 if (render_manager_.dom_ui())
883 return render_manager_.dom_ui()->force_bookmark_bar_visible();
884 return false; // Default.
885}
886
[email protected]3edd9522009-03-04 22:19:41887void TabContents::ToolbarSizeChanged(bool is_animating) {
888 TabContentsDelegate* d = delegate();
889 if (d)
890 d->ToolbarSizeChanged(this, is_animating);
891}
[email protected]616ed5a2008-11-21 22:27:24892
[email protected]d5f942ba2008-09-26 19:30:34893void TabContents::OnStartDownload(DownloadItem* download) {
894 DCHECK(download);
[email protected]d5f942ba2008-09-26 19:30:34895
896 // Download in a constrained popup is shown in the tab that opened it.
[email protected]b6c874582009-05-08 19:38:31897 TabContents* tab_contents = delegate()->GetConstrainingContents(this);
[email protected]d5f942ba2008-09-26 19:30:34898
[email protected]59560e0b2009-06-04 03:30:22899 if (tab_contents && tab_contents->delegate())
900 tab_contents->delegate()->OnStartDownload(download);
[email protected]3edd9522009-03-04 22:19:41901}
[email protected]3edd9522009-03-04 22:19:41902
[email protected]d5f942ba2008-09-26 19:30:34903void TabContents::WillClose(ConstrainedWindow* window) {
904 ConstrainedWindowList::iterator it =
905 find(child_windows_.begin(), child_windows_.end(), window);
906 if (it != child_windows_.end())
907 child_windows_.erase(it);
[email protected]66ba4932009-06-04 19:22:13908}
[email protected]d5f942ba2008-09-26 19:30:34909
[email protected]66ba4932009-06-04 19:22:13910void TabContents::WillCloseBlockedPopupContainer(
911 BlockedPopupContainer* container) {
912 DCHECK(blocked_popups_ == container);
913 blocked_popups_ = NULL;
[email protected]d5f942ba2008-09-26 19:30:34914}
915
[email protected]d5f942ba2008-09-26 19:30:34916void TabContents::DidMoveOrResize(ConstrainedWindow* window) {
[email protected]332af7732009-03-11 13:21:35917#if defined(OS_WIN)
[email protected]92edc472009-02-10 20:32:06918 UpdateWindow(GetNativeView());
[email protected]332af7732009-03-11 13:21:35919#endif
[email protected]d5f942ba2008-09-26 19:30:34920}
921
[email protected]e491f1c2009-05-22 20:28:12922void TabContents::StartFinding(string16 find_text,
923 bool forward_direction,
924 bool case_sensitive) {
[email protected]6e95706d2009-04-23 22:55:01925 // If find_text is empty, it means FindNext was pressed with a keyboard
926 // shortcut so unless we have something to search for we return early.
[email protected]e491f1c2009-05-22 20:28:12927 if (find_text.empty() && find_text_.empty()) {
928 if (last_search_prepopulate_text_->empty())
929 return;
930 // Try whatever we searched for last in any tab.
931 find_text = *last_search_prepopulate_text_;
932 }
[email protected]6e95706d2009-04-23 22:55:01933
934 // This is a FindNext operation if we are searching for the same text again,
935 // or if the passed in search text is empty (FindNext keyboard shortcut). The
936 // exception to this is if the Find was aborted (then we don't want FindNext
937 // because the highlighting has been cleared and we need it to reappear). We
938 // therefore treat FindNext after an aborted Find operation as a full fledged
939 // Find.
940 bool find_next = (find_text_ == find_text || find_text.empty()) &&
[email protected]e491f1c2009-05-22 20:28:12941 (last_search_case_sensitive_ == case_sensitive) &&
[email protected]6e95706d2009-04-23 22:55:01942 !find_op_aborted_;
943 if (!find_next)
944 current_find_request_id_ = find_request_id_counter_++;
945
946 if (!find_text.empty())
947 find_text_ = find_text;
[email protected]e491f1c2009-05-22 20:28:12948 last_search_case_sensitive_ = case_sensitive;
[email protected]6e95706d2009-04-23 22:55:01949
950 find_op_aborted_ = false;
951
952 // Keep track of what the last search was across the tabs.
[email protected]e491f1c2009-05-22 20:28:12953 *last_search_prepopulate_text_ = find_text;
[email protected]6e95706d2009-04-23 22:55:01954
955 render_view_host()->StartFinding(current_find_request_id_,
956 find_text_,
957 forward_direction,
[email protected]e491f1c2009-05-22 20:28:12958 case_sensitive,
[email protected]6e95706d2009-04-23 22:55:01959 find_next);
960}
961
962void TabContents::StopFinding(bool clear_selection) {
[email protected]2d2dffc2009-06-09 21:41:00963 // When |clear_selection| is true, it means the find string has been cleared
964 // by the user, but the UI has not been dismissed.
965 if (!clear_selection)
966 find_ui_active_ = false;
[email protected]6e95706d2009-04-23 22:55:01967 find_op_aborted_ = true;
[email protected]e491f1c2009-05-22 20:28:12968 last_search_result_ = FindNotificationDetails();
[email protected]6e95706d2009-04-23 22:55:01969 render_view_host()->StopFinding(clear_selection);
970}
971
[email protected]420ae012009-04-24 05:16:32972void TabContents::OnJavaScriptMessageBoxClosed(IPC::Message* reply_msg,
973 bool success,
974 const std::wstring& prompt) {
975 last_javascript_message_dismissal_ = base::TimeTicks::Now();
976 render_manager_.OnJavaScriptMessageBoxClosed(reply_msg, success, prompt);
977}
978
[email protected]571e31152009-05-15 19:34:02979void TabContents::OnJavaScriptMessageBoxWindowDestroyed() {
980 render_manager_.OnJavaScriptMessageBoxWindowDestroyed();
981}
982
[email protected]420ae012009-04-24 05:16:32983void TabContents::OnSavePage() {
984 // If we can not save the page, try to download it.
985 if (!SavePackage::IsSavableContents(contents_mime_type())) {
986 DownloadManager* dlm = profile()->GetDownloadManager();
987 const GURL& current_page_url = GetURL();
988 if (dlm && current_page_url.is_valid())
[email protected]d82ed61e2009-06-16 02:46:22989 dlm->DownloadUrl(current_page_url, GURL(), "", this);
[email protected]420ae012009-04-24 05:16:32990 return;
991 }
992
993 Stop();
994
995 // Create the save package and possibly prompt the user for the name to save
996 // the page as. The user prompt is an asynchronous operation that runs on
997 // another thread.
[email protected]d82ed61e2009-06-16 02:46:22998 save_package_ = new SavePackage(this);
[email protected]420ae012009-04-24 05:16:32999 save_package_->GetSaveInfo();
1000}
1001
1002// Used in automated testing to bypass prompting the user for file names.
1003// Instead, the names and paths are hard coded rather than running them through
1004// file name sanitation and extension / mime checking.
1005void TabContents::SavePage(const std::wstring& main_file,
1006 const std::wstring& dir_path,
1007 SavePackage::SavePackageType save_type) {
1008 // Stop the page from navigating.
1009 Stop();
1010
[email protected]d82ed61e2009-06-16 02:46:221011 save_package_ = new SavePackage(this, save_type,
[email protected]420ae012009-04-24 05:16:321012 FilePath::FromWStringHack(main_file),
1013 FilePath::FromWStringHack(dir_path));
1014 save_package_->Init();
1015}
1016
1017void TabContents::PrintPreview() {
1018 // We don't show the print preview yet, only the print dialog.
1019 PrintNow();
1020}
1021
1022bool TabContents::PrintNow() {
1023 // We can't print interstitial page for now.
1024 if (showing_interstitial_page())
1025 return false;
1026
1027 return render_view_host()->PrintPages();
1028}
1029
1030bool TabContents::IsActiveEntry(int32 page_id) {
1031 NavigationEntry* active_entry = controller_.GetActiveEntry();
1032 return (active_entry != NULL &&
1033 active_entry->site_instance() == GetSiteInstance() &&
1034 active_entry->page_id() == page_id);
1035}
1036
[email protected]96d185d2009-04-24 03:28:541037// Notifies the RenderWidgetHost instance about the fact that the page is
1038// loading, or done loading and calls the base implementation.
1039void TabContents::SetIsLoading(bool is_loading,
1040 LoadNotificationDetails* details) {
1041 if (is_loading == is_loading_)
1042 return;
1043
1044 if (!is_loading) {
1045 load_state_ = net::LOAD_STATE_IDLE;
1046 load_state_host_.clear();
1047 }
1048
1049 render_manager_.SetIsLoading(is_loading);
1050
1051 is_loading_ = is_loading;
1052 waiting_for_response_ = is_loading;
1053
1054 if (delegate_)
1055 delegate_->LoadingStateChanged(this);
[email protected]329581b2009-04-28 06:52:351056 NotifyNavigationStateChanged(INVALIDATE_LOAD);
[email protected]96d185d2009-04-24 03:28:541057
1058 NotificationType type = is_loading ? NotificationType::LOAD_START :
1059 NotificationType::LOAD_STOP;
[email protected]ce5c4502009-05-06 16:46:111060 NotificationDetails det = NotificationService::NoDetails();
[email protected]96d185d2009-04-24 03:28:541061 if (details)
1062 det = Details<LoadNotificationDetails>(details);
1063 NotificationService::current()->Notify(type,
1064 Source<NavigationController>(&controller_),
1065 det);
1066}
1067
[email protected]ce494a312009-06-10 23:54:201068#if defined(OS_WIN) || defined(OS_LINUX)
[email protected]2c4410d2009-05-06 23:46:221069void TabContents::CreateBlockedPopupContainerIfNecessary() {
1070 if (blocked_popups_)
1071 return;
1072
[email protected]4d4c0b92009-06-08 23:13:011073 blocked_popups_ = BlockedPopupContainer::Create(this, profile());
[email protected]2c4410d2009-05-06 23:46:221074}
1075
[email protected]b6c874582009-05-08 19:38:311076void TabContents::AddPopup(TabContents* new_contents,
1077 const gfx::Rect& initial_pos,
1078 const std::string& host) {
[email protected]2c4410d2009-05-06 23:46:221079 CreateBlockedPopupContainerIfNecessary();
1080 blocked_popups_->AddTabContents(new_contents, initial_pos, host);
[email protected]2c4410d2009-05-06 23:46:221081}
[email protected]66ba4932009-06-04 19:22:131082#endif
[email protected]2c4410d2009-05-06 23:46:221083
[email protected]e69bce3dd2009-04-20 22:05:121084// TODO(brettw) This should be on the TabContentsView.
[email protected]66ba4932009-06-04 19:22:131085void TabContents::RepositionSupressedPopupsToFit() {
[email protected]d6598c052008-11-05 19:03:251086 if (blocked_popups_)
[email protected]4d4c0b92009-06-08 23:13:011087 blocked_popups_->RepositionBlockedPopupContainer();
[email protected]d5f942ba2008-09-26 19:30:341088}
1089
[email protected]b9681312008-11-07 00:08:261090bool TabContents::ShowingBlockedPopupNotification() const {
1091 return blocked_popups_ != NULL &&
[email protected]2c4410d2009-05-06 23:46:221092 blocked_popups_->GetBlockedPopupCount() != 0;
[email protected]b9681312008-11-07 00:08:261093}
[email protected]616ed5a2008-11-21 22:27:241094
1095namespace {
1096bool TransitionIsReload(PageTransition::Type transition) {
1097 return PageTransition::StripQualifier(transition) == PageTransition::RELOAD;
1098}
1099}
1100
1101void TabContents::ExpireInfoBars(
1102 const NavigationController::LoadCommittedDetails& details) {
1103 // Only hide InfoBars when the user has done something that makes the main
1104 // frame load. We don't want various automatic or subframe navigations making
1105 // it disappear.
1106 if (!details.is_user_initiated_main_frame_load())
1107 return;
1108
[email protected]f86a07022008-11-25 01:06:051109 for (int i = infobar_delegate_count() - 1; i >= 0; --i) {
[email protected]616ed5a2008-11-21 22:27:241110 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
[email protected]f86a07022008-11-25 01:06:051111 if (delegate->ShouldExpire(details))
[email protected]616ed5a2008-11-21 22:27:241112 RemoveInfoBar(delegate);
[email protected]616ed5a2008-11-21 22:27:241113 }
1114}
[email protected]fdd61c62009-04-22 19:22:571115
1116void TabContents::OnGearsCreateShortcutDone(
1117 const GearsShortcutData2& shortcut_data, bool success) {
1118 NavigationEntry* current_entry = controller_.GetLastCommittedEntry();
1119 bool same_page =
1120 current_entry && pending_install_.page_id == current_entry->page_id();
1121
1122 if (success && same_page) {
1123 // Only switch to app mode if the user chose to create a shortcut and
1124 // we're still on the same page that it corresponded to.
1125 if (delegate())
1126 delegate()->ConvertContentsToApplication(this);
1127 }
1128
1129 // Reset the page id to indicate no requests are pending.
1130 pending_install_.page_id = 0;
1131 pending_install_.callback_functor = NULL;
1132}
[email protected]96d185d2009-04-24 03:28:541133
1134DOMUI* TabContents::GetDOMUIForCurrentState() {
1135 // When there is a pending navigation entry, we want to use the pending DOMUI
1136 // that goes along with it to control the basic flags. For example, we want to
1137 // show the pending URL in the URL bar, so we want the display_url flag to
1138 // be from the pending entry.
1139 //
1140 // The confusion comes because there are multiple possibilities for the
1141 // initial load in a tab as a side effect of the way the RenderViewHostManager
1142 // works.
1143 //
1144 // - For the very first tab the load looks "normal". The new tab DOM UI is
1145 // the pending one, and we want it to apply here.
1146 //
1147 // - For subsequent new tabs, they'll get a new SiteInstance which will then
1148 // get switched to the one previously associated with the new tab pages.
1149 // This switching will cause the manager to commit the RVH/DOMUI. So we'll
1150 // have a committed DOM UI in this case.
1151 //
1152 // This condition handles all of these cases:
1153 //
1154 // - First load in first tab: no committed nav entry + pending nav entry +
1155 // pending dom ui:
1156 // -> Use pending DOM UI if any.
1157 //
1158 // - First load in second tab: no committed nav entry + pending nav entry +
1159 // no pending DOM UI:
1160 // -> Use the committed DOM UI if any.
1161 //
1162 // - Second navigation in any tab: committed nav entry + pending nav entry:
1163 // -> Use pending DOM UI if any.
1164 //
1165 // - Normal state with no load: committed nav entry + no pending nav entry:
1166 // -> Use committed DOM UI.
1167 if (controller_.pending_entry() &&
1168 (controller_.GetLastCommittedEntry() ||
1169 render_manager_.pending_dom_ui()))
1170 return render_manager_.pending_dom_ui();
1171 return render_manager_.dom_ui();
1172}
[email protected]420ae012009-04-24 05:16:321173
1174void TabContents::DidNavigateMainFramePostCommit(
1175 const NavigationController::LoadCommittedDetails& details,
1176 const ViewHostMsg_FrameNavigate_Params& params) {
[email protected]420ae012009-04-24 05:16:321177 if (details.is_user_initiated_main_frame_load()) {
1178 // Clear the status bubble. This is a workaround for a bug where WebKit
1179 // doesn't let us know that the cursor left an element during a
1180 // transition (this is also why the mouse cursor remains as a hand after
1181 // clicking on a link); see bugs 1184641 and 980803. We don't want to
1182 // clear the bubble when a user navigates to a named anchor in the same
1183 // page.
1184 UpdateTargetURL(details.entry->page_id(), GURL());
1185
1186 // UpdateHelpersForDidNavigate will handle the case where the password_form
1187 // origin is valid.
1188 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1189 // cleaned up and covered by tests.
1190 if (!params.password_form.origin.is_valid())
1191 GetPasswordManager()->DidNavigate();
1192 }
1193
1194 // The keyword generator uses the navigation entries, so must be called after
1195 // the commit.
1196 GenerateKeywordIfNecessary(params);
1197
1198 // Allow the new page to set the title again.
1199 received_page_title_ = false;
1200
1201 // Get the favicon, either from history or request it from the net.
1202 fav_icon_helper_.FetchFavIcon(details.entry->url());
1203
[email protected]ce5c4502009-05-06 16:46:111204 // Disable all page actions.
1205 enabled_page_actions_.clear();
1206
[email protected]420ae012009-04-24 05:16:321207 // Close constrained popups if necessary.
1208 MaybeCloseChildWindows(details.previous_url, details.entry->url());
1209
1210 // Update the starred state.
1211 UpdateStarredStateForCurrentURL();
1212}
1213
1214void TabContents::DidNavigateAnyFramePostCommit(
1215 RenderViewHost* render_view_host,
1216 const NavigationController::LoadCommittedDetails& details,
1217 const ViewHostMsg_FrameNavigate_Params& params) {
1218 // If we navigate, start showing messages again. This does nothing to prevent
1219 // a malicious script from spamming messages, since the script could just
1220 // reload the page to stop blocking.
1221 suppress_javascript_messages_ = false;
1222
1223 // Update history. Note that this needs to happen after the entry is complete,
1224 // which WillNavigate[Main,Sub]Frame will do before this function is called.
1225 if (params.should_update_history) {
1226 // Most of the time, the displayURL matches the loaded URL, but for about:
1227 // URLs, we use a data: URL as the real value. We actually want to save
1228 // the about: URL to the history db and keep the data: URL hidden. This is
1229 // what the TabContents' URL getter does.
1230 UpdateHistoryForNavigation(GetURL(), params);
1231 }
1232
1233 // Notify the password manager of the navigation or form submit.
1234 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1235 // cleaned up and covered by tests.
1236 if (params.password_form.origin.is_valid())
1237 GetPasswordManager()->ProvisionallySavePassword(params.password_form);
1238}
1239
1240void TabContents::MaybeCloseChildWindows(const GURL& previous_url,
1241 const GURL& current_url) {
1242 if (net::RegistryControlledDomainService::SameDomainOrHost(
1243 previous_url, current_url))
1244 return;
1245
1246 // Clear out any child windows since we are leaving this page entirely.
1247 // We use indices instead of iterators in case CloseWindow does something
1248 // that may invalidate an iterator.
1249 int size = static_cast<int>(child_windows_.size());
1250 for (int i = size - 1; i >= 0; --i) {
1251 ConstrainedWindow* window = child_windows_[i];
1252 if (window)
1253 window->CloseConstrainedWindow();
1254 }
1255}
1256
1257void TabContents::UpdateStarredStateForCurrentURL() {
1258 BookmarkModel* model = profile()->GetBookmarkModel();
1259 const bool old_state = is_starred_;
1260 is_starred_ = (model && model->IsBookmarked(GetURL()));
1261
1262 if (is_starred_ != old_state && delegate())
1263 delegate()->URLStarredChanged(this, is_starred_);
1264}
1265
1266void TabContents::UpdateAlternateErrorPageURL() {
1267 GURL url = GetAlternateErrorPageURL();
1268 render_view_host()->SetAlternateErrorPageURL(url);
1269}
1270
1271void TabContents::UpdateWebPreferences() {
1272 render_view_host()->UpdateWebPreferences(GetWebkitPrefs());
1273}
1274
1275void TabContents::UpdateMaxPageIDIfNecessary(SiteInstance* site_instance,
1276 RenderViewHost* rvh) {
1277 // If we are creating a RVH for a restored controller, then we might
1278 // have more page IDs than the SiteInstance's current max page ID. We must
1279 // make sure that the max page ID is larger than any restored page ID.
1280 // Note that it is ok for conflicting page IDs to exist in another tab
1281 // (i.e., NavigationController), but if any page ID is larger than the max,
1282 // the back/forward list will get confused.
1283 int max_restored_page_id = controller_.max_restored_page_id();
1284 if (max_restored_page_id > 0) {
1285 int curr_max_page_id = site_instance->max_page_id();
1286 if (max_restored_page_id > curr_max_page_id) {
1287 // Need to update the site instance immediately.
1288 site_instance->UpdateMaxPageID(max_restored_page_id);
1289
1290 // Also tell the renderer to update its internal representation. We
1291 // need to reserve enough IDs to make all restored page IDs less than
1292 // the max.
1293 if (curr_max_page_id < 0)
1294 curr_max_page_id = 0;
1295 rvh->ReservePageIDRange(max_restored_page_id - curr_max_page_id);
1296 }
1297 }
1298}
1299
1300void TabContents::UpdateHistoryForNavigation(
1301 const GURL& display_url,
1302 const ViewHostMsg_FrameNavigate_Params& params) {
1303 if (profile()->IsOffTheRecord())
1304 return;
1305
1306 // Add to history service.
1307 HistoryService* hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1308 if (hs) {
1309 if (PageTransition::IsMainFrame(params.transition) &&
1310 display_url != params.url) {
1311 // Hack on the "display" URL so that it will appear in history. For some
1312 // types of URLs, we will display a magic URL that is different from where
1313 // the page is actually navigated. We want the user to see in history
1314 // what they saw in the URL bar, so we add the display URL as a redirect.
1315 // This only applies to the main frame, as the display URL doesn't apply
1316 // to sub-frames.
1317 std::vector<GURL> redirects = params.redirects;
1318 if (!redirects.empty())
1319 redirects.back() = display_url;
1320 hs->AddPage(display_url, this, params.page_id, params.referrer,
1321 params.transition, redirects);
1322 } else {
1323 hs->AddPage(params.url, this, params.page_id, params.referrer,
1324 params.transition, params.redirects);
1325 }
1326 }
1327}
1328
1329bool TabContents::UpdateTitleForEntry(NavigationEntry* entry,
1330 const std::wstring& title) {
1331 // For file URLs without a title, use the pathname instead. In the case of a
1332 // synthesized title, we don't want the update to count toward the "one set
1333 // per page of the title to history."
1334 std::wstring final_title;
1335 bool explicit_set;
1336 if (entry->url().SchemeIsFile() && title.empty()) {
1337 final_title = UTF8ToWide(entry->url().ExtractFileName());
1338 explicit_set = false; // Don't count synthetic titles toward the set limit.
1339 } else {
1340 TrimWhitespace(title, TRIM_ALL, &final_title);
1341 explicit_set = true;
1342 }
1343
1344 if (final_title == UTF16ToWideHack(entry->title()))
1345 return false; // Nothing changed, don't bother.
1346
1347 entry->set_title(WideToUTF16Hack(final_title));
1348
1349 // Update the history system for this page.
1350 if (!profile()->IsOffTheRecord() && !received_page_title_) {
1351 HistoryService* hs =
1352 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1353 if (hs)
1354 hs->SetPageTitle(entry->display_url(), final_title);
1355
1356 // Don't allow the title to be saved again for explicitly set ones.
1357 received_page_title_ = explicit_set;
1358 }
1359
1360 // Lastly, set the title for the view.
1361 view_->SetPageTitle(final_title);
1362
1363 return true;
1364}
1365
1366void TabContents::NotifySwapped() {
1367 // After sending out a swap notification, we need to send a disconnect
1368 // notification so that clients that pick up a pointer to |this| can NULL the
1369 // pointer. See Bug 1230284.
1370 notify_disconnection_ = true;
1371 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341372 NotificationType::TAB_CONTENTS_SWAPPED,
[email protected]d82ed61e2009-06-16 02:46:221373 Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321374 NotificationService::NoDetails());
1375}
1376
1377void TabContents::NotifyConnected() {
1378 notify_disconnection_ = true;
1379 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341380 NotificationType::TAB_CONTENTS_CONNECTED,
[email protected]d82ed61e2009-06-16 02:46:221381 Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321382 NotificationService::NoDetails());
1383}
1384
1385void TabContents::NotifyDisconnected() {
1386 if (!notify_disconnection_)
1387 return;
1388
1389 notify_disconnection_ = false;
1390 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341391 NotificationType::TAB_CONTENTS_DISCONNECTED,
[email protected]d82ed61e2009-06-16 02:46:221392 Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321393 NotificationService::NoDetails());
1394}
1395
1396void TabContents::GenerateKeywordIfNecessary(
1397 const ViewHostMsg_FrameNavigate_Params& params) {
1398 if (!params.searchable_form_url.is_valid())
1399 return;
1400
1401 if (profile()->IsOffTheRecord())
1402 return;
1403
1404 int last_index = controller_.last_committed_entry_index();
1405 // When there was no previous page, the last index will be 0. This is
1406 // normally due to a form submit that opened in a new tab.
1407 // TODO(brettw) bug 916126: we should support keywords when form submits
1408 // happen in new tabs.
1409 if (last_index <= 0)
1410 return;
1411 const NavigationEntry* previous_entry =
1412 controller_.GetEntryAtIndex(last_index - 1);
1413 if (IsFormSubmit(previous_entry)) {
1414 // Only generate a keyword if the previous page wasn't itself a form
1415 // submit.
1416 return;
1417 }
1418
1419 GURL keyword_url = previous_entry->user_typed_url().is_valid() ?
1420 previous_entry->user_typed_url() : previous_entry->url();
1421 std::wstring keyword =
1422 TemplateURLModel::GenerateKeyword(keyword_url, true); // autodetected
1423 if (keyword.empty())
1424 return;
1425
1426 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
1427 if (!url_model)
1428 return;
1429
1430 if (!url_model->loaded()) {
1431 url_model->Load();
1432 return;
1433 }
1434
1435 const TemplateURL* current_url;
1436 std::wstring url = UTF8ToWide(params.searchable_form_url.spec());
1437 if (!url_model->CanReplaceKeyword(keyword, url, &current_url))
1438 return;
1439
1440 if (current_url) {
1441 if (current_url->originating_url().is_valid()) {
1442 // The existing keyword was generated from an OpenSearch description
1443 // document, don't regenerate.
1444 return;
1445 }
1446 url_model->Remove(current_url);
1447 }
1448 TemplateURL* new_url = new TemplateURL();
1449 new_url->set_keyword(keyword);
1450 new_url->set_short_name(keyword);
1451 new_url->SetURL(url, 0, 0);
1452 new_url->add_input_encoding(params.searchable_form_encoding);
1453 DCHECK(controller_.GetLastCommittedEntry());
1454 const GURL& favicon_url =
1455 controller_.GetLastCommittedEntry()->favicon().url();
1456 if (favicon_url.is_valid()) {
1457 new_url->SetFavIconURL(favicon_url);
1458 } else {
1459 // The favicon url isn't valid. This means there really isn't a favicon,
1460 // or the favicon url wasn't obtained before the load started. This assumes
1461 // the later.
1462 // TODO(sky): Need a way to set the favicon that doesn't involve generating
1463 // its url.
1464 new_url->SetFavIconURL(TemplateURL::GenerateFaviconURL(params.referrer));
1465 }
1466 new_url->set_safe_for_autoreplace(true);
1467 url_model->Add(new_url);
1468}
1469
1470RenderViewHostDelegate::View* TabContents::GetViewDelegate() const {
1471 return view_.get();
1472}
1473
1474RenderViewHostDelegate::Save* TabContents::GetSaveDelegate() const {
1475 return save_package_.get(); // May be NULL, but we can return NULL.
1476}
1477
[email protected]80d96fa2009-06-10 22:34:511478RendererPreferences TabContents::GetRendererPrefs() const {
1479 if (delegate())
1480 return delegate()->GetRendererPrefs();
1481 else
1482 return RendererPreferences();
1483}
1484
[email protected]6dfed102009-04-28 03:09:531485ExtensionFunctionDispatcher* TabContents::CreateExtensionFunctionDispatcher(
1486 RenderViewHost* render_view_host,
1487 const std::string& extension_id) {
1488 return delegate()->CreateExtensionFunctionDispatcher(render_view_host,
1489 extension_id);
1490}
1491
[email protected]57c6a652009-05-04 07:58:341492TabContents* TabContents::GetAsTabContents() {
1493 return this;
1494}
1495
[email protected]420ae012009-04-24 05:16:321496void TabContents::RenderViewCreated(RenderViewHost* render_view_host) {
1497 NavigationEntry* entry = controller_.GetActiveEntry();
1498 if (!entry)
1499 return;
1500
1501 // When we're creating views, we're still doing initial setup, so we always
1502 // use the pending DOM UI rather than any possibly existing committed one.
1503 if (render_manager_.pending_dom_ui()) {
1504 render_manager_.pending_dom_ui()->RenderViewCreated(render_view_host);
1505 }
1506
1507 if (entry->IsViewSourceMode()) {
1508 // Put the renderer in view source mode.
1509 render_view_host->Send(
1510 new ViewMsg_EnableViewSourceMode(render_view_host->routing_id()));
1511 }
[email protected]0666aef2009-05-13 19:48:081512
1513 view()->RenderViewCreated(render_view_host);
[email protected]420ae012009-04-24 05:16:321514}
1515
1516void TabContents::RenderViewReady(RenderViewHost* rvh) {
1517 if (rvh != render_view_host()) {
1518 // Don't notify the world, since this came from a renderer in the
1519 // background.
1520 return;
1521 }
1522
1523 NotifyConnected();
1524 SetIsCrashed(false);
1525}
1526
1527void TabContents::RenderViewGone(RenderViewHost* rvh) {
1528 // Ask the print preview if this renderer was valuable.
1529 if (!printing_.OnRenderViewGone(rvh))
1530 return;
1531 if (rvh != render_view_host()) {
1532 // The pending page's RenderViewHost is gone.
1533 return;
1534 }
1535
1536 SetIsLoading(false, NULL);
1537 NotifyDisconnected();
1538 SetIsCrashed(true);
1539
[email protected]8e537302009-06-10 21:19:581540 // Tell the view that we've crashed so it can prepare the sad tab page.
1541 view_->OnTabCrashed();
[email protected]420ae012009-04-24 05:16:321542
1543 // Hide any visible hung renderer warning for this web contents' process.
[email protected]d82ed61e2009-06-16 02:46:221544 HungRendererDialog::HideForTabContents(this);
[email protected]420ae012009-04-24 05:16:321545}
1546
1547void TabContents::DidNavigate(RenderViewHost* rvh,
1548 const ViewHostMsg_FrameNavigate_Params& params) {
1549 if (PageTransition::IsMainFrame(params.transition))
1550 render_manager_.DidNavigateMainFrame(rvh);
1551
1552 // Update the site of the SiteInstance if it doesn't have one yet.
1553 if (!GetSiteInstance()->has_site())
1554 GetSiteInstance()->SetSite(params.url);
1555
1556 // Need to update MIME type here because it's referred to in
1557 // UpdateNavigationCommands() called by RendererDidNavigate() to
1558 // determine whether or not to enable the encoding menu.
1559 // It's updated only for the main frame. For a subframe,
1560 // RenderView::UpdateURL does not set params.contents_mime_type.
1561 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
1562 // TODO(jungshik): Add a test for the encoding menu to avoid
1563 // regressing it again.
1564 if (PageTransition::IsMainFrame(params.transition))
1565 contents_mime_type_ = params.contents_mime_type;
1566
1567 NavigationController::LoadCommittedDetails details;
1568 if (!controller_.RendererDidNavigate(params, &details))
1569 return; // No navigation happened.
1570
1571 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
1572 // for the appropriate notification (best) or you can add it to
1573 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
1574 // necessary, please).
1575
1576 // Run post-commit tasks.
1577 if (details.is_main_frame)
1578 DidNavigateMainFramePostCommit(details, params);
1579 DidNavigateAnyFramePostCommit(rvh, details, params);
1580}
1581
1582void TabContents::UpdateState(RenderViewHost* rvh,
1583 int32 page_id,
1584 const std::string& state) {
1585 DCHECK(rvh == render_view_host());
1586
1587 // We must be prepared to handle state updates for any page, these occur
1588 // when the user is scrolling and entering form data, as well as when we're
1589 // leaving a page, in which case our state may have already been moved to
1590 // the next page. The navigation controller will look up the appropriate
1591 // NavigationEntry and update it when it is notified via the delegate.
1592
1593 int entry_index = controller_.GetEntryIndexWithPageID(
1594 GetSiteInstance(), page_id);
1595 if (entry_index < 0)
1596 return;
1597 NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
1598
1599 if (state == entry->content_state())
1600 return; // Nothing to update.
1601 entry->set_content_state(state);
1602 controller_.NotifyEntryChanged(entry, entry_index);
1603}
1604
1605void TabContents::UpdateTitle(RenderViewHost* rvh,
1606 int32 page_id, const std::wstring& title) {
1607 // If we have a title, that's a pretty good indication that we've started
1608 // getting useful data.
1609 SetNotWaitingForResponse();
1610
1611 DCHECK(rvh == render_view_host());
1612 NavigationEntry* entry = controller_.GetEntryWithPageID(GetSiteInstance(),
1613 page_id);
1614 if (!entry || !UpdateTitleForEntry(entry, title))
1615 return;
1616
1617 // Broadcast notifications when the UI should be updated.
1618 if (entry == controller_.GetEntryAtOffset(0))
[email protected]c9cd2222009-05-06 05:16:501619 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:321620}
1621
[email protected]420ae012009-04-24 05:16:321622void TabContents::UpdateEncoding(RenderViewHost* render_view_host,
1623 const std::wstring& encoding) {
1624 set_encoding(encoding);
1625}
1626
1627void TabContents::UpdateTargetURL(int32 page_id, const GURL& url) {
1628 if (delegate())
1629 delegate()->UpdateTargetURL(this, url);
1630}
1631
1632void TabContents::UpdateThumbnail(const GURL& url,
1633 const SkBitmap& bitmap,
1634 const ThumbnailScore& score) {
1635 // Tell History about this thumbnail
[email protected]449478302009-06-09 20:04:281636 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kThumbnailStore)) {
1637 profile()->GetThumbnailStore()->
1638 SetPageThumbnail(url, bitmap, score, !profile()->IsOffTheRecord());
1639 } else {
1640 HistoryService* hs;
1641 if (!profile()->IsOffTheRecord() &&
1642 (hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS))) {
1643 hs->SetPageThumbnail(url, bitmap, score);
1644 }
[email protected]420ae012009-04-24 05:16:321645 }
1646}
1647
[email protected]0df30122009-06-03 12:13:081648void TabContents::UpdateInspectorSettings(const std::wstring& raw_settings) {
1649 profile()->GetPrefs()->SetString(prefs::kWebKitInspectorSettings,
1650 raw_settings);
1651}
1652
[email protected]420ae012009-04-24 05:16:321653void TabContents::Close(RenderViewHost* rvh) {
1654 // Ignore this if it comes from a RenderViewHost that we aren't showing.
1655 if (delegate() && rvh == render_view_host())
1656 delegate()->CloseContents(this);
1657}
1658
1659void TabContents::RequestMove(const gfx::Rect& new_bounds) {
1660 if (delegate() && delegate()->IsPopup(this))
1661 delegate()->MoveContents(this, new_bounds);
1662}
1663
[email protected]329581b2009-04-28 06:52:351664void TabContents::DidStartLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321665 SetIsLoading(true, NULL);
1666}
1667
[email protected]329581b2009-04-28 06:52:351668void TabContents::DidStopLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321669 scoped_ptr<LoadNotificationDetails> details;
1670
1671 NavigationEntry* entry = controller_.GetActiveEntry();
1672 // An entry may not exist for a stop when loading an initial blank page or
1673 // if an iframe injected by script into a blank page finishes loading.
1674 if (entry) {
1675 scoped_ptr<base::ProcessMetrics> metrics(
1676 base::ProcessMetrics::CreateProcessMetrics(
1677 process()->process().handle()));
1678
1679 base::TimeDelta elapsed = base::TimeTicks::Now() - current_load_start_;
1680
1681 details.reset(new LoadNotificationDetails(
1682 entry->display_url(),
1683 entry->transition_type(),
1684 elapsed,
1685 &controller_,
1686 controller_.GetCurrentEntryIndex()));
1687 }
1688
1689 // Tell PasswordManager we've finished a page load, which serves as a
1690 // green light to save pending passwords and reset itself.
1691 GetPasswordManager()->DidStopLoading();
1692
1693 SetIsLoading(false, details.get());
1694}
1695
1696void TabContents::DidStartProvisionalLoadForFrame(
1697 RenderViewHost* render_view_host,
1698 bool is_main_frame,
1699 const GURL& url) {
1700 ProvisionalLoadDetails details(is_main_frame,
1701 controller_.IsURLInPageNavigation(url),
1702 url, std::string(), false);
1703 NotificationService::current()->Notify(
1704 NotificationType::FRAME_PROVISIONAL_LOAD_START,
1705 Source<NavigationController>(&controller_),
1706 Details<ProvisionalLoadDetails>(&details));
1707}
1708
1709void TabContents::DidRedirectProvisionalLoad(int32 page_id,
1710 const GURL& source_url,
1711 const GURL& target_url) {
1712 NavigationEntry* entry;
1713 if (page_id == -1)
1714 entry = controller_.pending_entry();
1715 else
1716 entry = controller_.GetEntryWithPageID(GetSiteInstance(), page_id);
1717 if (!entry || entry->url() != source_url)
1718 return;
1719 entry->set_url(target_url);
1720}
1721
1722void TabContents::DidLoadResourceFromMemoryCache(
1723 const GURL& url,
1724 const std::string& frame_origin,
1725 const std::string& main_frame_origin,
1726 const std::string& security_info) {
1727 // Send out a notification that we loaded a resource from our memory cache.
1728 int cert_id = 0, cert_status = 0, security_bits = 0;
1729 SSLManager::DeserializeSecurityInfo(security_info,
1730 &cert_id, &cert_status,
1731 &security_bits);
1732 LoadFromMemoryCacheDetails details(url, frame_origin, main_frame_origin,
[email protected]9ae66cbf2009-05-12 16:21:031733 process()->pid(), cert_id, cert_status);
[email protected]420ae012009-04-24 05:16:321734
1735 NotificationService::current()->Notify(
1736 NotificationType::LOAD_FROM_MEMORY_CACHE,
1737 Source<NavigationController>(&controller_),
1738 Details<LoadFromMemoryCacheDetails>(&details));
1739}
1740
1741void TabContents::DidFailProvisionalLoadWithError(
1742 RenderViewHost* render_view_host,
1743 bool is_main_frame,
1744 int error_code,
1745 const GURL& url,
1746 bool showing_repost_interstitial) {
1747 if (net::ERR_ABORTED == error_code) {
1748 // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
1749 // This means that the interstitial won't be torn down properly, which is
1750 // bad. But if we have an interstitial, go back to another tab type, and
1751 // then load the same interstitial again, we could end up getting the first
1752 // interstitial's "failed" message (as a result of the cancel) when we're on
1753 // the second one.
1754 //
1755 // We can't tell this apart, so we think we're tearing down the current page
1756 // which will cause a crash later one. There is also some code in
1757 // RenderViewHostManager::RendererAbortedProvisionalLoad that is commented
1758 // out because of this problem.
1759 //
1760 // http://code.google.com/p/chromium/issues/detail?id=2855
1761 // Because this will not tear down the interstitial properly, if "back" is
1762 // back to another tab type, the interstitial will still be somewhat alive
1763 // in the previous tab type. If you navigate somewhere that activates the
1764 // tab with the interstitial again, you'll see a flash before the new load
1765 // commits of the interstitial page.
1766 if (showing_interstitial_page()) {
1767 LOG(WARNING) << "Discarding message during interstitial.";
1768 return;
1769 }
1770
1771 // This will discard our pending entry if we cancelled the load (e.g., if we
1772 // decided to download the file instead of load it). Only discard the
1773 // pending entry if the URLs match, otherwise the user initiated a navigate
1774 // before the page loaded so that the discard would discard the wrong entry.
1775 NavigationEntry* pending_entry = controller_.pending_entry();
1776 if (pending_entry && pending_entry->url() == url)
1777 controller_.DiscardNonCommittedEntries();
1778
1779 render_manager_.RendererAbortedProvisionalLoad(render_view_host);
1780 }
1781
1782 // Send out a notification that we failed a provisional load with an error.
1783 ProvisionalLoadDetails details(is_main_frame,
1784 controller_.IsURLInPageNavigation(url),
1785 url, std::string(), false);
1786 details.set_error_code(error_code);
1787
1788 NotificationService::current()->Notify(
1789 NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR,
1790 Source<NavigationController>(&controller_),
1791 Details<ProvisionalLoadDetails>(&details));
1792}
1793
1794void TabContents::UpdateFavIconURL(RenderViewHost* render_view_host,
1795 int32 page_id,
1796 const GURL& icon_url) {
1797 fav_icon_helper_.SetFavIconURL(icon_url);
1798}
1799
1800void TabContents::DidDownloadImage(
1801 RenderViewHost* render_view_host,
1802 int id,
1803 const GURL& image_url,
1804 bool errored,
1805 const SkBitmap& image) {
1806 // A notification for downloading would be more flexible, but for now I'm
1807 // forwarding to the two places that could possibly have initiated the
1808 // request. If we end up with another place invoking DownloadImage, probably
1809 // best to refactor out into notification service, or something similar.
1810 if (errored)
1811 fav_icon_helper_.FavIconDownloadFailed(id);
1812 else
1813 fav_icon_helper_.SetFavIcon(id, image_url, image);
1814}
1815
1816void TabContents::RequestOpenURL(const GURL& url, const GURL& referrer,
1817 WindowOpenDisposition disposition) {
1818 if (render_manager_.dom_ui()) {
1819 // When we're a DOM UI, it will provide a page transition type for us (this
1820 // is so the new tab page can specify AUTO_BOOKMARK for automatically
1821 // generated suggestions).
1822 //
1823 // Note also that we hide the referrer for DOM UI pages. We don't really
[email protected]60e448982009-05-06 04:21:161824 // want web sites to see a referrer of "chrome://blah" (and some
1825 // chrome: URLs might have search terms or other stuff we don't want to
[email protected]420ae012009-04-24 05:16:321826 // send to the site), so we send no referrer.
1827 OpenURL(url, GURL(), disposition,
1828 render_manager_.dom_ui()->link_transition_type());
1829 } else {
1830 OpenURL(url, referrer, disposition, PageTransition::LINK);
1831 }
1832}
1833
1834void TabContents::DomOperationResponse(const std::string& json_string,
1835 int automation_id) {
1836 DomOperationNotificationDetails details(json_string, automation_id);
1837 NotificationService::current()->Notify(
[email protected]d82ed61e2009-06-16 02:46:221838 NotificationType::DOM_OPERATION_RESPONSE, Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321839 Details<DomOperationNotificationDetails>(&details));
1840}
1841
1842void TabContents::ProcessDOMUIMessage(const std::string& message,
1843 const std::string& content) {
1844 if (!render_manager_.dom_ui()) {
1845 // We shouldn't get a DOM UI message when we haven't enabled the DOM UI.
1846 // Because the renderer might be owned and sending random messages, we need
1847 // to ignore these inproper ones.
1848 NOTREACHED();
1849 return;
1850 }
1851 render_manager_.dom_ui()->ProcessDOMUIMessage(message, content);
1852}
1853
[email protected]09b8f82f2009-06-16 20:22:111854void TabContents::DocumentLoadedInFrame() {
1855 controller_.DocumentLoadedInFrame();
1856}
1857
[email protected]420ae012009-04-24 05:16:321858void TabContents::ProcessExternalHostMessage(const std::string& message,
1859 const std::string& origin,
1860 const std::string& target) {
1861 if (delegate())
1862 delegate()->ForwardMessageToExternalHost(message, origin, target);
1863}
1864
1865void TabContents::GoToEntryAtOffset(int offset) {
1866 controller_.GoToOffset(offset);
1867}
1868
1869void TabContents::GetHistoryListCount(int* back_list_count,
1870 int* forward_list_count) {
1871 int current_index = controller_.last_committed_entry_index();
1872 *back_list_count = current_index;
1873 *forward_list_count = controller_.entry_count() - current_index - 1;
1874}
1875
1876void TabContents::RunFileChooser(bool multiple_files,
1877 const string16& title,
1878 const FilePath& default_file) {
1879 if (!select_file_dialog_.get())
1880 select_file_dialog_ = SelectFileDialog::Create(this);
1881 SelectFileDialog::Type dialog_type =
1882 multiple_files ? SelectFileDialog::SELECT_OPEN_MULTI_FILE :
1883 SelectFileDialog::SELECT_OPEN_FILE;
1884 select_file_dialog_->SelectFile(dialog_type, title, default_file,
1885 NULL, 0, FILE_PATH_LITERAL(""),
1886 view_->GetTopLevelNativeWindow(), NULL);
1887}
1888
1889void TabContents::RunJavaScriptMessage(
1890 const std::wstring& message,
1891 const std::wstring& default_prompt,
1892 const GURL& frame_url,
1893 const int flags,
1894 IPC::Message* reply_msg,
1895 bool* did_suppress_message) {
1896 // Suppress javascript messages when requested and when inside a constrained
1897 // popup window (because that activates them and breaks them out of the
1898 // constrained window jail).
1899 bool suppress_this_message = suppress_javascript_messages_;
1900 if (delegate())
1901 suppress_this_message |=
[email protected]b6c874582009-05-08 19:38:311902 (delegate()->GetConstrainingContents(this) != this);
[email protected]420ae012009-04-24 05:16:321903
1904 *did_suppress_message = suppress_this_message;
1905
1906 if (!suppress_this_message) {
1907 base::TimeDelta time_since_last_message(
1908 base::TimeTicks::Now() - last_javascript_message_dismissal_);
1909 bool show_suppress_checkbox = false;
1910 // Show a checkbox offering to suppress further messages if this message is
1911 // being displayed within kJavascriptMessageExpectedDelay of the last one.
1912 if (time_since_last_message <
1913 base::TimeDelta::FromMilliseconds(kJavascriptMessageExpectedDelay))
1914 show_suppress_checkbox = true;
1915
[email protected]d82ed61e2009-06-16 02:46:221916 RunJavascriptMessageBox(this, frame_url, flags, message, default_prompt,
[email protected]420ae012009-04-24 05:16:321917 show_suppress_checkbox, reply_msg);
1918 } else {
1919 // If we are suppressing messages, just reply as is if the user immediately
1920 // pressed "Cancel".
1921 OnJavaScriptMessageBoxClosed(reply_msg, false, std::wstring());
1922 }
1923}
1924
1925void TabContents::RunBeforeUnloadConfirm(const std::wstring& message,
1926 IPC::Message* reply_msg) {
[email protected]d82ed61e2009-06-16 02:46:221927 RunBeforeUnloadDialog(this, message, reply_msg);
[email protected]420ae012009-04-24 05:16:321928}
1929
1930void TabContents::ShowModalHTMLDialog(const GURL& url, int width, int height,
1931 const std::string& json_arguments,
1932 IPC::Message* reply_msg) {
1933 if (delegate()) {
1934 HtmlDialogUIDelegate* dialog_delegate =
1935 new ModalHtmlDialogDelegate(url, width, height, json_arguments,
[email protected]d82ed61e2009-06-16 02:46:221936 reply_msg, this);
[email protected]420ae012009-04-24 05:16:321937 delegate()->ShowHtmlDialog(dialog_delegate, NULL);
1938 }
1939}
1940
1941void TabContents::PasswordFormsSeen(
[email protected]ed3fb032009-06-16 19:50:561942 const std::vector<webkit_glue::PasswordForm>& forms) {
[email protected]420ae012009-04-24 05:16:321943 GetPasswordManager()->PasswordFormsSeen(forms);
1944}
1945
1946void TabContents::AutofillFormSubmitted(
[email protected]daa8c58e2009-06-15 17:21:101947 const webkit_glue::AutofillForm& form) {
[email protected]420ae012009-04-24 05:16:321948 GetAutofillManager()->AutofillFormSubmitted(form);
1949}
1950
1951void TabContents::GetAutofillSuggestions(const std::wstring& field_name,
1952 const std::wstring& user_text, int64 node_id, int request_id) {
1953 GetAutofillManager()->FetchValuesForName(field_name, user_text,
1954 kMaxAutofillMenuItems, node_id, request_id);
1955}
1956
1957void TabContents::RemoveAutofillEntry(const std::wstring& field_name,
1958 const std::wstring& value) {
1959 GetAutofillManager()->RemoveValueForName(field_name, value);
1960}
1961
1962// Checks to see if we should generate a keyword based on the OSDD, and if
1963// necessary uses TemplateURLFetcher to download the OSDD and create a keyword.
1964void TabContents::PageHasOSDD(RenderViewHost* render_view_host,
1965 int32 page_id, const GURL& url,
1966 bool autodetected) {
1967 // Make sure page_id is the current page, and the TemplateURLModel is loaded.
1968 DCHECK(url.is_valid());
1969 if (!IsActiveEntry(page_id))
1970 return;
1971 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
1972 if (!url_model)
1973 return;
1974 if (!url_model->loaded()) {
1975 url_model->Load();
1976 return;
1977 }
1978 if (!profile()->GetTemplateURLFetcher())
1979 return;
1980
1981 if (profile()->IsOffTheRecord())
1982 return;
1983
1984 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
1985 DCHECK(entry);
1986
1987 const NavigationEntry* base_entry = entry;
1988 if (IsFormSubmit(base_entry)) {
1989 // If the current page is a form submit, find the last page that was not
1990 // a form submit and use its url to generate the keyword from.
1991 int index = controller_.last_committed_entry_index() - 1;
1992 while (index >= 0 && IsFormSubmit(controller_.GetEntryAtIndex(index)))
1993 index--;
1994 if (index >= 0)
1995 base_entry = controller_.GetEntryAtIndex(index);
1996 else
1997 base_entry = NULL;
1998 }
1999
2000 // We want to use the user typed URL if available since that represents what
2001 // the user typed to get here, and fall back on the regular URL if not.
2002 if (!base_entry)
2003 return;
2004 GURL keyword_url = base_entry->user_typed_url().is_valid() ?
2005 base_entry->user_typed_url() : base_entry->url();
2006 if (!keyword_url.is_valid())
2007 return;
2008 std::wstring keyword = TemplateURLModel::GenerateKeyword(keyword_url,
2009 autodetected);
2010 if (keyword.empty())
2011 return;
2012 const TemplateURL* template_url =
2013 url_model->GetTemplateURLForKeyword(keyword);
2014 if (template_url && (!template_url->safe_for_autoreplace() ||
2015 template_url->originating_url() == url)) {
2016 // Either there is a user created TemplateURL for this keyword, or the
2017 // keyword has the same OSDD url and we've parsed it.
2018 return;
2019 }
2020
2021 // Download the OpenSearch description document. If this is successful a
2022 // new keyword will be created when done.
2023#if defined(OS_WIN)
2024 gfx::NativeView ancestor = GetAncestor(view_->GetNativeView(), GA_ROOT);
2025#else
2026 gfx::NativeView ancestor = NULL;
2027#endif
2028 profile()->GetTemplateURLFetcher()->ScheduleDownload(
2029 keyword,
2030 url,
2031 base_entry->favicon().url(),
2032 ancestor,
2033 autodetected);
2034}
2035
2036void TabContents::InspectElementReply(int num_resources) {
2037 // We have received reply from inspect element request. Notify the
2038 // automation provider in case we need to notify automation client.
2039 NotificationService::current()->Notify(
[email protected]d82ed61e2009-06-16 02:46:222040 NotificationType::DOM_INSPECT_ELEMENT_RESPONSE, Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:322041 Details<int>(&num_resources));
2042}
2043
2044void TabContents::DidGetPrintedPagesCount(int cookie, int number_pages) {
2045 printing_.DidGetPrintedPagesCount(cookie, number_pages);
2046}
2047
2048void TabContents::DidPrintPage(const ViewHostMsg_DidPrintPage_Params& params) {
2049 printing_.DidPrintPage(params);
2050}
2051
2052GURL TabContents::GetAlternateErrorPageURL() const {
2053 GURL url;
2054 // Disable alternate error pages when in OffTheRecord/Incognito mode.
2055 if (profile()->IsOffTheRecord())
2056 return url;
2057
2058 PrefService* prefs = profile()->GetPrefs();
2059 DCHECK(prefs);
2060 if (prefs->GetBoolean(prefs::kAlternateErrorPagesEnabled)) {
2061 url = google_util::AppendGoogleLocaleParam(GURL(kLinkDoctorBaseURL));
2062 url = google_util::AppendGoogleTLDParam(url);
2063 }
2064 return url;
2065}
2066
2067WebPreferences TabContents::GetWebkitPrefs() {
2068 PrefService* prefs = render_view_host()->process()->profile()->GetPrefs();
2069 bool isDomUI = false;
2070 return RenderViewHostDelegateHelper::GetWebkitPrefs(prefs, isDomUI);
2071}
2072
2073void TabContents::OnMissingPluginStatus(int status) {
2074#if defined(OS_WIN)
2075// TODO(PORT): pull in when plug-ins work
2076 GetPluginInstaller()->OnMissingPluginStatus(status);
2077#endif
2078}
2079
2080void TabContents::OnCrashedPlugin(const FilePath& plugin_path) {
2081#if defined(OS_WIN)
2082// TODO(PORT): pull in when plug-ins work
2083 DCHECK(!plugin_path.value().empty());
2084
2085 std::wstring plugin_name = plugin_path.ToWStringHack();
2086 scoped_ptr<FileVersionInfo> version_info(
2087 FileVersionInfo::CreateFileVersionInfo(plugin_path));
2088 if (version_info.get()) {
2089 const std::wstring& product_name = version_info->product_name();
2090 if (!product_name.empty())
2091 plugin_name = product_name;
2092 }
2093 AddInfoBar(new SimpleAlertInfoBarDelegate(
2094 this, l10n_util::GetStringF(IDS_PLUGIN_CRASHED_PROMPT, plugin_name),
2095 NULL));
2096#endif
2097}
2098
2099void TabContents::OnCrashedWorker() {
2100 AddInfoBar(new SimpleAlertInfoBarDelegate(
2101 this, l10n_util::GetString(IDS_WEBWORKER_CRASHED_PROMPT),
2102 NULL));
2103}
2104
2105void TabContents::OnJSOutOfMemory() {
2106 AddInfoBar(new SimpleAlertInfoBarDelegate(
2107 this, l10n_util::GetString(IDS_JS_OUT_OF_MEMORY_PROMPT), NULL));
2108}
2109
2110void TabContents::ShouldClosePage(bool proceed) {
2111 render_manager_.ShouldClosePage(proceed);
2112}
2113
2114void TabContents::OnCrossSiteResponse(int new_render_process_host_id,
2115 int new_request_id) {
[email protected]57c6a652009-05-04 07:58:342116 // Allows the TabContents to react when a cross-site response is ready to be
[email protected]420ae012009-04-24 05:16:322117 // delivered to a pending RenderViewHost. We must first run the onunload
2118 // handler of the old RenderViewHost before we can allow it to proceed.
2119 render_manager_.OnCrossSiteResponse(new_render_process_host_id,
2120 new_request_id);
2121}
2122
2123bool TabContents::CanBlur() const {
2124 return delegate() ? delegate()->CanBlur() : true;
2125}
2126
2127gfx::Rect TabContents::GetRootWindowResizerRect() const {
2128 if (delegate())
2129 return delegate()->GetRootWindowResizerRect();
2130 return gfx::Rect();
2131}
2132
2133void TabContents::RendererUnresponsive(RenderViewHost* rvh,
2134 bool is_during_unload) {
2135 if (is_during_unload) {
2136 // Hang occurred while firing the beforeunload/unload handler.
2137 // Pretend the handler fired so tab closing continues as if it had.
[email protected]829e7612009-04-25 01:15:112138 rvh->set_sudden_termination_allowed(true);
[email protected]420ae012009-04-24 05:16:322139
2140 if (!render_manager_.ShouldCloseTabOnUnresponsiveRenderer())
2141 return;
2142
2143 // If the tab hangs in the beforeunload/unload handler there's really
2144 // nothing we can do to recover. Pretend the unload listeners have
2145 // all fired and close the tab. If the hang is in the beforeunload handler
2146 // then the user will not have the option of cancelling the close.
2147 Close(rvh);
2148 return;
2149 }
2150
2151 if (render_view_host() && render_view_host()->IsRenderViewLive())
[email protected]d82ed61e2009-06-16 02:46:222152 HungRendererDialog::ShowForTabContents(this);
[email protected]420ae012009-04-24 05:16:322153}
2154
2155void TabContents::RendererResponsive(RenderViewHost* render_view_host) {
[email protected]d82ed61e2009-06-16 02:46:222156 HungRendererDialog::HideForTabContents(this);
[email protected]420ae012009-04-24 05:16:322157}
2158
2159void TabContents::LoadStateChanged(const GURL& url,
2160 net::LoadState load_state) {
2161 load_state_ = load_state;
[email protected]d686e812009-06-03 19:10:292162 std::wstring languages =
2163 profile()->GetPrefs()->GetString(prefs::kAcceptLanguages);
2164 load_state_host_.clear();
2165 std::string host = url.host();
2166 net::IDNToUnicode(host.c_str(), host.size(), languages, &load_state_host_);
[email protected]420ae012009-04-24 05:16:322167 if (load_state_ == net::LOAD_STATE_READING_RESPONSE)
2168 SetNotWaitingForResponse();
2169 if (is_loading())
[email protected]c9cd2222009-05-06 05:16:502170 NotifyNavigationStateChanged(INVALIDATE_LOAD | INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:322171}
2172
2173void TabContents::OnDidGetApplicationInfo(
2174 int32 page_id,
2175 const webkit_glue::WebApplicationInfo& info) {
2176 if (pending_install_.page_id != page_id)
2177 return; // The user clicked create on a separate page. Ignore this.
2178
2179 pending_install_.callback_functor =
2180 new GearsCreateShortcutCallbackFunctor(this);
2181 GearsCreateShortcut(
2182 info, pending_install_.title, pending_install_.url, pending_install_.icon,
2183 NewCallback(pending_install_.callback_functor,
2184 &GearsCreateShortcutCallbackFunctor::Run));
2185}
2186
[email protected]14ce83f2009-05-28 18:35:242187void TabContents::OnUserGesture() {
2188 // See comment in RenderViewHostDelegate::OnUserGesture as to why we do this.
2189#if defined(OS_WIN) || defined(OS_LINUX)
[email protected]420ae012009-04-24 05:16:322190 DownloadRequestManager* drm = g_browser_process->download_request_manager();
2191 if (drm)
2192 drm->OnUserGesture(this);
2193#endif
[email protected]09b8f82f2009-06-16 20:22:112194 controller_.OnUserGesture();
[email protected]420ae012009-04-24 05:16:322195}
2196
2197void TabContents::OnFindReply(int request_id,
2198 int number_of_matches,
2199 const gfx::Rect& selection_rect,
2200 int active_match_ordinal,
2201 bool final_update) {
2202 // Ignore responses for requests other than the one we have most recently
2203 // issued. That way we won't act on stale results when the user has
2204 // already typed in another query.
2205 if (request_id != current_find_request_id_)
2206 return;
2207
2208 if (number_of_matches == -1)
[email protected]e491f1c2009-05-22 20:28:122209 number_of_matches = last_search_result_.number_of_matches();
[email protected]420ae012009-04-24 05:16:322210 if (active_match_ordinal == -1)
[email protected]e491f1c2009-05-22 20:28:122211 active_match_ordinal = last_search_result_.active_match_ordinal();
[email protected]420ae012009-04-24 05:16:322212
[email protected]2c355c282009-05-21 23:24:432213 gfx::Rect selection = selection_rect;
2214 if (selection.IsEmpty())
[email protected]e491f1c2009-05-22 20:28:122215 selection = last_search_result_.selection_rect();
[email protected]2c355c282009-05-21 23:24:432216
[email protected]420ae012009-04-24 05:16:322217 // Notify the UI, automation and any other observers that a find result was
2218 // found.
[email protected]e491f1c2009-05-22 20:28:122219 last_search_result_ = FindNotificationDetails(request_id, number_of_matches,
2220 selection, active_match_ordinal,
2221 final_update);
[email protected]420ae012009-04-24 05:16:322222 NotificationService::current()->Notify(
2223 NotificationType::FIND_RESULT_AVAILABLE,
2224 Source<TabContents>(this),
[email protected]e491f1c2009-05-22 20:28:122225 Details<FindNotificationDetails>(&last_search_result_));
[email protected]420ae012009-04-24 05:16:322226}
2227
[email protected]829e7612009-04-25 01:15:112228bool TabContents::IsExternalTabContainer() const {
[email protected]420ae012009-04-24 05:16:322229 if (!delegate())
[email protected]829e7612009-04-25 01:15:112230 return false;
[email protected]420ae012009-04-24 05:16:322231
[email protected]829e7612009-04-25 01:15:112232 return delegate()->IsExternalTabContainer();
[email protected]420ae012009-04-24 05:16:322233}
2234
2235void TabContents::FileSelected(const FilePath& path,
2236 int index, void* params) {
2237 render_view_host()->FileSelected(path);
2238}
2239
2240void TabContents::MultiFilesSelected(const std::vector<FilePath>& files,
2241 void* params) {
2242 render_view_host()->MultiFilesSelected(files);
2243}
2244
2245void TabContents::FileSelectionCanceled(void* params) {
2246 // If the user cancels choosing a file to upload we pass back an
2247 // empty vector.
2248 render_view_host()->MultiFilesSelected(std::vector<FilePath>());
2249}
2250
2251void TabContents::BeforeUnloadFiredFromRenderManager(
2252 bool proceed,
2253 bool* proceed_to_fire_unload) {
2254 if (delegate())
2255 delegate()->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
2256}
2257
2258void TabContents::UpdateRenderViewSizeForRenderManager() {
2259 // TODO(brettw) this is a hack. See TabContentsView::SizeContents.
2260 view_->SizeContents(view_->GetContainerSize());
2261}
2262
2263DOMUI* TabContents::CreateDOMUIForRenderManager(const GURL& url) {
[email protected]d82ed61e2009-06-16 02:46:222264 return DOMUIFactory::CreateDOMUIForURL(this, url);
[email protected]420ae012009-04-24 05:16:322265}
2266
2267NavigationEntry*
2268TabContents::GetLastCommittedNavigationEntryForRenderManager() {
2269 return controller_.GetLastCommittedEntry();
2270}
2271
2272bool TabContents::CreateRenderViewForRenderManager(
2273 RenderViewHost* render_view_host) {
2274 // When we're running a DOM UI, the RenderViewHost needs to be put in DOM UI
2275 // mode before CreateRenderView is called. When we're asked to create a
2276 // RenderView, that means it's for the pending entry, so we have to use the
2277 // pending DOM UI.
2278 if (render_manager_.pending_dom_ui())
2279 render_view_host->AllowDOMUIBindings();
2280
[email protected]1adff062009-06-02 18:39:552281 // Ditto for extension bindings.
2282 if (controller().pending_entry()->url().SchemeIs(chrome::kExtensionScheme))
2283 render_view_host->AllowExtensionBindings();
2284
[email protected]420ae012009-04-24 05:16:322285 RenderWidgetHostView* rwh_view = view_->CreateViewForWidget(render_view_host);
2286 if (!render_view_host->CreateRenderView())
2287 return false;
2288
2289 // Now that the RenderView has been created, we need to tell it its size.
2290 rwh_view->SetSize(view_->GetContainerSize());
2291
2292 UpdateMaxPageIDIfNecessary(render_view_host->site_instance(),
2293 render_view_host);
2294 return true;
2295}
2296
2297void TabContents::Observe(NotificationType type,
2298 const NotificationSource& source,
2299 const NotificationDetails& details) {
2300 switch (type.value) {
2301 case NotificationType::BOOKMARK_MODEL_LOADED:
2302 // BookmarkModel finished loading, fall through to update starred state.
2303 case NotificationType::URLS_STARRED: {
2304 // Somewhere, a URL has been starred.
2305 // Ignore notifications for profiles other than our current one.
2306 Profile* source_profile = Source<Profile>(source).ptr();
2307 if (!source_profile || !source_profile->IsSameProfile(profile()))
2308 return;
2309
2310 UpdateStarredStateForCurrentURL();
2311 break;
2312 }
2313 case NotificationType::PREF_CHANGED: {
2314 std::wstring* pref_name_in = Details<std::wstring>(details).ptr();
2315 DCHECK(Source<PrefService>(source).ptr() == profile()->GetPrefs());
2316 if (*pref_name_in == prefs::kAlternateErrorPagesEnabled) {
2317 UpdateAlternateErrorPageURL();
2318 } else if (*pref_name_in == prefs::kDefaultCharset ||
2319 StartsWithASCII(WideToUTF8(*pref_name_in), "webkit.webprefs.", true)
2320 ) {
2321 UpdateWebPreferences();
2322 } else {
2323 NOTREACHED() << "unexpected pref change notification" << *pref_name_in;
2324 }
2325 break;
2326 }
2327 case NotificationType::RENDER_WIDGET_HOST_DESTROYED:
2328 view_->RenderWidgetHostDestroyed(Source<RenderWidgetHost>(source).ptr());
2329 break;
2330
2331 case NotificationType::NAV_ENTRY_COMMITTED: {
2332 DCHECK(&controller_ == Source<NavigationController>(source).ptr());
2333
2334 NavigationController::LoadCommittedDetails& committed_details =
2335 *(Details<NavigationController::LoadCommittedDetails>(details).ptr());
2336 ExpireInfoBars(committed_details);
2337 break;
2338 }
2339
2340 default:
2341 NOTREACHED();
2342 }
2343}