blob: 9453f989dec9685a7477c7d001bcf280835be2f8 [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]449478302009-06-09 20:04:2841#include "chrome/browser/thumbnail_store.h"
[email protected]420ae012009-04-24 05:16:3242#include "chrome/browser/search_engines/template_url_fetcher.h"
43#include "chrome/browser/search_engines/template_url_model.h"
[email protected]35f7d212009-04-29 21:19:2744#include "chrome/common/chrome_switches.h"
[email protected]bfd04a62009-02-01 18:16:5645#include "chrome/common/notification_service.h"
[email protected]ce5c4502009-05-06 16:46:1146#include "chrome/common/page_action.h"
initial.commit09911bf2008-07-26 23:55:2947#include "chrome/common/pref_names.h"
[email protected]1eb89e82008-08-15 12:27:0348#include "chrome/common/pref_service.h"
[email protected]420ae012009-04-24 05:16:3249#include "chrome/common/render_messages.h"
[email protected]96d185d2009-04-24 03:28:5450#include "chrome/common/url_constants.h"
[email protected]8897c382009-05-06 17:53:2651#include "grit/generated_resources.h"
[email protected]420ae012009-04-24 05:16:3252#include "grit/locale_settings.h"
53#include "net/base/mime_util.h"
54#include "net/base/net_errors.h"
[email protected]d686e812009-06-03 19:10:2955#include "net/base/net_util.h"
[email protected]420ae012009-04-24 05:16:3256#include "net/base/registry_controlled_domain.h"
[email protected]3e45ba92009-02-20 21:09:0057
58#if defined(OS_WIN)
[email protected]66ba4932009-06-04 19:22:1359// For CRect
[email protected]9041a302009-06-04 19:36:3360#include <atlbase.h>
[email protected]326f7112009-06-04 19:30:2961#include <atlapp.h>
[email protected]66ba4932009-06-04 19:22:1362#include <atlmisc.h>
[email protected]3e45ba92009-02-20 21:09:0063// TODO(port): some of these headers should be ported.
[email protected]420ae012009-04-24 05:16:3264#include "chrome/browser/modal_html_dialog_delegate.h"
[email protected]2362e4f2009-05-08 00:34:0565#include "views/controls/scrollbar/native_scroll_bar.h"
[email protected]3e45ba92009-02-20 21:09:0066#endif
initial.commit09911bf2008-07-26 23:55:2967
[email protected]420ae012009-04-24 05:16:3268// Cross-Site Navigations
69//
70// If a TabContents is told to navigate to a different web site (as determined
71// by SiteInstance), it will replace its current RenderViewHost with a new
72// RenderViewHost dedicated to the new SiteInstance. This works as follows:
73//
74// - Navigate determines whether the destination is cross-site, and if so,
75// it creates a pending_render_view_host_ and moves into the PENDING
76// RendererState.
77// - The pending RVH is "suspended," so that no navigation messages are sent to
78// its renderer until the onbeforeunload JavaScript handler has a chance to
79// run in the current RVH.
80// - The pending RVH tells CrossSiteRequestManager (a thread-safe singleton)
81// that it has a pending cross-site request. ResourceDispatcherHost will
82// check for this when the response arrives.
83// - The current RVH runs its onbeforeunload handler. If it returns false, we
84// cancel all the pending logic and go back to NORMAL. Otherwise we allow
85// the pending RVH to send the navigation request to its renderer.
86// - ResourceDispatcherHost receives a ResourceRequest on the IO thread. It
87// checks CrossSiteRequestManager to see that the RVH responsible has a
88// pending cross-site request, and then installs a CrossSiteEventHandler.
89// - When RDH receives a response, the BufferedEventHandler determines whether
90// it is a download. If so, it sends a message to the new renderer causing
91// it to cancel the request, and the download proceeds in the download
92// thread. For now, we stay in a PENDING state (with a pending RVH) until
[email protected]57c6a652009-05-04 07:58:3493// the next DidNavigate event for this TabContents. This isn't ideal, but it
[email protected]420ae012009-04-24 05:16:3294// doesn't affect any functionality.
95// - After RDH receives a response and determines that it is safe and not a
96// download, it pauses the response to first run the old page's onunload
97// handler. It does this by asynchronously calling the OnCrossSiteResponse
[email protected]57c6a652009-05-04 07:58:3498// method of TabContents on the UI thread, which sends a ClosePage message
[email protected]420ae012009-04-24 05:16:3299// to the current RVH.
100// - Once the onunload handler is finished, a ClosePage_ACK message is sent to
101// the ResourceDispatcherHost, who unpauses the response. Data is then sent
102// to the pending RVH.
103// - The pending renderer sends a FrameNavigate message that invokes the
104// DidNavigate method. This replaces the current RVH with the
105// pending RVH and goes back to the NORMAL RendererState.
106
107namespace {
108
109// Amount of time we wait between when a key event is received and the renderer
110// is queried for its state and pushed to the NavigationEntry.
111const int kQueryStateDelay = 5000;
112
113const int kSyncWaitDelay = 40;
114
115// If another javascript message box is displayed within
116// kJavascriptMessageExpectedDelay of a previous javascript message box being
117// dismissed, display an option to suppress future message boxes from this
118// contents.
119const int kJavascriptMessageExpectedDelay = 1000;
120
[email protected]420ae012009-04-24 05:16:32121const char kLinkDoctorBaseURL[] =
122 "http://linkhelp.clients.google.com/tbproxy/lh/fixurl";
123
124// The printer icon in shell32.dll. That's a standard icon user will quickly
125// recognize.
126const int kShell32PrinterIcon = 17;
127
128// The list of prefs we want to observe.
129const wchar_t* kPrefsToObserve[] = {
130 prefs::kAlternateErrorPagesEnabled,
131 prefs::kWebKitJavaEnabled,
132 prefs::kWebKitJavascriptEnabled,
133 prefs::kWebKitLoadsImagesAutomatically,
134 prefs::kWebKitPluginsEnabled,
135 prefs::kWebKitUsesUniversalDetector,
136 prefs::kWebKitSerifFontFamily,
137 prefs::kWebKitSansSerifFontFamily,
138 prefs::kWebKitFixedFontFamily,
139 prefs::kWebKitDefaultFontSize,
140 prefs::kWebKitDefaultFixedFontSize,
141 prefs::kDefaultCharset
142 // kWebKitStandardFontIsSerif needs to be added
143 // if we let users pick which font to use, serif or sans-serif when
144 // no font is specified or a CSS generic family (serif or sans-serif)
145 // is not specified.
146};
147
148const int kPrefsToObserveLength = arraysize(kPrefsToObserve);
149
150// Limit on the number of suggestions to appear in the pop-up menu under an
151// text input element in a form.
152const int kMaxAutofillMenuItems = 6;
153
154// Returns true if the entry's transition type is FORM_SUBMIT.
155bool IsFormSubmit(const NavigationEntry* entry) {
156 return (PageTransition::StripQualifier(entry->transition_type()) ==
157 PageTransition::FORM_SUBMIT);
158}
159
160#if defined(OS_WIN)
161
162BOOL CALLBACK InvalidateWindow(HWND hwnd, LPARAM lparam) {
163 // Note: erase is required to properly paint some widgets borders. This can
164 // be seen with textfields.
165 InvalidateRect(hwnd, NULL, TRUE);
166 return TRUE;
167}
168#endif
169
[email protected]420ae012009-04-24 05:16:32170} // namespace
171
172// -----------------------------------------------------------------------------
173
[email protected]fdd61c62009-04-22 19:22:57174// static
175int TabContents::find_request_id_counter_ = -1;
176
[email protected]420ae012009-04-24 05:16:32177class TabContents::GearsCreateShortcutCallbackFunctor {
178 public:
179 explicit GearsCreateShortcutCallbackFunctor(TabContents* contents)
180 : contents_(contents) {}
181
182 void Run(const GearsShortcutData2& shortcut_data, bool success) {
183 if (contents_)
184 contents_->OnGearsCreateShortcutDone(shortcut_data, success);
185 delete this;
186 }
187 void Cancel() {
188 contents_ = NULL;
189 }
190
191 private:
192 TabContents* contents_;
193};
194
[email protected]420ae012009-04-24 05:16:32195TabContents::TabContents(Profile* profile,
196 SiteInstance* site_instance,
197 int routing_id,
198 base::WaitableEvent* modal_dialog_event)
[email protected]b680ad22009-04-15 23:19:42199 : delegate_(NULL),
[email protected]66ba4932009-06-04 19:22:13200 ALLOW_THIS_IN_INITIALIZER_LIST(controller_(this, profile)),
201 ALLOW_THIS_IN_INITIALIZER_LIST(view_(
[email protected]d82ed61e2009-06-16 02:46:22202 TabContentsView::Create(this))),
203 ALLOW_THIS_IN_INITIALIZER_LIST(render_manager_(this, this)),
[email protected]fdd61c62009-04-22 19:22:57204 property_bag_(),
205 registrar_(),
[email protected]d82ed61e2009-06-16 02:46:22206 ALLOW_THIS_IN_INITIALIZER_LIST(printing_(*this)),
[email protected]fdd61c62009-04-22 19:22:57207 save_package_(),
208 cancelable_consumer_(),
209 autofill_manager_(),
210 password_manager_(),
211 plugin_installer_(),
[email protected]d82ed61e2009-06-16 02:46:22212 ALLOW_THIS_IN_INITIALIZER_LIST(fav_icon_helper_(this)),
[email protected]fdd61c62009-04-22 19:22:57213 select_file_dialog_(),
214 pending_install_(),
[email protected]d5f942ba2008-09-26 19:30:34215 is_loading_(false),
initial.commit09911bf2008-07-26 23:55:29216 is_crashed_(false),
[email protected]d5f942ba2008-09-26 19:30:34217 waiting_for_response_(false),
[email protected]d5f942ba2008-09-26 19:30:34218 max_page_id_(-1),
[email protected]fdd61c62009-04-22 19:22:57219 current_load_start_(),
220 load_state_(net::LOAD_STATE_IDLE),
221 load_state_host_(),
222 received_page_title_(false),
223 is_starred_(false),
224 contents_mime_type_(),
225 encoding_(),
[email protected]332af7732009-03-11 13:21:35226 blocked_popups_(NULL),
[email protected]fdd61c62009-04-22 19:22:57227 infobar_delegates_(),
[email protected]fdd61c62009-04-22 19:22:57228 find_ui_active_(false),
229 find_op_aborted_(false),
230 current_find_request_id_(find_request_id_counter_++),
231 find_text_(),
[email protected]e491f1c2009-05-22 20:28:12232 last_search_case_sensitive_(false),
233 last_search_prepopulate_text_(NULL),
234 last_search_result_(),
[email protected]fdd61c62009-04-22 19:22:57235 capturing_contents_(false),
236 is_being_destroyed_(false),
237 notify_disconnection_(false),
238 history_requests_(),
239#if defined(OS_WIN)
240 message_box_active_(CreateEvent(NULL, TRUE, FALSE, NULL)),
241#endif
242 last_javascript_message_dismissal_(),
243 suppress_javascript_messages_(false) {
[email protected]420ae012009-04-24 05:16:32244 pending_install_.page_id = 0;
245 pending_install_.callback_functor = NULL;
246
247 render_manager_.Init(profile, site_instance, routing_id, modal_dialog_event);
248
249 view_->CreateView();
250
251 // Register for notifications about all interested prefs change.
252 PrefService* prefs = profile->GetPrefs();
253 if (prefs) {
254 for (int i = 0; i < kPrefsToObserveLength; ++i)
255 prefs->AddPrefObserver(kPrefsToObserve[i], this);
256 }
257
258 // Register for notifications about URL starredness changing on any profile.
259 registrar_.Add(this, NotificationType::URLS_STARRED,
260 NotificationService::AllSources());
261 registrar_.Add(this, NotificationType::BOOKMARK_MODEL_LOADED,
262 NotificationService::AllSources());
263 registrar_.Add(this, NotificationType::RENDER_WIDGET_HOST_DESTROYED,
264 NotificationService::AllSources());
265
266 // Keep a global copy of the previous search string (if any).
267 static string16 global_last_search = string16();
[email protected]e491f1c2009-05-22 20:28:12268 last_search_prepopulate_text_ = &global_last_search;
[email protected]332af7732009-03-11 13:21:35269}
initial.commit09911bf2008-07-26 23:55:29270
271TabContents::~TabContents() {
[email protected]420ae012009-04-24 05:16:32272 is_being_destroyed_ = true;
273
274 // We don't want any notifications while we're runnign our destructor.
275 registrar_.RemoveAll();
276
277 // Unregister the notifications of all observed prefs change.
278 PrefService* prefs = profile()->GetPrefs();
279 if (prefs) {
280 for (int i = 0; i < kPrefsToObserveLength; ++i)
281 prefs->RemovePrefObserver(kPrefsToObserve[i], this);
282 }
283
284 // Clean up subwindows like plugins and the find in page bar.
285 view_->OnContentsDestroy();
286
287 NotifyDisconnected();
[email protected]d82ed61e2009-06-16 02:46:22288 HungRendererDialog::HideForTabContents(this);
[email protected]420ae012009-04-24 05:16:32289
290 if (pending_install_.callback_functor)
291 pending_install_.callback_functor->Cancel();
292
293 // First cleanly close all child windows.
294 // TODO(mpcomplete): handle case if MaybeCloseChildWindows() already asked
295 // some of these to close. CloseWindows is async, so it might get called
296 // twice before it runs.
297 int size = static_cast<int>(child_windows_.size());
298 for (int i = size - 1; i >= 0; --i) {
299 ConstrainedWindow* window = child_windows_[i];
300 if (window)
301 window->CloseConstrainedWindow();
302 }
303
[email protected]66ba4932009-06-04 19:22:13304 if (blocked_popups_)
305 blocked_popups_->Destroy();
306
[email protected]420ae012009-04-24 05:16:32307 // Notify any observer that have a reference on this tab contents.
308 NotificationService::current()->Notify(
309 NotificationType::TAB_CONTENTS_DESTROYED,
310 Source<TabContents>(this),
311 NotificationService::NoDetails());
312
[email protected]1e5e74f2009-05-27 20:55:12313 // Notify any lasting InfobarDelegates that have not yet been removed that
314 // whatever infobar they were handling in this TabContents has closed,
315 // because the TabContents is going away entirely.
316 // This must happen after the TAB_CONTENTS_DESTROYED notification as the
317 // notification may trigger infobars calls that access their delegate. (and
318 // some implementations of InfoBarDelegate do delete themselves on
319 // InfoBarClosed()).
320 for (int i = 0; i < infobar_delegate_count(); ++i) {
321 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
322 delegate->InfoBarClosed();
323 }
324 infobar_delegates_.clear();
325
[email protected]420ae012009-04-24 05:16:32326 // TODO(brettw) this should be moved to the view.
327#if defined(OS_WIN)
328 // If we still have a window handle, destroy it. GetNativeView can return
329 // NULL if this contents was part of a window that closed.
330 if (GetNativeView())
331 ::DestroyWindow(GetNativeView());
332#endif
initial.commit09911bf2008-07-26 23:55:29333}
334
[email protected]d5f942ba2008-09-26 19:30:34335// static
336void TabContents::RegisterUserPrefs(PrefService* prefs) {
[email protected]420ae012009-04-24 05:16:32337 prefs->RegisterBooleanPref(prefs::kAlternateErrorPagesEnabled, true);
338
339 WebPreferences pref_defaults;
340 prefs->RegisterBooleanPref(prefs::kWebKitJavascriptEnabled,
341 pref_defaults.javascript_enabled);
342 prefs->RegisterBooleanPref(prefs::kWebKitWebSecurityEnabled,
343 pref_defaults.web_security_enabled);
344 prefs->RegisterBooleanPref(
345 prefs::kWebKitJavascriptCanOpenWindowsAutomatically, true);
346 prefs->RegisterBooleanPref(prefs::kWebKitLoadsImagesAutomatically,
347 pref_defaults.loads_images_automatically);
348 prefs->RegisterBooleanPref(prefs::kWebKitPluginsEnabled,
349 pref_defaults.plugins_enabled);
350 prefs->RegisterBooleanPref(prefs::kWebKitDomPasteEnabled,
351 pref_defaults.dom_paste_enabled);
352 prefs->RegisterBooleanPref(prefs::kWebKitShrinksStandaloneImagesToFit,
353 pref_defaults.shrinks_standalone_images_to_fit);
[email protected]0df30122009-06-03 12:13:08354 prefs->RegisterStringPref(prefs::kWebKitInspectorSettings,
355 pref_defaults.inspector_settings);
[email protected]420ae012009-04-24 05:16:32356 prefs->RegisterBooleanPref(prefs::kWebKitTextAreasAreResizable,
357 pref_defaults.text_areas_are_resizable);
358 prefs->RegisterBooleanPref(prefs::kWebKitJavaEnabled,
359 pref_defaults.java_enabled);
360
361 prefs->RegisterLocalizedStringPref(prefs::kAcceptLanguages,
362 IDS_ACCEPT_LANGUAGES);
363 prefs->RegisterLocalizedStringPref(prefs::kDefaultCharset,
364 IDS_DEFAULT_ENCODING);
365 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitStandardFontIsSerif,
366 IDS_STANDARD_FONT_IS_SERIF);
367 prefs->RegisterLocalizedStringPref(prefs::kWebKitFixedFontFamily,
368 IDS_FIXED_FONT_FAMILY);
369 prefs->RegisterLocalizedStringPref(prefs::kWebKitSerifFontFamily,
370 IDS_SERIF_FONT_FAMILY);
371 prefs->RegisterLocalizedStringPref(prefs::kWebKitSansSerifFontFamily,
372 IDS_SANS_SERIF_FONT_FAMILY);
373 prefs->RegisterLocalizedStringPref(prefs::kWebKitCursiveFontFamily,
374 IDS_CURSIVE_FONT_FAMILY);
375 prefs->RegisterLocalizedStringPref(prefs::kWebKitFantasyFontFamily,
376 IDS_FANTASY_FONT_FAMILY);
377 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFontSize,
378 IDS_DEFAULT_FONT_SIZE);
379 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFixedFontSize,
380 IDS_DEFAULT_FIXED_FONT_SIZE);
381 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumFontSize,
382 IDS_MINIMUM_FONT_SIZE);
383 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumLogicalFontSize,
384 IDS_MINIMUM_LOGICAL_FONT_SIZE);
385 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitUsesUniversalDetector,
386 IDS_USES_UNIVERSAL_DETECTOR);
387 prefs->RegisterLocalizedStringPref(prefs::kStaticEncodings,
388 IDS_STATIC_ENCODING_LIST);
initial.commit09911bf2008-07-26 23:55:29389}
390
[email protected]d5f942ba2008-09-26 19:30:34391bool TabContents::SupportsURL(GURL* url) {
[email protected]6e95706d2009-04-23 22:55:01392 // TODO(brettw) remove this function.
[email protected]9423d9412009-04-14 22:13:55393 return true;
[email protected]d5f942ba2008-09-26 19:30:34394}
395
[email protected]6e95706d2009-04-23 22:55:01396AutofillManager* TabContents::GetAutofillManager() {
397 if (autofill_manager_.get() == NULL)
398 autofill_manager_.reset(new AutofillManager(this));
399 return autofill_manager_.get();
400}
401
402PasswordManager* TabContents::GetPasswordManager() {
403 if (password_manager_.get() == NULL)
404 password_manager_.reset(new PasswordManager(this));
405 return password_manager_.get();
406}
407
408PluginInstaller* TabContents::GetPluginInstaller() {
409 if (plugin_installer_.get() == NULL)
410 plugin_installer_.reset(new PluginInstaller(this));
411 return plugin_installer_.get();
412}
413
[email protected]d5f942ba2008-09-26 19:30:34414const GURL& TabContents::GetURL() const {
415 // We may not have a navigation entry yet
[email protected]ce3fa3c2009-04-20 19:55:57416 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34417 return entry ? entry->display_url() : GURL::EmptyGURL();
418}
419
[email protected]96d185d2009-04-24 03:28:54420const string16& TabContents::GetTitle() const {
[email protected]4c6092c5b2009-06-06 00:23:55421 // Transient entries take precedence. They are used for interstitial pages
422 // that are shown on top of existing pages.
423 NavigationEntry* entry = controller_.GetTransientEntry();
424 if (entry)
425 return entry->GetTitleForDisplay(&controller_);
426
[email protected]96d185d2009-04-24 03:28:54427 DOMUI* our_dom_ui = render_manager_.pending_dom_ui() ?
428 render_manager_.pending_dom_ui() : render_manager_.dom_ui();
429 if (our_dom_ui) {
430 // Don't override the title in view source mode.
[email protected]4c6092c5b2009-06-06 00:23:55431 entry = controller_.GetActiveEntry();
[email protected]96d185d2009-04-24 03:28:54432 if (!(entry && entry->IsViewSourceMode())) {
433 // Give the DOM UI the chance to override our title.
434 const string16& title = our_dom_ui->overridden_title();
435 if (!title.empty())
436 return title;
437 }
438 }
439
440 // We use the title for the last committed entry rather than a pending
441 // navigation entry. For example, when the user types in a URL, we want to
442 // keep the old page's title until the new load has committed and we get a new
443 // title.
[email protected]96d185d2009-04-24 03:28:54444 entry = controller_.GetLastCommittedEntry();
445 if (entry)
446 return entry->GetTitleForDisplay(&controller_);
447 else if (controller_.LoadingURLLazily())
448 return controller_.GetLazyTitle();
449 return EmptyString16();
450}
451
[email protected]d5f942ba2008-09-26 19:30:34452int32 TabContents::GetMaxPageID() {
453 if (GetSiteInstance())
454 return GetSiteInstance()->max_page_id();
455 else
456 return max_page_id_;
457}
458
459void TabContents::UpdateMaxPageID(int32 page_id) {
460 // Ensure both the SiteInstance and RenderProcessHost update their max page
[email protected]57c6a652009-05-04 07:58:34461 // IDs in sync. Only TabContents will also have site instances, except during
[email protected]d5f942ba2008-09-26 19:30:34462 // testing.
463 if (GetSiteInstance())
464 GetSiteInstance()->UpdateMaxPageID(page_id);
[email protected]57c6a652009-05-04 07:58:34465 process()->UpdateMaxPageID(page_id);
[email protected]d5f942ba2008-09-26 19:30:34466}
467
[email protected]96d185d2009-04-24 03:28:54468SiteInstance* TabContents::GetSiteInstance() const {
469 return render_manager_.current_host()->site_instance();
470}
471
[email protected]d5f942ba2008-09-26 19:30:34472const std::wstring TabContents::GetDefaultTitle() const {
473 return l10n_util::GetString(IDS_DEFAULT_TAB_TITLE);
474}
475
[email protected]96d185d2009-04-24 03:28:54476bool TabContents::ShouldDisplayURL() {
477 // Don't hide the url in view source mode.
478 NavigationEntry* entry = controller_.GetActiveEntry();
479 if (entry && entry->IsViewSourceMode())
480 return true;
[email protected]83e3895b2009-06-11 00:07:16481
482 // Hide the URL in chrome-extension://.
483 if (GetURL().SchemeIs(chrome::kExtensionScheme))
484 return false;
485
[email protected]96d185d2009-04-24 03:28:54486 DOMUI* dom_ui = GetDOMUIForCurrentState();
487 if (dom_ui)
488 return !dom_ui->should_hide_url();
489 return true;
490}
491
[email protected]d5f942ba2008-09-26 19:30:34492SkBitmap TabContents::GetFavIcon() const {
493 // Like GetTitle(), we also want to use the favicon for the last committed
494 // entry rather than a pending navigation entry.
[email protected]ce3fa3c2009-04-20 19:55:57495 NavigationEntry* entry = controller_.GetTransientEntry();
[email protected]cbab76d2008-10-13 22:42:47496 if (entry)
497 return entry->favicon().bitmap();
498
[email protected]ce3fa3c2009-04-20 19:55:57499 entry = controller_.GetLastCommittedEntry();
[email protected]d5f942ba2008-09-26 19:30:34500 if (entry)
501 return entry->favicon().bitmap();
[email protected]ce3fa3c2009-04-20 19:55:57502 else if (controller_.LoadingURLLazily())
503 return controller_.GetLazyFavIcon();
[email protected]d5f942ba2008-09-26 19:30:34504 return SkBitmap();
505}
506
[email protected]96d185d2009-04-24 03:28:54507bool TabContents::ShouldDisplayFavIcon() {
508 // Always display a throbber during pending loads.
509 if (controller_.GetLastCommittedEntry() && controller_.pending_entry())
510 return true;
511
512 DOMUI* dom_ui = GetDOMUIForCurrentState();
513 if (dom_ui)
514 return !dom_ui->hide_favicon();
515 return true;
516}
517
[email protected]96d185d2009-04-24 03:28:54518std::wstring TabContents::GetStatusText() const {
519 if (!is_loading() || load_state_ == net::LOAD_STATE_IDLE)
520 return std::wstring();
521
522 switch (load_state_) {
523 case net::LOAD_STATE_WAITING_FOR_CACHE:
524 return l10n_util::GetString(IDS_LOAD_STATE_WAITING_FOR_CACHE);
525 case net::LOAD_STATE_RESOLVING_PROXY_FOR_URL:
526 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_PROXY_FOR_URL);
527 case net::LOAD_STATE_RESOLVING_HOST:
528 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_HOST);
529 case net::LOAD_STATE_CONNECTING:
530 return l10n_util::GetString(IDS_LOAD_STATE_CONNECTING);
531 case net::LOAD_STATE_SENDING_REQUEST:
532 return l10n_util::GetString(IDS_LOAD_STATE_SENDING_REQUEST);
533 case net::LOAD_STATE_WAITING_FOR_RESPONSE:
534 return l10n_util::GetStringF(IDS_LOAD_STATE_WAITING_FOR_RESPONSE,
535 load_state_host_);
536 // Ignore net::LOAD_STATE_READING_RESPONSE and net::LOAD_STATE_IDLE
537 case net::LOAD_STATE_IDLE:
538 case net::LOAD_STATE_READING_RESPONSE:
539 break;
540 }
541
542 return std::wstring();
543}
544
[email protected]d5f942ba2008-09-26 19:30:34545void TabContents::SetIsCrashed(bool state) {
546 if (state == is_crashed_)
547 return;
548
549 is_crashed_ = state;
[email protected]c9cd2222009-05-06 05:16:50550 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]d5f942ba2008-09-26 19:30:34551}
552
[email protected]ce5c4502009-05-06 16:46:11553void TabContents::EnablePageAction(const PageAction* page_action) {
554 DCHECK(page_action);
555
556 if (IsPageActionEnabled(page_action))
557 return; // Already enabled.
558
559 enabled_page_actions_.insert(page_action);
560}
561
562bool TabContents::IsPageActionEnabled(const PageAction* page_action) {
563 DCHECK(page_action);
564 return enabled_page_actions_.end() != enabled_page_actions_.find(page_action);
565}
566
567
[email protected]d5f942ba2008-09-26 19:30:34568void TabContents::NotifyNavigationStateChanged(unsigned changed_flags) {
569 if (delegate_)
570 delegate_->NavigationStateChanged(this, changed_flags);
571}
572
[email protected]96d185d2009-04-24 03:28:54573void TabContents::DidBecomeSelected() {
574 controller_.SetActive(true);
575
576 if (render_widget_host_view())
577 render_widget_host_view()->DidBecomeSelected();
578
579 // If pid() is -1, that means the RenderProcessHost still hasn't been
580 // initialized. It'll register with CacheManagerHost when it is.
581 if (process()->pid() != -1)
582 WebCacheManager::GetInstance()->ObserveActivity(process()->pid());
583}
584
585void TabContents::WasHidden() {
586 if (!capturing_contents()) {
587 // |render_view_host()| can be NULL if the user middle clicks a link to open
588 // a tab in then background, then closes the tab before selecting it. This
589 // is because closing the tab calls TabContents::Destroy(), which removes
590 // the |render_view_host()|; then when we actually destroy the window,
591 // OnWindowPosChanged() notices and calls HideContents() (which calls us).
592 if (render_widget_host_view())
593 render_widget_host_view()->WasHidden();
594
595 // Loop through children and send WasHidden to them, too.
596 int count = static_cast<int>(child_windows_.size());
597 for (int i = count - 1; i >= 0; --i) {
598 ConstrainedWindow* window = child_windows_.at(i);
599 window->WasHidden();
600 }
601 }
602
603 NotificationService::current()->Notify(
604 NotificationType::TAB_CONTENTS_HIDDEN,
605 Source<TabContents>(this),
606 NotificationService::NoDetails());
607}
608
[email protected]d5f942ba2008-09-26 19:30:34609void TabContents::Activate() {
610 if (delegate_)
611 delegate_->ActivateContents(this);
612}
613
[email protected]96d185d2009-04-24 03:28:54614void TabContents::ShowContents() {
615 if (render_widget_host_view())
616 render_widget_host_view()->DidBecomeSelected();
617
618 // Loop through children and send DidBecomeSelected to them, too.
619 int count = static_cast<int>(child_windows_.size());
620 for (int i = count - 1; i >= 0; --i) {
621 ConstrainedWindow* window = child_windows_.at(i);
622 window->DidBecomeSelected();
623 }
624}
625
626void TabContents::HideContents() {
627 // TODO(pkasting): http://b/1239839 Right now we purposefully don't call
628 // our superclass HideContents(), because some callers want to be very picky
629 // about the order in which these get called. In addition to making the code
630 // here practically impossible to understand, this also means we end up
631 // calling TabContents::WasHidden() twice if callers call both versions of
[email protected]57c6a652009-05-04 07:58:34632 // HideContents() on a TabContents.
[email protected]96d185d2009-04-24 03:28:54633 WasHidden();
634}
635
[email protected]c0588052008-10-27 23:01:50636void TabContents::OpenURL(const GURL& url, const GURL& referrer,
[email protected]d5f942ba2008-09-26 19:30:34637 WindowOpenDisposition disposition,
638 PageTransition::Type transition) {
639 if (delegate_)
[email protected]c0588052008-10-27 23:01:50640 delegate_->OpenURLFromTab(this, url, referrer, disposition, transition);
[email protected]d5f942ba2008-09-26 19:30:34641}
642
643bool TabContents::NavigateToPendingEntry(bool reload) {
[email protected]96d185d2009-04-24 03:28:54644 const NavigationEntry& entry = *controller_.pending_entry();
645
646 RenderViewHost* dest_render_view_host = render_manager_.Navigate(entry);
647 if (!dest_render_view_host)
648 return false; // Unable to create the desired render view host.
649
650 // Tell DevTools agent that it is attached prior to the navigation.
[email protected]684b4ba22009-05-07 06:27:41651 DevToolsManager* devtools_manager = g_browser_process->devtools_manager();
[email protected]7e8e6b62009-05-08 11:28:32652 if (devtools_manager) { // NULL in unit tests.
[email protected]684b4ba22009-05-07 06:27:41653 devtools_manager->OnNavigatingToPendingEntry(
654 render_view_host(),
655 dest_render_view_host,
656 controller_.pending_entry()->url());
[email protected]7e8e6b62009-05-08 11:28:32657 }
[email protected]96d185d2009-04-24 03:28:54658
659 // Used for page load time metrics.
660 current_load_start_ = base::TimeTicks::Now();
661
662 // Navigate in the desired RenderViewHost.
663 dest_render_view_host->NavigateToEntry(entry, reload);
664
665 if (entry.page_id() == -1) {
666 // HACK!! This code suppresses javascript: URLs from being added to
667 // session history, which is what we want to do for javascript: URLs that
668 // do not generate content. What we really need is a message from the
669 // renderer telling us that a new page was not created. The same message
670 // could be used for mailto: URLs and the like.
671 if (entry.url().SchemeIs(chrome::kJavaScriptScheme))
672 return false;
673 }
674
675 // Clear any provisional password saves - this stops password infobars
676 // showing up on pages the user navigates to while the right page is
677 // loading.
678 GetPasswordManager()->ClearProvisionalSave();
679
680 if (reload && !profile()->IsOffTheRecord()) {
681 HistoryService* history =
682 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
683 if (history)
684 history->SetFavIconOutOfDateForPage(entry.url());
685 }
686
[email protected]d5f942ba2008-09-26 19:30:34687 return true;
688}
689
[email protected]96d185d2009-04-24 03:28:54690void TabContents::Stop() {
691 render_manager_.Stop();
692 printing_.Stop();
693}
694
695void TabContents::Cut() {
696 render_view_host()->Cut();
697}
698
699void TabContents::Copy() {
700 render_view_host()->Copy();
701}
702
703void TabContents::Paste() {
704 render_view_host()->Paste();
705}
706
707void TabContents::DisassociateFromPopupCount() {
708 render_view_host()->DisassociateFromPopupCount();
709}
710
711TabContents* TabContents::Clone() {
712 // We create a new SiteInstance so that the new tab won't share processes
713 // with the old one. This can be changed in the future if we need it to share
714 // processes for some reason.
[email protected]420ae012009-04-24 05:16:32715 TabContents* tc = new TabContents(profile(),
[email protected]96d185d2009-04-24 03:28:54716 SiteInstance::CreateSiteInstance(profile()),
717 MSG_ROUTING_NONE, NULL);
718 tc->controller().CopyStateFrom(controller_);
719 return tc;
720}
721
[email protected]420ae012009-04-24 05:16:32722void TabContents::CreateShortcut() {
723 NavigationEntry* entry = controller_.GetLastCommittedEntry();
724 if (!entry)
725 return;
726
727 // We only allow one pending install request. By resetting the page id we
728 // effectively cancel the pending install request.
729 pending_install_.page_id = entry->page_id();
730 pending_install_.icon = GetFavIcon();
731 pending_install_.title = UTF16ToWideHack(GetTitle());
732 pending_install_.url = GetURL();
733 if (pending_install_.callback_functor) {
734 pending_install_.callback_functor->Cancel();
735 pending_install_.callback_functor = NULL;
736 }
737 DCHECK(!pending_install_.icon.isNull()) << "Menu item should be disabled.";
738 if (pending_install_.title.empty())
739 pending_install_.title = UTF8ToWide(GetURL().spec());
740
741 // Request the application info. When done OnDidGetApplicationInfo is invoked
742 // and we'll create the shortcut.
743 render_view_host()->GetApplicationInfo(pending_install_.page_id);
744}
745
[email protected]76f68dc2009-03-10 20:31:32746#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29747ConstrainedWindow* TabContents::CreateConstrainedDialog(
[email protected]c2dacc92008-10-16 23:51:38748 views::WindowDelegate* window_delegate,
749 views::View* contents_view) {
initial.commit09911bf2008-07-26 23:55:29750 ConstrainedWindow* window =
751 ConstrainedWindow::CreateConstrainedDialog(
752 this, gfx::Rect(), contents_view, window_delegate);
753 child_windows_.push_back(window);
754 return window;
755}
[email protected]f3332e12009-03-23 15:28:57756#endif
initial.commit09911bf2008-07-26 23:55:29757
758void TabContents::AddNewContents(TabContents* new_contents,
759 WindowOpenDisposition disposition,
760 const gfx::Rect& initial_pos,
[email protected]c88a70fe2009-05-05 20:00:22761 bool user_gesture,
762 const GURL& creator_url) {
initial.commit09911bf2008-07-26 23:55:29763 if (!delegate_)
764 return;
765
[email protected]ce494a312009-06-10 23:54:20766#if defined(OS_WIN) || defined(OS_LINUX)
[email protected]35f7d212009-04-29 21:19:27767 if ((disposition == NEW_POPUP) && !user_gesture &&
768 !CommandLine::ForCurrentProcess()->HasSwitch(
769 switches::kDisablePopupBlocking)) {
[email protected]2c4410d2009-05-06 23:46:22770 // Unrequested popups from normal pages are constrained unless they're in
[email protected]b6c874582009-05-08 19:38:31771 // the whitelist. The popup owner will handle checking this.
772 delegate_->GetConstrainingContents(this)->AddPopup(new_contents,
773 initial_pos,
774 creator_url.is_valid() ? creator_url.host() : std::string());
775 } else {
[email protected]0aa55312008-10-17 21:53:08776 new_contents->DisassociateFromPopupCount();
initial.commit09911bf2008-07-26 23:55:29777 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
778 user_gesture);
779 }
[email protected]b6c874582009-05-08 19:38:31780 PopupNotificationVisibilityChanged(ShowingBlockedPopupNotification());
[email protected]f3332e12009-03-23 15:28:57781#else
782 // TODO(port): implement the popup blocker stuff
783 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
784 user_gesture);
785#endif
initial.commit09911bf2008-07-26 23:55:29786}
787
initial.commit09911bf2008-07-26 23:55:29788void TabContents::CloseAllSuppressedPopups() {
[email protected]d6598c052008-11-05 19:03:25789 if (blocked_popups_)
[email protected]2c4410d2009-05-06 23:46:22790 blocked_popups_->CloseAll();
initial.commit09911bf2008-07-26 23:55:29791}
792
[email protected]96d185d2009-04-24 03:28:54793void TabContents::PopupNotificationVisibilityChanged(bool visible) {
794 render_view_host()->PopupNotificationVisibilityChanged(visible);
795}
796
797gfx::NativeView TabContents::GetContentNativeView() {
798 return view_->GetContentNativeView();
799}
800
801gfx::NativeView TabContents::GetNativeView() const {
802 return view_->GetNativeView();
803}
804
805void TabContents::GetContainerBounds(gfx::Rect *out) const {
806 view_->GetContainerBounds(out);
807}
808
809void TabContents::Focus() {
810 view_->Focus();
811}
812
[email protected]90daadb42009-06-08 21:27:28813void TabContents::FocusThroughTabTraversal(bool reverse) {
[email protected]7e383692009-06-12 19:14:54814 if (showing_interstitial_page()) {
815 render_manager_.interstitial_page()->FocusThroughTabTraversal(reverse);
816 return;
817 }
[email protected]96d185d2009-04-24 03:28:54818 render_view_host()->SetInitialFocus(reverse);
819}
820
821bool TabContents::FocusLocationBarByDefault() {
822 DOMUI* dom_ui = GetDOMUIForCurrentState();
823 if (dom_ui)
824 return dom_ui->focus_location_bar_by_default();
825 return false;
826}
827
[email protected]616ed5a2008-11-21 22:27:24828void TabContents::AddInfoBar(InfoBarDelegate* delegate) {
829 // Look through the existing InfoBarDelegates we have for a match. If we've
830 // already got one that matches, then we don't add the new one.
[email protected]f86a07022008-11-25 01:06:05831 for (int i = 0; i < infobar_delegate_count(); ++i) {
[email protected]616ed5a2008-11-21 22:27:24832 if (GetInfoBarDelegateAt(i)->EqualsDelegate(delegate))
833 return;
834 }
835
836 infobar_delegates_.push_back(delegate);
[email protected]bfd04a62009-02-01 18:16:56837 NotificationService::current()->Notify(
838 NotificationType::TAB_CONTENTS_INFOBAR_ADDED,
839 Source<TabContents>(this),
840 Details<InfoBarDelegate>(delegate));
[email protected]616ed5a2008-11-21 22:27:24841
842 // Add ourselves as an observer for navigations the first time a delegate is
843 // added. We use this notification to expire InfoBars that need to expire on
844 // page transitions.
845 if (infobar_delegates_.size() == 1) {
[email protected]bfd04a62009-02-01 18:16:56846 registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57847 Source<NavigationController>(&controller_));
[email protected]616ed5a2008-11-21 22:27:24848 }
849}
850
851void TabContents::RemoveInfoBar(InfoBarDelegate* delegate) {
852 std::vector<InfoBarDelegate*>::iterator it =
853 find(infobar_delegates_.begin(), infobar_delegates_.end(), delegate);
854 if (it != infobar_delegates_.end()) {
855 InfoBarDelegate* delegate = *it;
[email protected]bfd04a62009-02-01 18:16:56856 NotificationService::current()->Notify(
857 NotificationType::TAB_CONTENTS_INFOBAR_REMOVED,
858 Source<TabContents>(this),
859 Details<InfoBarDelegate>(delegate));
[email protected]f86a07022008-11-25 01:06:05860 infobar_delegates_.erase(it);
[email protected]616ed5a2008-11-21 22:27:24861
[email protected]6a02963e2009-01-06 16:58:03862 // Remove ourselves as an observer if we are tracking no more InfoBars.
863 if (infobar_delegates_.empty()) {
[email protected]bfd04a62009-02-01 18:16:56864 registrar_.Remove(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57865 Source<NavigationController>(&controller_));
[email protected]6a02963e2009-01-06 16:58:03866 }
[email protected]616ed5a2008-11-21 22:27:24867 }
868}
[email protected]3edd9522009-03-04 22:19:41869
[email protected]96d185d2009-04-24 03:28:54870bool TabContents::IsBookmarkBarAlwaysVisible() {
871 // See GetDOMUIForCurrentState() comment for more info. This case is very
872 // similar, but for non-first loads, we want to use the committed entry. This
873 // is so the bookmarks bar disappears at the same time the page does.
874 if (controller_.GetLastCommittedEntry()) {
875 // Not the first load, always use the committed DOM UI.
876 if (render_manager_.dom_ui())
877 return render_manager_.dom_ui()->force_bookmark_bar_visible();
878 return false; // Default.
879 }
880
881 // When it's the first load, we know either the pending one or the committed
882 // one will have the DOM UI in it (see GetDOMUIForCurrentState), and only one
883 // of them will be valid, so we can just check both.
884 if (render_manager_.pending_dom_ui())
885 return render_manager_.pending_dom_ui()->force_bookmark_bar_visible();
886 if (render_manager_.dom_ui())
887 return render_manager_.dom_ui()->force_bookmark_bar_visible();
888 return false; // Default.
889}
890
[email protected]3edd9522009-03-04 22:19:41891void TabContents::ToolbarSizeChanged(bool is_animating) {
892 TabContentsDelegate* d = delegate();
893 if (d)
894 d->ToolbarSizeChanged(this, is_animating);
895}
[email protected]616ed5a2008-11-21 22:27:24896
[email protected]d5f942ba2008-09-26 19:30:34897void TabContents::OnStartDownload(DownloadItem* download) {
898 DCHECK(download);
[email protected]d5f942ba2008-09-26 19:30:34899
900 // Download in a constrained popup is shown in the tab that opened it.
[email protected]b6c874582009-05-08 19:38:31901 TabContents* tab_contents = delegate()->GetConstrainingContents(this);
[email protected]d5f942ba2008-09-26 19:30:34902
[email protected]59560e0b2009-06-04 03:30:22903 if (tab_contents && tab_contents->delegate())
904 tab_contents->delegate()->OnStartDownload(download);
[email protected]3edd9522009-03-04 22:19:41905}
[email protected]3edd9522009-03-04 22:19:41906
[email protected]d5f942ba2008-09-26 19:30:34907void TabContents::WillClose(ConstrainedWindow* window) {
908 ConstrainedWindowList::iterator it =
909 find(child_windows_.begin(), child_windows_.end(), window);
910 if (it != child_windows_.end())
911 child_windows_.erase(it);
[email protected]66ba4932009-06-04 19:22:13912}
[email protected]d5f942ba2008-09-26 19:30:34913
[email protected]66ba4932009-06-04 19:22:13914void TabContents::WillCloseBlockedPopupContainer(
915 BlockedPopupContainer* container) {
916 DCHECK(blocked_popups_ == container);
917 blocked_popups_ = NULL;
[email protected]d5f942ba2008-09-26 19:30:34918}
919
[email protected]d5f942ba2008-09-26 19:30:34920void TabContents::DidMoveOrResize(ConstrainedWindow* window) {
[email protected]332af7732009-03-11 13:21:35921#if defined(OS_WIN)
[email protected]92edc472009-02-10 20:32:06922 UpdateWindow(GetNativeView());
[email protected]332af7732009-03-11 13:21:35923#endif
[email protected]d5f942ba2008-09-26 19:30:34924}
925
[email protected]e491f1c2009-05-22 20:28:12926void TabContents::StartFinding(string16 find_text,
927 bool forward_direction,
928 bool case_sensitive) {
[email protected]6e95706d2009-04-23 22:55:01929 // If find_text is empty, it means FindNext was pressed with a keyboard
930 // shortcut so unless we have something to search for we return early.
[email protected]e491f1c2009-05-22 20:28:12931 if (find_text.empty() && find_text_.empty()) {
932 if (last_search_prepopulate_text_->empty())
933 return;
934 // Try whatever we searched for last in any tab.
935 find_text = *last_search_prepopulate_text_;
936 }
[email protected]6e95706d2009-04-23 22:55:01937
938 // This is a FindNext operation if we are searching for the same text again,
939 // or if the passed in search text is empty (FindNext keyboard shortcut). The
940 // exception to this is if the Find was aborted (then we don't want FindNext
941 // because the highlighting has been cleared and we need it to reappear). We
942 // therefore treat FindNext after an aborted Find operation as a full fledged
943 // Find.
944 bool find_next = (find_text_ == find_text || find_text.empty()) &&
[email protected]e491f1c2009-05-22 20:28:12945 (last_search_case_sensitive_ == case_sensitive) &&
[email protected]6e95706d2009-04-23 22:55:01946 !find_op_aborted_;
947 if (!find_next)
948 current_find_request_id_ = find_request_id_counter_++;
949
950 if (!find_text.empty())
951 find_text_ = find_text;
[email protected]e491f1c2009-05-22 20:28:12952 last_search_case_sensitive_ = case_sensitive;
[email protected]6e95706d2009-04-23 22:55:01953
954 find_op_aborted_ = false;
955
956 // Keep track of what the last search was across the tabs.
[email protected]e491f1c2009-05-22 20:28:12957 *last_search_prepopulate_text_ = find_text;
[email protected]6e95706d2009-04-23 22:55:01958
959 render_view_host()->StartFinding(current_find_request_id_,
960 find_text_,
961 forward_direction,
[email protected]e491f1c2009-05-22 20:28:12962 case_sensitive,
[email protected]6e95706d2009-04-23 22:55:01963 find_next);
964}
965
966void TabContents::StopFinding(bool clear_selection) {
[email protected]2d2dffc2009-06-09 21:41:00967 // When |clear_selection| is true, it means the find string has been cleared
968 // by the user, but the UI has not been dismissed.
969 if (!clear_selection)
970 find_ui_active_ = false;
[email protected]6e95706d2009-04-23 22:55:01971 find_op_aborted_ = true;
[email protected]e491f1c2009-05-22 20:28:12972 last_search_result_ = FindNotificationDetails();
[email protected]6e95706d2009-04-23 22:55:01973 render_view_host()->StopFinding(clear_selection);
974}
975
[email protected]420ae012009-04-24 05:16:32976void TabContents::OnJavaScriptMessageBoxClosed(IPC::Message* reply_msg,
977 bool success,
978 const std::wstring& prompt) {
979 last_javascript_message_dismissal_ = base::TimeTicks::Now();
980 render_manager_.OnJavaScriptMessageBoxClosed(reply_msg, success, prompt);
981}
982
[email protected]571e31152009-05-15 19:34:02983void TabContents::OnJavaScriptMessageBoxWindowDestroyed() {
984 render_manager_.OnJavaScriptMessageBoxWindowDestroyed();
985}
986
[email protected]420ae012009-04-24 05:16:32987void TabContents::OnSavePage() {
988 // If we can not save the page, try to download it.
989 if (!SavePackage::IsSavableContents(contents_mime_type())) {
990 DownloadManager* dlm = profile()->GetDownloadManager();
991 const GURL& current_page_url = GetURL();
992 if (dlm && current_page_url.is_valid())
[email protected]d82ed61e2009-06-16 02:46:22993 dlm->DownloadUrl(current_page_url, GURL(), "", this);
[email protected]420ae012009-04-24 05:16:32994 return;
995 }
996
997 Stop();
998
999 // Create the save package and possibly prompt the user for the name to save
1000 // the page as. The user prompt is an asynchronous operation that runs on
1001 // another thread.
[email protected]d82ed61e2009-06-16 02:46:221002 save_package_ = new SavePackage(this);
[email protected]420ae012009-04-24 05:16:321003 save_package_->GetSaveInfo();
1004}
1005
1006// Used in automated testing to bypass prompting the user for file names.
1007// Instead, the names and paths are hard coded rather than running them through
1008// file name sanitation and extension / mime checking.
1009void TabContents::SavePage(const std::wstring& main_file,
1010 const std::wstring& dir_path,
1011 SavePackage::SavePackageType save_type) {
1012 // Stop the page from navigating.
1013 Stop();
1014
[email protected]d82ed61e2009-06-16 02:46:221015 save_package_ = new SavePackage(this, save_type,
[email protected]420ae012009-04-24 05:16:321016 FilePath::FromWStringHack(main_file),
1017 FilePath::FromWStringHack(dir_path));
1018 save_package_->Init();
1019}
1020
1021void TabContents::PrintPreview() {
1022 // We don't show the print preview yet, only the print dialog.
1023 PrintNow();
1024}
1025
1026bool TabContents::PrintNow() {
1027 // We can't print interstitial page for now.
1028 if (showing_interstitial_page())
1029 return false;
1030
1031 return render_view_host()->PrintPages();
1032}
1033
1034bool TabContents::IsActiveEntry(int32 page_id) {
1035 NavigationEntry* active_entry = controller_.GetActiveEntry();
1036 return (active_entry != NULL &&
1037 active_entry->site_instance() == GetSiteInstance() &&
1038 active_entry->page_id() == page_id);
1039}
1040
[email protected]96d185d2009-04-24 03:28:541041// Notifies the RenderWidgetHost instance about the fact that the page is
1042// loading, or done loading and calls the base implementation.
1043void TabContents::SetIsLoading(bool is_loading,
1044 LoadNotificationDetails* details) {
1045 if (is_loading == is_loading_)
1046 return;
1047
1048 if (!is_loading) {
1049 load_state_ = net::LOAD_STATE_IDLE;
1050 load_state_host_.clear();
1051 }
1052
1053 render_manager_.SetIsLoading(is_loading);
1054
1055 is_loading_ = is_loading;
1056 waiting_for_response_ = is_loading;
1057
1058 if (delegate_)
1059 delegate_->LoadingStateChanged(this);
[email protected]329581b2009-04-28 06:52:351060 NotifyNavigationStateChanged(INVALIDATE_LOAD);
[email protected]96d185d2009-04-24 03:28:541061
1062 NotificationType type = is_loading ? NotificationType::LOAD_START :
1063 NotificationType::LOAD_STOP;
[email protected]ce5c4502009-05-06 16:46:111064 NotificationDetails det = NotificationService::NoDetails();
[email protected]96d185d2009-04-24 03:28:541065 if (details)
1066 det = Details<LoadNotificationDetails>(details);
1067 NotificationService::current()->Notify(type,
1068 Source<NavigationController>(&controller_),
1069 det);
1070}
1071
[email protected]ce494a312009-06-10 23:54:201072#if defined(OS_WIN) || defined(OS_LINUX)
[email protected]2c4410d2009-05-06 23:46:221073void TabContents::CreateBlockedPopupContainerIfNecessary() {
1074 if (blocked_popups_)
1075 return;
1076
[email protected]4d4c0b92009-06-08 23:13:011077 blocked_popups_ = BlockedPopupContainer::Create(this, profile());
[email protected]2c4410d2009-05-06 23:46:221078}
1079
[email protected]b6c874582009-05-08 19:38:311080void TabContents::AddPopup(TabContents* new_contents,
1081 const gfx::Rect& initial_pos,
1082 const std::string& host) {
[email protected]2c4410d2009-05-06 23:46:221083 CreateBlockedPopupContainerIfNecessary();
1084 blocked_popups_->AddTabContents(new_contents, initial_pos, host);
[email protected]2c4410d2009-05-06 23:46:221085}
[email protected]66ba4932009-06-04 19:22:131086#endif
[email protected]2c4410d2009-05-06 23:46:221087
[email protected]e69bce3dd2009-04-20 22:05:121088// TODO(brettw) This should be on the TabContentsView.
[email protected]66ba4932009-06-04 19:22:131089void TabContents::RepositionSupressedPopupsToFit() {
[email protected]d6598c052008-11-05 19:03:251090 if (blocked_popups_)
[email protected]4d4c0b92009-06-08 23:13:011091 blocked_popups_->RepositionBlockedPopupContainer();
[email protected]d5f942ba2008-09-26 19:30:341092}
1093
[email protected]b9681312008-11-07 00:08:261094bool TabContents::ShowingBlockedPopupNotification() const {
1095 return blocked_popups_ != NULL &&
[email protected]2c4410d2009-05-06 23:46:221096 blocked_popups_->GetBlockedPopupCount() != 0;
[email protected]b9681312008-11-07 00:08:261097}
[email protected]616ed5a2008-11-21 22:27:241098
1099namespace {
1100bool TransitionIsReload(PageTransition::Type transition) {
1101 return PageTransition::StripQualifier(transition) == PageTransition::RELOAD;
1102}
1103}
1104
1105void TabContents::ExpireInfoBars(
1106 const NavigationController::LoadCommittedDetails& details) {
1107 // Only hide InfoBars when the user has done something that makes the main
1108 // frame load. We don't want various automatic or subframe navigations making
1109 // it disappear.
1110 if (!details.is_user_initiated_main_frame_load())
1111 return;
1112
[email protected]f86a07022008-11-25 01:06:051113 for (int i = infobar_delegate_count() - 1; i >= 0; --i) {
[email protected]616ed5a2008-11-21 22:27:241114 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
[email protected]f86a07022008-11-25 01:06:051115 if (delegate->ShouldExpire(details))
[email protected]616ed5a2008-11-21 22:27:241116 RemoveInfoBar(delegate);
[email protected]616ed5a2008-11-21 22:27:241117 }
1118}
[email protected]fdd61c62009-04-22 19:22:571119
1120void TabContents::OnGearsCreateShortcutDone(
1121 const GearsShortcutData2& shortcut_data, bool success) {
1122 NavigationEntry* current_entry = controller_.GetLastCommittedEntry();
1123 bool same_page =
1124 current_entry && pending_install_.page_id == current_entry->page_id();
1125
1126 if (success && same_page) {
1127 // Only switch to app mode if the user chose to create a shortcut and
1128 // we're still on the same page that it corresponded to.
1129 if (delegate())
1130 delegate()->ConvertContentsToApplication(this);
1131 }
1132
1133 // Reset the page id to indicate no requests are pending.
1134 pending_install_.page_id = 0;
1135 pending_install_.callback_functor = NULL;
1136}
[email protected]96d185d2009-04-24 03:28:541137
1138DOMUI* TabContents::GetDOMUIForCurrentState() {
1139 // When there is a pending navigation entry, we want to use the pending DOMUI
1140 // that goes along with it to control the basic flags. For example, we want to
1141 // show the pending URL in the URL bar, so we want the display_url flag to
1142 // be from the pending entry.
1143 //
1144 // The confusion comes because there are multiple possibilities for the
1145 // initial load in a tab as a side effect of the way the RenderViewHostManager
1146 // works.
1147 //
1148 // - For the very first tab the load looks "normal". The new tab DOM UI is
1149 // the pending one, and we want it to apply here.
1150 //
1151 // - For subsequent new tabs, they'll get a new SiteInstance which will then
1152 // get switched to the one previously associated with the new tab pages.
1153 // This switching will cause the manager to commit the RVH/DOMUI. So we'll
1154 // have a committed DOM UI in this case.
1155 //
1156 // This condition handles all of these cases:
1157 //
1158 // - First load in first tab: no committed nav entry + pending nav entry +
1159 // pending dom ui:
1160 // -> Use pending DOM UI if any.
1161 //
1162 // - First load in second tab: no committed nav entry + pending nav entry +
1163 // no pending DOM UI:
1164 // -> Use the committed DOM UI if any.
1165 //
1166 // - Second navigation in any tab: committed nav entry + pending nav entry:
1167 // -> Use pending DOM UI if any.
1168 //
1169 // - Normal state with no load: committed nav entry + no pending nav entry:
1170 // -> Use committed DOM UI.
1171 if (controller_.pending_entry() &&
1172 (controller_.GetLastCommittedEntry() ||
1173 render_manager_.pending_dom_ui()))
1174 return render_manager_.pending_dom_ui();
1175 return render_manager_.dom_ui();
1176}
[email protected]420ae012009-04-24 05:16:321177
1178void TabContents::DidNavigateMainFramePostCommit(
1179 const NavigationController::LoadCommittedDetails& details,
1180 const ViewHostMsg_FrameNavigate_Params& params) {
[email protected]420ae012009-04-24 05:16:321181 if (details.is_user_initiated_main_frame_load()) {
1182 // Clear the status bubble. This is a workaround for a bug where WebKit
1183 // doesn't let us know that the cursor left an element during a
1184 // transition (this is also why the mouse cursor remains as a hand after
1185 // clicking on a link); see bugs 1184641 and 980803. We don't want to
1186 // clear the bubble when a user navigates to a named anchor in the same
1187 // page.
1188 UpdateTargetURL(details.entry->page_id(), GURL());
1189
1190 // UpdateHelpersForDidNavigate will handle the case where the password_form
1191 // origin is valid.
1192 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1193 // cleaned up and covered by tests.
1194 if (!params.password_form.origin.is_valid())
1195 GetPasswordManager()->DidNavigate();
1196 }
1197
1198 // The keyword generator uses the navigation entries, so must be called after
1199 // the commit.
1200 GenerateKeywordIfNecessary(params);
1201
1202 // Allow the new page to set the title again.
1203 received_page_title_ = false;
1204
1205 // Get the favicon, either from history or request it from the net.
1206 fav_icon_helper_.FetchFavIcon(details.entry->url());
1207
[email protected]ce5c4502009-05-06 16:46:111208 // Disable all page actions.
1209 enabled_page_actions_.clear();
1210
[email protected]420ae012009-04-24 05:16:321211 // Close constrained popups if necessary.
1212 MaybeCloseChildWindows(details.previous_url, details.entry->url());
1213
1214 // Update the starred state.
1215 UpdateStarredStateForCurrentURL();
1216}
1217
1218void TabContents::DidNavigateAnyFramePostCommit(
1219 RenderViewHost* render_view_host,
1220 const NavigationController::LoadCommittedDetails& details,
1221 const ViewHostMsg_FrameNavigate_Params& params) {
1222 // If we navigate, start showing messages again. This does nothing to prevent
1223 // a malicious script from spamming messages, since the script could just
1224 // reload the page to stop blocking.
1225 suppress_javascript_messages_ = false;
1226
1227 // Update history. Note that this needs to happen after the entry is complete,
1228 // which WillNavigate[Main,Sub]Frame will do before this function is called.
1229 if (params.should_update_history) {
1230 // Most of the time, the displayURL matches the loaded URL, but for about:
1231 // URLs, we use a data: URL as the real value. We actually want to save
1232 // the about: URL to the history db and keep the data: URL hidden. This is
1233 // what the TabContents' URL getter does.
1234 UpdateHistoryForNavigation(GetURL(), params);
1235 }
1236
1237 // Notify the password manager of the navigation or form submit.
1238 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1239 // cleaned up and covered by tests.
1240 if (params.password_form.origin.is_valid())
1241 GetPasswordManager()->ProvisionallySavePassword(params.password_form);
1242}
1243
1244void TabContents::MaybeCloseChildWindows(const GURL& previous_url,
1245 const GURL& current_url) {
1246 if (net::RegistryControlledDomainService::SameDomainOrHost(
1247 previous_url, current_url))
1248 return;
1249
1250 // Clear out any child windows since we are leaving this page entirely.
1251 // We use indices instead of iterators in case CloseWindow does something
1252 // that may invalidate an iterator.
1253 int size = static_cast<int>(child_windows_.size());
1254 for (int i = size - 1; i >= 0; --i) {
1255 ConstrainedWindow* window = child_windows_[i];
1256 if (window)
1257 window->CloseConstrainedWindow();
1258 }
1259}
1260
1261void TabContents::UpdateStarredStateForCurrentURL() {
1262 BookmarkModel* model = profile()->GetBookmarkModel();
1263 const bool old_state = is_starred_;
1264 is_starred_ = (model && model->IsBookmarked(GetURL()));
1265
1266 if (is_starred_ != old_state && delegate())
1267 delegate()->URLStarredChanged(this, is_starred_);
1268}
1269
1270void TabContents::UpdateAlternateErrorPageURL() {
1271 GURL url = GetAlternateErrorPageURL();
1272 render_view_host()->SetAlternateErrorPageURL(url);
1273}
1274
1275void TabContents::UpdateWebPreferences() {
1276 render_view_host()->UpdateWebPreferences(GetWebkitPrefs());
1277}
1278
1279void TabContents::UpdateMaxPageIDIfNecessary(SiteInstance* site_instance,
1280 RenderViewHost* rvh) {
1281 // If we are creating a RVH for a restored controller, then we might
1282 // have more page IDs than the SiteInstance's current max page ID. We must
1283 // make sure that the max page ID is larger than any restored page ID.
1284 // Note that it is ok for conflicting page IDs to exist in another tab
1285 // (i.e., NavigationController), but if any page ID is larger than the max,
1286 // the back/forward list will get confused.
1287 int max_restored_page_id = controller_.max_restored_page_id();
1288 if (max_restored_page_id > 0) {
1289 int curr_max_page_id = site_instance->max_page_id();
1290 if (max_restored_page_id > curr_max_page_id) {
1291 // Need to update the site instance immediately.
1292 site_instance->UpdateMaxPageID(max_restored_page_id);
1293
1294 // Also tell the renderer to update its internal representation. We
1295 // need to reserve enough IDs to make all restored page IDs less than
1296 // the max.
1297 if (curr_max_page_id < 0)
1298 curr_max_page_id = 0;
1299 rvh->ReservePageIDRange(max_restored_page_id - curr_max_page_id);
1300 }
1301 }
1302}
1303
1304void TabContents::UpdateHistoryForNavigation(
1305 const GURL& display_url,
1306 const ViewHostMsg_FrameNavigate_Params& params) {
1307 if (profile()->IsOffTheRecord())
1308 return;
1309
1310 // Add to history service.
1311 HistoryService* hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1312 if (hs) {
1313 if (PageTransition::IsMainFrame(params.transition) &&
1314 display_url != params.url) {
1315 // Hack on the "display" URL so that it will appear in history. For some
1316 // types of URLs, we will display a magic URL that is different from where
1317 // the page is actually navigated. We want the user to see in history
1318 // what they saw in the URL bar, so we add the display URL as a redirect.
1319 // This only applies to the main frame, as the display URL doesn't apply
1320 // to sub-frames.
1321 std::vector<GURL> redirects = params.redirects;
1322 if (!redirects.empty())
1323 redirects.back() = display_url;
1324 hs->AddPage(display_url, this, params.page_id, params.referrer,
1325 params.transition, redirects);
1326 } else {
1327 hs->AddPage(params.url, this, params.page_id, params.referrer,
1328 params.transition, params.redirects);
1329 }
1330 }
1331}
1332
1333bool TabContents::UpdateTitleForEntry(NavigationEntry* entry,
1334 const std::wstring& title) {
1335 // For file URLs without a title, use the pathname instead. In the case of a
1336 // synthesized title, we don't want the update to count toward the "one set
1337 // per page of the title to history."
1338 std::wstring final_title;
1339 bool explicit_set;
1340 if (entry->url().SchemeIsFile() && title.empty()) {
1341 final_title = UTF8ToWide(entry->url().ExtractFileName());
1342 explicit_set = false; // Don't count synthetic titles toward the set limit.
1343 } else {
1344 TrimWhitespace(title, TRIM_ALL, &final_title);
1345 explicit_set = true;
1346 }
1347
1348 if (final_title == UTF16ToWideHack(entry->title()))
1349 return false; // Nothing changed, don't bother.
1350
1351 entry->set_title(WideToUTF16Hack(final_title));
1352
1353 // Update the history system for this page.
1354 if (!profile()->IsOffTheRecord() && !received_page_title_) {
1355 HistoryService* hs =
1356 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1357 if (hs)
1358 hs->SetPageTitle(entry->display_url(), final_title);
1359
1360 // Don't allow the title to be saved again for explicitly set ones.
1361 received_page_title_ = explicit_set;
1362 }
1363
1364 // Lastly, set the title for the view.
1365 view_->SetPageTitle(final_title);
1366
1367 return true;
1368}
1369
1370void TabContents::NotifySwapped() {
1371 // After sending out a swap notification, we need to send a disconnect
1372 // notification so that clients that pick up a pointer to |this| can NULL the
1373 // pointer. See Bug 1230284.
1374 notify_disconnection_ = true;
1375 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341376 NotificationType::TAB_CONTENTS_SWAPPED,
[email protected]d82ed61e2009-06-16 02:46:221377 Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321378 NotificationService::NoDetails());
1379}
1380
1381void TabContents::NotifyConnected() {
1382 notify_disconnection_ = true;
1383 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341384 NotificationType::TAB_CONTENTS_CONNECTED,
[email protected]d82ed61e2009-06-16 02:46:221385 Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321386 NotificationService::NoDetails());
1387}
1388
1389void TabContents::NotifyDisconnected() {
1390 if (!notify_disconnection_)
1391 return;
1392
1393 notify_disconnection_ = false;
1394 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341395 NotificationType::TAB_CONTENTS_DISCONNECTED,
[email protected]d82ed61e2009-06-16 02:46:221396 Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321397 NotificationService::NoDetails());
1398}
1399
1400void TabContents::GenerateKeywordIfNecessary(
1401 const ViewHostMsg_FrameNavigate_Params& params) {
1402 if (!params.searchable_form_url.is_valid())
1403 return;
1404
1405 if (profile()->IsOffTheRecord())
1406 return;
1407
1408 int last_index = controller_.last_committed_entry_index();
1409 // When there was no previous page, the last index will be 0. This is
1410 // normally due to a form submit that opened in a new tab.
1411 // TODO(brettw) bug 916126: we should support keywords when form submits
1412 // happen in new tabs.
1413 if (last_index <= 0)
1414 return;
1415 const NavigationEntry* previous_entry =
1416 controller_.GetEntryAtIndex(last_index - 1);
1417 if (IsFormSubmit(previous_entry)) {
1418 // Only generate a keyword if the previous page wasn't itself a form
1419 // submit.
1420 return;
1421 }
1422
1423 GURL keyword_url = previous_entry->user_typed_url().is_valid() ?
1424 previous_entry->user_typed_url() : previous_entry->url();
1425 std::wstring keyword =
1426 TemplateURLModel::GenerateKeyword(keyword_url, true); // autodetected
1427 if (keyword.empty())
1428 return;
1429
1430 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
1431 if (!url_model)
1432 return;
1433
1434 if (!url_model->loaded()) {
1435 url_model->Load();
1436 return;
1437 }
1438
1439 const TemplateURL* current_url;
1440 std::wstring url = UTF8ToWide(params.searchable_form_url.spec());
1441 if (!url_model->CanReplaceKeyword(keyword, url, &current_url))
1442 return;
1443
1444 if (current_url) {
1445 if (current_url->originating_url().is_valid()) {
1446 // The existing keyword was generated from an OpenSearch description
1447 // document, don't regenerate.
1448 return;
1449 }
1450 url_model->Remove(current_url);
1451 }
1452 TemplateURL* new_url = new TemplateURL();
1453 new_url->set_keyword(keyword);
1454 new_url->set_short_name(keyword);
1455 new_url->SetURL(url, 0, 0);
1456 new_url->add_input_encoding(params.searchable_form_encoding);
1457 DCHECK(controller_.GetLastCommittedEntry());
1458 const GURL& favicon_url =
1459 controller_.GetLastCommittedEntry()->favicon().url();
1460 if (favicon_url.is_valid()) {
1461 new_url->SetFavIconURL(favicon_url);
1462 } else {
1463 // The favicon url isn't valid. This means there really isn't a favicon,
1464 // or the favicon url wasn't obtained before the load started. This assumes
1465 // the later.
1466 // TODO(sky): Need a way to set the favicon that doesn't involve generating
1467 // its url.
1468 new_url->SetFavIconURL(TemplateURL::GenerateFaviconURL(params.referrer));
1469 }
1470 new_url->set_safe_for_autoreplace(true);
1471 url_model->Add(new_url);
1472}
1473
1474RenderViewHostDelegate::View* TabContents::GetViewDelegate() const {
1475 return view_.get();
1476}
1477
1478RenderViewHostDelegate::Save* TabContents::GetSaveDelegate() const {
1479 return save_package_.get(); // May be NULL, but we can return NULL.
1480}
1481
[email protected]80d96fa2009-06-10 22:34:511482RendererPreferences TabContents::GetRendererPrefs() const {
1483 if (delegate())
1484 return delegate()->GetRendererPrefs();
1485 else
1486 return RendererPreferences();
1487}
1488
[email protected]6dfed102009-04-28 03:09:531489ExtensionFunctionDispatcher* TabContents::CreateExtensionFunctionDispatcher(
1490 RenderViewHost* render_view_host,
1491 const std::string& extension_id) {
1492 return delegate()->CreateExtensionFunctionDispatcher(render_view_host,
1493 extension_id);
1494}
1495
[email protected]57c6a652009-05-04 07:58:341496TabContents* TabContents::GetAsTabContents() {
1497 return this;
1498}
1499
[email protected]420ae012009-04-24 05:16:321500void TabContents::RenderViewCreated(RenderViewHost* render_view_host) {
1501 NavigationEntry* entry = controller_.GetActiveEntry();
1502 if (!entry)
1503 return;
1504
1505 // When we're creating views, we're still doing initial setup, so we always
1506 // use the pending DOM UI rather than any possibly existing committed one.
1507 if (render_manager_.pending_dom_ui()) {
1508 render_manager_.pending_dom_ui()->RenderViewCreated(render_view_host);
1509 }
1510
1511 if (entry->IsViewSourceMode()) {
1512 // Put the renderer in view source mode.
1513 render_view_host->Send(
1514 new ViewMsg_EnableViewSourceMode(render_view_host->routing_id()));
1515 }
[email protected]0666aef2009-05-13 19:48:081516
1517 view()->RenderViewCreated(render_view_host);
[email protected]420ae012009-04-24 05:16:321518}
1519
1520void TabContents::RenderViewReady(RenderViewHost* rvh) {
1521 if (rvh != render_view_host()) {
1522 // Don't notify the world, since this came from a renderer in the
1523 // background.
1524 return;
1525 }
1526
1527 NotifyConnected();
1528 SetIsCrashed(false);
1529}
1530
1531void TabContents::RenderViewGone(RenderViewHost* rvh) {
1532 // Ask the print preview if this renderer was valuable.
1533 if (!printing_.OnRenderViewGone(rvh))
1534 return;
1535 if (rvh != render_view_host()) {
1536 // The pending page's RenderViewHost is gone.
1537 return;
1538 }
1539
1540 SetIsLoading(false, NULL);
1541 NotifyDisconnected();
1542 SetIsCrashed(true);
1543
[email protected]8e537302009-06-10 21:19:581544 // Tell the view that we've crashed so it can prepare the sad tab page.
1545 view_->OnTabCrashed();
[email protected]420ae012009-04-24 05:16:321546
1547 // Hide any visible hung renderer warning for this web contents' process.
[email protected]d82ed61e2009-06-16 02:46:221548 HungRendererDialog::HideForTabContents(this);
[email protected]420ae012009-04-24 05:16:321549}
1550
1551void TabContents::DidNavigate(RenderViewHost* rvh,
1552 const ViewHostMsg_FrameNavigate_Params& params) {
1553 if (PageTransition::IsMainFrame(params.transition))
1554 render_manager_.DidNavigateMainFrame(rvh);
1555
1556 // Update the site of the SiteInstance if it doesn't have one yet.
1557 if (!GetSiteInstance()->has_site())
1558 GetSiteInstance()->SetSite(params.url);
1559
1560 // Need to update MIME type here because it's referred to in
1561 // UpdateNavigationCommands() called by RendererDidNavigate() to
1562 // determine whether or not to enable the encoding menu.
1563 // It's updated only for the main frame. For a subframe,
1564 // RenderView::UpdateURL does not set params.contents_mime_type.
1565 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
1566 // TODO(jungshik): Add a test for the encoding menu to avoid
1567 // regressing it again.
1568 if (PageTransition::IsMainFrame(params.transition))
1569 contents_mime_type_ = params.contents_mime_type;
1570
1571 NavigationController::LoadCommittedDetails details;
1572 if (!controller_.RendererDidNavigate(params, &details))
1573 return; // No navigation happened.
1574
1575 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
1576 // for the appropriate notification (best) or you can add it to
1577 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
1578 // necessary, please).
1579
1580 // Run post-commit tasks.
1581 if (details.is_main_frame)
1582 DidNavigateMainFramePostCommit(details, params);
1583 DidNavigateAnyFramePostCommit(rvh, details, params);
1584}
1585
1586void TabContents::UpdateState(RenderViewHost* rvh,
1587 int32 page_id,
1588 const std::string& state) {
1589 DCHECK(rvh == render_view_host());
1590
1591 // We must be prepared to handle state updates for any page, these occur
1592 // when the user is scrolling and entering form data, as well as when we're
1593 // leaving a page, in which case our state may have already been moved to
1594 // the next page. The navigation controller will look up the appropriate
1595 // NavigationEntry and update it when it is notified via the delegate.
1596
1597 int entry_index = controller_.GetEntryIndexWithPageID(
1598 GetSiteInstance(), page_id);
1599 if (entry_index < 0)
1600 return;
1601 NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
1602
1603 if (state == entry->content_state())
1604 return; // Nothing to update.
1605 entry->set_content_state(state);
1606 controller_.NotifyEntryChanged(entry, entry_index);
1607}
1608
1609void TabContents::UpdateTitle(RenderViewHost* rvh,
1610 int32 page_id, const std::wstring& title) {
1611 // If we have a title, that's a pretty good indication that we've started
1612 // getting useful data.
1613 SetNotWaitingForResponse();
1614
1615 DCHECK(rvh == render_view_host());
1616 NavigationEntry* entry = controller_.GetEntryWithPageID(GetSiteInstance(),
1617 page_id);
1618 if (!entry || !UpdateTitleForEntry(entry, title))
1619 return;
1620
1621 // Broadcast notifications when the UI should be updated.
1622 if (entry == controller_.GetEntryAtOffset(0))
[email protected]c9cd2222009-05-06 05:16:501623 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:321624}
1625
[email protected]420ae012009-04-24 05:16:321626void TabContents::UpdateEncoding(RenderViewHost* render_view_host,
1627 const std::wstring& encoding) {
1628 set_encoding(encoding);
1629}
1630
1631void TabContents::UpdateTargetURL(int32 page_id, const GURL& url) {
1632 if (delegate())
1633 delegate()->UpdateTargetURL(this, url);
1634}
1635
1636void TabContents::UpdateThumbnail(const GURL& url,
1637 const SkBitmap& bitmap,
1638 const ThumbnailScore& score) {
1639 // Tell History about this thumbnail
[email protected]449478302009-06-09 20:04:281640 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kThumbnailStore)) {
1641 profile()->GetThumbnailStore()->
1642 SetPageThumbnail(url, bitmap, score, !profile()->IsOffTheRecord());
1643 } else {
1644 HistoryService* hs;
1645 if (!profile()->IsOffTheRecord() &&
1646 (hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS))) {
1647 hs->SetPageThumbnail(url, bitmap, score);
1648 }
[email protected]420ae012009-04-24 05:16:321649 }
1650}
1651
[email protected]0df30122009-06-03 12:13:081652void TabContents::UpdateInspectorSettings(const std::wstring& raw_settings) {
1653 profile()->GetPrefs()->SetString(prefs::kWebKitInspectorSettings,
1654 raw_settings);
1655}
1656
[email protected]420ae012009-04-24 05:16:321657void TabContents::Close(RenderViewHost* rvh) {
1658 // Ignore this if it comes from a RenderViewHost that we aren't showing.
1659 if (delegate() && rvh == render_view_host())
1660 delegate()->CloseContents(this);
1661}
1662
1663void TabContents::RequestMove(const gfx::Rect& new_bounds) {
1664 if (delegate() && delegate()->IsPopup(this))
1665 delegate()->MoveContents(this, new_bounds);
1666}
1667
[email protected]329581b2009-04-28 06:52:351668void TabContents::DidStartLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321669 SetIsLoading(true, NULL);
1670}
1671
[email protected]329581b2009-04-28 06:52:351672void TabContents::DidStopLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321673 scoped_ptr<LoadNotificationDetails> details;
1674
1675 NavigationEntry* entry = controller_.GetActiveEntry();
1676 // An entry may not exist for a stop when loading an initial blank page or
1677 // if an iframe injected by script into a blank page finishes loading.
1678 if (entry) {
1679 scoped_ptr<base::ProcessMetrics> metrics(
1680 base::ProcessMetrics::CreateProcessMetrics(
1681 process()->process().handle()));
1682
1683 base::TimeDelta elapsed = base::TimeTicks::Now() - current_load_start_;
1684
1685 details.reset(new LoadNotificationDetails(
1686 entry->display_url(),
1687 entry->transition_type(),
1688 elapsed,
1689 &controller_,
1690 controller_.GetCurrentEntryIndex()));
1691 }
1692
1693 // Tell PasswordManager we've finished a page load, which serves as a
1694 // green light to save pending passwords and reset itself.
1695 GetPasswordManager()->DidStopLoading();
1696
1697 SetIsLoading(false, details.get());
1698}
1699
1700void TabContents::DidStartProvisionalLoadForFrame(
1701 RenderViewHost* render_view_host,
1702 bool is_main_frame,
1703 const GURL& url) {
1704 ProvisionalLoadDetails details(is_main_frame,
1705 controller_.IsURLInPageNavigation(url),
1706 url, std::string(), false);
1707 NotificationService::current()->Notify(
1708 NotificationType::FRAME_PROVISIONAL_LOAD_START,
1709 Source<NavigationController>(&controller_),
1710 Details<ProvisionalLoadDetails>(&details));
1711}
1712
1713void TabContents::DidRedirectProvisionalLoad(int32 page_id,
1714 const GURL& source_url,
1715 const GURL& target_url) {
1716 NavigationEntry* entry;
1717 if (page_id == -1)
1718 entry = controller_.pending_entry();
1719 else
1720 entry = controller_.GetEntryWithPageID(GetSiteInstance(), page_id);
1721 if (!entry || entry->url() != source_url)
1722 return;
1723 entry->set_url(target_url);
1724}
1725
1726void TabContents::DidLoadResourceFromMemoryCache(
1727 const GURL& url,
1728 const std::string& frame_origin,
1729 const std::string& main_frame_origin,
1730 const std::string& security_info) {
1731 // Send out a notification that we loaded a resource from our memory cache.
1732 int cert_id = 0, cert_status = 0, security_bits = 0;
1733 SSLManager::DeserializeSecurityInfo(security_info,
1734 &cert_id, &cert_status,
1735 &security_bits);
1736 LoadFromMemoryCacheDetails details(url, frame_origin, main_frame_origin,
[email protected]9ae66cbf2009-05-12 16:21:031737 process()->pid(), cert_id, cert_status);
[email protected]420ae012009-04-24 05:16:321738
1739 NotificationService::current()->Notify(
1740 NotificationType::LOAD_FROM_MEMORY_CACHE,
1741 Source<NavigationController>(&controller_),
1742 Details<LoadFromMemoryCacheDetails>(&details));
1743}
1744
1745void TabContents::DidFailProvisionalLoadWithError(
1746 RenderViewHost* render_view_host,
1747 bool is_main_frame,
1748 int error_code,
1749 const GURL& url,
1750 bool showing_repost_interstitial) {
1751 if (net::ERR_ABORTED == error_code) {
1752 // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
1753 // This means that the interstitial won't be torn down properly, which is
1754 // bad. But if we have an interstitial, go back to another tab type, and
1755 // then load the same interstitial again, we could end up getting the first
1756 // interstitial's "failed" message (as a result of the cancel) when we're on
1757 // the second one.
1758 //
1759 // We can't tell this apart, so we think we're tearing down the current page
1760 // which will cause a crash later one. There is also some code in
1761 // RenderViewHostManager::RendererAbortedProvisionalLoad that is commented
1762 // out because of this problem.
1763 //
1764 // http://code.google.com/p/chromium/issues/detail?id=2855
1765 // Because this will not tear down the interstitial properly, if "back" is
1766 // back to another tab type, the interstitial will still be somewhat alive
1767 // in the previous tab type. If you navigate somewhere that activates the
1768 // tab with the interstitial again, you'll see a flash before the new load
1769 // commits of the interstitial page.
1770 if (showing_interstitial_page()) {
1771 LOG(WARNING) << "Discarding message during interstitial.";
1772 return;
1773 }
1774
1775 // This will discard our pending entry if we cancelled the load (e.g., if we
1776 // decided to download the file instead of load it). Only discard the
1777 // pending entry if the URLs match, otherwise the user initiated a navigate
1778 // before the page loaded so that the discard would discard the wrong entry.
1779 NavigationEntry* pending_entry = controller_.pending_entry();
1780 if (pending_entry && pending_entry->url() == url)
1781 controller_.DiscardNonCommittedEntries();
1782
1783 render_manager_.RendererAbortedProvisionalLoad(render_view_host);
1784 }
1785
1786 // Send out a notification that we failed a provisional load with an error.
1787 ProvisionalLoadDetails details(is_main_frame,
1788 controller_.IsURLInPageNavigation(url),
1789 url, std::string(), false);
1790 details.set_error_code(error_code);
1791
1792 NotificationService::current()->Notify(
1793 NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR,
1794 Source<NavigationController>(&controller_),
1795 Details<ProvisionalLoadDetails>(&details));
1796}
1797
1798void TabContents::UpdateFavIconURL(RenderViewHost* render_view_host,
1799 int32 page_id,
1800 const GURL& icon_url) {
1801 fav_icon_helper_.SetFavIconURL(icon_url);
1802}
1803
1804void TabContents::DidDownloadImage(
1805 RenderViewHost* render_view_host,
1806 int id,
1807 const GURL& image_url,
1808 bool errored,
1809 const SkBitmap& image) {
1810 // A notification for downloading would be more flexible, but for now I'm
1811 // forwarding to the two places that could possibly have initiated the
1812 // request. If we end up with another place invoking DownloadImage, probably
1813 // best to refactor out into notification service, or something similar.
1814 if (errored)
1815 fav_icon_helper_.FavIconDownloadFailed(id);
1816 else
1817 fav_icon_helper_.SetFavIcon(id, image_url, image);
1818}
1819
1820void TabContents::RequestOpenURL(const GURL& url, const GURL& referrer,
1821 WindowOpenDisposition disposition) {
1822 if (render_manager_.dom_ui()) {
1823 // When we're a DOM UI, it will provide a page transition type for us (this
1824 // is so the new tab page can specify AUTO_BOOKMARK for automatically
1825 // generated suggestions).
1826 //
1827 // Note also that we hide the referrer for DOM UI pages. We don't really
[email protected]60e448982009-05-06 04:21:161828 // want web sites to see a referrer of "chrome://blah" (and some
1829 // chrome: URLs might have search terms or other stuff we don't want to
[email protected]420ae012009-04-24 05:16:321830 // send to the site), so we send no referrer.
1831 OpenURL(url, GURL(), disposition,
1832 render_manager_.dom_ui()->link_transition_type());
1833 } else {
1834 OpenURL(url, referrer, disposition, PageTransition::LINK);
1835 }
1836}
1837
1838void TabContents::DomOperationResponse(const std::string& json_string,
1839 int automation_id) {
1840 DomOperationNotificationDetails details(json_string, automation_id);
1841 NotificationService::current()->Notify(
[email protected]d82ed61e2009-06-16 02:46:221842 NotificationType::DOM_OPERATION_RESPONSE, Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321843 Details<DomOperationNotificationDetails>(&details));
1844}
1845
1846void TabContents::ProcessDOMUIMessage(const std::string& message,
1847 const std::string& content) {
1848 if (!render_manager_.dom_ui()) {
1849 // We shouldn't get a DOM UI message when we haven't enabled the DOM UI.
1850 // Because the renderer might be owned and sending random messages, we need
1851 // to ignore these inproper ones.
1852 NOTREACHED();
1853 return;
1854 }
1855 render_manager_.dom_ui()->ProcessDOMUIMessage(message, content);
1856}
1857
[email protected]b8028622009-06-15 08:20:171858void TabContents::DocumentLoadedInFrame() {
1859 controller_.DocumentLoadedInFrame();
1860}
1861
[email protected]420ae012009-04-24 05:16:321862void TabContents::ProcessExternalHostMessage(const std::string& message,
1863 const std::string& origin,
1864 const std::string& target) {
1865 if (delegate())
1866 delegate()->ForwardMessageToExternalHost(message, origin, target);
1867}
1868
1869void TabContents::GoToEntryAtOffset(int offset) {
1870 controller_.GoToOffset(offset);
1871}
1872
1873void TabContents::GetHistoryListCount(int* back_list_count,
1874 int* forward_list_count) {
1875 int current_index = controller_.last_committed_entry_index();
1876 *back_list_count = current_index;
1877 *forward_list_count = controller_.entry_count() - current_index - 1;
1878}
1879
1880void TabContents::RunFileChooser(bool multiple_files,
1881 const string16& title,
1882 const FilePath& default_file) {
1883 if (!select_file_dialog_.get())
1884 select_file_dialog_ = SelectFileDialog::Create(this);
1885 SelectFileDialog::Type dialog_type =
1886 multiple_files ? SelectFileDialog::SELECT_OPEN_MULTI_FILE :
1887 SelectFileDialog::SELECT_OPEN_FILE;
1888 select_file_dialog_->SelectFile(dialog_type, title, default_file,
1889 NULL, 0, FILE_PATH_LITERAL(""),
1890 view_->GetTopLevelNativeWindow(), NULL);
1891}
1892
1893void TabContents::RunJavaScriptMessage(
1894 const std::wstring& message,
1895 const std::wstring& default_prompt,
1896 const GURL& frame_url,
1897 const int flags,
1898 IPC::Message* reply_msg,
1899 bool* did_suppress_message) {
1900 // Suppress javascript messages when requested and when inside a constrained
1901 // popup window (because that activates them and breaks them out of the
1902 // constrained window jail).
1903 bool suppress_this_message = suppress_javascript_messages_;
1904 if (delegate())
1905 suppress_this_message |=
[email protected]b6c874582009-05-08 19:38:311906 (delegate()->GetConstrainingContents(this) != this);
[email protected]420ae012009-04-24 05:16:321907
1908 *did_suppress_message = suppress_this_message;
1909
1910 if (!suppress_this_message) {
1911 base::TimeDelta time_since_last_message(
1912 base::TimeTicks::Now() - last_javascript_message_dismissal_);
1913 bool show_suppress_checkbox = false;
1914 // Show a checkbox offering to suppress further messages if this message is
1915 // being displayed within kJavascriptMessageExpectedDelay of the last one.
1916 if (time_since_last_message <
1917 base::TimeDelta::FromMilliseconds(kJavascriptMessageExpectedDelay))
1918 show_suppress_checkbox = true;
1919
[email protected]d82ed61e2009-06-16 02:46:221920 RunJavascriptMessageBox(this, frame_url, flags, message, default_prompt,
[email protected]420ae012009-04-24 05:16:321921 show_suppress_checkbox, reply_msg);
1922 } else {
1923 // If we are suppressing messages, just reply as is if the user immediately
1924 // pressed "Cancel".
1925 OnJavaScriptMessageBoxClosed(reply_msg, false, std::wstring());
1926 }
1927}
1928
1929void TabContents::RunBeforeUnloadConfirm(const std::wstring& message,
1930 IPC::Message* reply_msg) {
[email protected]d82ed61e2009-06-16 02:46:221931 RunBeforeUnloadDialog(this, message, reply_msg);
[email protected]420ae012009-04-24 05:16:321932}
1933
1934void TabContents::ShowModalHTMLDialog(const GURL& url, int width, int height,
1935 const std::string& json_arguments,
1936 IPC::Message* reply_msg) {
1937 if (delegate()) {
1938 HtmlDialogUIDelegate* dialog_delegate =
1939 new ModalHtmlDialogDelegate(url, width, height, json_arguments,
[email protected]d82ed61e2009-06-16 02:46:221940 reply_msg, this);
[email protected]420ae012009-04-24 05:16:321941 delegate()->ShowHtmlDialog(dialog_delegate, NULL);
1942 }
1943}
1944
1945void TabContents::PasswordFormsSeen(
1946 const std::vector<PasswordForm>& forms) {
1947 GetPasswordManager()->PasswordFormsSeen(forms);
1948}
1949
1950void TabContents::AutofillFormSubmitted(
[email protected]daa8c58e2009-06-15 17:21:101951 const webkit_glue::AutofillForm& form) {
[email protected]420ae012009-04-24 05:16:321952 GetAutofillManager()->AutofillFormSubmitted(form);
1953}
1954
1955void TabContents::GetAutofillSuggestions(const std::wstring& field_name,
1956 const std::wstring& user_text, int64 node_id, int request_id) {
1957 GetAutofillManager()->FetchValuesForName(field_name, user_text,
1958 kMaxAutofillMenuItems, node_id, request_id);
1959}
1960
1961void TabContents::RemoveAutofillEntry(const std::wstring& field_name,
1962 const std::wstring& value) {
1963 GetAutofillManager()->RemoveValueForName(field_name, value);
1964}
1965
1966// Checks to see if we should generate a keyword based on the OSDD, and if
1967// necessary uses TemplateURLFetcher to download the OSDD and create a keyword.
1968void TabContents::PageHasOSDD(RenderViewHost* render_view_host,
1969 int32 page_id, const GURL& url,
1970 bool autodetected) {
1971 // Make sure page_id is the current page, and the TemplateURLModel is loaded.
1972 DCHECK(url.is_valid());
1973 if (!IsActiveEntry(page_id))
1974 return;
1975 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
1976 if (!url_model)
1977 return;
1978 if (!url_model->loaded()) {
1979 url_model->Load();
1980 return;
1981 }
1982 if (!profile()->GetTemplateURLFetcher())
1983 return;
1984
1985 if (profile()->IsOffTheRecord())
1986 return;
1987
1988 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
1989 DCHECK(entry);
1990
1991 const NavigationEntry* base_entry = entry;
1992 if (IsFormSubmit(base_entry)) {
1993 // If the current page is a form submit, find the last page that was not
1994 // a form submit and use its url to generate the keyword from.
1995 int index = controller_.last_committed_entry_index() - 1;
1996 while (index >= 0 && IsFormSubmit(controller_.GetEntryAtIndex(index)))
1997 index--;
1998 if (index >= 0)
1999 base_entry = controller_.GetEntryAtIndex(index);
2000 else
2001 base_entry = NULL;
2002 }
2003
2004 // We want to use the user typed URL if available since that represents what
2005 // the user typed to get here, and fall back on the regular URL if not.
2006 if (!base_entry)
2007 return;
2008 GURL keyword_url = base_entry->user_typed_url().is_valid() ?
2009 base_entry->user_typed_url() : base_entry->url();
2010 if (!keyword_url.is_valid())
2011 return;
2012 std::wstring keyword = TemplateURLModel::GenerateKeyword(keyword_url,
2013 autodetected);
2014 if (keyword.empty())
2015 return;
2016 const TemplateURL* template_url =
2017 url_model->GetTemplateURLForKeyword(keyword);
2018 if (template_url && (!template_url->safe_for_autoreplace() ||
2019 template_url->originating_url() == url)) {
2020 // Either there is a user created TemplateURL for this keyword, or the
2021 // keyword has the same OSDD url and we've parsed it.
2022 return;
2023 }
2024
2025 // Download the OpenSearch description document. If this is successful a
2026 // new keyword will be created when done.
2027#if defined(OS_WIN)
2028 gfx::NativeView ancestor = GetAncestor(view_->GetNativeView(), GA_ROOT);
2029#else
2030 gfx::NativeView ancestor = NULL;
2031#endif
2032 profile()->GetTemplateURLFetcher()->ScheduleDownload(
2033 keyword,
2034 url,
2035 base_entry->favicon().url(),
2036 ancestor,
2037 autodetected);
2038}
2039
2040void TabContents::InspectElementReply(int num_resources) {
2041 // We have received reply from inspect element request. Notify the
2042 // automation provider in case we need to notify automation client.
2043 NotificationService::current()->Notify(
[email protected]d82ed61e2009-06-16 02:46:222044 NotificationType::DOM_INSPECT_ELEMENT_RESPONSE, Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:322045 Details<int>(&num_resources));
2046}
2047
2048void TabContents::DidGetPrintedPagesCount(int cookie, int number_pages) {
2049 printing_.DidGetPrintedPagesCount(cookie, number_pages);
2050}
2051
2052void TabContents::DidPrintPage(const ViewHostMsg_DidPrintPage_Params& params) {
2053 printing_.DidPrintPage(params);
2054}
2055
2056GURL TabContents::GetAlternateErrorPageURL() const {
2057 GURL url;
2058 // Disable alternate error pages when in OffTheRecord/Incognito mode.
2059 if (profile()->IsOffTheRecord())
2060 return url;
2061
2062 PrefService* prefs = profile()->GetPrefs();
2063 DCHECK(prefs);
2064 if (prefs->GetBoolean(prefs::kAlternateErrorPagesEnabled)) {
2065 url = google_util::AppendGoogleLocaleParam(GURL(kLinkDoctorBaseURL));
2066 url = google_util::AppendGoogleTLDParam(url);
2067 }
2068 return url;
2069}
2070
2071WebPreferences TabContents::GetWebkitPrefs() {
2072 PrefService* prefs = render_view_host()->process()->profile()->GetPrefs();
2073 bool isDomUI = false;
2074 return RenderViewHostDelegateHelper::GetWebkitPrefs(prefs, isDomUI);
2075}
2076
2077void TabContents::OnMissingPluginStatus(int status) {
2078#if defined(OS_WIN)
2079// TODO(PORT): pull in when plug-ins work
2080 GetPluginInstaller()->OnMissingPluginStatus(status);
2081#endif
2082}
2083
2084void TabContents::OnCrashedPlugin(const FilePath& plugin_path) {
2085#if defined(OS_WIN)
2086// TODO(PORT): pull in when plug-ins work
2087 DCHECK(!plugin_path.value().empty());
2088
2089 std::wstring plugin_name = plugin_path.ToWStringHack();
2090 scoped_ptr<FileVersionInfo> version_info(
2091 FileVersionInfo::CreateFileVersionInfo(plugin_path));
2092 if (version_info.get()) {
2093 const std::wstring& product_name = version_info->product_name();
2094 if (!product_name.empty())
2095 plugin_name = product_name;
2096 }
2097 AddInfoBar(new SimpleAlertInfoBarDelegate(
2098 this, l10n_util::GetStringF(IDS_PLUGIN_CRASHED_PROMPT, plugin_name),
2099 NULL));
2100#endif
2101}
2102
2103void TabContents::OnCrashedWorker() {
2104 AddInfoBar(new SimpleAlertInfoBarDelegate(
2105 this, l10n_util::GetString(IDS_WEBWORKER_CRASHED_PROMPT),
2106 NULL));
2107}
2108
2109void TabContents::OnJSOutOfMemory() {
2110 AddInfoBar(new SimpleAlertInfoBarDelegate(
2111 this, l10n_util::GetString(IDS_JS_OUT_OF_MEMORY_PROMPT), NULL));
2112}
2113
2114void TabContents::ShouldClosePage(bool proceed) {
2115 render_manager_.ShouldClosePage(proceed);
2116}
2117
2118void TabContents::OnCrossSiteResponse(int new_render_process_host_id,
2119 int new_request_id) {
[email protected]57c6a652009-05-04 07:58:342120 // Allows the TabContents to react when a cross-site response is ready to be
[email protected]420ae012009-04-24 05:16:322121 // delivered to a pending RenderViewHost. We must first run the onunload
2122 // handler of the old RenderViewHost before we can allow it to proceed.
2123 render_manager_.OnCrossSiteResponse(new_render_process_host_id,
2124 new_request_id);
2125}
2126
2127bool TabContents::CanBlur() const {
2128 return delegate() ? delegate()->CanBlur() : true;
2129}
2130
2131gfx::Rect TabContents::GetRootWindowResizerRect() const {
2132 if (delegate())
2133 return delegate()->GetRootWindowResizerRect();
2134 return gfx::Rect();
2135}
2136
2137void TabContents::RendererUnresponsive(RenderViewHost* rvh,
2138 bool is_during_unload) {
2139 if (is_during_unload) {
2140 // Hang occurred while firing the beforeunload/unload handler.
2141 // Pretend the handler fired so tab closing continues as if it had.
[email protected]829e7612009-04-25 01:15:112142 rvh->set_sudden_termination_allowed(true);
[email protected]420ae012009-04-24 05:16:322143
2144 if (!render_manager_.ShouldCloseTabOnUnresponsiveRenderer())
2145 return;
2146
2147 // If the tab hangs in the beforeunload/unload handler there's really
2148 // nothing we can do to recover. Pretend the unload listeners have
2149 // all fired and close the tab. If the hang is in the beforeunload handler
2150 // then the user will not have the option of cancelling the close.
2151 Close(rvh);
2152 return;
2153 }
2154
2155 if (render_view_host() && render_view_host()->IsRenderViewLive())
[email protected]d82ed61e2009-06-16 02:46:222156 HungRendererDialog::ShowForTabContents(this);
[email protected]420ae012009-04-24 05:16:322157}
2158
2159void TabContents::RendererResponsive(RenderViewHost* render_view_host) {
[email protected]d82ed61e2009-06-16 02:46:222160 HungRendererDialog::HideForTabContents(this);
[email protected]420ae012009-04-24 05:16:322161}
2162
2163void TabContents::LoadStateChanged(const GURL& url,
2164 net::LoadState load_state) {
2165 load_state_ = load_state;
[email protected]d686e812009-06-03 19:10:292166 std::wstring languages =
2167 profile()->GetPrefs()->GetString(prefs::kAcceptLanguages);
2168 load_state_host_.clear();
2169 std::string host = url.host();
2170 net::IDNToUnicode(host.c_str(), host.size(), languages, &load_state_host_);
[email protected]420ae012009-04-24 05:16:322171 if (load_state_ == net::LOAD_STATE_READING_RESPONSE)
2172 SetNotWaitingForResponse();
2173 if (is_loading())
[email protected]c9cd2222009-05-06 05:16:502174 NotifyNavigationStateChanged(INVALIDATE_LOAD | INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:322175}
2176
2177void TabContents::OnDidGetApplicationInfo(
2178 int32 page_id,
2179 const webkit_glue::WebApplicationInfo& info) {
2180 if (pending_install_.page_id != page_id)
2181 return; // The user clicked create on a separate page. Ignore this.
2182
2183 pending_install_.callback_functor =
2184 new GearsCreateShortcutCallbackFunctor(this);
2185 GearsCreateShortcut(
2186 info, pending_install_.title, pending_install_.url, pending_install_.icon,
2187 NewCallback(pending_install_.callback_functor,
2188 &GearsCreateShortcutCallbackFunctor::Run));
2189}
2190
[email protected]14ce83f2009-05-28 18:35:242191void TabContents::OnUserGesture() {
2192 // See comment in RenderViewHostDelegate::OnUserGesture as to why we do this.
2193#if defined(OS_WIN) || defined(OS_LINUX)
[email protected]420ae012009-04-24 05:16:322194 DownloadRequestManager* drm = g_browser_process->download_request_manager();
2195 if (drm)
2196 drm->OnUserGesture(this);
2197#endif
[email protected]b8028622009-06-15 08:20:172198 controller_.OnUserGesture();
[email protected]420ae012009-04-24 05:16:322199}
2200
2201void TabContents::OnFindReply(int request_id,
2202 int number_of_matches,
2203 const gfx::Rect& selection_rect,
2204 int active_match_ordinal,
2205 bool final_update) {
2206 // Ignore responses for requests other than the one we have most recently
2207 // issued. That way we won't act on stale results when the user has
2208 // already typed in another query.
2209 if (request_id != current_find_request_id_)
2210 return;
2211
2212 if (number_of_matches == -1)
[email protected]e491f1c2009-05-22 20:28:122213 number_of_matches = last_search_result_.number_of_matches();
[email protected]420ae012009-04-24 05:16:322214 if (active_match_ordinal == -1)
[email protected]e491f1c2009-05-22 20:28:122215 active_match_ordinal = last_search_result_.active_match_ordinal();
[email protected]420ae012009-04-24 05:16:322216
[email protected]2c355c282009-05-21 23:24:432217 gfx::Rect selection = selection_rect;
2218 if (selection.IsEmpty())
[email protected]e491f1c2009-05-22 20:28:122219 selection = last_search_result_.selection_rect();
[email protected]2c355c282009-05-21 23:24:432220
[email protected]420ae012009-04-24 05:16:322221 // Notify the UI, automation and any other observers that a find result was
2222 // found.
[email protected]e491f1c2009-05-22 20:28:122223 last_search_result_ = FindNotificationDetails(request_id, number_of_matches,
2224 selection, active_match_ordinal,
2225 final_update);
[email protected]420ae012009-04-24 05:16:322226 NotificationService::current()->Notify(
2227 NotificationType::FIND_RESULT_AVAILABLE,
2228 Source<TabContents>(this),
[email protected]e491f1c2009-05-22 20:28:122229 Details<FindNotificationDetails>(&last_search_result_));
[email protected]420ae012009-04-24 05:16:322230}
2231
[email protected]829e7612009-04-25 01:15:112232bool TabContents::IsExternalTabContainer() const {
[email protected]420ae012009-04-24 05:16:322233 if (!delegate())
[email protected]829e7612009-04-25 01:15:112234 return false;
[email protected]420ae012009-04-24 05:16:322235
[email protected]829e7612009-04-25 01:15:112236 return delegate()->IsExternalTabContainer();
[email protected]420ae012009-04-24 05:16:322237}
2238
2239void TabContents::FileSelected(const FilePath& path,
2240 int index, void* params) {
2241 render_view_host()->FileSelected(path);
2242}
2243
2244void TabContents::MultiFilesSelected(const std::vector<FilePath>& files,
2245 void* params) {
2246 render_view_host()->MultiFilesSelected(files);
2247}
2248
2249void TabContents::FileSelectionCanceled(void* params) {
2250 // If the user cancels choosing a file to upload we pass back an
2251 // empty vector.
2252 render_view_host()->MultiFilesSelected(std::vector<FilePath>());
2253}
2254
2255void TabContents::BeforeUnloadFiredFromRenderManager(
2256 bool proceed,
2257 bool* proceed_to_fire_unload) {
2258 if (delegate())
2259 delegate()->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
2260}
2261
2262void TabContents::UpdateRenderViewSizeForRenderManager() {
2263 // TODO(brettw) this is a hack. See TabContentsView::SizeContents.
2264 view_->SizeContents(view_->GetContainerSize());
2265}
2266
2267DOMUI* TabContents::CreateDOMUIForRenderManager(const GURL& url) {
[email protected]d82ed61e2009-06-16 02:46:222268 return DOMUIFactory::CreateDOMUIForURL(this, url);
[email protected]420ae012009-04-24 05:16:322269}
2270
2271NavigationEntry*
2272TabContents::GetLastCommittedNavigationEntryForRenderManager() {
2273 return controller_.GetLastCommittedEntry();
2274}
2275
2276bool TabContents::CreateRenderViewForRenderManager(
2277 RenderViewHost* render_view_host) {
2278 // When we're running a DOM UI, the RenderViewHost needs to be put in DOM UI
2279 // mode before CreateRenderView is called. When we're asked to create a
2280 // RenderView, that means it's for the pending entry, so we have to use the
2281 // pending DOM UI.
2282 if (render_manager_.pending_dom_ui())
2283 render_view_host->AllowDOMUIBindings();
2284
[email protected]1adff062009-06-02 18:39:552285 // Ditto for extension bindings.
2286 if (controller().pending_entry()->url().SchemeIs(chrome::kExtensionScheme))
2287 render_view_host->AllowExtensionBindings();
2288
[email protected]420ae012009-04-24 05:16:322289 RenderWidgetHostView* rwh_view = view_->CreateViewForWidget(render_view_host);
2290 if (!render_view_host->CreateRenderView())
2291 return false;
2292
2293 // Now that the RenderView has been created, we need to tell it its size.
2294 rwh_view->SetSize(view_->GetContainerSize());
2295
2296 UpdateMaxPageIDIfNecessary(render_view_host->site_instance(),
2297 render_view_host);
2298 return true;
2299}
2300
2301void TabContents::Observe(NotificationType type,
2302 const NotificationSource& source,
2303 const NotificationDetails& details) {
2304 switch (type.value) {
2305 case NotificationType::BOOKMARK_MODEL_LOADED:
2306 // BookmarkModel finished loading, fall through to update starred state.
2307 case NotificationType::URLS_STARRED: {
2308 // Somewhere, a URL has been starred.
2309 // Ignore notifications for profiles other than our current one.
2310 Profile* source_profile = Source<Profile>(source).ptr();
2311 if (!source_profile || !source_profile->IsSameProfile(profile()))
2312 return;
2313
2314 UpdateStarredStateForCurrentURL();
2315 break;
2316 }
2317 case NotificationType::PREF_CHANGED: {
2318 std::wstring* pref_name_in = Details<std::wstring>(details).ptr();
2319 DCHECK(Source<PrefService>(source).ptr() == profile()->GetPrefs());
2320 if (*pref_name_in == prefs::kAlternateErrorPagesEnabled) {
2321 UpdateAlternateErrorPageURL();
2322 } else if (*pref_name_in == prefs::kDefaultCharset ||
2323 StartsWithASCII(WideToUTF8(*pref_name_in), "webkit.webprefs.", true)
2324 ) {
2325 UpdateWebPreferences();
2326 } else {
2327 NOTREACHED() << "unexpected pref change notification" << *pref_name_in;
2328 }
2329 break;
2330 }
2331 case NotificationType::RENDER_WIDGET_HOST_DESTROYED:
2332 view_->RenderWidgetHostDestroyed(Source<RenderWidgetHost>(source).ptr());
2333 break;
2334
2335 case NotificationType::NAV_ENTRY_COMMITTED: {
2336 DCHECK(&controller_ == Source<NavigationController>(source).ptr());
2337
2338 NavigationController::LoadCommittedDetails& committed_details =
2339 *(Details<NavigationController::LoadCommittedDetails>(details).ptr());
2340 ExpireInfoBars(committed_details);
2341 break;
2342 }
2343
2344 default:
2345 NOTREACHED();
2346 }
2347}