blob: 38c6d19c0da77f6de17e658ad3ebd5e9e8c8641a [file] [log] [blame]
license.botbf09a502008-08-24 00:55:551// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
2// 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]420ae012009-04-24 05:16:3214#include "chrome/browser/bookmarks/bookmark_model.h"
[email protected]96d185d2009-04-24 03:28:5415#include "chrome/browser/browser_process.h"
initial.commit09911bf2008-07-26 23:55:2916#include "chrome/browser/cert_store.h"
[email protected]96d185d2009-04-24 03:28:5417#include "chrome/browser/debugger/devtools_manager.h"
[email protected]420ae012009-04-24 05:16:3218#include "chrome/browser/dom_operation_notification_details.h"
[email protected]96d185d2009-04-24 03:28:5419#include "chrome/browser/dom_ui/dom_ui.h"
20#include "chrome/browser/dom_ui/dom_ui_factory.h"
[email protected]bcef0dc02009-02-28 00:35:0221#include "chrome/browser/download/download_item_model.h"
[email protected]420ae012009-04-24 05:16:3222#include "chrome/browser/download/download_manager.h"
23#include "chrome/browser/download/download_request_manager.h"
[email protected]bcef0dc02009-02-28 00:35:0224#include "chrome/browser/download/download_shelf.h"
[email protected]420ae012009-04-24 05:16:3225#include "chrome/browser/gears_integration.h"
26#include "chrome/browser/google_util.h"
27#include "chrome/browser/jsmessage_box_handler.h"
28#include "chrome/browser/load_from_memory_cache_details.h"
29#include "chrome/browser/load_notification_details.h"
[email protected]fdd61c62009-04-22 19:22:5730#include "chrome/browser/password_manager/password_manager.h"
31#include "chrome/browser/plugin_installer.h"
[email protected]96d185d2009-04-24 03:28:5432#include "chrome/browser/renderer_host/render_widget_host_view.h"
33#include "chrome/browser/renderer_host/web_cache_manager.h"
[email protected]f3ec7742009-01-15 00:59:1634#include "chrome/browser/tab_contents/navigation_entry.h"
[email protected]57c6a652009-05-04 07:58:3435#include "chrome/browser/tab_contents/tab_contents.h"
[email protected]f3ec7742009-01-15 00:59:1636#include "chrome/browser/tab_contents/tab_contents_delegate.h"
[email protected]fdd61c62009-04-22 19:22:5737#include "chrome/browser/tab_contents/tab_contents_view.h"
[email protected]420ae012009-04-24 05:16:3238#include "chrome/browser/search_engines/template_url_fetcher.h"
39#include "chrome/browser/search_engines/template_url_model.h"
[email protected]35f7d212009-04-29 21:19:2740#include "chrome/common/chrome_switches.h"
[email protected]bfd04a62009-02-01 18:16:5641#include "chrome/common/notification_service.h"
initial.commit09911bf2008-07-26 23:55:2942#include "chrome/common/pref_names.h"
[email protected]1eb89e82008-08-15 12:27:0343#include "chrome/common/pref_service.h"
[email protected]420ae012009-04-24 05:16:3244#include "chrome/common/render_messages.h"
[email protected]96d185d2009-04-24 03:28:5445#include "chrome/common/url_constants.h"
[email protected]420ae012009-04-24 05:16:3246//#include "grit/generated_resources.h"
47#include "grit/locale_settings.h"
48#include "net/base/mime_util.h"
49#include "net/base/net_errors.h"
50#include "net/base/registry_controlled_domain.h"
[email protected]3e45ba92009-02-20 21:09:0051
52#if defined(OS_WIN)
53// TODO(port): some of these headers should be ported.
[email protected]420ae012009-04-24 05:16:3254#include "chrome/browser/modal_html_dialog_delegate.h"
[email protected]3e45ba92009-02-20 21:09:0055#include "chrome/browser/tab_contents/infobar_delegate.h"
[email protected]3e45ba92009-02-20 21:09:0056#include "chrome/browser/views/blocked_popup_container.h"
[email protected]420ae012009-04-24 05:16:3257#include "chrome/browser/views/download_started_animation.h"
58#include "chrome/browser/views/hung_renderer_view.h" // TODO(brettw) delete me.
[email protected]6f329092009-03-17 04:56:5559#include "chrome/views/controls/scrollbar/native_scroll_bar.h"
[email protected]3e45ba92009-02-20 21:09:0060#endif
initial.commit09911bf2008-07-26 23:55:2961
[email protected]420ae012009-04-24 05:16:3262#include "grit/generated_resources.h"
63
64// Cross-Site Navigations
65//
66// If a TabContents is told to navigate to a different web site (as determined
67// by SiteInstance), it will replace its current RenderViewHost with a new
68// RenderViewHost dedicated to the new SiteInstance. This works as follows:
69//
70// - Navigate determines whether the destination is cross-site, and if so,
71// it creates a pending_render_view_host_ and moves into the PENDING
72// RendererState.
73// - The pending RVH is "suspended," so that no navigation messages are sent to
74// its renderer until the onbeforeunload JavaScript handler has a chance to
75// run in the current RVH.
76// - The pending RVH tells CrossSiteRequestManager (a thread-safe singleton)
77// that it has a pending cross-site request. ResourceDispatcherHost will
78// check for this when the response arrives.
79// - The current RVH runs its onbeforeunload handler. If it returns false, we
80// cancel all the pending logic and go back to NORMAL. Otherwise we allow
81// the pending RVH to send the navigation request to its renderer.
82// - ResourceDispatcherHost receives a ResourceRequest on the IO thread. It
83// checks CrossSiteRequestManager to see that the RVH responsible has a
84// pending cross-site request, and then installs a CrossSiteEventHandler.
85// - When RDH receives a response, the BufferedEventHandler determines whether
86// it is a download. If so, it sends a message to the new renderer causing
87// it to cancel the request, and the download proceeds in the download
88// thread. For now, we stay in a PENDING state (with a pending RVH) until
[email protected]57c6a652009-05-04 07:58:3489// the next DidNavigate event for this TabContents. This isn't ideal, but it
[email protected]420ae012009-04-24 05:16:3290// doesn't affect any functionality.
91// - After RDH receives a response and determines that it is safe and not a
92// download, it pauses the response to first run the old page's onunload
93// handler. It does this by asynchronously calling the OnCrossSiteResponse
[email protected]57c6a652009-05-04 07:58:3494// method of TabContents on the UI thread, which sends a ClosePage message
[email protected]420ae012009-04-24 05:16:3295// to the current RVH.
96// - Once the onunload handler is finished, a ClosePage_ACK message is sent to
97// the ResourceDispatcherHost, who unpauses the response. Data is then sent
98// to the pending RVH.
99// - The pending renderer sends a FrameNavigate message that invokes the
100// DidNavigate method. This replaces the current RVH with the
101// pending RVH and goes back to the NORMAL RendererState.
102
103namespace {
104
105// Amount of time we wait between when a key event is received and the renderer
106// is queried for its state and pushed to the NavigationEntry.
107const int kQueryStateDelay = 5000;
108
109const int kSyncWaitDelay = 40;
110
111// If another javascript message box is displayed within
112// kJavascriptMessageExpectedDelay of a previous javascript message box being
113// dismissed, display an option to suppress future message boxes from this
114// contents.
115const int kJavascriptMessageExpectedDelay = 1000;
116
117// Minimum amount of time in ms that has to elapse since the download shelf was
118// shown for us to hide it when navigating away from the current page.
119const int kDownloadShelfHideDelay = 5000;
120
121const 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]57c6a652009-05-04 07:58:34170// TODO(brettw) TabContents should be removed, then this hack is unnecessary.
171TabContents* AsWC(TabContents* tc) {
172 return static_cast<TabContents*>(tc);
[email protected]420ae012009-04-24 05:16:32173}
174
175} // namespace
176
177// -----------------------------------------------------------------------------
178
[email protected]fdd61c62009-04-22 19:22:57179// static
180int TabContents::find_request_id_counter_ = -1;
181
[email protected]420ae012009-04-24 05:16:32182class TabContents::GearsCreateShortcutCallbackFunctor {
183 public:
184 explicit GearsCreateShortcutCallbackFunctor(TabContents* contents)
185 : contents_(contents) {}
186
187 void Run(const GearsShortcutData2& shortcut_data, bool success) {
188 if (contents_)
189 contents_->OnGearsCreateShortcutDone(shortcut_data, success);
190 delete this;
191 }
192 void Cancel() {
193 contents_ = NULL;
194 }
195
196 private:
197 TabContents* contents_;
198};
199
[email protected]57c6a652009-05-04 07:58:34200// TODO(brettw) many of the data members here have casts to TabContents.
201// This object is the same as TabContents and is currently being merged.
[email protected]fdd61c62009-04-22 19:22:57202// When this merge is done, the casts can be removed.
[email protected]420ae012009-04-24 05:16:32203TabContents::TabContents(Profile* profile,
204 SiteInstance* site_instance,
205 int routing_id,
206 base::WaitableEvent* modal_dialog_event)
[email protected]b680ad22009-04-15 23:19:42207 : delegate_(NULL),
[email protected]ce3fa3c2009-04-20 19:55:57208 controller_(this, profile),
[email protected]57c6a652009-05-04 07:58:34209 view_(TabContentsView::Create(static_cast<TabContents*>(this))),
[email protected]fdd61c62009-04-22 19:22:57210 ALLOW_THIS_IN_INITIALIZER_LIST(render_manager_(
[email protected]57c6a652009-05-04 07:58:34211 static_cast<TabContents*>(this),
212 static_cast<TabContents*>(this))),
[email protected]fdd61c62009-04-22 19:22:57213 property_bag_(),
214 registrar_(),
[email protected]57c6a652009-05-04 07:58:34215 printing_(*static_cast<TabContents*>(this)),
[email protected]fdd61c62009-04-22 19:22:57216 save_package_(),
217 cancelable_consumer_(),
218 autofill_manager_(),
219 password_manager_(),
220 plugin_installer_(),
221 ALLOW_THIS_IN_INITIALIZER_LIST(fav_icon_helper_(
[email protected]57c6a652009-05-04 07:58:34222 static_cast<TabContents*>(this))),
[email protected]fdd61c62009-04-22 19:22:57223 select_file_dialog_(),
224 pending_install_(),
[email protected]d5f942ba2008-09-26 19:30:34225 is_loading_(false),
initial.commit09911bf2008-07-26 23:55:29226 is_crashed_(false),
[email protected]d5f942ba2008-09-26 19:30:34227 waiting_for_response_(false),
[email protected]d5f942ba2008-09-26 19:30:34228 max_page_id_(-1),
[email protected]fdd61c62009-04-22 19:22:57229 current_load_start_(),
230 load_state_(net::LOAD_STATE_IDLE),
231 load_state_host_(),
232 received_page_title_(false),
233 is_starred_(false),
234 contents_mime_type_(),
235 encoding_(),
236 download_shelf_(),
237 shelf_visible_(false),
[email protected]332af7732009-03-11 13:21:35238 blocked_popups_(NULL),
[email protected]fdd61c62009-04-22 19:22:57239 infobar_delegates_(),
240 last_download_shelf_show_(),
241 find_ui_active_(false),
242 find_op_aborted_(false),
243 current_find_request_id_(find_request_id_counter_++),
244 find_text_(),
245 find_prepopulate_text_(NULL),
246 find_result_(),
247 capturing_contents_(false),
248 is_being_destroyed_(false),
249 notify_disconnection_(false),
250 history_requests_(),
251#if defined(OS_WIN)
252 message_box_active_(CreateEvent(NULL, TRUE, FALSE, NULL)),
253#endif
254 last_javascript_message_dismissal_(),
255 suppress_javascript_messages_(false) {
[email protected]420ae012009-04-24 05:16:32256
257 pending_install_.page_id = 0;
258 pending_install_.callback_functor = NULL;
259
260 render_manager_.Init(profile, site_instance, routing_id, modal_dialog_event);
261
262 view_->CreateView();
263
264 // Register for notifications about all interested prefs change.
265 PrefService* prefs = profile->GetPrefs();
266 if (prefs) {
267 for (int i = 0; i < kPrefsToObserveLength; ++i)
268 prefs->AddPrefObserver(kPrefsToObserve[i], this);
269 }
270
271 // Register for notifications about URL starredness changing on any profile.
272 registrar_.Add(this, NotificationType::URLS_STARRED,
273 NotificationService::AllSources());
274 registrar_.Add(this, NotificationType::BOOKMARK_MODEL_LOADED,
275 NotificationService::AllSources());
276 registrar_.Add(this, NotificationType::RENDER_WIDGET_HOST_DESTROYED,
277 NotificationService::AllSources());
278
279 // Keep a global copy of the previous search string (if any).
280 static string16 global_last_search = string16();
281 find_prepopulate_text_ = &global_last_search;
[email protected]332af7732009-03-11 13:21:35282}
initial.commit09911bf2008-07-26 23:55:29283
284TabContents::~TabContents() {
[email protected]420ae012009-04-24 05:16:32285 is_being_destroyed_ = true;
286
287 // We don't want any notifications while we're runnign our destructor.
288 registrar_.RemoveAll();
289
290 // Unregister the notifications of all observed prefs change.
291 PrefService* prefs = profile()->GetPrefs();
292 if (prefs) {
293 for (int i = 0; i < kPrefsToObserveLength; ++i)
294 prefs->RemovePrefObserver(kPrefsToObserve[i], this);
295 }
296
297 // Clean up subwindows like plugins and the find in page bar.
298 view_->OnContentsDestroy();
299
300 NotifyDisconnected();
[email protected]57c6a652009-05-04 07:58:34301 HungRendererWarning::HideForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:32302
303 if (pending_install_.callback_functor)
304 pending_install_.callback_functor->Cancel();
305
306 // First cleanly close all child windows.
307 // TODO(mpcomplete): handle case if MaybeCloseChildWindows() already asked
308 // some of these to close. CloseWindows is async, so it might get called
309 // twice before it runs.
310 int size = static_cast<int>(child_windows_.size());
311 for (int i = size - 1; i >= 0; --i) {
312 ConstrainedWindow* window = child_windows_[i];
313 if (window)
314 window->CloseConstrainedWindow();
315 }
316
317 // Notify any lasting InfobarDelegates that have not yet been removed that
318 // whatever infobar they were handling in this TabContents has closed,
319 // because the TabContents is going away entirely.
320 for (int i = 0; i < infobar_delegate_count(); ++i) {
321 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
322 delegate->InfoBarClosed();
323 }
324 infobar_delegates_.clear();
325
326 // Notify any observer that have a reference on this tab contents.
327 NotificationService::current()->Notify(
328 NotificationType::TAB_CONTENTS_DESTROYED,
329 Source<TabContents>(this),
330 NotificationService::NoDetails());
331
332 // TODO(brettw) this should be moved to the view.
333#if defined(OS_WIN)
334 // If we still have a window handle, destroy it. GetNativeView can return
335 // NULL if this contents was part of a window that closed.
336 if (GetNativeView())
337 ::DestroyWindow(GetNativeView());
338#endif
initial.commit09911bf2008-07-26 23:55:29339}
340
[email protected]d5f942ba2008-09-26 19:30:34341// static
342void TabContents::RegisterUserPrefs(PrefService* prefs) {
[email protected]420ae012009-04-24 05:16:32343 prefs->RegisterBooleanPref(prefs::kAlternateErrorPagesEnabled, true);
344
345 WebPreferences pref_defaults;
346 prefs->RegisterBooleanPref(prefs::kWebKitJavascriptEnabled,
347 pref_defaults.javascript_enabled);
348 prefs->RegisterBooleanPref(prefs::kWebKitWebSecurityEnabled,
349 pref_defaults.web_security_enabled);
350 prefs->RegisterBooleanPref(
351 prefs::kWebKitJavascriptCanOpenWindowsAutomatically, true);
352 prefs->RegisterBooleanPref(prefs::kWebKitLoadsImagesAutomatically,
353 pref_defaults.loads_images_automatically);
354 prefs->RegisterBooleanPref(prefs::kWebKitPluginsEnabled,
355 pref_defaults.plugins_enabled);
356 prefs->RegisterBooleanPref(prefs::kWebKitDomPasteEnabled,
357 pref_defaults.dom_paste_enabled);
358 prefs->RegisterBooleanPref(prefs::kWebKitShrinksStandaloneImagesToFit,
359 pref_defaults.shrinks_standalone_images_to_fit);
360 prefs->RegisterBooleanPref(prefs::kWebKitDeveloperExtrasEnabled,
361 true);
362 prefs->RegisterBooleanPref(prefs::kWebKitTextAreasAreResizable,
363 pref_defaults.text_areas_are_resizable);
364 prefs->RegisterBooleanPref(prefs::kWebKitJavaEnabled,
365 pref_defaults.java_enabled);
366
367 prefs->RegisterLocalizedStringPref(prefs::kAcceptLanguages,
368 IDS_ACCEPT_LANGUAGES);
369 prefs->RegisterLocalizedStringPref(prefs::kDefaultCharset,
370 IDS_DEFAULT_ENCODING);
371 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitStandardFontIsSerif,
372 IDS_STANDARD_FONT_IS_SERIF);
373 prefs->RegisterLocalizedStringPref(prefs::kWebKitFixedFontFamily,
374 IDS_FIXED_FONT_FAMILY);
375 prefs->RegisterLocalizedStringPref(prefs::kWebKitSerifFontFamily,
376 IDS_SERIF_FONT_FAMILY);
377 prefs->RegisterLocalizedStringPref(prefs::kWebKitSansSerifFontFamily,
378 IDS_SANS_SERIF_FONT_FAMILY);
379 prefs->RegisterLocalizedStringPref(prefs::kWebKitCursiveFontFamily,
380 IDS_CURSIVE_FONT_FAMILY);
381 prefs->RegisterLocalizedStringPref(prefs::kWebKitFantasyFontFamily,
382 IDS_FANTASY_FONT_FAMILY);
383 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFontSize,
384 IDS_DEFAULT_FONT_SIZE);
385 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFixedFontSize,
386 IDS_DEFAULT_FIXED_FONT_SIZE);
387 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumFontSize,
388 IDS_MINIMUM_FONT_SIZE);
389 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumLogicalFontSize,
390 IDS_MINIMUM_LOGICAL_FONT_SIZE);
391 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitUsesUniversalDetector,
392 IDS_USES_UNIVERSAL_DETECTOR);
393 prefs->RegisterLocalizedStringPref(prefs::kStaticEncodings,
394 IDS_STATIC_ENCODING_LIST);
395
[email protected]d5f942ba2008-09-26 19:30:34396 prefs->RegisterBooleanPref(prefs::kBlockPopups, false);
initial.commit09911bf2008-07-26 23:55:29397}
398
[email protected]d5f942ba2008-09-26 19:30:34399bool TabContents::SupportsURL(GURL* url) {
[email protected]6e95706d2009-04-23 22:55:01400 // TODO(brettw) remove this function.
[email protected]9423d9412009-04-14 22:13:55401 return true;
[email protected]d5f942ba2008-09-26 19:30:34402}
403
[email protected]6e95706d2009-04-23 22:55:01404AutofillManager* TabContents::GetAutofillManager() {
405 if (autofill_manager_.get() == NULL)
406 autofill_manager_.reset(new AutofillManager(this));
407 return autofill_manager_.get();
408}
409
410PasswordManager* TabContents::GetPasswordManager() {
411 if (password_manager_.get() == NULL)
412 password_manager_.reset(new PasswordManager(this));
413 return password_manager_.get();
414}
415
416PluginInstaller* TabContents::GetPluginInstaller() {
417 if (plugin_installer_.get() == NULL)
418 plugin_installer_.reset(new PluginInstaller(this));
419 return plugin_installer_.get();
420}
421
[email protected]d5f942ba2008-09-26 19:30:34422const GURL& TabContents::GetURL() const {
423 // We may not have a navigation entry yet
[email protected]ce3fa3c2009-04-20 19:55:57424 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34425 return entry ? entry->display_url() : GURL::EmptyGURL();
426}
427
[email protected]96d185d2009-04-24 03:28:54428const string16& TabContents::GetTitle() const {
429 DOMUI* our_dom_ui = render_manager_.pending_dom_ui() ?
430 render_manager_.pending_dom_ui() : render_manager_.dom_ui();
431 if (our_dom_ui) {
432 // Don't override the title in view source mode.
433 NavigationEntry* entry = controller_.GetActiveEntry();
434 if (!(entry && entry->IsViewSourceMode())) {
435 // Give the DOM UI the chance to override our title.
436 const string16& title = our_dom_ui->overridden_title();
437 if (!title.empty())
438 return title;
439 }
440 }
441
442 // We use the title for the last committed entry rather than a pending
443 // navigation entry. For example, when the user types in a URL, we want to
444 // keep the old page's title until the new load has committed and we get a new
445 // title.
446 // The exception is with transient pages, for which we really want to use
447 // their title, as they are not committed.
448 NavigationEntry* entry = controller_.GetTransientEntry();
449 if (entry)
450 return entry->GetTitleForDisplay(&controller_);
451
452 entry = controller_.GetLastCommittedEntry();
453 if (entry)
454 return entry->GetTitleForDisplay(&controller_);
455 else if (controller_.LoadingURLLazily())
456 return controller_.GetLazyTitle();
457 return EmptyString16();
458}
459
[email protected]d5f942ba2008-09-26 19:30:34460int32 TabContents::GetMaxPageID() {
461 if (GetSiteInstance())
462 return GetSiteInstance()->max_page_id();
463 else
464 return max_page_id_;
465}
466
467void TabContents::UpdateMaxPageID(int32 page_id) {
468 // Ensure both the SiteInstance and RenderProcessHost update their max page
[email protected]57c6a652009-05-04 07:58:34469 // IDs in sync. Only TabContents will also have site instances, except during
[email protected]d5f942ba2008-09-26 19:30:34470 // testing.
471 if (GetSiteInstance())
472 GetSiteInstance()->UpdateMaxPageID(page_id);
[email protected]57c6a652009-05-04 07:58:34473 process()->UpdateMaxPageID(page_id);
[email protected]d5f942ba2008-09-26 19:30:34474}
475
[email protected]96d185d2009-04-24 03:28:54476SiteInstance* TabContents::GetSiteInstance() const {
477 return render_manager_.current_host()->site_instance();
478}
479
[email protected]d5f942ba2008-09-26 19:30:34480const std::wstring TabContents::GetDefaultTitle() const {
481 return l10n_util::GetString(IDS_DEFAULT_TAB_TITLE);
482}
483
[email protected]96d185d2009-04-24 03:28:54484bool TabContents::ShouldDisplayURL() {
485 // Don't hide the url in view source mode.
486 NavigationEntry* entry = controller_.GetActiveEntry();
487 if (entry && entry->IsViewSourceMode())
488 return true;
489 DOMUI* dom_ui = GetDOMUIForCurrentState();
490 if (dom_ui)
491 return !dom_ui->should_hide_url();
492 return true;
493}
494
[email protected]d5f942ba2008-09-26 19:30:34495SkBitmap TabContents::GetFavIcon() const {
496 // Like GetTitle(), we also want to use the favicon for the last committed
497 // entry rather than a pending navigation entry.
[email protected]ce3fa3c2009-04-20 19:55:57498 NavigationEntry* entry = controller_.GetTransientEntry();
[email protected]cbab76d2008-10-13 22:42:47499 if (entry)
500 return entry->favicon().bitmap();
501
[email protected]ce3fa3c2009-04-20 19:55:57502 entry = controller_.GetLastCommittedEntry();
[email protected]d5f942ba2008-09-26 19:30:34503 if (entry)
504 return entry->favicon().bitmap();
[email protected]ce3fa3c2009-04-20 19:55:57505 else if (controller_.LoadingURLLazily())
506 return controller_.GetLazyFavIcon();
[email protected]d5f942ba2008-09-26 19:30:34507 return SkBitmap();
508}
509
[email protected]96d185d2009-04-24 03:28:54510bool TabContents::ShouldDisplayFavIcon() {
511 // Always display a throbber during pending loads.
512 if (controller_.GetLastCommittedEntry() && controller_.pending_entry())
513 return true;
514
515 DOMUI* dom_ui = GetDOMUIForCurrentState();
516 if (dom_ui)
517 return !dom_ui->hide_favicon();
518 return true;
519}
520
[email protected]3e45ba92009-02-20 21:09:00521#if defined(OS_WIN)
[email protected]d5f942ba2008-09-26 19:30:34522SecurityStyle TabContents::GetSecurityStyle() const {
523 // We may not have a navigation entry yet.
[email protected]ce3fa3c2009-04-20 19:55:57524 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34525 return entry ? entry->ssl().security_style() : SECURITY_STYLE_UNKNOWN;
526}
527
528bool TabContents::GetSSLEVText(std::wstring* ev_text,
529 std::wstring* ev_tooltip_text) const {
530 DCHECK(ev_text && ev_tooltip_text);
531 ev_text->clear();
532 ev_tooltip_text->clear();
533
[email protected]ce3fa3c2009-04-20 19:55:57534 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34535 if (!entry ||
536 net::IsCertStatusError(entry->ssl().cert_status()) ||
537 ((entry->ssl().cert_status() & net::CERT_STATUS_IS_EV) == 0))
538 return false;
539
540 scoped_refptr<net::X509Certificate> cert;
541 CertStore::GetSharedInstance()->RetrieveCert(entry->ssl().cert_id(), &cert);
542 if (!cert.get()) {
543 NOTREACHED();
544 return false;
545 }
546
547 return SSLManager::GetEVCertNames(*cert, ev_text, ev_tooltip_text);
548}
[email protected]76f68dc2009-03-10 20:31:32549#endif
[email protected]d5f942ba2008-09-26 19:30:34550
[email protected]96d185d2009-04-24 03:28:54551std::wstring TabContents::GetStatusText() const {
552 if (!is_loading() || load_state_ == net::LOAD_STATE_IDLE)
553 return std::wstring();
554
555 switch (load_state_) {
556 case net::LOAD_STATE_WAITING_FOR_CACHE:
557 return l10n_util::GetString(IDS_LOAD_STATE_WAITING_FOR_CACHE);
558 case net::LOAD_STATE_RESOLVING_PROXY_FOR_URL:
559 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_PROXY_FOR_URL);
560 case net::LOAD_STATE_RESOLVING_HOST:
561 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_HOST);
562 case net::LOAD_STATE_CONNECTING:
563 return l10n_util::GetString(IDS_LOAD_STATE_CONNECTING);
564 case net::LOAD_STATE_SENDING_REQUEST:
565 return l10n_util::GetString(IDS_LOAD_STATE_SENDING_REQUEST);
566 case net::LOAD_STATE_WAITING_FOR_RESPONSE:
567 return l10n_util::GetStringF(IDS_LOAD_STATE_WAITING_FOR_RESPONSE,
568 load_state_host_);
569 // Ignore net::LOAD_STATE_READING_RESPONSE and net::LOAD_STATE_IDLE
570 case net::LOAD_STATE_IDLE:
571 case net::LOAD_STATE_READING_RESPONSE:
572 break;
573 }
574
575 return std::wstring();
576}
577
[email protected]d5f942ba2008-09-26 19:30:34578void TabContents::SetIsCrashed(bool state) {
579 if (state == is_crashed_)
580 return;
581
582 is_crashed_ = state;
583 if (delegate_)
584 delegate_->ContentsStateChanged(this);
585}
586
587void TabContents::NotifyNavigationStateChanged(unsigned changed_flags) {
588 if (delegate_)
589 delegate_->NavigationStateChanged(this, changed_flags);
590}
591
[email protected]96d185d2009-04-24 03:28:54592void TabContents::DidBecomeSelected() {
593 controller_.SetActive(true);
594
595 if (render_widget_host_view())
596 render_widget_host_view()->DidBecomeSelected();
597
598 // If pid() is -1, that means the RenderProcessHost still hasn't been
599 // initialized. It'll register with CacheManagerHost when it is.
600 if (process()->pid() != -1)
601 WebCacheManager::GetInstance()->ObserveActivity(process()->pid());
602}
603
604void TabContents::WasHidden() {
605 if (!capturing_contents()) {
606 // |render_view_host()| can be NULL if the user middle clicks a link to open
607 // a tab in then background, then closes the tab before selecting it. This
608 // is because closing the tab calls TabContents::Destroy(), which removes
609 // the |render_view_host()|; then when we actually destroy the window,
610 // OnWindowPosChanged() notices and calls HideContents() (which calls us).
611 if (render_widget_host_view())
612 render_widget_host_view()->WasHidden();
613
614 // Loop through children and send WasHidden to them, too.
615 int count = static_cast<int>(child_windows_.size());
616 for (int i = count - 1; i >= 0; --i) {
617 ConstrainedWindow* window = child_windows_.at(i);
618 window->WasHidden();
619 }
620 }
621
622 NotificationService::current()->Notify(
623 NotificationType::TAB_CONTENTS_HIDDEN,
624 Source<TabContents>(this),
625 NotificationService::NoDetails());
626}
627
[email protected]d5f942ba2008-09-26 19:30:34628void TabContents::Activate() {
629 if (delegate_)
630 delegate_->ActivateContents(this);
631}
632
[email protected]96d185d2009-04-24 03:28:54633void TabContents::ShowContents() {
634 if (render_widget_host_view())
635 render_widget_host_view()->DidBecomeSelected();
636
637 // Loop through children and send DidBecomeSelected to them, too.
638 int count = static_cast<int>(child_windows_.size());
639 for (int i = count - 1; i >= 0; --i) {
640 ConstrainedWindow* window = child_windows_.at(i);
641 window->DidBecomeSelected();
642 }
643}
644
645void TabContents::HideContents() {
646 // TODO(pkasting): http://b/1239839 Right now we purposefully don't call
647 // our superclass HideContents(), because some callers want to be very picky
648 // about the order in which these get called. In addition to making the code
649 // here practically impossible to understand, this also means we end up
650 // calling TabContents::WasHidden() twice if callers call both versions of
[email protected]57c6a652009-05-04 07:58:34651 // HideContents() on a TabContents.
[email protected]96d185d2009-04-24 03:28:54652 WasHidden();
653}
654
[email protected]c0588052008-10-27 23:01:50655void TabContents::OpenURL(const GURL& url, const GURL& referrer,
[email protected]d5f942ba2008-09-26 19:30:34656 WindowOpenDisposition disposition,
657 PageTransition::Type transition) {
658 if (delegate_)
[email protected]c0588052008-10-27 23:01:50659 delegate_->OpenURLFromTab(this, url, referrer, disposition, transition);
[email protected]d5f942ba2008-09-26 19:30:34660}
661
662bool TabContents::NavigateToPendingEntry(bool reload) {
[email protected]96d185d2009-04-24 03:28:54663 const NavigationEntry& entry = *controller_.pending_entry();
664
665 RenderViewHost* dest_render_view_host = render_manager_.Navigate(entry);
666 if (!dest_render_view_host)
667 return false; // Unable to create the desired render view host.
668
669 // Tell DevTools agent that it is attached prior to the navigation.
670 DevToolsManager* dev_tools_manager = g_browser_process->devtools_manager();
671 if (dev_tools_manager) // NULL in unit tests.
[email protected]fab08162009-05-05 10:32:33672 dev_tools_manager->OnNavigatingToPendingEntry(*this,
673 dest_render_view_host);
[email protected]96d185d2009-04-24 03:28:54674
675 // Used for page load time metrics.
676 current_load_start_ = base::TimeTicks::Now();
677
678 // Navigate in the desired RenderViewHost.
679 dest_render_view_host->NavigateToEntry(entry, reload);
680
681 if (entry.page_id() == -1) {
682 // HACK!! This code suppresses javascript: URLs from being added to
683 // session history, which is what we want to do for javascript: URLs that
684 // do not generate content. What we really need is a message from the
685 // renderer telling us that a new page was not created. The same message
686 // could be used for mailto: URLs and the like.
687 if (entry.url().SchemeIs(chrome::kJavaScriptScheme))
688 return false;
689 }
690
691 // Clear any provisional password saves - this stops password infobars
692 // showing up on pages the user navigates to while the right page is
693 // loading.
694 GetPasswordManager()->ClearProvisionalSave();
695
696 if (reload && !profile()->IsOffTheRecord()) {
697 HistoryService* history =
698 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
699 if (history)
700 history->SetFavIconOutOfDateForPage(entry.url());
701 }
702
[email protected]d5f942ba2008-09-26 19:30:34703 return true;
704}
705
[email protected]96d185d2009-04-24 03:28:54706void TabContents::Stop() {
707 render_manager_.Stop();
708 printing_.Stop();
709}
710
711void TabContents::Cut() {
712 render_view_host()->Cut();
713}
714
715void TabContents::Copy() {
716 render_view_host()->Copy();
717}
718
719void TabContents::Paste() {
720 render_view_host()->Paste();
721}
722
723void TabContents::DisassociateFromPopupCount() {
724 render_view_host()->DisassociateFromPopupCount();
725}
726
727TabContents* TabContents::Clone() {
728 // We create a new SiteInstance so that the new tab won't share processes
729 // with the old one. This can be changed in the future if we need it to share
730 // processes for some reason.
[email protected]420ae012009-04-24 05:16:32731 TabContents* tc = new TabContents(profile(),
[email protected]96d185d2009-04-24 03:28:54732 SiteInstance::CreateSiteInstance(profile()),
733 MSG_ROUTING_NONE, NULL);
734 tc->controller().CopyStateFrom(controller_);
735 return tc;
736}
737
[email protected]420ae012009-04-24 05:16:32738void TabContents::CreateShortcut() {
739 NavigationEntry* entry = controller_.GetLastCommittedEntry();
740 if (!entry)
741 return;
742
743 // We only allow one pending install request. By resetting the page id we
744 // effectively cancel the pending install request.
745 pending_install_.page_id = entry->page_id();
746 pending_install_.icon = GetFavIcon();
747 pending_install_.title = UTF16ToWideHack(GetTitle());
748 pending_install_.url = GetURL();
749 if (pending_install_.callback_functor) {
750 pending_install_.callback_functor->Cancel();
751 pending_install_.callback_functor = NULL;
752 }
753 DCHECK(!pending_install_.icon.isNull()) << "Menu item should be disabled.";
754 if (pending_install_.title.empty())
755 pending_install_.title = UTF8ToWide(GetURL().spec());
756
757 // Request the application info. When done OnDidGetApplicationInfo is invoked
758 // and we'll create the shortcut.
759 render_view_host()->GetApplicationInfo(pending_install_.page_id);
760}
761
[email protected]76f68dc2009-03-10 20:31:32762#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29763ConstrainedWindow* TabContents::CreateConstrainedDialog(
[email protected]c2dacc92008-10-16 23:51:38764 views::WindowDelegate* window_delegate,
765 views::View* contents_view) {
initial.commit09911bf2008-07-26 23:55:29766 ConstrainedWindow* window =
767 ConstrainedWindow::CreateConstrainedDialog(
768 this, gfx::Rect(), contents_view, window_delegate);
769 child_windows_.push_back(window);
770 return window;
771}
[email protected]f3332e12009-03-23 15:28:57772#endif
initial.commit09911bf2008-07-26 23:55:29773
774void TabContents::AddNewContents(TabContents* new_contents,
775 WindowOpenDisposition disposition,
776 const gfx::Rect& initial_pos,
[email protected]c88a70fe2009-05-05 20:00:22777 bool user_gesture,
778 const GURL& creator_url) {
initial.commit09911bf2008-07-26 23:55:29779 if (!delegate_)
780 return;
781
[email protected]f3332e12009-03-23 15:28:57782#if defined(OS_WIN)
[email protected]35f7d212009-04-29 21:19:27783 if ((disposition == NEW_POPUP) && !user_gesture &&
784 !CommandLine::ForCurrentProcess()->HasSwitch(
785 switches::kDisablePopupBlocking)) {
[email protected]3b0a45e82008-10-13 21:01:03786 // Unrequested popups from normal pages are constrained.
787 TabContents* popup_owner = this;
788 TabContents* our_owner = delegate_->GetConstrainingContents(this);
789 if (our_owner)
790 popup_owner = our_owner;
791 popup_owner->AddConstrainedPopup(new_contents, initial_pos);
initial.commit09911bf2008-07-26 23:55:29792 } else {
[email protected]0aa55312008-10-17 21:53:08793 new_contents->DisassociateFromPopupCount();
794
initial.commit09911bf2008-07-26 23:55:29795 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
796 user_gesture);
[email protected]634a6f92008-12-01 21:39:31797
798 PopupNotificationVisibilityChanged(ShowingBlockedPopupNotification());
initial.commit09911bf2008-07-26 23:55:29799 }
[email protected]f3332e12009-03-23 15:28:57800#else
801 // TODO(port): implement the popup blocker stuff
802 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
803 user_gesture);
804#endif
initial.commit09911bf2008-07-26 23:55:29805}
806
[email protected]f3332e12009-03-23 15:28:57807#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29808void TabContents::AddConstrainedPopup(TabContents* new_contents,
809 const gfx::Rect& initial_pos) {
[email protected]d6598c052008-11-05 19:03:25810 if (!blocked_popups_) {
811 CRect client_rect;
[email protected]92edc472009-02-10 20:32:06812 GetClientRect(GetNativeView(), &client_rect);
[email protected]d6598c052008-11-05 19:03:25813 gfx::Point anchor_position(
814 client_rect.Width() -
815 views::NativeScrollBar::GetVerticalScrollBarWidth(),
816 client_rect.Height());
initial.commit09911bf2008-07-26 23:55:29817
[email protected]d6598c052008-11-05 19:03:25818 blocked_popups_ = BlockedPopupContainer::Create(
819 this, profile(), anchor_position);
820 child_windows_.push_back(blocked_popups_);
821 }
822
823 blocked_popups_->AddTabContents(new_contents, initial_pos);
[email protected]634a6f92008-12-01 21:39:31824 PopupNotificationVisibilityChanged(ShowingBlockedPopupNotification());
initial.commit09911bf2008-07-26 23:55:29825}
826
initial.commit09911bf2008-07-26 23:55:29827void TabContents::CloseAllSuppressedPopups() {
[email protected]d6598c052008-11-05 19:03:25828 if (blocked_popups_)
829 blocked_popups_->CloseAllPopups();
initial.commit09911bf2008-07-26 23:55:29830}
[email protected]332af7732009-03-11 13:21:35831#endif
initial.commit09911bf2008-07-26 23:55:29832
[email protected]96d185d2009-04-24 03:28:54833void TabContents::PopupNotificationVisibilityChanged(bool visible) {
834 render_view_host()->PopupNotificationVisibilityChanged(visible);
835}
836
837gfx::NativeView TabContents::GetContentNativeView() {
838 return view_->GetContentNativeView();
839}
840
841gfx::NativeView TabContents::GetNativeView() const {
842 return view_->GetNativeView();
843}
844
845void TabContents::GetContainerBounds(gfx::Rect *out) const {
846 view_->GetContainerBounds(out);
847}
848
849void TabContents::Focus() {
850 view_->Focus();
851}
852
853void TabContents::SetInitialFocus(bool reverse) {
854 render_view_host()->SetInitialFocus(reverse);
855}
856
857bool TabContents::FocusLocationBarByDefault() {
858 DOMUI* dom_ui = GetDOMUIForCurrentState();
859 if (dom_ui)
860 return dom_ui->focus_location_bar_by_default();
861 return false;
862}
863
[email protected]616ed5a2008-11-21 22:27:24864void TabContents::AddInfoBar(InfoBarDelegate* delegate) {
865 // Look through the existing InfoBarDelegates we have for a match. If we've
866 // already got one that matches, then we don't add the new one.
[email protected]f86a07022008-11-25 01:06:05867 for (int i = 0; i < infobar_delegate_count(); ++i) {
[email protected]616ed5a2008-11-21 22:27:24868 if (GetInfoBarDelegateAt(i)->EqualsDelegate(delegate))
869 return;
870 }
871
872 infobar_delegates_.push_back(delegate);
[email protected]bfd04a62009-02-01 18:16:56873 NotificationService::current()->Notify(
874 NotificationType::TAB_CONTENTS_INFOBAR_ADDED,
875 Source<TabContents>(this),
876 Details<InfoBarDelegate>(delegate));
[email protected]616ed5a2008-11-21 22:27:24877
878 // Add ourselves as an observer for navigations the first time a delegate is
879 // added. We use this notification to expire InfoBars that need to expire on
880 // page transitions.
881 if (infobar_delegates_.size() == 1) {
[email protected]bfd04a62009-02-01 18:16:56882 registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57883 Source<NavigationController>(&controller_));
[email protected]616ed5a2008-11-21 22:27:24884 }
885}
886
887void TabContents::RemoveInfoBar(InfoBarDelegate* delegate) {
888 std::vector<InfoBarDelegate*>::iterator it =
889 find(infobar_delegates_.begin(), infobar_delegates_.end(), delegate);
890 if (it != infobar_delegates_.end()) {
891 InfoBarDelegate* delegate = *it;
[email protected]bfd04a62009-02-01 18:16:56892 NotificationService::current()->Notify(
893 NotificationType::TAB_CONTENTS_INFOBAR_REMOVED,
894 Source<TabContents>(this),
895 Details<InfoBarDelegate>(delegate));
[email protected]f86a07022008-11-25 01:06:05896 infobar_delegates_.erase(it);
[email protected]616ed5a2008-11-21 22:27:24897
[email protected]6a02963e2009-01-06 16:58:03898 // Remove ourselves as an observer if we are tracking no more InfoBars.
899 if (infobar_delegates_.empty()) {
[email protected]bfd04a62009-02-01 18:16:56900 registrar_.Remove(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57901 Source<NavigationController>(&controller_));
[email protected]6a02963e2009-01-06 16:58:03902 }
[email protected]616ed5a2008-11-21 22:27:24903 }
904}
[email protected]3edd9522009-03-04 22:19:41905
[email protected]96d185d2009-04-24 03:28:54906bool TabContents::IsBookmarkBarAlwaysVisible() {
907 // See GetDOMUIForCurrentState() comment for more info. This case is very
908 // similar, but for non-first loads, we want to use the committed entry. This
909 // is so the bookmarks bar disappears at the same time the page does.
910 if (controller_.GetLastCommittedEntry()) {
911 // Not the first load, always use the committed DOM UI.
912 if (render_manager_.dom_ui())
913 return render_manager_.dom_ui()->force_bookmark_bar_visible();
914 return false; // Default.
915 }
916
917 // When it's the first load, we know either the pending one or the committed
918 // one will have the DOM UI in it (see GetDOMUIForCurrentState), and only one
919 // of them will be valid, so we can just check both.
920 if (render_manager_.pending_dom_ui())
921 return render_manager_.pending_dom_ui()->force_bookmark_bar_visible();
922 if (render_manager_.dom_ui())
923 return render_manager_.dom_ui()->force_bookmark_bar_visible();
924 return false; // Default.
925}
926
927void TabContents::SetDownloadShelfVisible(bool visible) {
928 if (shelf_visible_ != visible) {
929 if (visible) {
930 // Invoke GetDownloadShelf to force the shelf to be created.
931 GetDownloadShelf();
932 }
933 shelf_visible_ = visible;
934
935 if (delegate_)
936 delegate_->ContentsStateChanged(this);
937 }
938
939 // SetShelfVisible can force-close the shelf, so make sure we lay out
940 // everything correctly, as if the animation had finished. This doesn't
941 // matter for showing the shelf, as the show animation will do it.
942 ToolbarSizeChanged(false);
943
944 if (visible) {
945 // Always set this value as it reflects the last time the download shelf
946 // was made visible (even if it was already visible).
947 last_download_shelf_show_ = base::TimeTicks::Now();
948 }
949}
950
[email protected]3edd9522009-03-04 22:19:41951void TabContents::ToolbarSizeChanged(bool is_animating) {
952 TabContentsDelegate* d = delegate();
953 if (d)
954 d->ToolbarSizeChanged(this, is_animating);
955}
[email protected]616ed5a2008-11-21 22:27:24956
[email protected]d5f942ba2008-09-26 19:30:34957void TabContents::OnStartDownload(DownloadItem* download) {
958 DCHECK(download);
959 TabContents* tab_contents = this;
960
[email protected]3edd9522009-03-04 22:19:41961// TODO(port): port contraining contents.
962#if defined(OS_WIN)
[email protected]d5f942ba2008-09-26 19:30:34963 // Download in a constrained popup is shown in the tab that opened it.
964 TabContents* constraining_tab = delegate()->GetConstrainingContents(this);
965 if (constraining_tab)
966 tab_contents = constraining_tab;
[email protected]3edd9522009-03-04 22:19:41967#endif
[email protected]d5f942ba2008-09-26 19:30:34968
[email protected]bcef0dc02009-02-28 00:35:02969 // GetDownloadShelf creates the download shelf if it was not yet created.
970 tab_contents->GetDownloadShelf()->AddDownload(
971 new DownloadItemModel(download));
[email protected]d5f942ba2008-09-26 19:30:34972 tab_contents->SetDownloadShelfVisible(true);
973
[email protected]3edd9522009-03-04 22:19:41974// TODO(port): port animatinos.
975#if defined(OS_WIN)
[email protected]d5f942ba2008-09-26 19:30:34976 // This animation will delete itself when it finishes, or if we become hidden
977 // or destroyed.
[email protected]92edc472009-02-10 20:32:06978 if (IsWindowVisible(GetNativeView())) { // For minimized windows, unit
979 // tests, etc.
[email protected]d5f942ba2008-09-26 19:30:34980 new DownloadStartedAnimation(tab_contents);
981 }
[email protected]3edd9522009-03-04 22:19:41982#endif
[email protected]d5f942ba2008-09-26 19:30:34983}
984
[email protected]bcef0dc02009-02-28 00:35:02985DownloadShelf* TabContents::GetDownloadShelf() {
986 if (!download_shelf_.get())
987 download_shelf_.reset(DownloadShelf::Create(this));
988 return download_shelf_.get();
initial.commit09911bf2008-07-26 23:55:29989}
990
[email protected]bcef0dc02009-02-28 00:35:02991void TabContents::MigrateShelfFrom(TabContents* tab_contents) {
992 download_shelf_.reset(tab_contents->GetDownloadShelf());
993 download_shelf_->ChangeTabContents(tab_contents, this);
994 tab_contents->ReleaseDownloadShelf();
initial.commit09911bf2008-07-26 23:55:29995}
996
[email protected]3edd9522009-03-04 22:19:41997void TabContents::ReleaseDownloadShelf() {
998 download_shelf_.release();
999}
1000
1001// static
1002void TabContents::MigrateShelf(TabContents* from, TabContents* to) {
1003 bool was_shelf_visible = from->IsDownloadShelfVisible();
1004 if (was_shelf_visible)
1005 to->MigrateShelfFrom(from);
1006 to->SetDownloadShelfVisible(was_shelf_visible);
1007}
[email protected]3edd9522009-03-04 22:19:411008
[email protected]d5f942ba2008-09-26 19:30:341009void TabContents::WillClose(ConstrainedWindow* window) {
1010 ConstrainedWindowList::iterator it =
1011 find(child_windows_.begin(), child_windows_.end(), window);
1012 if (it != child_windows_.end())
1013 child_windows_.erase(it);
1014
[email protected]332af7732009-03-11 13:21:351015#if defined(OS_WIN)
[email protected]d6598c052008-11-05 19:03:251016 if (window == blocked_popups_)
1017 blocked_popups_ = NULL;
1018
[email protected]92edc472009-02-10 20:32:061019 if (::IsWindow(GetNativeView())) {
[email protected]d5f942ba2008-09-26 19:30:341020 CRect client_rect;
[email protected]92edc472009-02-10 20:32:061021 GetClientRect(GetNativeView(), &client_rect);
[email protected]d5f942ba2008-09-26 19:30:341022 RepositionSupressedPopupsToFit(
1023 gfx::Size(client_rect.Width(), client_rect.Height()));
1024 }
[email protected]332af7732009-03-11 13:21:351025#endif
[email protected]d5f942ba2008-09-26 19:30:341026}
1027
[email protected]d5f942ba2008-09-26 19:30:341028void TabContents::DidMoveOrResize(ConstrainedWindow* window) {
[email protected]332af7732009-03-11 13:21:351029#if defined(OS_WIN)
[email protected]92edc472009-02-10 20:32:061030 UpdateWindow(GetNativeView());
[email protected]332af7732009-03-11 13:21:351031#endif
[email protected]d5f942ba2008-09-26 19:30:341032}
1033
[email protected]6e95706d2009-04-23 22:55:011034void TabContents::StartFinding(const string16& find_text,
1035 bool forward_direction) {
1036 // If find_text is empty, it means FindNext was pressed with a keyboard
1037 // shortcut so unless we have something to search for we return early.
1038 if (find_text.empty() && find_text_.empty())
1039 return;
1040
1041 // This is a FindNext operation if we are searching for the same text again,
1042 // or if the passed in search text is empty (FindNext keyboard shortcut). The
1043 // exception to this is if the Find was aborted (then we don't want FindNext
1044 // because the highlighting has been cleared and we need it to reappear). We
1045 // therefore treat FindNext after an aborted Find operation as a full fledged
1046 // Find.
1047 bool find_next = (find_text_ == find_text || find_text.empty()) &&
1048 !find_op_aborted_;
1049 if (!find_next)
1050 current_find_request_id_ = find_request_id_counter_++;
1051
1052 if (!find_text.empty())
1053 find_text_ = find_text;
1054
1055 find_op_aborted_ = false;
1056
1057 // Keep track of what the last search was across the tabs.
1058 *find_prepopulate_text_ = find_text;
1059
1060 render_view_host()->StartFinding(current_find_request_id_,
1061 find_text_,
1062 forward_direction,
1063 false, // case sensitive
1064 find_next);
1065}
1066
1067void TabContents::StopFinding(bool clear_selection) {
1068 find_ui_active_ = false;
1069 find_op_aborted_ = true;
1070 find_result_ = FindNotificationDetails();
1071 render_view_host()->StopFinding(clear_selection);
1072}
1073
[email protected]420ae012009-04-24 05:16:321074void TabContents::OnJavaScriptMessageBoxClosed(IPC::Message* reply_msg,
1075 bool success,
1076 const std::wstring& prompt) {
1077 last_javascript_message_dismissal_ = base::TimeTicks::Now();
1078 render_manager_.OnJavaScriptMessageBoxClosed(reply_msg, success, prompt);
1079}
1080
1081void TabContents::OnSavePage() {
1082 // If we can not save the page, try to download it.
1083 if (!SavePackage::IsSavableContents(contents_mime_type())) {
1084 DownloadManager* dlm = profile()->GetDownloadManager();
1085 const GURL& current_page_url = GetURL();
1086 if (dlm && current_page_url.is_valid())
[email protected]c9825a42009-05-01 22:51:501087 dlm->DownloadUrl(current_page_url, GURL(), "", AsWC(this));
[email protected]420ae012009-04-24 05:16:321088 return;
1089 }
1090
1091 Stop();
1092
1093 // Create the save package and possibly prompt the user for the name to save
1094 // the page as. The user prompt is an asynchronous operation that runs on
1095 // another thread.
1096 save_package_ = new SavePackage(AsWC(this));
1097 save_package_->GetSaveInfo();
1098}
1099
1100// Used in automated testing to bypass prompting the user for file names.
1101// Instead, the names and paths are hard coded rather than running them through
1102// file name sanitation and extension / mime checking.
1103void TabContents::SavePage(const std::wstring& main_file,
1104 const std::wstring& dir_path,
1105 SavePackage::SavePackageType save_type) {
1106 // Stop the page from navigating.
1107 Stop();
1108
1109 save_package_ = new SavePackage(AsWC(this), save_type,
1110 FilePath::FromWStringHack(main_file),
1111 FilePath::FromWStringHack(dir_path));
1112 save_package_->Init();
1113}
1114
1115void TabContents::PrintPreview() {
1116 // We don't show the print preview yet, only the print dialog.
1117 PrintNow();
1118}
1119
1120bool TabContents::PrintNow() {
1121 // We can't print interstitial page for now.
1122 if (showing_interstitial_page())
1123 return false;
1124
1125 return render_view_host()->PrintPages();
1126}
1127
1128bool TabContents::IsActiveEntry(int32 page_id) {
1129 NavigationEntry* active_entry = controller_.GetActiveEntry();
1130 return (active_entry != NULL &&
1131 active_entry->site_instance() == GetSiteInstance() &&
1132 active_entry->page_id() == page_id);
1133}
1134
[email protected]96d185d2009-04-24 03:28:541135// Notifies the RenderWidgetHost instance about the fact that the page is
1136// loading, or done loading and calls the base implementation.
1137void TabContents::SetIsLoading(bool is_loading,
1138 LoadNotificationDetails* details) {
1139 if (is_loading == is_loading_)
1140 return;
1141
1142 if (!is_loading) {
1143 load_state_ = net::LOAD_STATE_IDLE;
1144 load_state_host_.clear();
1145 }
1146
1147 render_manager_.SetIsLoading(is_loading);
1148
1149 is_loading_ = is_loading;
1150 waiting_for_response_ = is_loading;
1151
1152 if (delegate_)
1153 delegate_->LoadingStateChanged(this);
[email protected]329581b2009-04-28 06:52:351154 NotifyNavigationStateChanged(INVALIDATE_LOAD);
[email protected]96d185d2009-04-24 03:28:541155
1156 NotificationType type = is_loading ? NotificationType::LOAD_START :
1157 NotificationType::LOAD_STOP;
1158 NotificationDetails det = NotificationService::NoDetails();;
1159 if (details)
1160 det = Details<LoadNotificationDetails>(details);
1161 NotificationService::current()->Notify(type,
1162 Source<NavigationController>(&controller_),
1163 det);
1164}
1165
[email protected]76f68dc2009-03-10 20:31:321166#if defined(OS_WIN)
[email protected]e69bce3dd2009-04-20 22:05:121167// TODO(brettw) This should be on the TabContentsView.
[email protected]d5f942ba2008-09-26 19:30:341168void TabContents::RepositionSupressedPopupsToFit(const gfx::Size& new_size) {
1169 // TODO(erg): There's no way to detect whether scroll bars are
1170 // visible, so for beta, we're just going to assume that the
1171 // vertical scroll bar is visible, and not care about covering up
1172 // the horizontal scroll bar. Fixing this is half of
1173 // http://b/1118139.
1174 gfx::Point anchor_position(
1175 new_size.width() -
[email protected]c2dacc92008-10-16 23:51:381176 views::NativeScrollBar::GetVerticalScrollBarWidth(),
[email protected]d5f942ba2008-09-26 19:30:341177 new_size.height());
[email protected]d6598c052008-11-05 19:03:251178
1179 if (blocked_popups_)
1180 blocked_popups_->RepositionConstrainedWindowTo(anchor_position);
[email protected]d5f942ba2008-09-26 19:30:341181}
1182
[email protected]b9681312008-11-07 00:08:261183bool TabContents::ShowingBlockedPopupNotification() const {
1184 return blocked_popups_ != NULL &&
1185 blocked_popups_->GetTabContentsCount() != 0;
1186}
[email protected]332af7732009-03-11 13:21:351187#endif // defined(OS_WIN)
[email protected]616ed5a2008-11-21 22:27:241188
1189namespace {
1190bool TransitionIsReload(PageTransition::Type transition) {
1191 return PageTransition::StripQualifier(transition) == PageTransition::RELOAD;
1192}
1193}
1194
1195void TabContents::ExpireInfoBars(
1196 const NavigationController::LoadCommittedDetails& details) {
1197 // Only hide InfoBars when the user has done something that makes the main
1198 // frame load. We don't want various automatic or subframe navigations making
1199 // it disappear.
1200 if (!details.is_user_initiated_main_frame_load())
1201 return;
1202
[email protected]f86a07022008-11-25 01:06:051203 for (int i = infobar_delegate_count() - 1; i >= 0; --i) {
[email protected]616ed5a2008-11-21 22:27:241204 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
[email protected]f86a07022008-11-25 01:06:051205 if (delegate->ShouldExpire(details))
[email protected]616ed5a2008-11-21 22:27:241206 RemoveInfoBar(delegate);
[email protected]616ed5a2008-11-21 22:27:241207 }
1208}
[email protected]fdd61c62009-04-22 19:22:571209
1210void TabContents::OnGearsCreateShortcutDone(
1211 const GearsShortcutData2& shortcut_data, bool success) {
1212 NavigationEntry* current_entry = controller_.GetLastCommittedEntry();
1213 bool same_page =
1214 current_entry && pending_install_.page_id == current_entry->page_id();
1215
1216 if (success && same_page) {
1217 // Only switch to app mode if the user chose to create a shortcut and
1218 // we're still on the same page that it corresponded to.
1219 if (delegate())
1220 delegate()->ConvertContentsToApplication(this);
1221 }
1222
1223 // Reset the page id to indicate no requests are pending.
1224 pending_install_.page_id = 0;
1225 pending_install_.callback_functor = NULL;
1226}
[email protected]96d185d2009-04-24 03:28:541227
1228DOMUI* TabContents::GetDOMUIForCurrentState() {
1229 // When there is a pending navigation entry, we want to use the pending DOMUI
1230 // that goes along with it to control the basic flags. For example, we want to
1231 // show the pending URL in the URL bar, so we want the display_url flag to
1232 // be from the pending entry.
1233 //
1234 // The confusion comes because there are multiple possibilities for the
1235 // initial load in a tab as a side effect of the way the RenderViewHostManager
1236 // works.
1237 //
1238 // - For the very first tab the load looks "normal". The new tab DOM UI is
1239 // the pending one, and we want it to apply here.
1240 //
1241 // - For subsequent new tabs, they'll get a new SiteInstance which will then
1242 // get switched to the one previously associated with the new tab pages.
1243 // This switching will cause the manager to commit the RVH/DOMUI. So we'll
1244 // have a committed DOM UI in this case.
1245 //
1246 // This condition handles all of these cases:
1247 //
1248 // - First load in first tab: no committed nav entry + pending nav entry +
1249 // pending dom ui:
1250 // -> Use pending DOM UI if any.
1251 //
1252 // - First load in second tab: no committed nav entry + pending nav entry +
1253 // no pending DOM UI:
1254 // -> Use the committed DOM UI if any.
1255 //
1256 // - Second navigation in any tab: committed nav entry + pending nav entry:
1257 // -> Use pending DOM UI if any.
1258 //
1259 // - Normal state with no load: committed nav entry + no pending nav entry:
1260 // -> Use committed DOM UI.
1261 if (controller_.pending_entry() &&
1262 (controller_.GetLastCommittedEntry() ||
1263 render_manager_.pending_dom_ui()))
1264 return render_manager_.pending_dom_ui();
1265 return render_manager_.dom_ui();
1266}
[email protected]420ae012009-04-24 05:16:321267
1268void TabContents::DidNavigateMainFramePostCommit(
1269 const NavigationController::LoadCommittedDetails& details,
1270 const ViewHostMsg_FrameNavigate_Params& params) {
1271 // Hide the download shelf if all the following conditions are true:
1272 // - there are no active downloads.
1273 // - this is a navigation to a different TLD.
1274 // - at least 5 seconds have elapsed since the download shelf was shown.
1275 // TODO(jcampan): bug 1156075 when user gestures are reliable, they should
1276 // be used to ensure we are hiding only on user initiated
1277 // navigations.
1278 DownloadManager* download_manager = profile()->GetDownloadManager();
1279 // download_manager can be NULL in unit test context.
1280 if (download_manager && download_manager->in_progress_count() == 0 &&
1281 !details.previous_url.is_empty() &&
1282 !net::RegistryControlledDomainService::SameDomainOrHost(
1283 details.previous_url, details.entry->url())) {
1284 base::TimeDelta time_delta(
1285 base::TimeTicks::Now() - last_download_shelf_show_);
1286 if (time_delta >
1287 base::TimeDelta::FromMilliseconds(kDownloadShelfHideDelay)) {
1288 SetDownloadShelfVisible(false);
1289 }
1290 }
1291
1292 if (details.is_user_initiated_main_frame_load()) {
1293 // Clear the status bubble. This is a workaround for a bug where WebKit
1294 // doesn't let us know that the cursor left an element during a
1295 // transition (this is also why the mouse cursor remains as a hand after
1296 // clicking on a link); see bugs 1184641 and 980803. We don't want to
1297 // clear the bubble when a user navigates to a named anchor in the same
1298 // page.
1299 UpdateTargetURL(details.entry->page_id(), GURL());
1300
1301 // UpdateHelpersForDidNavigate will handle the case where the password_form
1302 // origin is valid.
1303 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1304 // cleaned up and covered by tests.
1305 if (!params.password_form.origin.is_valid())
1306 GetPasswordManager()->DidNavigate();
1307 }
1308
1309 // The keyword generator uses the navigation entries, so must be called after
1310 // the commit.
1311 GenerateKeywordIfNecessary(params);
1312
1313 // Allow the new page to set the title again.
1314 received_page_title_ = false;
1315
1316 // Get the favicon, either from history or request it from the net.
1317 fav_icon_helper_.FetchFavIcon(details.entry->url());
1318
1319 // Close constrained popups if necessary.
1320 MaybeCloseChildWindows(details.previous_url, details.entry->url());
1321
1322 // Update the starred state.
1323 UpdateStarredStateForCurrentURL();
1324}
1325
1326void TabContents::DidNavigateAnyFramePostCommit(
1327 RenderViewHost* render_view_host,
1328 const NavigationController::LoadCommittedDetails& details,
1329 const ViewHostMsg_FrameNavigate_Params& params) {
1330 // If we navigate, start showing messages again. This does nothing to prevent
1331 // a malicious script from spamming messages, since the script could just
1332 // reload the page to stop blocking.
1333 suppress_javascript_messages_ = false;
1334
1335 // Update history. Note that this needs to happen after the entry is complete,
1336 // which WillNavigate[Main,Sub]Frame will do before this function is called.
1337 if (params.should_update_history) {
1338 // Most of the time, the displayURL matches the loaded URL, but for about:
1339 // URLs, we use a data: URL as the real value. We actually want to save
1340 // the about: URL to the history db and keep the data: URL hidden. This is
1341 // what the TabContents' URL getter does.
1342 UpdateHistoryForNavigation(GetURL(), params);
1343 }
1344
1345 // Notify the password manager of the navigation or form submit.
1346 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1347 // cleaned up and covered by tests.
1348 if (params.password_form.origin.is_valid())
1349 GetPasswordManager()->ProvisionallySavePassword(params.password_form);
1350}
1351
1352void TabContents::MaybeCloseChildWindows(const GURL& previous_url,
1353 const GURL& current_url) {
1354 if (net::RegistryControlledDomainService::SameDomainOrHost(
1355 previous_url, current_url))
1356 return;
1357
1358 // Clear out any child windows since we are leaving this page entirely.
1359 // We use indices instead of iterators in case CloseWindow does something
1360 // that may invalidate an iterator.
1361 int size = static_cast<int>(child_windows_.size());
1362 for (int i = size - 1; i >= 0; --i) {
1363 ConstrainedWindow* window = child_windows_[i];
1364 if (window)
1365 window->CloseConstrainedWindow();
1366 }
1367}
1368
1369void TabContents::UpdateStarredStateForCurrentURL() {
1370 BookmarkModel* model = profile()->GetBookmarkModel();
1371 const bool old_state = is_starred_;
1372 is_starred_ = (model && model->IsBookmarked(GetURL()));
1373
1374 if (is_starred_ != old_state && delegate())
1375 delegate()->URLStarredChanged(this, is_starred_);
1376}
1377
1378void TabContents::UpdateAlternateErrorPageURL() {
1379 GURL url = GetAlternateErrorPageURL();
1380 render_view_host()->SetAlternateErrorPageURL(url);
1381}
1382
1383void TabContents::UpdateWebPreferences() {
1384 render_view_host()->UpdateWebPreferences(GetWebkitPrefs());
1385}
1386
1387void TabContents::UpdateMaxPageIDIfNecessary(SiteInstance* site_instance,
1388 RenderViewHost* rvh) {
1389 // If we are creating a RVH for a restored controller, then we might
1390 // have more page IDs than the SiteInstance's current max page ID. We must
1391 // make sure that the max page ID is larger than any restored page ID.
1392 // Note that it is ok for conflicting page IDs to exist in another tab
1393 // (i.e., NavigationController), but if any page ID is larger than the max,
1394 // the back/forward list will get confused.
1395 int max_restored_page_id = controller_.max_restored_page_id();
1396 if (max_restored_page_id > 0) {
1397 int curr_max_page_id = site_instance->max_page_id();
1398 if (max_restored_page_id > curr_max_page_id) {
1399 // Need to update the site instance immediately.
1400 site_instance->UpdateMaxPageID(max_restored_page_id);
1401
1402 // Also tell the renderer to update its internal representation. We
1403 // need to reserve enough IDs to make all restored page IDs less than
1404 // the max.
1405 if (curr_max_page_id < 0)
1406 curr_max_page_id = 0;
1407 rvh->ReservePageIDRange(max_restored_page_id - curr_max_page_id);
1408 }
1409 }
1410}
1411
1412void TabContents::UpdateHistoryForNavigation(
1413 const GURL& display_url,
1414 const ViewHostMsg_FrameNavigate_Params& params) {
1415 if (profile()->IsOffTheRecord())
1416 return;
1417
1418 // Add to history service.
1419 HistoryService* hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1420 if (hs) {
1421 if (PageTransition::IsMainFrame(params.transition) &&
1422 display_url != params.url) {
1423 // Hack on the "display" URL so that it will appear in history. For some
1424 // types of URLs, we will display a magic URL that is different from where
1425 // the page is actually navigated. We want the user to see in history
1426 // what they saw in the URL bar, so we add the display URL as a redirect.
1427 // This only applies to the main frame, as the display URL doesn't apply
1428 // to sub-frames.
1429 std::vector<GURL> redirects = params.redirects;
1430 if (!redirects.empty())
1431 redirects.back() = display_url;
1432 hs->AddPage(display_url, this, params.page_id, params.referrer,
1433 params.transition, redirects);
1434 } else {
1435 hs->AddPage(params.url, this, params.page_id, params.referrer,
1436 params.transition, params.redirects);
1437 }
1438 }
1439}
1440
1441bool TabContents::UpdateTitleForEntry(NavigationEntry* entry,
1442 const std::wstring& title) {
1443 // For file URLs without a title, use the pathname instead. In the case of a
1444 // synthesized title, we don't want the update to count toward the "one set
1445 // per page of the title to history."
1446 std::wstring final_title;
1447 bool explicit_set;
1448 if (entry->url().SchemeIsFile() && title.empty()) {
1449 final_title = UTF8ToWide(entry->url().ExtractFileName());
1450 explicit_set = false; // Don't count synthetic titles toward the set limit.
1451 } else {
1452 TrimWhitespace(title, TRIM_ALL, &final_title);
1453 explicit_set = true;
1454 }
1455
1456 if (final_title == UTF16ToWideHack(entry->title()))
1457 return false; // Nothing changed, don't bother.
1458
1459 entry->set_title(WideToUTF16Hack(final_title));
1460
1461 // Update the history system for this page.
1462 if (!profile()->IsOffTheRecord() && !received_page_title_) {
1463 HistoryService* hs =
1464 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1465 if (hs)
1466 hs->SetPageTitle(entry->display_url(), final_title);
1467
1468 // Don't allow the title to be saved again for explicitly set ones.
1469 received_page_title_ = explicit_set;
1470 }
1471
1472 // Lastly, set the title for the view.
1473 view_->SetPageTitle(final_title);
1474
1475 return true;
1476}
1477
1478void TabContents::NotifySwapped() {
1479 // After sending out a swap notification, we need to send a disconnect
1480 // notification so that clients that pick up a pointer to |this| can NULL the
1481 // pointer. See Bug 1230284.
1482 notify_disconnection_ = true;
1483 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341484 NotificationType::TAB_CONTENTS_SWAPPED,
1485 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321486 NotificationService::NoDetails());
1487}
1488
1489void TabContents::NotifyConnected() {
1490 notify_disconnection_ = true;
1491 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341492 NotificationType::TAB_CONTENTS_CONNECTED,
1493 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321494 NotificationService::NoDetails());
1495}
1496
1497void TabContents::NotifyDisconnected() {
1498 if (!notify_disconnection_)
1499 return;
1500
1501 notify_disconnection_ = false;
1502 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341503 NotificationType::TAB_CONTENTS_DISCONNECTED,
1504 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321505 NotificationService::NoDetails());
1506}
1507
1508void TabContents::GenerateKeywordIfNecessary(
1509 const ViewHostMsg_FrameNavigate_Params& params) {
1510 if (!params.searchable_form_url.is_valid())
1511 return;
1512
1513 if (profile()->IsOffTheRecord())
1514 return;
1515
1516 int last_index = controller_.last_committed_entry_index();
1517 // When there was no previous page, the last index will be 0. This is
1518 // normally due to a form submit that opened in a new tab.
1519 // TODO(brettw) bug 916126: we should support keywords when form submits
1520 // happen in new tabs.
1521 if (last_index <= 0)
1522 return;
1523 const NavigationEntry* previous_entry =
1524 controller_.GetEntryAtIndex(last_index - 1);
1525 if (IsFormSubmit(previous_entry)) {
1526 // Only generate a keyword if the previous page wasn't itself a form
1527 // submit.
1528 return;
1529 }
1530
1531 GURL keyword_url = previous_entry->user_typed_url().is_valid() ?
1532 previous_entry->user_typed_url() : previous_entry->url();
1533 std::wstring keyword =
1534 TemplateURLModel::GenerateKeyword(keyword_url, true); // autodetected
1535 if (keyword.empty())
1536 return;
1537
1538 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
1539 if (!url_model)
1540 return;
1541
1542 if (!url_model->loaded()) {
1543 url_model->Load();
1544 return;
1545 }
1546
1547 const TemplateURL* current_url;
1548 std::wstring url = UTF8ToWide(params.searchable_form_url.spec());
1549 if (!url_model->CanReplaceKeyword(keyword, url, &current_url))
1550 return;
1551
1552 if (current_url) {
1553 if (current_url->originating_url().is_valid()) {
1554 // The existing keyword was generated from an OpenSearch description
1555 // document, don't regenerate.
1556 return;
1557 }
1558 url_model->Remove(current_url);
1559 }
1560 TemplateURL* new_url = new TemplateURL();
1561 new_url->set_keyword(keyword);
1562 new_url->set_short_name(keyword);
1563 new_url->SetURL(url, 0, 0);
1564 new_url->add_input_encoding(params.searchable_form_encoding);
1565 DCHECK(controller_.GetLastCommittedEntry());
1566 const GURL& favicon_url =
1567 controller_.GetLastCommittedEntry()->favicon().url();
1568 if (favicon_url.is_valid()) {
1569 new_url->SetFavIconURL(favicon_url);
1570 } else {
1571 // The favicon url isn't valid. This means there really isn't a favicon,
1572 // or the favicon url wasn't obtained before the load started. This assumes
1573 // the later.
1574 // TODO(sky): Need a way to set the favicon that doesn't involve generating
1575 // its url.
1576 new_url->SetFavIconURL(TemplateURL::GenerateFaviconURL(params.referrer));
1577 }
1578 new_url->set_safe_for_autoreplace(true);
1579 url_model->Add(new_url);
1580}
1581
1582RenderViewHostDelegate::View* TabContents::GetViewDelegate() const {
1583 return view_.get();
1584}
1585
1586RenderViewHostDelegate::Save* TabContents::GetSaveDelegate() const {
1587 return save_package_.get(); // May be NULL, but we can return NULL.
1588}
1589
1590Profile* TabContents::GetProfile() const {
1591 return profile();
1592}
1593
[email protected]6dfed102009-04-28 03:09:531594ExtensionFunctionDispatcher* TabContents::CreateExtensionFunctionDispatcher(
1595 RenderViewHost* render_view_host,
1596 const std::string& extension_id) {
1597 return delegate()->CreateExtensionFunctionDispatcher(render_view_host,
1598 extension_id);
1599}
1600
[email protected]57c6a652009-05-04 07:58:341601TabContents* TabContents::GetAsTabContents() {
1602 return this;
1603}
1604
[email protected]420ae012009-04-24 05:16:321605void TabContents::RenderViewCreated(RenderViewHost* render_view_host) {
1606 NavigationEntry* entry = controller_.GetActiveEntry();
1607 if (!entry)
1608 return;
1609
1610 // When we're creating views, we're still doing initial setup, so we always
1611 // use the pending DOM UI rather than any possibly existing committed one.
1612 if (render_manager_.pending_dom_ui()) {
1613 render_manager_.pending_dom_ui()->RenderViewCreated(render_view_host);
1614 }
1615
1616 if (entry->IsViewSourceMode()) {
1617 // Put the renderer in view source mode.
1618 render_view_host->Send(
1619 new ViewMsg_EnableViewSourceMode(render_view_host->routing_id()));
1620 }
1621}
1622
1623void TabContents::RenderViewReady(RenderViewHost* rvh) {
1624 if (rvh != render_view_host()) {
1625 // Don't notify the world, since this came from a renderer in the
1626 // background.
1627 return;
1628 }
1629
1630 NotifyConnected();
1631 SetIsCrashed(false);
1632}
1633
1634void TabContents::RenderViewGone(RenderViewHost* rvh) {
1635 // Ask the print preview if this renderer was valuable.
1636 if (!printing_.OnRenderViewGone(rvh))
1637 return;
1638 if (rvh != render_view_host()) {
1639 // The pending page's RenderViewHost is gone.
1640 return;
1641 }
1642
1643 SetIsLoading(false, NULL);
1644 NotifyDisconnected();
1645 SetIsCrashed(true);
1646
1647 // Force an invalidation to render sad tab. The view will notice we crashed
1648 // when it paints.
1649 view_->Invalidate();
1650
1651 // Hide any visible hung renderer warning for this web contents' process.
[email protected]57c6a652009-05-04 07:58:341652 HungRendererWarning::HideForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:321653}
1654
1655void TabContents::DidNavigate(RenderViewHost* rvh,
1656 const ViewHostMsg_FrameNavigate_Params& params) {
1657 if (PageTransition::IsMainFrame(params.transition))
1658 render_manager_.DidNavigateMainFrame(rvh);
1659
1660 // Update the site of the SiteInstance if it doesn't have one yet.
1661 if (!GetSiteInstance()->has_site())
1662 GetSiteInstance()->SetSite(params.url);
1663
1664 // Need to update MIME type here because it's referred to in
1665 // UpdateNavigationCommands() called by RendererDidNavigate() to
1666 // determine whether or not to enable the encoding menu.
1667 // It's updated only for the main frame. For a subframe,
1668 // RenderView::UpdateURL does not set params.contents_mime_type.
1669 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
1670 // TODO(jungshik): Add a test for the encoding menu to avoid
1671 // regressing it again.
1672 if (PageTransition::IsMainFrame(params.transition))
1673 contents_mime_type_ = params.contents_mime_type;
1674
1675 NavigationController::LoadCommittedDetails details;
1676 if (!controller_.RendererDidNavigate(params, &details))
1677 return; // No navigation happened.
1678
1679 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
1680 // for the appropriate notification (best) or you can add it to
1681 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
1682 // necessary, please).
1683
1684 // Run post-commit tasks.
1685 if (details.is_main_frame)
1686 DidNavigateMainFramePostCommit(details, params);
1687 DidNavigateAnyFramePostCommit(rvh, details, params);
1688}
1689
1690void TabContents::UpdateState(RenderViewHost* rvh,
1691 int32 page_id,
1692 const std::string& state) {
1693 DCHECK(rvh == render_view_host());
1694
1695 // We must be prepared to handle state updates for any page, these occur
1696 // when the user is scrolling and entering form data, as well as when we're
1697 // leaving a page, in which case our state may have already been moved to
1698 // the next page. The navigation controller will look up the appropriate
1699 // NavigationEntry and update it when it is notified via the delegate.
1700
1701 int entry_index = controller_.GetEntryIndexWithPageID(
1702 GetSiteInstance(), page_id);
1703 if (entry_index < 0)
1704 return;
1705 NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
1706
1707 if (state == entry->content_state())
1708 return; // Nothing to update.
1709 entry->set_content_state(state);
1710 controller_.NotifyEntryChanged(entry, entry_index);
1711}
1712
1713void TabContents::UpdateTitle(RenderViewHost* rvh,
1714 int32 page_id, const std::wstring& title) {
1715 // If we have a title, that's a pretty good indication that we've started
1716 // getting useful data.
1717 SetNotWaitingForResponse();
1718
1719 DCHECK(rvh == render_view_host());
1720 NavigationEntry* entry = controller_.GetEntryWithPageID(GetSiteInstance(),
1721 page_id);
1722 if (!entry || !UpdateTitleForEntry(entry, title))
1723 return;
1724
1725 // Broadcast notifications when the UI should be updated.
1726 if (entry == controller_.GetEntryAtOffset(0))
1727 NotifyNavigationStateChanged(INVALIDATE_TITLE);
1728}
1729
[email protected]420ae012009-04-24 05:16:321730void TabContents::UpdateEncoding(RenderViewHost* render_view_host,
1731 const std::wstring& encoding) {
1732 set_encoding(encoding);
1733}
1734
1735void TabContents::UpdateTargetURL(int32 page_id, const GURL& url) {
1736 if (delegate())
1737 delegate()->UpdateTargetURL(this, url);
1738}
1739
1740void TabContents::UpdateThumbnail(const GURL& url,
1741 const SkBitmap& bitmap,
1742 const ThumbnailScore& score) {
1743 // Tell History about this thumbnail
1744 HistoryService* hs;
1745 if (!profile()->IsOffTheRecord() &&
1746 (hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS))) {
1747 hs->SetPageThumbnail(url, bitmap, score);
1748 }
1749}
1750
1751void TabContents::Close(RenderViewHost* rvh) {
1752 // Ignore this if it comes from a RenderViewHost that we aren't showing.
1753 if (delegate() && rvh == render_view_host())
1754 delegate()->CloseContents(this);
1755}
1756
1757void TabContents::RequestMove(const gfx::Rect& new_bounds) {
1758 if (delegate() && delegate()->IsPopup(this))
1759 delegate()->MoveContents(this, new_bounds);
1760}
1761
[email protected]329581b2009-04-28 06:52:351762void TabContents::DidStartLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321763 SetIsLoading(true, NULL);
1764}
1765
[email protected]329581b2009-04-28 06:52:351766void TabContents::DidStopLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321767 scoped_ptr<LoadNotificationDetails> details;
1768
1769 NavigationEntry* entry = controller_.GetActiveEntry();
1770 // An entry may not exist for a stop when loading an initial blank page or
1771 // if an iframe injected by script into a blank page finishes loading.
1772 if (entry) {
1773 scoped_ptr<base::ProcessMetrics> metrics(
1774 base::ProcessMetrics::CreateProcessMetrics(
1775 process()->process().handle()));
1776
1777 base::TimeDelta elapsed = base::TimeTicks::Now() - current_load_start_;
1778
1779 details.reset(new LoadNotificationDetails(
1780 entry->display_url(),
1781 entry->transition_type(),
1782 elapsed,
1783 &controller_,
1784 controller_.GetCurrentEntryIndex()));
1785 }
1786
1787 // Tell PasswordManager we've finished a page load, which serves as a
1788 // green light to save pending passwords and reset itself.
1789 GetPasswordManager()->DidStopLoading();
1790
1791 SetIsLoading(false, details.get());
1792}
1793
1794void TabContents::DidStartProvisionalLoadForFrame(
1795 RenderViewHost* render_view_host,
1796 bool is_main_frame,
1797 const GURL& url) {
1798 ProvisionalLoadDetails details(is_main_frame,
1799 controller_.IsURLInPageNavigation(url),
1800 url, std::string(), false);
1801 NotificationService::current()->Notify(
1802 NotificationType::FRAME_PROVISIONAL_LOAD_START,
1803 Source<NavigationController>(&controller_),
1804 Details<ProvisionalLoadDetails>(&details));
1805}
1806
1807void TabContents::DidRedirectProvisionalLoad(int32 page_id,
1808 const GURL& source_url,
1809 const GURL& target_url) {
1810 NavigationEntry* entry;
1811 if (page_id == -1)
1812 entry = controller_.pending_entry();
1813 else
1814 entry = controller_.GetEntryWithPageID(GetSiteInstance(), page_id);
1815 if (!entry || entry->url() != source_url)
1816 return;
1817 entry->set_url(target_url);
1818}
1819
1820void TabContents::DidLoadResourceFromMemoryCache(
1821 const GURL& url,
1822 const std::string& frame_origin,
1823 const std::string& main_frame_origin,
1824 const std::string& security_info) {
1825 // Send out a notification that we loaded a resource from our memory cache.
1826 int cert_id = 0, cert_status = 0, security_bits = 0;
1827 SSLManager::DeserializeSecurityInfo(security_info,
1828 &cert_id, &cert_status,
1829 &security_bits);
1830 LoadFromMemoryCacheDetails details(url, frame_origin, main_frame_origin,
1831 cert_id, cert_status);
1832
1833 NotificationService::current()->Notify(
1834 NotificationType::LOAD_FROM_MEMORY_CACHE,
1835 Source<NavigationController>(&controller_),
1836 Details<LoadFromMemoryCacheDetails>(&details));
1837}
1838
1839void TabContents::DidFailProvisionalLoadWithError(
1840 RenderViewHost* render_view_host,
1841 bool is_main_frame,
1842 int error_code,
1843 const GURL& url,
1844 bool showing_repost_interstitial) {
1845 if (net::ERR_ABORTED == error_code) {
1846 // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
1847 // This means that the interstitial won't be torn down properly, which is
1848 // bad. But if we have an interstitial, go back to another tab type, and
1849 // then load the same interstitial again, we could end up getting the first
1850 // interstitial's "failed" message (as a result of the cancel) when we're on
1851 // the second one.
1852 //
1853 // We can't tell this apart, so we think we're tearing down the current page
1854 // which will cause a crash later one. There is also some code in
1855 // RenderViewHostManager::RendererAbortedProvisionalLoad that is commented
1856 // out because of this problem.
1857 //
1858 // http://code.google.com/p/chromium/issues/detail?id=2855
1859 // Because this will not tear down the interstitial properly, if "back" is
1860 // back to another tab type, the interstitial will still be somewhat alive
1861 // in the previous tab type. If you navigate somewhere that activates the
1862 // tab with the interstitial again, you'll see a flash before the new load
1863 // commits of the interstitial page.
1864 if (showing_interstitial_page()) {
1865 LOG(WARNING) << "Discarding message during interstitial.";
1866 return;
1867 }
1868
1869 // This will discard our pending entry if we cancelled the load (e.g., if we
1870 // decided to download the file instead of load it). Only discard the
1871 // pending entry if the URLs match, otherwise the user initiated a navigate
1872 // before the page loaded so that the discard would discard the wrong entry.
1873 NavigationEntry* pending_entry = controller_.pending_entry();
1874 if (pending_entry && pending_entry->url() == url)
1875 controller_.DiscardNonCommittedEntries();
1876
1877 render_manager_.RendererAbortedProvisionalLoad(render_view_host);
1878 }
1879
1880 // Send out a notification that we failed a provisional load with an error.
1881 ProvisionalLoadDetails details(is_main_frame,
1882 controller_.IsURLInPageNavigation(url),
1883 url, std::string(), false);
1884 details.set_error_code(error_code);
1885
1886 NotificationService::current()->Notify(
1887 NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR,
1888 Source<NavigationController>(&controller_),
1889 Details<ProvisionalLoadDetails>(&details));
1890}
1891
1892void TabContents::UpdateFavIconURL(RenderViewHost* render_view_host,
1893 int32 page_id,
1894 const GURL& icon_url) {
1895 fav_icon_helper_.SetFavIconURL(icon_url);
1896}
1897
1898void TabContents::DidDownloadImage(
1899 RenderViewHost* render_view_host,
1900 int id,
1901 const GURL& image_url,
1902 bool errored,
1903 const SkBitmap& image) {
1904 // A notification for downloading would be more flexible, but for now I'm
1905 // forwarding to the two places that could possibly have initiated the
1906 // request. If we end up with another place invoking DownloadImage, probably
1907 // best to refactor out into notification service, or something similar.
1908 if (errored)
1909 fav_icon_helper_.FavIconDownloadFailed(id);
1910 else
1911 fav_icon_helper_.SetFavIcon(id, image_url, image);
1912}
1913
1914void TabContents::RequestOpenURL(const GURL& url, const GURL& referrer,
1915 WindowOpenDisposition disposition) {
1916 if (render_manager_.dom_ui()) {
1917 // When we're a DOM UI, it will provide a page transition type for us (this
1918 // is so the new tab page can specify AUTO_BOOKMARK for automatically
1919 // generated suggestions).
1920 //
1921 // Note also that we hide the referrer for DOM UI pages. We don't really
1922 // want web sites to see a referrer of "chrome-ui://blah" (and some
1923 // chrome-ui URLs might have search terms or other stuff we don't want to
1924 // send to the site), so we send no referrer.
1925 OpenURL(url, GURL(), disposition,
1926 render_manager_.dom_ui()->link_transition_type());
1927 } else {
1928 OpenURL(url, referrer, disposition, PageTransition::LINK);
1929 }
1930}
1931
1932void TabContents::DomOperationResponse(const std::string& json_string,
1933 int automation_id) {
1934 DomOperationNotificationDetails details(json_string, automation_id);
1935 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341936 NotificationType::DOM_OPERATION_RESPONSE, Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321937 Details<DomOperationNotificationDetails>(&details));
1938}
1939
1940void TabContents::ProcessDOMUIMessage(const std::string& message,
1941 const std::string& content) {
1942 if (!render_manager_.dom_ui()) {
1943 // We shouldn't get a DOM UI message when we haven't enabled the DOM UI.
1944 // Because the renderer might be owned and sending random messages, we need
1945 // to ignore these inproper ones.
1946 NOTREACHED();
1947 return;
1948 }
1949 render_manager_.dom_ui()->ProcessDOMUIMessage(message, content);
1950}
1951
1952void TabContents::ProcessExternalHostMessage(const std::string& message,
1953 const std::string& origin,
1954 const std::string& target) {
1955 if (delegate())
1956 delegate()->ForwardMessageToExternalHost(message, origin, target);
1957}
1958
1959void TabContents::GoToEntryAtOffset(int offset) {
1960 controller_.GoToOffset(offset);
1961}
1962
1963void TabContents::GetHistoryListCount(int* back_list_count,
1964 int* forward_list_count) {
1965 int current_index = controller_.last_committed_entry_index();
1966 *back_list_count = current_index;
1967 *forward_list_count = controller_.entry_count() - current_index - 1;
1968}
1969
1970void TabContents::RunFileChooser(bool multiple_files,
1971 const string16& title,
1972 const FilePath& default_file) {
1973 if (!select_file_dialog_.get())
1974 select_file_dialog_ = SelectFileDialog::Create(this);
1975 SelectFileDialog::Type dialog_type =
1976 multiple_files ? SelectFileDialog::SELECT_OPEN_MULTI_FILE :
1977 SelectFileDialog::SELECT_OPEN_FILE;
1978 select_file_dialog_->SelectFile(dialog_type, title, default_file,
1979 NULL, 0, FILE_PATH_LITERAL(""),
1980 view_->GetTopLevelNativeWindow(), NULL);
1981}
1982
1983void TabContents::RunJavaScriptMessage(
1984 const std::wstring& message,
1985 const std::wstring& default_prompt,
1986 const GURL& frame_url,
1987 const int flags,
1988 IPC::Message* reply_msg,
1989 bool* did_suppress_message) {
1990 // Suppress javascript messages when requested and when inside a constrained
1991 // popup window (because that activates them and breaks them out of the
1992 // constrained window jail).
1993 bool suppress_this_message = suppress_javascript_messages_;
1994 if (delegate())
1995 suppress_this_message |=
1996 (delegate()->GetConstrainingContents(this) != NULL);
1997
1998 *did_suppress_message = suppress_this_message;
1999
2000 if (!suppress_this_message) {
2001 base::TimeDelta time_since_last_message(
2002 base::TimeTicks::Now() - last_javascript_message_dismissal_);
2003 bool show_suppress_checkbox = false;
2004 // Show a checkbox offering to suppress further messages if this message is
2005 // being displayed within kJavascriptMessageExpectedDelay of the last one.
2006 if (time_since_last_message <
2007 base::TimeDelta::FromMilliseconds(kJavascriptMessageExpectedDelay))
2008 show_suppress_checkbox = true;
2009
2010 RunJavascriptMessageBox(AsWC(this), frame_url, flags, message, default_prompt,
2011 show_suppress_checkbox, reply_msg);
2012 } else {
2013 // If we are suppressing messages, just reply as is if the user immediately
2014 // pressed "Cancel".
2015 OnJavaScriptMessageBoxClosed(reply_msg, false, std::wstring());
2016 }
2017}
2018
2019void TabContents::RunBeforeUnloadConfirm(const std::wstring& message,
2020 IPC::Message* reply_msg) {
2021 RunBeforeUnloadDialog(AsWC(this), message, reply_msg);
2022}
2023
2024void TabContents::ShowModalHTMLDialog(const GURL& url, int width, int height,
2025 const std::string& json_arguments,
2026 IPC::Message* reply_msg) {
2027 if (delegate()) {
2028 HtmlDialogUIDelegate* dialog_delegate =
2029 new ModalHtmlDialogDelegate(url, width, height, json_arguments,
2030 reply_msg, AsWC(this));
2031 delegate()->ShowHtmlDialog(dialog_delegate, NULL);
2032 }
2033}
2034
2035void TabContents::PasswordFormsSeen(
2036 const std::vector<PasswordForm>& forms) {
2037 GetPasswordManager()->PasswordFormsSeen(forms);
2038}
2039
2040void TabContents::AutofillFormSubmitted(
2041 const AutofillForm& form) {
2042 GetAutofillManager()->AutofillFormSubmitted(form);
2043}
2044
2045void TabContents::GetAutofillSuggestions(const std::wstring& field_name,
2046 const std::wstring& user_text, int64 node_id, int request_id) {
2047 GetAutofillManager()->FetchValuesForName(field_name, user_text,
2048 kMaxAutofillMenuItems, node_id, request_id);
2049}
2050
2051void TabContents::RemoveAutofillEntry(const std::wstring& field_name,
2052 const std::wstring& value) {
2053 GetAutofillManager()->RemoveValueForName(field_name, value);
2054}
2055
2056// Checks to see if we should generate a keyword based on the OSDD, and if
2057// necessary uses TemplateURLFetcher to download the OSDD and create a keyword.
2058void TabContents::PageHasOSDD(RenderViewHost* render_view_host,
2059 int32 page_id, const GURL& url,
2060 bool autodetected) {
2061 // Make sure page_id is the current page, and the TemplateURLModel is loaded.
2062 DCHECK(url.is_valid());
2063 if (!IsActiveEntry(page_id))
2064 return;
2065 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
2066 if (!url_model)
2067 return;
2068 if (!url_model->loaded()) {
2069 url_model->Load();
2070 return;
2071 }
2072 if (!profile()->GetTemplateURLFetcher())
2073 return;
2074
2075 if (profile()->IsOffTheRecord())
2076 return;
2077
2078 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
2079 DCHECK(entry);
2080
2081 const NavigationEntry* base_entry = entry;
2082 if (IsFormSubmit(base_entry)) {
2083 // If the current page is a form submit, find the last page that was not
2084 // a form submit and use its url to generate the keyword from.
2085 int index = controller_.last_committed_entry_index() - 1;
2086 while (index >= 0 && IsFormSubmit(controller_.GetEntryAtIndex(index)))
2087 index--;
2088 if (index >= 0)
2089 base_entry = controller_.GetEntryAtIndex(index);
2090 else
2091 base_entry = NULL;
2092 }
2093
2094 // We want to use the user typed URL if available since that represents what
2095 // the user typed to get here, and fall back on the regular URL if not.
2096 if (!base_entry)
2097 return;
2098 GURL keyword_url = base_entry->user_typed_url().is_valid() ?
2099 base_entry->user_typed_url() : base_entry->url();
2100 if (!keyword_url.is_valid())
2101 return;
2102 std::wstring keyword = TemplateURLModel::GenerateKeyword(keyword_url,
2103 autodetected);
2104 if (keyword.empty())
2105 return;
2106 const TemplateURL* template_url =
2107 url_model->GetTemplateURLForKeyword(keyword);
2108 if (template_url && (!template_url->safe_for_autoreplace() ||
2109 template_url->originating_url() == url)) {
2110 // Either there is a user created TemplateURL for this keyword, or the
2111 // keyword has the same OSDD url and we've parsed it.
2112 return;
2113 }
2114
2115 // Download the OpenSearch description document. If this is successful a
2116 // new keyword will be created when done.
2117#if defined(OS_WIN)
2118 gfx::NativeView ancestor = GetAncestor(view_->GetNativeView(), GA_ROOT);
2119#else
2120 gfx::NativeView ancestor = NULL;
2121#endif
2122 profile()->GetTemplateURLFetcher()->ScheduleDownload(
2123 keyword,
2124 url,
2125 base_entry->favicon().url(),
2126 ancestor,
2127 autodetected);
2128}
2129
2130void TabContents::InspectElementReply(int num_resources) {
2131 // We have received reply from inspect element request. Notify the
2132 // automation provider in case we need to notify automation client.
2133 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:342134 NotificationType::DOM_INSPECT_ELEMENT_RESPONSE, Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:322135 Details<int>(&num_resources));
2136}
2137
2138void TabContents::DidGetPrintedPagesCount(int cookie, int number_pages) {
2139 printing_.DidGetPrintedPagesCount(cookie, number_pages);
2140}
2141
2142void TabContents::DidPrintPage(const ViewHostMsg_DidPrintPage_Params& params) {
2143 printing_.DidPrintPage(params);
2144}
2145
2146GURL TabContents::GetAlternateErrorPageURL() const {
2147 GURL url;
2148 // Disable alternate error pages when in OffTheRecord/Incognito mode.
2149 if (profile()->IsOffTheRecord())
2150 return url;
2151
2152 PrefService* prefs = profile()->GetPrefs();
2153 DCHECK(prefs);
2154 if (prefs->GetBoolean(prefs::kAlternateErrorPagesEnabled)) {
2155 url = google_util::AppendGoogleLocaleParam(GURL(kLinkDoctorBaseURL));
2156 url = google_util::AppendGoogleTLDParam(url);
2157 }
2158 return url;
2159}
2160
2161WebPreferences TabContents::GetWebkitPrefs() {
2162 PrefService* prefs = render_view_host()->process()->profile()->GetPrefs();
2163 bool isDomUI = false;
2164 return RenderViewHostDelegateHelper::GetWebkitPrefs(prefs, isDomUI);
2165}
2166
2167void TabContents::OnMissingPluginStatus(int status) {
2168#if defined(OS_WIN)
2169// TODO(PORT): pull in when plug-ins work
2170 GetPluginInstaller()->OnMissingPluginStatus(status);
2171#endif
2172}
2173
2174void TabContents::OnCrashedPlugin(const FilePath& plugin_path) {
2175#if defined(OS_WIN)
2176// TODO(PORT): pull in when plug-ins work
2177 DCHECK(!plugin_path.value().empty());
2178
2179 std::wstring plugin_name = plugin_path.ToWStringHack();
2180 scoped_ptr<FileVersionInfo> version_info(
2181 FileVersionInfo::CreateFileVersionInfo(plugin_path));
2182 if (version_info.get()) {
2183 const std::wstring& product_name = version_info->product_name();
2184 if (!product_name.empty())
2185 plugin_name = product_name;
2186 }
2187 AddInfoBar(new SimpleAlertInfoBarDelegate(
2188 this, l10n_util::GetStringF(IDS_PLUGIN_CRASHED_PROMPT, plugin_name),
2189 NULL));
2190#endif
2191}
2192
2193void TabContents::OnCrashedWorker() {
2194 AddInfoBar(new SimpleAlertInfoBarDelegate(
2195 this, l10n_util::GetString(IDS_WEBWORKER_CRASHED_PROMPT),
2196 NULL));
2197}
2198
2199void TabContents::OnJSOutOfMemory() {
2200 AddInfoBar(new SimpleAlertInfoBarDelegate(
2201 this, l10n_util::GetString(IDS_JS_OUT_OF_MEMORY_PROMPT), NULL));
2202}
2203
2204void TabContents::ShouldClosePage(bool proceed) {
2205 render_manager_.ShouldClosePage(proceed);
2206}
2207
2208void TabContents::OnCrossSiteResponse(int new_render_process_host_id,
2209 int new_request_id) {
[email protected]57c6a652009-05-04 07:58:342210 // Allows the TabContents to react when a cross-site response is ready to be
[email protected]420ae012009-04-24 05:16:322211 // delivered to a pending RenderViewHost. We must first run the onunload
2212 // handler of the old RenderViewHost before we can allow it to proceed.
2213 render_manager_.OnCrossSiteResponse(new_render_process_host_id,
2214 new_request_id);
2215}
2216
2217bool TabContents::CanBlur() const {
2218 return delegate() ? delegate()->CanBlur() : true;
2219}
2220
2221gfx::Rect TabContents::GetRootWindowResizerRect() const {
2222 if (delegate())
2223 return delegate()->GetRootWindowResizerRect();
2224 return gfx::Rect();
2225}
2226
2227void TabContents::RendererUnresponsive(RenderViewHost* rvh,
2228 bool is_during_unload) {
2229 if (is_during_unload) {
2230 // Hang occurred while firing the beforeunload/unload handler.
2231 // Pretend the handler fired so tab closing continues as if it had.
[email protected]829e7612009-04-25 01:15:112232 rvh->set_sudden_termination_allowed(true);
[email protected]420ae012009-04-24 05:16:322233
2234 if (!render_manager_.ShouldCloseTabOnUnresponsiveRenderer())
2235 return;
2236
2237 // If the tab hangs in the beforeunload/unload handler there's really
2238 // nothing we can do to recover. Pretend the unload listeners have
2239 // all fired and close the tab. If the hang is in the beforeunload handler
2240 // then the user will not have the option of cancelling the close.
2241 Close(rvh);
2242 return;
2243 }
2244
2245 if (render_view_host() && render_view_host()->IsRenderViewLive())
[email protected]57c6a652009-05-04 07:58:342246 HungRendererWarning::ShowForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:322247}
2248
2249void TabContents::RendererResponsive(RenderViewHost* render_view_host) {
[email protected]57c6a652009-05-04 07:58:342250 HungRendererWarning::HideForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:322251}
2252
2253void TabContents::LoadStateChanged(const GURL& url,
2254 net::LoadState load_state) {
2255 load_state_ = load_state;
2256 load_state_host_ = UTF8ToWide(url.host());
2257 if (load_state_ == net::LOAD_STATE_READING_RESPONSE)
2258 SetNotWaitingForResponse();
2259 if (is_loading())
2260 NotifyNavigationStateChanged(INVALIDATE_LOAD | INVALIDATE_FAVICON);
2261}
2262
2263void TabContents::OnDidGetApplicationInfo(
2264 int32 page_id,
2265 const webkit_glue::WebApplicationInfo& info) {
2266 if (pending_install_.page_id != page_id)
2267 return; // The user clicked create on a separate page. Ignore this.
2268
2269 pending_install_.callback_functor =
2270 new GearsCreateShortcutCallbackFunctor(this);
2271 GearsCreateShortcut(
2272 info, pending_install_.title, pending_install_.url, pending_install_.icon,
2273 NewCallback(pending_install_.callback_functor,
2274 &GearsCreateShortcutCallbackFunctor::Run));
2275}
2276
2277void TabContents::OnEnterOrSpace() {
2278 // See comment in RenderViewHostDelegate::OnEnterOrSpace as to why we do this.
2279#if defined(OS_WIN)
2280 // TODO(port): this is stubbed in BrowserProcess
2281 DownloadRequestManager* drm = g_browser_process->download_request_manager();
2282 if (drm)
2283 drm->OnUserGesture(this);
2284#endif
2285}
2286
2287void TabContents::OnFindReply(int request_id,
2288 int number_of_matches,
2289 const gfx::Rect& selection_rect,
2290 int active_match_ordinal,
2291 bool final_update) {
2292 // Ignore responses for requests other than the one we have most recently
2293 // issued. That way we won't act on stale results when the user has
2294 // already typed in another query.
2295 if (request_id != current_find_request_id_)
2296 return;
2297
2298 if (number_of_matches == -1)
2299 number_of_matches = find_result_.number_of_matches();
2300 if (active_match_ordinal == -1)
2301 active_match_ordinal = find_result_.active_match_ordinal();
2302
2303 // Notify the UI, automation and any other observers that a find result was
2304 // found.
2305 find_result_ = FindNotificationDetails(request_id, number_of_matches,
2306 selection_rect, active_match_ordinal,
2307 final_update);
2308 NotificationService::current()->Notify(
2309 NotificationType::FIND_RESULT_AVAILABLE,
2310 Source<TabContents>(this),
2311 Details<FindNotificationDetails>(&find_result_));
2312}
2313
[email protected]829e7612009-04-25 01:15:112314bool TabContents::IsExternalTabContainer() const {
[email protected]420ae012009-04-24 05:16:322315 if (!delegate())
[email protected]829e7612009-04-25 01:15:112316 return false;
[email protected]420ae012009-04-24 05:16:322317
[email protected]829e7612009-04-25 01:15:112318 return delegate()->IsExternalTabContainer();
[email protected]420ae012009-04-24 05:16:322319}
2320
2321void TabContents::FileSelected(const FilePath& path,
2322 int index, void* params) {
2323 render_view_host()->FileSelected(path);
2324}
2325
2326void TabContents::MultiFilesSelected(const std::vector<FilePath>& files,
2327 void* params) {
2328 render_view_host()->MultiFilesSelected(files);
2329}
2330
2331void TabContents::FileSelectionCanceled(void* params) {
2332 // If the user cancels choosing a file to upload we pass back an
2333 // empty vector.
2334 render_view_host()->MultiFilesSelected(std::vector<FilePath>());
2335}
2336
2337void TabContents::BeforeUnloadFiredFromRenderManager(
2338 bool proceed,
2339 bool* proceed_to_fire_unload) {
2340 if (delegate())
2341 delegate()->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
2342}
2343
2344void TabContents::UpdateRenderViewSizeForRenderManager() {
2345 // TODO(brettw) this is a hack. See TabContentsView::SizeContents.
2346 view_->SizeContents(view_->GetContainerSize());
2347}
2348
2349DOMUI* TabContents::CreateDOMUIForRenderManager(const GURL& url) {
2350 return DOMUIFactory::CreateDOMUIForURL(AsWC(this), url);
2351}
2352
2353NavigationEntry*
2354TabContents::GetLastCommittedNavigationEntryForRenderManager() {
2355 return controller_.GetLastCommittedEntry();
2356}
2357
2358bool TabContents::CreateRenderViewForRenderManager(
2359 RenderViewHost* render_view_host) {
2360 // When we're running a DOM UI, the RenderViewHost needs to be put in DOM UI
2361 // mode before CreateRenderView is called. When we're asked to create a
2362 // RenderView, that means it's for the pending entry, so we have to use the
2363 // pending DOM UI.
2364 if (render_manager_.pending_dom_ui())
2365 render_view_host->AllowDOMUIBindings();
2366
2367 RenderWidgetHostView* rwh_view = view_->CreateViewForWidget(render_view_host);
2368 if (!render_view_host->CreateRenderView())
2369 return false;
2370
2371 // Now that the RenderView has been created, we need to tell it its size.
2372 rwh_view->SetSize(view_->GetContainerSize());
2373
2374 UpdateMaxPageIDIfNecessary(render_view_host->site_instance(),
2375 render_view_host);
2376 return true;
2377}
2378
2379void TabContents::Observe(NotificationType type,
2380 const NotificationSource& source,
2381 const NotificationDetails& details) {
2382 switch (type.value) {
2383 case NotificationType::BOOKMARK_MODEL_LOADED:
2384 // BookmarkModel finished loading, fall through to update starred state.
2385 case NotificationType::URLS_STARRED: {
2386 // Somewhere, a URL has been starred.
2387 // Ignore notifications for profiles other than our current one.
2388 Profile* source_profile = Source<Profile>(source).ptr();
2389 if (!source_profile || !source_profile->IsSameProfile(profile()))
2390 return;
2391
2392 UpdateStarredStateForCurrentURL();
2393 break;
2394 }
2395 case NotificationType::PREF_CHANGED: {
2396 std::wstring* pref_name_in = Details<std::wstring>(details).ptr();
2397 DCHECK(Source<PrefService>(source).ptr() == profile()->GetPrefs());
2398 if (*pref_name_in == prefs::kAlternateErrorPagesEnabled) {
2399 UpdateAlternateErrorPageURL();
2400 } else if (*pref_name_in == prefs::kDefaultCharset ||
2401 StartsWithASCII(WideToUTF8(*pref_name_in), "webkit.webprefs.", true)
2402 ) {
2403 UpdateWebPreferences();
2404 } else {
2405 NOTREACHED() << "unexpected pref change notification" << *pref_name_in;
2406 }
2407 break;
2408 }
2409 case NotificationType::RENDER_WIDGET_HOST_DESTROYED:
2410 view_->RenderWidgetHostDestroyed(Source<RenderWidgetHost>(source).ptr());
2411 break;
2412
2413 case NotificationType::NAV_ENTRY_COMMITTED: {
2414 DCHECK(&controller_ == Source<NavigationController>(source).ptr());
2415
2416 NavigationController::LoadCommittedDetails& committed_details =
2417 *(Details<NavigationController::LoadCommittedDetails>(details).ptr());
2418 ExpireInfoBars(committed_details);
2419 break;
2420 }
2421
2422 default:
2423 NOTREACHED();
2424 }
2425}