blob: 83c49c6e8c96002417138ecab48097aeff4d5d20 [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;
[email protected]c9cd2222009-05-06 05:16:50583 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]d5f942ba2008-09-26 19:30:34584}
585
586void TabContents::NotifyNavigationStateChanged(unsigned changed_flags) {
587 if (delegate_)
588 delegate_->NavigationStateChanged(this, changed_flags);
589}
590
[email protected]96d185d2009-04-24 03:28:54591void TabContents::DidBecomeSelected() {
592 controller_.SetActive(true);
593
594 if (render_widget_host_view())
595 render_widget_host_view()->DidBecomeSelected();
596
597 // If pid() is -1, that means the RenderProcessHost still hasn't been
598 // initialized. It'll register with CacheManagerHost when it is.
599 if (process()->pid() != -1)
600 WebCacheManager::GetInstance()->ObserveActivity(process()->pid());
601}
602
603void TabContents::WasHidden() {
604 if (!capturing_contents()) {
605 // |render_view_host()| can be NULL if the user middle clicks a link to open
606 // a tab in then background, then closes the tab before selecting it. This
607 // is because closing the tab calls TabContents::Destroy(), which removes
608 // the |render_view_host()|; then when we actually destroy the window,
609 // OnWindowPosChanged() notices and calls HideContents() (which calls us).
610 if (render_widget_host_view())
611 render_widget_host_view()->WasHidden();
612
613 // Loop through children and send WasHidden to them, too.
614 int count = static_cast<int>(child_windows_.size());
615 for (int i = count - 1; i >= 0; --i) {
616 ConstrainedWindow* window = child_windows_.at(i);
617 window->WasHidden();
618 }
619 }
620
621 NotificationService::current()->Notify(
622 NotificationType::TAB_CONTENTS_HIDDEN,
623 Source<TabContents>(this),
624 NotificationService::NoDetails());
625}
626
[email protected]d5f942ba2008-09-26 19:30:34627void TabContents::Activate() {
628 if (delegate_)
629 delegate_->ActivateContents(this);
630}
631
[email protected]96d185d2009-04-24 03:28:54632void TabContents::ShowContents() {
633 if (render_widget_host_view())
634 render_widget_host_view()->DidBecomeSelected();
635
636 // Loop through children and send DidBecomeSelected to them, too.
637 int count = static_cast<int>(child_windows_.size());
638 for (int i = count - 1; i >= 0; --i) {
639 ConstrainedWindow* window = child_windows_.at(i);
640 window->DidBecomeSelected();
641 }
642}
643
644void TabContents::HideContents() {
645 // TODO(pkasting): http://b/1239839 Right now we purposefully don't call
646 // our superclass HideContents(), because some callers want to be very picky
647 // about the order in which these get called. In addition to making the code
648 // here practically impossible to understand, this also means we end up
649 // calling TabContents::WasHidden() twice if callers call both versions of
[email protected]57c6a652009-05-04 07:58:34650 // HideContents() on a TabContents.
[email protected]96d185d2009-04-24 03:28:54651 WasHidden();
652}
653
[email protected]c0588052008-10-27 23:01:50654void TabContents::OpenURL(const GURL& url, const GURL& referrer,
[email protected]d5f942ba2008-09-26 19:30:34655 WindowOpenDisposition disposition,
656 PageTransition::Type transition) {
657 if (delegate_)
[email protected]c0588052008-10-27 23:01:50658 delegate_->OpenURLFromTab(this, url, referrer, disposition, transition);
[email protected]d5f942ba2008-09-26 19:30:34659}
660
661bool TabContents::NavigateToPendingEntry(bool reload) {
[email protected]96d185d2009-04-24 03:28:54662 const NavigationEntry& entry = *controller_.pending_entry();
663
664 RenderViewHost* dest_render_view_host = render_manager_.Navigate(entry);
665 if (!dest_render_view_host)
666 return false; // Unable to create the desired render view host.
667
668 // Tell DevTools agent that it is attached prior to the navigation.
669 DevToolsManager* dev_tools_manager = g_browser_process->devtools_manager();
670 if (dev_tools_manager) // NULL in unit tests.
[email protected]fab08162009-05-05 10:32:33671 dev_tools_manager->OnNavigatingToPendingEntry(*this,
672 dest_render_view_host);
[email protected]96d185d2009-04-24 03:28:54673
674 // Used for page load time metrics.
675 current_load_start_ = base::TimeTicks::Now();
676
677 // Navigate in the desired RenderViewHost.
678 dest_render_view_host->NavigateToEntry(entry, reload);
679
680 if (entry.page_id() == -1) {
681 // HACK!! This code suppresses javascript: URLs from being added to
682 // session history, which is what we want to do for javascript: URLs that
683 // do not generate content. What we really need is a message from the
684 // renderer telling us that a new page was not created. The same message
685 // could be used for mailto: URLs and the like.
686 if (entry.url().SchemeIs(chrome::kJavaScriptScheme))
687 return false;
688 }
689
690 // Clear any provisional password saves - this stops password infobars
691 // showing up on pages the user navigates to while the right page is
692 // loading.
693 GetPasswordManager()->ClearProvisionalSave();
694
695 if (reload && !profile()->IsOffTheRecord()) {
696 HistoryService* history =
697 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
698 if (history)
699 history->SetFavIconOutOfDateForPage(entry.url());
700 }
701
[email protected]d5f942ba2008-09-26 19:30:34702 return true;
703}
704
[email protected]96d185d2009-04-24 03:28:54705void TabContents::Stop() {
706 render_manager_.Stop();
707 printing_.Stop();
708}
709
710void TabContents::Cut() {
711 render_view_host()->Cut();
712}
713
714void TabContents::Copy() {
715 render_view_host()->Copy();
716}
717
718void TabContents::Paste() {
719 render_view_host()->Paste();
720}
721
722void TabContents::DisassociateFromPopupCount() {
723 render_view_host()->DisassociateFromPopupCount();
724}
725
726TabContents* TabContents::Clone() {
727 // We create a new SiteInstance so that the new tab won't share processes
728 // with the old one. This can be changed in the future if we need it to share
729 // processes for some reason.
[email protected]420ae012009-04-24 05:16:32730 TabContents* tc = new TabContents(profile(),
[email protected]96d185d2009-04-24 03:28:54731 SiteInstance::CreateSiteInstance(profile()),
732 MSG_ROUTING_NONE, NULL);
733 tc->controller().CopyStateFrom(controller_);
734 return tc;
735}
736
[email protected]420ae012009-04-24 05:16:32737void TabContents::CreateShortcut() {
738 NavigationEntry* entry = controller_.GetLastCommittedEntry();
739 if (!entry)
740 return;
741
742 // We only allow one pending install request. By resetting the page id we
743 // effectively cancel the pending install request.
744 pending_install_.page_id = entry->page_id();
745 pending_install_.icon = GetFavIcon();
746 pending_install_.title = UTF16ToWideHack(GetTitle());
747 pending_install_.url = GetURL();
748 if (pending_install_.callback_functor) {
749 pending_install_.callback_functor->Cancel();
750 pending_install_.callback_functor = NULL;
751 }
752 DCHECK(!pending_install_.icon.isNull()) << "Menu item should be disabled.";
753 if (pending_install_.title.empty())
754 pending_install_.title = UTF8ToWide(GetURL().spec());
755
756 // Request the application info. When done OnDidGetApplicationInfo is invoked
757 // and we'll create the shortcut.
758 render_view_host()->GetApplicationInfo(pending_install_.page_id);
759}
760
[email protected]76f68dc2009-03-10 20:31:32761#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29762ConstrainedWindow* TabContents::CreateConstrainedDialog(
[email protected]c2dacc92008-10-16 23:51:38763 views::WindowDelegate* window_delegate,
764 views::View* contents_view) {
initial.commit09911bf2008-07-26 23:55:29765 ConstrainedWindow* window =
766 ConstrainedWindow::CreateConstrainedDialog(
767 this, gfx::Rect(), contents_view, window_delegate);
768 child_windows_.push_back(window);
769 return window;
770}
[email protected]f3332e12009-03-23 15:28:57771#endif
initial.commit09911bf2008-07-26 23:55:29772
773void TabContents::AddNewContents(TabContents* new_contents,
774 WindowOpenDisposition disposition,
775 const gfx::Rect& initial_pos,
[email protected]c88a70fe2009-05-05 20:00:22776 bool user_gesture,
777 const GURL& creator_url) {
initial.commit09911bf2008-07-26 23:55:29778 if (!delegate_)
779 return;
780
[email protected]f3332e12009-03-23 15:28:57781#if defined(OS_WIN)
[email protected]35f7d212009-04-29 21:19:27782 if ((disposition == NEW_POPUP) && !user_gesture &&
783 !CommandLine::ForCurrentProcess()->HasSwitch(
784 switches::kDisablePopupBlocking)) {
[email protected]3b0a45e82008-10-13 21:01:03785 // Unrequested popups from normal pages are constrained.
786 TabContents* popup_owner = this;
787 TabContents* our_owner = delegate_->GetConstrainingContents(this);
788 if (our_owner)
789 popup_owner = our_owner;
790 popup_owner->AddConstrainedPopup(new_contents, initial_pos);
initial.commit09911bf2008-07-26 23:55:29791 } else {
[email protected]0aa55312008-10-17 21:53:08792 new_contents->DisassociateFromPopupCount();
793
initial.commit09911bf2008-07-26 23:55:29794 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
795 user_gesture);
[email protected]634a6f92008-12-01 21:39:31796
797 PopupNotificationVisibilityChanged(ShowingBlockedPopupNotification());
initial.commit09911bf2008-07-26 23:55:29798 }
[email protected]f3332e12009-03-23 15:28:57799#else
800 // TODO(port): implement the popup blocker stuff
801 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
802 user_gesture);
803#endif
initial.commit09911bf2008-07-26 23:55:29804}
805
[email protected]f3332e12009-03-23 15:28:57806#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29807void TabContents::AddConstrainedPopup(TabContents* new_contents,
808 const gfx::Rect& initial_pos) {
[email protected]d6598c052008-11-05 19:03:25809 if (!blocked_popups_) {
810 CRect client_rect;
[email protected]92edc472009-02-10 20:32:06811 GetClientRect(GetNativeView(), &client_rect);
[email protected]d6598c052008-11-05 19:03:25812 gfx::Point anchor_position(
813 client_rect.Width() -
814 views::NativeScrollBar::GetVerticalScrollBarWidth(),
815 client_rect.Height());
initial.commit09911bf2008-07-26 23:55:29816
[email protected]d6598c052008-11-05 19:03:25817 blocked_popups_ = BlockedPopupContainer::Create(
818 this, profile(), anchor_position);
819 child_windows_.push_back(blocked_popups_);
820 }
821
822 blocked_popups_->AddTabContents(new_contents, initial_pos);
[email protected]634a6f92008-12-01 21:39:31823 PopupNotificationVisibilityChanged(ShowingBlockedPopupNotification());
initial.commit09911bf2008-07-26 23:55:29824}
825
initial.commit09911bf2008-07-26 23:55:29826void TabContents::CloseAllSuppressedPopups() {
[email protected]d6598c052008-11-05 19:03:25827 if (blocked_popups_)
828 blocked_popups_->CloseAllPopups();
initial.commit09911bf2008-07-26 23:55:29829}
[email protected]332af7732009-03-11 13:21:35830#endif
initial.commit09911bf2008-07-26 23:55:29831
[email protected]96d185d2009-04-24 03:28:54832void TabContents::PopupNotificationVisibilityChanged(bool visible) {
833 render_view_host()->PopupNotificationVisibilityChanged(visible);
834}
835
836gfx::NativeView TabContents::GetContentNativeView() {
837 return view_->GetContentNativeView();
838}
839
840gfx::NativeView TabContents::GetNativeView() const {
841 return view_->GetNativeView();
842}
843
844void TabContents::GetContainerBounds(gfx::Rect *out) const {
845 view_->GetContainerBounds(out);
846}
847
848void TabContents::Focus() {
849 view_->Focus();
850}
851
852void TabContents::SetInitialFocus(bool reverse) {
853 render_view_host()->SetInitialFocus(reverse);
854}
855
856bool TabContents::FocusLocationBarByDefault() {
857 DOMUI* dom_ui = GetDOMUIForCurrentState();
858 if (dom_ui)
859 return dom_ui->focus_location_bar_by_default();
860 return false;
861}
862
[email protected]616ed5a2008-11-21 22:27:24863void TabContents::AddInfoBar(InfoBarDelegate* delegate) {
864 // Look through the existing InfoBarDelegates we have for a match. If we've
865 // already got one that matches, then we don't add the new one.
[email protected]f86a07022008-11-25 01:06:05866 for (int i = 0; i < infobar_delegate_count(); ++i) {
[email protected]616ed5a2008-11-21 22:27:24867 if (GetInfoBarDelegateAt(i)->EqualsDelegate(delegate))
868 return;
869 }
870
871 infobar_delegates_.push_back(delegate);
[email protected]bfd04a62009-02-01 18:16:56872 NotificationService::current()->Notify(
873 NotificationType::TAB_CONTENTS_INFOBAR_ADDED,
874 Source<TabContents>(this),
875 Details<InfoBarDelegate>(delegate));
[email protected]616ed5a2008-11-21 22:27:24876
877 // Add ourselves as an observer for navigations the first time a delegate is
878 // added. We use this notification to expire InfoBars that need to expire on
879 // page transitions.
880 if (infobar_delegates_.size() == 1) {
[email protected]bfd04a62009-02-01 18:16:56881 registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57882 Source<NavigationController>(&controller_));
[email protected]616ed5a2008-11-21 22:27:24883 }
884}
885
886void TabContents::RemoveInfoBar(InfoBarDelegate* delegate) {
887 std::vector<InfoBarDelegate*>::iterator it =
888 find(infobar_delegates_.begin(), infobar_delegates_.end(), delegate);
889 if (it != infobar_delegates_.end()) {
890 InfoBarDelegate* delegate = *it;
[email protected]bfd04a62009-02-01 18:16:56891 NotificationService::current()->Notify(
892 NotificationType::TAB_CONTENTS_INFOBAR_REMOVED,
893 Source<TabContents>(this),
894 Details<InfoBarDelegate>(delegate));
[email protected]f86a07022008-11-25 01:06:05895 infobar_delegates_.erase(it);
[email protected]616ed5a2008-11-21 22:27:24896
[email protected]6a02963e2009-01-06 16:58:03897 // Remove ourselves as an observer if we are tracking no more InfoBars.
898 if (infobar_delegates_.empty()) {
[email protected]bfd04a62009-02-01 18:16:56899 registrar_.Remove(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57900 Source<NavigationController>(&controller_));
[email protected]6a02963e2009-01-06 16:58:03901 }
[email protected]616ed5a2008-11-21 22:27:24902 }
903}
[email protected]3edd9522009-03-04 22:19:41904
[email protected]96d185d2009-04-24 03:28:54905bool TabContents::IsBookmarkBarAlwaysVisible() {
906 // See GetDOMUIForCurrentState() comment for more info. This case is very
907 // similar, but for non-first loads, we want to use the committed entry. This
908 // is so the bookmarks bar disappears at the same time the page does.
909 if (controller_.GetLastCommittedEntry()) {
910 // Not the first load, always use the committed DOM UI.
911 if (render_manager_.dom_ui())
912 return render_manager_.dom_ui()->force_bookmark_bar_visible();
913 return false; // Default.
914 }
915
916 // When it's the first load, we know either the pending one or the committed
917 // one will have the DOM UI in it (see GetDOMUIForCurrentState), and only one
918 // of them will be valid, so we can just check both.
919 if (render_manager_.pending_dom_ui())
920 return render_manager_.pending_dom_ui()->force_bookmark_bar_visible();
921 if (render_manager_.dom_ui())
922 return render_manager_.dom_ui()->force_bookmark_bar_visible();
923 return false; // Default.
924}
925
926void TabContents::SetDownloadShelfVisible(bool visible) {
927 if (shelf_visible_ != visible) {
928 if (visible) {
929 // Invoke GetDownloadShelf to force the shelf to be created.
930 GetDownloadShelf();
931 }
932 shelf_visible_ = visible;
933
[email protected]c9cd2222009-05-06 05:16:50934 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]96d185d2009-04-24 03:28:54935 }
936
937 // SetShelfVisible can force-close the shelf, so make sure we lay out
938 // everything correctly, as if the animation had finished. This doesn't
939 // matter for showing the shelf, as the show animation will do it.
940 ToolbarSizeChanged(false);
941
942 if (visible) {
943 // Always set this value as it reflects the last time the download shelf
944 // was made visible (even if it was already visible).
945 last_download_shelf_show_ = base::TimeTicks::Now();
946 }
947}
948
[email protected]3edd9522009-03-04 22:19:41949void TabContents::ToolbarSizeChanged(bool is_animating) {
950 TabContentsDelegate* d = delegate();
951 if (d)
952 d->ToolbarSizeChanged(this, is_animating);
953}
[email protected]616ed5a2008-11-21 22:27:24954
[email protected]d5f942ba2008-09-26 19:30:34955void TabContents::OnStartDownload(DownloadItem* download) {
956 DCHECK(download);
957 TabContents* tab_contents = this;
958
[email protected]3edd9522009-03-04 22:19:41959// TODO(port): port contraining contents.
960#if defined(OS_WIN)
[email protected]d5f942ba2008-09-26 19:30:34961 // Download in a constrained popup is shown in the tab that opened it.
962 TabContents* constraining_tab = delegate()->GetConstrainingContents(this);
963 if (constraining_tab)
964 tab_contents = constraining_tab;
[email protected]3edd9522009-03-04 22:19:41965#endif
[email protected]d5f942ba2008-09-26 19:30:34966
[email protected]bcef0dc02009-02-28 00:35:02967 // GetDownloadShelf creates the download shelf if it was not yet created.
968 tab_contents->GetDownloadShelf()->AddDownload(
969 new DownloadItemModel(download));
[email protected]d5f942ba2008-09-26 19:30:34970 tab_contents->SetDownloadShelfVisible(true);
971
[email protected]3edd9522009-03-04 22:19:41972// TODO(port): port animatinos.
973#if defined(OS_WIN)
[email protected]d5f942ba2008-09-26 19:30:34974 // This animation will delete itself when it finishes, or if we become hidden
975 // or destroyed.
[email protected]92edc472009-02-10 20:32:06976 if (IsWindowVisible(GetNativeView())) { // For minimized windows, unit
977 // tests, etc.
[email protected]d5f942ba2008-09-26 19:30:34978 new DownloadStartedAnimation(tab_contents);
979 }
[email protected]3edd9522009-03-04 22:19:41980#endif
[email protected]d5f942ba2008-09-26 19:30:34981}
982
[email protected]bcef0dc02009-02-28 00:35:02983DownloadShelf* TabContents::GetDownloadShelf() {
984 if (!download_shelf_.get())
985 download_shelf_.reset(DownloadShelf::Create(this));
986 return download_shelf_.get();
initial.commit09911bf2008-07-26 23:55:29987}
988
[email protected]bcef0dc02009-02-28 00:35:02989void TabContents::MigrateShelfFrom(TabContents* tab_contents) {
990 download_shelf_.reset(tab_contents->GetDownloadShelf());
991 download_shelf_->ChangeTabContents(tab_contents, this);
992 tab_contents->ReleaseDownloadShelf();
initial.commit09911bf2008-07-26 23:55:29993}
994
[email protected]3edd9522009-03-04 22:19:41995void TabContents::ReleaseDownloadShelf() {
996 download_shelf_.release();
997}
998
999// static
1000void TabContents::MigrateShelf(TabContents* from, TabContents* to) {
1001 bool was_shelf_visible = from->IsDownloadShelfVisible();
1002 if (was_shelf_visible)
1003 to->MigrateShelfFrom(from);
1004 to->SetDownloadShelfVisible(was_shelf_visible);
1005}
[email protected]3edd9522009-03-04 22:19:411006
[email protected]d5f942ba2008-09-26 19:30:341007void TabContents::WillClose(ConstrainedWindow* window) {
1008 ConstrainedWindowList::iterator it =
1009 find(child_windows_.begin(), child_windows_.end(), window);
1010 if (it != child_windows_.end())
1011 child_windows_.erase(it);
1012
[email protected]332af7732009-03-11 13:21:351013#if defined(OS_WIN)
[email protected]d6598c052008-11-05 19:03:251014 if (window == blocked_popups_)
1015 blocked_popups_ = NULL;
1016
[email protected]92edc472009-02-10 20:32:061017 if (::IsWindow(GetNativeView())) {
[email protected]d5f942ba2008-09-26 19:30:341018 CRect client_rect;
[email protected]92edc472009-02-10 20:32:061019 GetClientRect(GetNativeView(), &client_rect);
[email protected]d5f942ba2008-09-26 19:30:341020 RepositionSupressedPopupsToFit(
1021 gfx::Size(client_rect.Width(), client_rect.Height()));
1022 }
[email protected]332af7732009-03-11 13:21:351023#endif
[email protected]d5f942ba2008-09-26 19:30:341024}
1025
[email protected]d5f942ba2008-09-26 19:30:341026void TabContents::DidMoveOrResize(ConstrainedWindow* window) {
[email protected]332af7732009-03-11 13:21:351027#if defined(OS_WIN)
[email protected]92edc472009-02-10 20:32:061028 UpdateWindow(GetNativeView());
[email protected]332af7732009-03-11 13:21:351029#endif
[email protected]d5f942ba2008-09-26 19:30:341030}
1031
[email protected]6e95706d2009-04-23 22:55:011032void TabContents::StartFinding(const string16& find_text,
1033 bool forward_direction) {
1034 // If find_text is empty, it means FindNext was pressed with a keyboard
1035 // shortcut so unless we have something to search for we return early.
1036 if (find_text.empty() && find_text_.empty())
1037 return;
1038
1039 // This is a FindNext operation if we are searching for the same text again,
1040 // or if the passed in search text is empty (FindNext keyboard shortcut). The
1041 // exception to this is if the Find was aborted (then we don't want FindNext
1042 // because the highlighting has been cleared and we need it to reappear). We
1043 // therefore treat FindNext after an aborted Find operation as a full fledged
1044 // Find.
1045 bool find_next = (find_text_ == find_text || find_text.empty()) &&
1046 !find_op_aborted_;
1047 if (!find_next)
1048 current_find_request_id_ = find_request_id_counter_++;
1049
1050 if (!find_text.empty())
1051 find_text_ = find_text;
1052
1053 find_op_aborted_ = false;
1054
1055 // Keep track of what the last search was across the tabs.
1056 *find_prepopulate_text_ = find_text;
1057
1058 render_view_host()->StartFinding(current_find_request_id_,
1059 find_text_,
1060 forward_direction,
1061 false, // case sensitive
1062 find_next);
1063}
1064
1065void TabContents::StopFinding(bool clear_selection) {
1066 find_ui_active_ = false;
1067 find_op_aborted_ = true;
1068 find_result_ = FindNotificationDetails();
1069 render_view_host()->StopFinding(clear_selection);
1070}
1071
[email protected]420ae012009-04-24 05:16:321072void TabContents::OnJavaScriptMessageBoxClosed(IPC::Message* reply_msg,
1073 bool success,
1074 const std::wstring& prompt) {
1075 last_javascript_message_dismissal_ = base::TimeTicks::Now();
1076 render_manager_.OnJavaScriptMessageBoxClosed(reply_msg, success, prompt);
1077}
1078
1079void TabContents::OnSavePage() {
1080 // If we can not save the page, try to download it.
1081 if (!SavePackage::IsSavableContents(contents_mime_type())) {
1082 DownloadManager* dlm = profile()->GetDownloadManager();
1083 const GURL& current_page_url = GetURL();
1084 if (dlm && current_page_url.is_valid())
[email protected]c9825a42009-05-01 22:51:501085 dlm->DownloadUrl(current_page_url, GURL(), "", AsWC(this));
[email protected]420ae012009-04-24 05:16:321086 return;
1087 }
1088
1089 Stop();
1090
1091 // Create the save package and possibly prompt the user for the name to save
1092 // the page as. The user prompt is an asynchronous operation that runs on
1093 // another thread.
1094 save_package_ = new SavePackage(AsWC(this));
1095 save_package_->GetSaveInfo();
1096}
1097
1098// Used in automated testing to bypass prompting the user for file names.
1099// Instead, the names and paths are hard coded rather than running them through
1100// file name sanitation and extension / mime checking.
1101void TabContents::SavePage(const std::wstring& main_file,
1102 const std::wstring& dir_path,
1103 SavePackage::SavePackageType save_type) {
1104 // Stop the page from navigating.
1105 Stop();
1106
1107 save_package_ = new SavePackage(AsWC(this), save_type,
1108 FilePath::FromWStringHack(main_file),
1109 FilePath::FromWStringHack(dir_path));
1110 save_package_->Init();
1111}
1112
1113void TabContents::PrintPreview() {
1114 // We don't show the print preview yet, only the print dialog.
1115 PrintNow();
1116}
1117
1118bool TabContents::PrintNow() {
1119 // We can't print interstitial page for now.
1120 if (showing_interstitial_page())
1121 return false;
1122
1123 return render_view_host()->PrintPages();
1124}
1125
1126bool TabContents::IsActiveEntry(int32 page_id) {
1127 NavigationEntry* active_entry = controller_.GetActiveEntry();
1128 return (active_entry != NULL &&
1129 active_entry->site_instance() == GetSiteInstance() &&
1130 active_entry->page_id() == page_id);
1131}
1132
[email protected]96d185d2009-04-24 03:28:541133// Notifies the RenderWidgetHost instance about the fact that the page is
1134// loading, or done loading and calls the base implementation.
1135void TabContents::SetIsLoading(bool is_loading,
1136 LoadNotificationDetails* details) {
1137 if (is_loading == is_loading_)
1138 return;
1139
1140 if (!is_loading) {
1141 load_state_ = net::LOAD_STATE_IDLE;
1142 load_state_host_.clear();
1143 }
1144
1145 render_manager_.SetIsLoading(is_loading);
1146
1147 is_loading_ = is_loading;
1148 waiting_for_response_ = is_loading;
1149
1150 if (delegate_)
1151 delegate_->LoadingStateChanged(this);
[email protected]329581b2009-04-28 06:52:351152 NotifyNavigationStateChanged(INVALIDATE_LOAD);
[email protected]96d185d2009-04-24 03:28:541153
1154 NotificationType type = is_loading ? NotificationType::LOAD_START :
1155 NotificationType::LOAD_STOP;
1156 NotificationDetails det = NotificationService::NoDetails();;
1157 if (details)
1158 det = Details<LoadNotificationDetails>(details);
1159 NotificationService::current()->Notify(type,
1160 Source<NavigationController>(&controller_),
1161 det);
1162}
1163
[email protected]76f68dc2009-03-10 20:31:321164#if defined(OS_WIN)
[email protected]e69bce3dd2009-04-20 22:05:121165// TODO(brettw) This should be on the TabContentsView.
[email protected]d5f942ba2008-09-26 19:30:341166void TabContents::RepositionSupressedPopupsToFit(const gfx::Size& new_size) {
1167 // TODO(erg): There's no way to detect whether scroll bars are
1168 // visible, so for beta, we're just going to assume that the
1169 // vertical scroll bar is visible, and not care about covering up
1170 // the horizontal scroll bar. Fixing this is half of
1171 // http://b/1118139.
1172 gfx::Point anchor_position(
1173 new_size.width() -
[email protected]c2dacc92008-10-16 23:51:381174 views::NativeScrollBar::GetVerticalScrollBarWidth(),
[email protected]d5f942ba2008-09-26 19:30:341175 new_size.height());
[email protected]d6598c052008-11-05 19:03:251176
1177 if (blocked_popups_)
1178 blocked_popups_->RepositionConstrainedWindowTo(anchor_position);
[email protected]d5f942ba2008-09-26 19:30:341179}
1180
[email protected]b9681312008-11-07 00:08:261181bool TabContents::ShowingBlockedPopupNotification() const {
1182 return blocked_popups_ != NULL &&
1183 blocked_popups_->GetTabContentsCount() != 0;
1184}
[email protected]332af7732009-03-11 13:21:351185#endif // defined(OS_WIN)
[email protected]616ed5a2008-11-21 22:27:241186
1187namespace {
1188bool TransitionIsReload(PageTransition::Type transition) {
1189 return PageTransition::StripQualifier(transition) == PageTransition::RELOAD;
1190}
1191}
1192
1193void TabContents::ExpireInfoBars(
1194 const NavigationController::LoadCommittedDetails& details) {
1195 // Only hide InfoBars when the user has done something that makes the main
1196 // frame load. We don't want various automatic or subframe navigations making
1197 // it disappear.
1198 if (!details.is_user_initiated_main_frame_load())
1199 return;
1200
[email protected]f86a07022008-11-25 01:06:051201 for (int i = infobar_delegate_count() - 1; i >= 0; --i) {
[email protected]616ed5a2008-11-21 22:27:241202 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
[email protected]f86a07022008-11-25 01:06:051203 if (delegate->ShouldExpire(details))
[email protected]616ed5a2008-11-21 22:27:241204 RemoveInfoBar(delegate);
[email protected]616ed5a2008-11-21 22:27:241205 }
1206}
[email protected]fdd61c62009-04-22 19:22:571207
1208void TabContents::OnGearsCreateShortcutDone(
1209 const GearsShortcutData2& shortcut_data, bool success) {
1210 NavigationEntry* current_entry = controller_.GetLastCommittedEntry();
1211 bool same_page =
1212 current_entry && pending_install_.page_id == current_entry->page_id();
1213
1214 if (success && same_page) {
1215 // Only switch to app mode if the user chose to create a shortcut and
1216 // we're still on the same page that it corresponded to.
1217 if (delegate())
1218 delegate()->ConvertContentsToApplication(this);
1219 }
1220
1221 // Reset the page id to indicate no requests are pending.
1222 pending_install_.page_id = 0;
1223 pending_install_.callback_functor = NULL;
1224}
[email protected]96d185d2009-04-24 03:28:541225
1226DOMUI* TabContents::GetDOMUIForCurrentState() {
1227 // When there is a pending navigation entry, we want to use the pending DOMUI
1228 // that goes along with it to control the basic flags. For example, we want to
1229 // show the pending URL in the URL bar, so we want the display_url flag to
1230 // be from the pending entry.
1231 //
1232 // The confusion comes because there are multiple possibilities for the
1233 // initial load in a tab as a side effect of the way the RenderViewHostManager
1234 // works.
1235 //
1236 // - For the very first tab the load looks "normal". The new tab DOM UI is
1237 // the pending one, and we want it to apply here.
1238 //
1239 // - For subsequent new tabs, they'll get a new SiteInstance which will then
1240 // get switched to the one previously associated with the new tab pages.
1241 // This switching will cause the manager to commit the RVH/DOMUI. So we'll
1242 // have a committed DOM UI in this case.
1243 //
1244 // This condition handles all of these cases:
1245 //
1246 // - First load in first tab: no committed nav entry + pending nav entry +
1247 // pending dom ui:
1248 // -> Use pending DOM UI if any.
1249 //
1250 // - First load in second tab: no committed nav entry + pending nav entry +
1251 // no pending DOM UI:
1252 // -> Use the committed DOM UI if any.
1253 //
1254 // - Second navigation in any tab: committed nav entry + pending nav entry:
1255 // -> Use pending DOM UI if any.
1256 //
1257 // - Normal state with no load: committed nav entry + no pending nav entry:
1258 // -> Use committed DOM UI.
1259 if (controller_.pending_entry() &&
1260 (controller_.GetLastCommittedEntry() ||
1261 render_manager_.pending_dom_ui()))
1262 return render_manager_.pending_dom_ui();
1263 return render_manager_.dom_ui();
1264}
[email protected]420ae012009-04-24 05:16:321265
1266void TabContents::DidNavigateMainFramePostCommit(
1267 const NavigationController::LoadCommittedDetails& details,
1268 const ViewHostMsg_FrameNavigate_Params& params) {
1269 // Hide the download shelf if all the following conditions are true:
1270 // - there are no active downloads.
1271 // - this is a navigation to a different TLD.
1272 // - at least 5 seconds have elapsed since the download shelf was shown.
1273 // TODO(jcampan): bug 1156075 when user gestures are reliable, they should
1274 // be used to ensure we are hiding only on user initiated
1275 // navigations.
1276 DownloadManager* download_manager = profile()->GetDownloadManager();
1277 // download_manager can be NULL in unit test context.
1278 if (download_manager && download_manager->in_progress_count() == 0 &&
1279 !details.previous_url.is_empty() &&
1280 !net::RegistryControlledDomainService::SameDomainOrHost(
1281 details.previous_url, details.entry->url())) {
1282 base::TimeDelta time_delta(
1283 base::TimeTicks::Now() - last_download_shelf_show_);
1284 if (time_delta >
1285 base::TimeDelta::FromMilliseconds(kDownloadShelfHideDelay)) {
1286 SetDownloadShelfVisible(false);
1287 }
1288 }
1289
1290 if (details.is_user_initiated_main_frame_load()) {
1291 // Clear the status bubble. This is a workaround for a bug where WebKit
1292 // doesn't let us know that the cursor left an element during a
1293 // transition (this is also why the mouse cursor remains as a hand after
1294 // clicking on a link); see bugs 1184641 and 980803. We don't want to
1295 // clear the bubble when a user navigates to a named anchor in the same
1296 // page.
1297 UpdateTargetURL(details.entry->page_id(), GURL());
1298
1299 // UpdateHelpersForDidNavigate will handle the case where the password_form
1300 // origin is valid.
1301 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1302 // cleaned up and covered by tests.
1303 if (!params.password_form.origin.is_valid())
1304 GetPasswordManager()->DidNavigate();
1305 }
1306
1307 // The keyword generator uses the navigation entries, so must be called after
1308 // the commit.
1309 GenerateKeywordIfNecessary(params);
1310
1311 // Allow the new page to set the title again.
1312 received_page_title_ = false;
1313
1314 // Get the favicon, either from history or request it from the net.
1315 fav_icon_helper_.FetchFavIcon(details.entry->url());
1316
1317 // Close constrained popups if necessary.
1318 MaybeCloseChildWindows(details.previous_url, details.entry->url());
1319
1320 // Update the starred state.
1321 UpdateStarredStateForCurrentURL();
1322}
1323
1324void TabContents::DidNavigateAnyFramePostCommit(
1325 RenderViewHost* render_view_host,
1326 const NavigationController::LoadCommittedDetails& details,
1327 const ViewHostMsg_FrameNavigate_Params& params) {
1328 // If we navigate, start showing messages again. This does nothing to prevent
1329 // a malicious script from spamming messages, since the script could just
1330 // reload the page to stop blocking.
1331 suppress_javascript_messages_ = false;
1332
1333 // Update history. Note that this needs to happen after the entry is complete,
1334 // which WillNavigate[Main,Sub]Frame will do before this function is called.
1335 if (params.should_update_history) {
1336 // Most of the time, the displayURL matches the loaded URL, but for about:
1337 // URLs, we use a data: URL as the real value. We actually want to save
1338 // the about: URL to the history db and keep the data: URL hidden. This is
1339 // what the TabContents' URL getter does.
1340 UpdateHistoryForNavigation(GetURL(), params);
1341 }
1342
1343 // Notify the password manager of the navigation or form submit.
1344 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1345 // cleaned up and covered by tests.
1346 if (params.password_form.origin.is_valid())
1347 GetPasswordManager()->ProvisionallySavePassword(params.password_form);
1348}
1349
1350void TabContents::MaybeCloseChildWindows(const GURL& previous_url,
1351 const GURL& current_url) {
1352 if (net::RegistryControlledDomainService::SameDomainOrHost(
1353 previous_url, current_url))
1354 return;
1355
1356 // Clear out any child windows since we are leaving this page entirely.
1357 // We use indices instead of iterators in case CloseWindow does something
1358 // that may invalidate an iterator.
1359 int size = static_cast<int>(child_windows_.size());
1360 for (int i = size - 1; i >= 0; --i) {
1361 ConstrainedWindow* window = child_windows_[i];
1362 if (window)
1363 window->CloseConstrainedWindow();
1364 }
1365}
1366
1367void TabContents::UpdateStarredStateForCurrentURL() {
1368 BookmarkModel* model = profile()->GetBookmarkModel();
1369 const bool old_state = is_starred_;
1370 is_starred_ = (model && model->IsBookmarked(GetURL()));
1371
1372 if (is_starred_ != old_state && delegate())
1373 delegate()->URLStarredChanged(this, is_starred_);
1374}
1375
1376void TabContents::UpdateAlternateErrorPageURL() {
1377 GURL url = GetAlternateErrorPageURL();
1378 render_view_host()->SetAlternateErrorPageURL(url);
1379}
1380
1381void TabContents::UpdateWebPreferences() {
1382 render_view_host()->UpdateWebPreferences(GetWebkitPrefs());
1383}
1384
1385void TabContents::UpdateMaxPageIDIfNecessary(SiteInstance* site_instance,
1386 RenderViewHost* rvh) {
1387 // If we are creating a RVH for a restored controller, then we might
1388 // have more page IDs than the SiteInstance's current max page ID. We must
1389 // make sure that the max page ID is larger than any restored page ID.
1390 // Note that it is ok for conflicting page IDs to exist in another tab
1391 // (i.e., NavigationController), but if any page ID is larger than the max,
1392 // the back/forward list will get confused.
1393 int max_restored_page_id = controller_.max_restored_page_id();
1394 if (max_restored_page_id > 0) {
1395 int curr_max_page_id = site_instance->max_page_id();
1396 if (max_restored_page_id > curr_max_page_id) {
1397 // Need to update the site instance immediately.
1398 site_instance->UpdateMaxPageID(max_restored_page_id);
1399
1400 // Also tell the renderer to update its internal representation. We
1401 // need to reserve enough IDs to make all restored page IDs less than
1402 // the max.
1403 if (curr_max_page_id < 0)
1404 curr_max_page_id = 0;
1405 rvh->ReservePageIDRange(max_restored_page_id - curr_max_page_id);
1406 }
1407 }
1408}
1409
1410void TabContents::UpdateHistoryForNavigation(
1411 const GURL& display_url,
1412 const ViewHostMsg_FrameNavigate_Params& params) {
1413 if (profile()->IsOffTheRecord())
1414 return;
1415
1416 // Add to history service.
1417 HistoryService* hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1418 if (hs) {
1419 if (PageTransition::IsMainFrame(params.transition) &&
1420 display_url != params.url) {
1421 // Hack on the "display" URL so that it will appear in history. For some
1422 // types of URLs, we will display a magic URL that is different from where
1423 // the page is actually navigated. We want the user to see in history
1424 // what they saw in the URL bar, so we add the display URL as a redirect.
1425 // This only applies to the main frame, as the display URL doesn't apply
1426 // to sub-frames.
1427 std::vector<GURL> redirects = params.redirects;
1428 if (!redirects.empty())
1429 redirects.back() = display_url;
1430 hs->AddPage(display_url, this, params.page_id, params.referrer,
1431 params.transition, redirects);
1432 } else {
1433 hs->AddPage(params.url, this, params.page_id, params.referrer,
1434 params.transition, params.redirects);
1435 }
1436 }
1437}
1438
1439bool TabContents::UpdateTitleForEntry(NavigationEntry* entry,
1440 const std::wstring& title) {
1441 // For file URLs without a title, use the pathname instead. In the case of a
1442 // synthesized title, we don't want the update to count toward the "one set
1443 // per page of the title to history."
1444 std::wstring final_title;
1445 bool explicit_set;
1446 if (entry->url().SchemeIsFile() && title.empty()) {
1447 final_title = UTF8ToWide(entry->url().ExtractFileName());
1448 explicit_set = false; // Don't count synthetic titles toward the set limit.
1449 } else {
1450 TrimWhitespace(title, TRIM_ALL, &final_title);
1451 explicit_set = true;
1452 }
1453
1454 if (final_title == UTF16ToWideHack(entry->title()))
1455 return false; // Nothing changed, don't bother.
1456
1457 entry->set_title(WideToUTF16Hack(final_title));
1458
1459 // Update the history system for this page.
1460 if (!profile()->IsOffTheRecord() && !received_page_title_) {
1461 HistoryService* hs =
1462 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1463 if (hs)
1464 hs->SetPageTitle(entry->display_url(), final_title);
1465
1466 // Don't allow the title to be saved again for explicitly set ones.
1467 received_page_title_ = explicit_set;
1468 }
1469
1470 // Lastly, set the title for the view.
1471 view_->SetPageTitle(final_title);
1472
1473 return true;
1474}
1475
1476void TabContents::NotifySwapped() {
1477 // After sending out a swap notification, we need to send a disconnect
1478 // notification so that clients that pick up a pointer to |this| can NULL the
1479 // pointer. See Bug 1230284.
1480 notify_disconnection_ = true;
1481 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341482 NotificationType::TAB_CONTENTS_SWAPPED,
1483 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321484 NotificationService::NoDetails());
1485}
1486
1487void TabContents::NotifyConnected() {
1488 notify_disconnection_ = true;
1489 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341490 NotificationType::TAB_CONTENTS_CONNECTED,
1491 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321492 NotificationService::NoDetails());
1493}
1494
1495void TabContents::NotifyDisconnected() {
1496 if (!notify_disconnection_)
1497 return;
1498
1499 notify_disconnection_ = false;
1500 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341501 NotificationType::TAB_CONTENTS_DISCONNECTED,
1502 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321503 NotificationService::NoDetails());
1504}
1505
1506void TabContents::GenerateKeywordIfNecessary(
1507 const ViewHostMsg_FrameNavigate_Params& params) {
1508 if (!params.searchable_form_url.is_valid())
1509 return;
1510
1511 if (profile()->IsOffTheRecord())
1512 return;
1513
1514 int last_index = controller_.last_committed_entry_index();
1515 // When there was no previous page, the last index will be 0. This is
1516 // normally due to a form submit that opened in a new tab.
1517 // TODO(brettw) bug 916126: we should support keywords when form submits
1518 // happen in new tabs.
1519 if (last_index <= 0)
1520 return;
1521 const NavigationEntry* previous_entry =
1522 controller_.GetEntryAtIndex(last_index - 1);
1523 if (IsFormSubmit(previous_entry)) {
1524 // Only generate a keyword if the previous page wasn't itself a form
1525 // submit.
1526 return;
1527 }
1528
1529 GURL keyword_url = previous_entry->user_typed_url().is_valid() ?
1530 previous_entry->user_typed_url() : previous_entry->url();
1531 std::wstring keyword =
1532 TemplateURLModel::GenerateKeyword(keyword_url, true); // autodetected
1533 if (keyword.empty())
1534 return;
1535
1536 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
1537 if (!url_model)
1538 return;
1539
1540 if (!url_model->loaded()) {
1541 url_model->Load();
1542 return;
1543 }
1544
1545 const TemplateURL* current_url;
1546 std::wstring url = UTF8ToWide(params.searchable_form_url.spec());
1547 if (!url_model->CanReplaceKeyword(keyword, url, &current_url))
1548 return;
1549
1550 if (current_url) {
1551 if (current_url->originating_url().is_valid()) {
1552 // The existing keyword was generated from an OpenSearch description
1553 // document, don't regenerate.
1554 return;
1555 }
1556 url_model->Remove(current_url);
1557 }
1558 TemplateURL* new_url = new TemplateURL();
1559 new_url->set_keyword(keyword);
1560 new_url->set_short_name(keyword);
1561 new_url->SetURL(url, 0, 0);
1562 new_url->add_input_encoding(params.searchable_form_encoding);
1563 DCHECK(controller_.GetLastCommittedEntry());
1564 const GURL& favicon_url =
1565 controller_.GetLastCommittedEntry()->favicon().url();
1566 if (favicon_url.is_valid()) {
1567 new_url->SetFavIconURL(favicon_url);
1568 } else {
1569 // The favicon url isn't valid. This means there really isn't a favicon,
1570 // or the favicon url wasn't obtained before the load started. This assumes
1571 // the later.
1572 // TODO(sky): Need a way to set the favicon that doesn't involve generating
1573 // its url.
1574 new_url->SetFavIconURL(TemplateURL::GenerateFaviconURL(params.referrer));
1575 }
1576 new_url->set_safe_for_autoreplace(true);
1577 url_model->Add(new_url);
1578}
1579
1580RenderViewHostDelegate::View* TabContents::GetViewDelegate() const {
1581 return view_.get();
1582}
1583
1584RenderViewHostDelegate::Save* TabContents::GetSaveDelegate() const {
1585 return save_package_.get(); // May be NULL, but we can return NULL.
1586}
1587
1588Profile* TabContents::GetProfile() const {
1589 return profile();
1590}
1591
[email protected]6dfed102009-04-28 03:09:531592ExtensionFunctionDispatcher* TabContents::CreateExtensionFunctionDispatcher(
1593 RenderViewHost* render_view_host,
1594 const std::string& extension_id) {
1595 return delegate()->CreateExtensionFunctionDispatcher(render_view_host,
1596 extension_id);
1597}
1598
[email protected]57c6a652009-05-04 07:58:341599TabContents* TabContents::GetAsTabContents() {
1600 return this;
1601}
1602
[email protected]420ae012009-04-24 05:16:321603void TabContents::RenderViewCreated(RenderViewHost* render_view_host) {
1604 NavigationEntry* entry = controller_.GetActiveEntry();
1605 if (!entry)
1606 return;
1607
1608 // When we're creating views, we're still doing initial setup, so we always
1609 // use the pending DOM UI rather than any possibly existing committed one.
1610 if (render_manager_.pending_dom_ui()) {
1611 render_manager_.pending_dom_ui()->RenderViewCreated(render_view_host);
1612 }
1613
1614 if (entry->IsViewSourceMode()) {
1615 // Put the renderer in view source mode.
1616 render_view_host->Send(
1617 new ViewMsg_EnableViewSourceMode(render_view_host->routing_id()));
1618 }
1619}
1620
1621void TabContents::RenderViewReady(RenderViewHost* rvh) {
1622 if (rvh != render_view_host()) {
1623 // Don't notify the world, since this came from a renderer in the
1624 // background.
1625 return;
1626 }
1627
1628 NotifyConnected();
1629 SetIsCrashed(false);
1630}
1631
1632void TabContents::RenderViewGone(RenderViewHost* rvh) {
1633 // Ask the print preview if this renderer was valuable.
1634 if (!printing_.OnRenderViewGone(rvh))
1635 return;
1636 if (rvh != render_view_host()) {
1637 // The pending page's RenderViewHost is gone.
1638 return;
1639 }
1640
1641 SetIsLoading(false, NULL);
1642 NotifyDisconnected();
1643 SetIsCrashed(true);
1644
1645 // Force an invalidation to render sad tab. The view will notice we crashed
1646 // when it paints.
1647 view_->Invalidate();
1648
1649 // Hide any visible hung renderer warning for this web contents' process.
[email protected]57c6a652009-05-04 07:58:341650 HungRendererWarning::HideForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:321651}
1652
1653void TabContents::DidNavigate(RenderViewHost* rvh,
1654 const ViewHostMsg_FrameNavigate_Params& params) {
1655 if (PageTransition::IsMainFrame(params.transition))
1656 render_manager_.DidNavigateMainFrame(rvh);
1657
1658 // Update the site of the SiteInstance if it doesn't have one yet.
1659 if (!GetSiteInstance()->has_site())
1660 GetSiteInstance()->SetSite(params.url);
1661
1662 // Need to update MIME type here because it's referred to in
1663 // UpdateNavigationCommands() called by RendererDidNavigate() to
1664 // determine whether or not to enable the encoding menu.
1665 // It's updated only for the main frame. For a subframe,
1666 // RenderView::UpdateURL does not set params.contents_mime_type.
1667 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
1668 // TODO(jungshik): Add a test for the encoding menu to avoid
1669 // regressing it again.
1670 if (PageTransition::IsMainFrame(params.transition))
1671 contents_mime_type_ = params.contents_mime_type;
1672
1673 NavigationController::LoadCommittedDetails details;
1674 if (!controller_.RendererDidNavigate(params, &details))
1675 return; // No navigation happened.
1676
1677 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
1678 // for the appropriate notification (best) or you can add it to
1679 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
1680 // necessary, please).
1681
1682 // Run post-commit tasks.
1683 if (details.is_main_frame)
1684 DidNavigateMainFramePostCommit(details, params);
1685 DidNavigateAnyFramePostCommit(rvh, details, params);
1686}
1687
1688void TabContents::UpdateState(RenderViewHost* rvh,
1689 int32 page_id,
1690 const std::string& state) {
1691 DCHECK(rvh == render_view_host());
1692
1693 // We must be prepared to handle state updates for any page, these occur
1694 // when the user is scrolling and entering form data, as well as when we're
1695 // leaving a page, in which case our state may have already been moved to
1696 // the next page. The navigation controller will look up the appropriate
1697 // NavigationEntry and update it when it is notified via the delegate.
1698
1699 int entry_index = controller_.GetEntryIndexWithPageID(
1700 GetSiteInstance(), page_id);
1701 if (entry_index < 0)
1702 return;
1703 NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
1704
1705 if (state == entry->content_state())
1706 return; // Nothing to update.
1707 entry->set_content_state(state);
1708 controller_.NotifyEntryChanged(entry, entry_index);
1709}
1710
1711void TabContents::UpdateTitle(RenderViewHost* rvh,
1712 int32 page_id, const std::wstring& title) {
1713 // If we have a title, that's a pretty good indication that we've started
1714 // getting useful data.
1715 SetNotWaitingForResponse();
1716
1717 DCHECK(rvh == render_view_host());
1718 NavigationEntry* entry = controller_.GetEntryWithPageID(GetSiteInstance(),
1719 page_id);
1720 if (!entry || !UpdateTitleForEntry(entry, title))
1721 return;
1722
1723 // Broadcast notifications when the UI should be updated.
1724 if (entry == controller_.GetEntryAtOffset(0))
[email protected]c9cd2222009-05-06 05:16:501725 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:321726}
1727
[email protected]420ae012009-04-24 05:16:321728void TabContents::UpdateEncoding(RenderViewHost* render_view_host,
1729 const std::wstring& encoding) {
1730 set_encoding(encoding);
1731}
1732
1733void TabContents::UpdateTargetURL(int32 page_id, const GURL& url) {
1734 if (delegate())
1735 delegate()->UpdateTargetURL(this, url);
1736}
1737
1738void TabContents::UpdateThumbnail(const GURL& url,
1739 const SkBitmap& bitmap,
1740 const ThumbnailScore& score) {
1741 // Tell History about this thumbnail
1742 HistoryService* hs;
1743 if (!profile()->IsOffTheRecord() &&
1744 (hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS))) {
1745 hs->SetPageThumbnail(url, bitmap, score);
1746 }
1747}
1748
1749void TabContents::Close(RenderViewHost* rvh) {
1750 // Ignore this if it comes from a RenderViewHost that we aren't showing.
1751 if (delegate() && rvh == render_view_host())
1752 delegate()->CloseContents(this);
1753}
1754
1755void TabContents::RequestMove(const gfx::Rect& new_bounds) {
1756 if (delegate() && delegate()->IsPopup(this))
1757 delegate()->MoveContents(this, new_bounds);
1758}
1759
[email protected]329581b2009-04-28 06:52:351760void TabContents::DidStartLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321761 SetIsLoading(true, NULL);
1762}
1763
[email protected]329581b2009-04-28 06:52:351764void TabContents::DidStopLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321765 scoped_ptr<LoadNotificationDetails> details;
1766
1767 NavigationEntry* entry = controller_.GetActiveEntry();
1768 // An entry may not exist for a stop when loading an initial blank page or
1769 // if an iframe injected by script into a blank page finishes loading.
1770 if (entry) {
1771 scoped_ptr<base::ProcessMetrics> metrics(
1772 base::ProcessMetrics::CreateProcessMetrics(
1773 process()->process().handle()));
1774
1775 base::TimeDelta elapsed = base::TimeTicks::Now() - current_load_start_;
1776
1777 details.reset(new LoadNotificationDetails(
1778 entry->display_url(),
1779 entry->transition_type(),
1780 elapsed,
1781 &controller_,
1782 controller_.GetCurrentEntryIndex()));
1783 }
1784
1785 // Tell PasswordManager we've finished a page load, which serves as a
1786 // green light to save pending passwords and reset itself.
1787 GetPasswordManager()->DidStopLoading();
1788
1789 SetIsLoading(false, details.get());
1790}
1791
1792void TabContents::DidStartProvisionalLoadForFrame(
1793 RenderViewHost* render_view_host,
1794 bool is_main_frame,
1795 const GURL& url) {
1796 ProvisionalLoadDetails details(is_main_frame,
1797 controller_.IsURLInPageNavigation(url),
1798 url, std::string(), false);
1799 NotificationService::current()->Notify(
1800 NotificationType::FRAME_PROVISIONAL_LOAD_START,
1801 Source<NavigationController>(&controller_),
1802 Details<ProvisionalLoadDetails>(&details));
1803}
1804
1805void TabContents::DidRedirectProvisionalLoad(int32 page_id,
1806 const GURL& source_url,
1807 const GURL& target_url) {
1808 NavigationEntry* entry;
1809 if (page_id == -1)
1810 entry = controller_.pending_entry();
1811 else
1812 entry = controller_.GetEntryWithPageID(GetSiteInstance(), page_id);
1813 if (!entry || entry->url() != source_url)
1814 return;
1815 entry->set_url(target_url);
1816}
1817
1818void TabContents::DidLoadResourceFromMemoryCache(
1819 const GURL& url,
1820 const std::string& frame_origin,
1821 const std::string& main_frame_origin,
1822 const std::string& security_info) {
1823 // Send out a notification that we loaded a resource from our memory cache.
1824 int cert_id = 0, cert_status = 0, security_bits = 0;
1825 SSLManager::DeserializeSecurityInfo(security_info,
1826 &cert_id, &cert_status,
1827 &security_bits);
1828 LoadFromMemoryCacheDetails details(url, frame_origin, main_frame_origin,
1829 cert_id, cert_status);
1830
1831 NotificationService::current()->Notify(
1832 NotificationType::LOAD_FROM_MEMORY_CACHE,
1833 Source<NavigationController>(&controller_),
1834 Details<LoadFromMemoryCacheDetails>(&details));
1835}
1836
1837void TabContents::DidFailProvisionalLoadWithError(
1838 RenderViewHost* render_view_host,
1839 bool is_main_frame,
1840 int error_code,
1841 const GURL& url,
1842 bool showing_repost_interstitial) {
1843 if (net::ERR_ABORTED == error_code) {
1844 // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
1845 // This means that the interstitial won't be torn down properly, which is
1846 // bad. But if we have an interstitial, go back to another tab type, and
1847 // then load the same interstitial again, we could end up getting the first
1848 // interstitial's "failed" message (as a result of the cancel) when we're on
1849 // the second one.
1850 //
1851 // We can't tell this apart, so we think we're tearing down the current page
1852 // which will cause a crash later one. There is also some code in
1853 // RenderViewHostManager::RendererAbortedProvisionalLoad that is commented
1854 // out because of this problem.
1855 //
1856 // http://code.google.com/p/chromium/issues/detail?id=2855
1857 // Because this will not tear down the interstitial properly, if "back" is
1858 // back to another tab type, the interstitial will still be somewhat alive
1859 // in the previous tab type. If you navigate somewhere that activates the
1860 // tab with the interstitial again, you'll see a flash before the new load
1861 // commits of the interstitial page.
1862 if (showing_interstitial_page()) {
1863 LOG(WARNING) << "Discarding message during interstitial.";
1864 return;
1865 }
1866
1867 // This will discard our pending entry if we cancelled the load (e.g., if we
1868 // decided to download the file instead of load it). Only discard the
1869 // pending entry if the URLs match, otherwise the user initiated a navigate
1870 // before the page loaded so that the discard would discard the wrong entry.
1871 NavigationEntry* pending_entry = controller_.pending_entry();
1872 if (pending_entry && pending_entry->url() == url)
1873 controller_.DiscardNonCommittedEntries();
1874
1875 render_manager_.RendererAbortedProvisionalLoad(render_view_host);
1876 }
1877
1878 // Send out a notification that we failed a provisional load with an error.
1879 ProvisionalLoadDetails details(is_main_frame,
1880 controller_.IsURLInPageNavigation(url),
1881 url, std::string(), false);
1882 details.set_error_code(error_code);
1883
1884 NotificationService::current()->Notify(
1885 NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR,
1886 Source<NavigationController>(&controller_),
1887 Details<ProvisionalLoadDetails>(&details));
1888}
1889
1890void TabContents::UpdateFavIconURL(RenderViewHost* render_view_host,
1891 int32 page_id,
1892 const GURL& icon_url) {
1893 fav_icon_helper_.SetFavIconURL(icon_url);
1894}
1895
1896void TabContents::DidDownloadImage(
1897 RenderViewHost* render_view_host,
1898 int id,
1899 const GURL& image_url,
1900 bool errored,
1901 const SkBitmap& image) {
1902 // A notification for downloading would be more flexible, but for now I'm
1903 // forwarding to the two places that could possibly have initiated the
1904 // request. If we end up with another place invoking DownloadImage, probably
1905 // best to refactor out into notification service, or something similar.
1906 if (errored)
1907 fav_icon_helper_.FavIconDownloadFailed(id);
1908 else
1909 fav_icon_helper_.SetFavIcon(id, image_url, image);
1910}
1911
1912void TabContents::RequestOpenURL(const GURL& url, const GURL& referrer,
1913 WindowOpenDisposition disposition) {
1914 if (render_manager_.dom_ui()) {
1915 // When we're a DOM UI, it will provide a page transition type for us (this
1916 // is so the new tab page can specify AUTO_BOOKMARK for automatically
1917 // generated suggestions).
1918 //
1919 // Note also that we hide the referrer for DOM UI pages. We don't really
[email protected]60e448982009-05-06 04:21:161920 // want web sites to see a referrer of "chrome://blah" (and some
1921 // chrome: URLs might have search terms or other stuff we don't want to
[email protected]420ae012009-04-24 05:16:321922 // send to the site), so we send no referrer.
1923 OpenURL(url, GURL(), disposition,
1924 render_manager_.dom_ui()->link_transition_type());
1925 } else {
1926 OpenURL(url, referrer, disposition, PageTransition::LINK);
1927 }
1928}
1929
1930void TabContents::DomOperationResponse(const std::string& json_string,
1931 int automation_id) {
1932 DomOperationNotificationDetails details(json_string, automation_id);
1933 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341934 NotificationType::DOM_OPERATION_RESPONSE, Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321935 Details<DomOperationNotificationDetails>(&details));
1936}
1937
1938void TabContents::ProcessDOMUIMessage(const std::string& message,
1939 const std::string& content) {
1940 if (!render_manager_.dom_ui()) {
1941 // We shouldn't get a DOM UI message when we haven't enabled the DOM UI.
1942 // Because the renderer might be owned and sending random messages, we need
1943 // to ignore these inproper ones.
1944 NOTREACHED();
1945 return;
1946 }
1947 render_manager_.dom_ui()->ProcessDOMUIMessage(message, content);
1948}
1949
1950void TabContents::ProcessExternalHostMessage(const std::string& message,
1951 const std::string& origin,
1952 const std::string& target) {
1953 if (delegate())
1954 delegate()->ForwardMessageToExternalHost(message, origin, target);
1955}
1956
1957void TabContents::GoToEntryAtOffset(int offset) {
1958 controller_.GoToOffset(offset);
1959}
1960
1961void TabContents::GetHistoryListCount(int* back_list_count,
1962 int* forward_list_count) {
1963 int current_index = controller_.last_committed_entry_index();
1964 *back_list_count = current_index;
1965 *forward_list_count = controller_.entry_count() - current_index - 1;
1966}
1967
1968void TabContents::RunFileChooser(bool multiple_files,
1969 const string16& title,
1970 const FilePath& default_file) {
1971 if (!select_file_dialog_.get())
1972 select_file_dialog_ = SelectFileDialog::Create(this);
1973 SelectFileDialog::Type dialog_type =
1974 multiple_files ? SelectFileDialog::SELECT_OPEN_MULTI_FILE :
1975 SelectFileDialog::SELECT_OPEN_FILE;
1976 select_file_dialog_->SelectFile(dialog_type, title, default_file,
1977 NULL, 0, FILE_PATH_LITERAL(""),
1978 view_->GetTopLevelNativeWindow(), NULL);
1979}
1980
1981void TabContents::RunJavaScriptMessage(
1982 const std::wstring& message,
1983 const std::wstring& default_prompt,
1984 const GURL& frame_url,
1985 const int flags,
1986 IPC::Message* reply_msg,
1987 bool* did_suppress_message) {
1988 // Suppress javascript messages when requested and when inside a constrained
1989 // popup window (because that activates them and breaks them out of the
1990 // constrained window jail).
1991 bool suppress_this_message = suppress_javascript_messages_;
1992 if (delegate())
1993 suppress_this_message |=
1994 (delegate()->GetConstrainingContents(this) != NULL);
1995
1996 *did_suppress_message = suppress_this_message;
1997
1998 if (!suppress_this_message) {
1999 base::TimeDelta time_since_last_message(
2000 base::TimeTicks::Now() - last_javascript_message_dismissal_);
2001 bool show_suppress_checkbox = false;
2002 // Show a checkbox offering to suppress further messages if this message is
2003 // being displayed within kJavascriptMessageExpectedDelay of the last one.
2004 if (time_since_last_message <
2005 base::TimeDelta::FromMilliseconds(kJavascriptMessageExpectedDelay))
2006 show_suppress_checkbox = true;
2007
2008 RunJavascriptMessageBox(AsWC(this), frame_url, flags, message, default_prompt,
2009 show_suppress_checkbox, reply_msg);
2010 } else {
2011 // If we are suppressing messages, just reply as is if the user immediately
2012 // pressed "Cancel".
2013 OnJavaScriptMessageBoxClosed(reply_msg, false, std::wstring());
2014 }
2015}
2016
2017void TabContents::RunBeforeUnloadConfirm(const std::wstring& message,
2018 IPC::Message* reply_msg) {
2019 RunBeforeUnloadDialog(AsWC(this), message, reply_msg);
2020}
2021
2022void TabContents::ShowModalHTMLDialog(const GURL& url, int width, int height,
2023 const std::string& json_arguments,
2024 IPC::Message* reply_msg) {
2025 if (delegate()) {
2026 HtmlDialogUIDelegate* dialog_delegate =
2027 new ModalHtmlDialogDelegate(url, width, height, json_arguments,
2028 reply_msg, AsWC(this));
2029 delegate()->ShowHtmlDialog(dialog_delegate, NULL);
2030 }
2031}
2032
2033void TabContents::PasswordFormsSeen(
2034 const std::vector<PasswordForm>& forms) {
2035 GetPasswordManager()->PasswordFormsSeen(forms);
2036}
2037
2038void TabContents::AutofillFormSubmitted(
2039 const AutofillForm& form) {
2040 GetAutofillManager()->AutofillFormSubmitted(form);
2041}
2042
2043void TabContents::GetAutofillSuggestions(const std::wstring& field_name,
2044 const std::wstring& user_text, int64 node_id, int request_id) {
2045 GetAutofillManager()->FetchValuesForName(field_name, user_text,
2046 kMaxAutofillMenuItems, node_id, request_id);
2047}
2048
2049void TabContents::RemoveAutofillEntry(const std::wstring& field_name,
2050 const std::wstring& value) {
2051 GetAutofillManager()->RemoveValueForName(field_name, value);
2052}
2053
2054// Checks to see if we should generate a keyword based on the OSDD, and if
2055// necessary uses TemplateURLFetcher to download the OSDD and create a keyword.
2056void TabContents::PageHasOSDD(RenderViewHost* render_view_host,
2057 int32 page_id, const GURL& url,
2058 bool autodetected) {
2059 // Make sure page_id is the current page, and the TemplateURLModel is loaded.
2060 DCHECK(url.is_valid());
2061 if (!IsActiveEntry(page_id))
2062 return;
2063 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
2064 if (!url_model)
2065 return;
2066 if (!url_model->loaded()) {
2067 url_model->Load();
2068 return;
2069 }
2070 if (!profile()->GetTemplateURLFetcher())
2071 return;
2072
2073 if (profile()->IsOffTheRecord())
2074 return;
2075
2076 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
2077 DCHECK(entry);
2078
2079 const NavigationEntry* base_entry = entry;
2080 if (IsFormSubmit(base_entry)) {
2081 // If the current page is a form submit, find the last page that was not
2082 // a form submit and use its url to generate the keyword from.
2083 int index = controller_.last_committed_entry_index() - 1;
2084 while (index >= 0 && IsFormSubmit(controller_.GetEntryAtIndex(index)))
2085 index--;
2086 if (index >= 0)
2087 base_entry = controller_.GetEntryAtIndex(index);
2088 else
2089 base_entry = NULL;
2090 }
2091
2092 // We want to use the user typed URL if available since that represents what
2093 // the user typed to get here, and fall back on the regular URL if not.
2094 if (!base_entry)
2095 return;
2096 GURL keyword_url = base_entry->user_typed_url().is_valid() ?
2097 base_entry->user_typed_url() : base_entry->url();
2098 if (!keyword_url.is_valid())
2099 return;
2100 std::wstring keyword = TemplateURLModel::GenerateKeyword(keyword_url,
2101 autodetected);
2102 if (keyword.empty())
2103 return;
2104 const TemplateURL* template_url =
2105 url_model->GetTemplateURLForKeyword(keyword);
2106 if (template_url && (!template_url->safe_for_autoreplace() ||
2107 template_url->originating_url() == url)) {
2108 // Either there is a user created TemplateURL for this keyword, or the
2109 // keyword has the same OSDD url and we've parsed it.
2110 return;
2111 }
2112
2113 // Download the OpenSearch description document. If this is successful a
2114 // new keyword will be created when done.
2115#if defined(OS_WIN)
2116 gfx::NativeView ancestor = GetAncestor(view_->GetNativeView(), GA_ROOT);
2117#else
2118 gfx::NativeView ancestor = NULL;
2119#endif
2120 profile()->GetTemplateURLFetcher()->ScheduleDownload(
2121 keyword,
2122 url,
2123 base_entry->favicon().url(),
2124 ancestor,
2125 autodetected);
2126}
2127
2128void TabContents::InspectElementReply(int num_resources) {
2129 // We have received reply from inspect element request. Notify the
2130 // automation provider in case we need to notify automation client.
2131 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:342132 NotificationType::DOM_INSPECT_ELEMENT_RESPONSE, Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:322133 Details<int>(&num_resources));
2134}
2135
2136void TabContents::DidGetPrintedPagesCount(int cookie, int number_pages) {
2137 printing_.DidGetPrintedPagesCount(cookie, number_pages);
2138}
2139
2140void TabContents::DidPrintPage(const ViewHostMsg_DidPrintPage_Params& params) {
2141 printing_.DidPrintPage(params);
2142}
2143
2144GURL TabContents::GetAlternateErrorPageURL() const {
2145 GURL url;
2146 // Disable alternate error pages when in OffTheRecord/Incognito mode.
2147 if (profile()->IsOffTheRecord())
2148 return url;
2149
2150 PrefService* prefs = profile()->GetPrefs();
2151 DCHECK(prefs);
2152 if (prefs->GetBoolean(prefs::kAlternateErrorPagesEnabled)) {
2153 url = google_util::AppendGoogleLocaleParam(GURL(kLinkDoctorBaseURL));
2154 url = google_util::AppendGoogleTLDParam(url);
2155 }
2156 return url;
2157}
2158
2159WebPreferences TabContents::GetWebkitPrefs() {
2160 PrefService* prefs = render_view_host()->process()->profile()->GetPrefs();
2161 bool isDomUI = false;
2162 return RenderViewHostDelegateHelper::GetWebkitPrefs(prefs, isDomUI);
2163}
2164
2165void TabContents::OnMissingPluginStatus(int status) {
2166#if defined(OS_WIN)
2167// TODO(PORT): pull in when plug-ins work
2168 GetPluginInstaller()->OnMissingPluginStatus(status);
2169#endif
2170}
2171
2172void TabContents::OnCrashedPlugin(const FilePath& plugin_path) {
2173#if defined(OS_WIN)
2174// TODO(PORT): pull in when plug-ins work
2175 DCHECK(!plugin_path.value().empty());
2176
2177 std::wstring plugin_name = plugin_path.ToWStringHack();
2178 scoped_ptr<FileVersionInfo> version_info(
2179 FileVersionInfo::CreateFileVersionInfo(plugin_path));
2180 if (version_info.get()) {
2181 const std::wstring& product_name = version_info->product_name();
2182 if (!product_name.empty())
2183 plugin_name = product_name;
2184 }
2185 AddInfoBar(new SimpleAlertInfoBarDelegate(
2186 this, l10n_util::GetStringF(IDS_PLUGIN_CRASHED_PROMPT, plugin_name),
2187 NULL));
2188#endif
2189}
2190
2191void TabContents::OnCrashedWorker() {
2192 AddInfoBar(new SimpleAlertInfoBarDelegate(
2193 this, l10n_util::GetString(IDS_WEBWORKER_CRASHED_PROMPT),
2194 NULL));
2195}
2196
2197void TabContents::OnJSOutOfMemory() {
2198 AddInfoBar(new SimpleAlertInfoBarDelegate(
2199 this, l10n_util::GetString(IDS_JS_OUT_OF_MEMORY_PROMPT), NULL));
2200}
2201
2202void TabContents::ShouldClosePage(bool proceed) {
2203 render_manager_.ShouldClosePage(proceed);
2204}
2205
2206void TabContents::OnCrossSiteResponse(int new_render_process_host_id,
2207 int new_request_id) {
[email protected]57c6a652009-05-04 07:58:342208 // Allows the TabContents to react when a cross-site response is ready to be
[email protected]420ae012009-04-24 05:16:322209 // delivered to a pending RenderViewHost. We must first run the onunload
2210 // handler of the old RenderViewHost before we can allow it to proceed.
2211 render_manager_.OnCrossSiteResponse(new_render_process_host_id,
2212 new_request_id);
2213}
2214
2215bool TabContents::CanBlur() const {
2216 return delegate() ? delegate()->CanBlur() : true;
2217}
2218
2219gfx::Rect TabContents::GetRootWindowResizerRect() const {
2220 if (delegate())
2221 return delegate()->GetRootWindowResizerRect();
2222 return gfx::Rect();
2223}
2224
2225void TabContents::RendererUnresponsive(RenderViewHost* rvh,
2226 bool is_during_unload) {
2227 if (is_during_unload) {
2228 // Hang occurred while firing the beforeunload/unload handler.
2229 // Pretend the handler fired so tab closing continues as if it had.
[email protected]829e7612009-04-25 01:15:112230 rvh->set_sudden_termination_allowed(true);
[email protected]420ae012009-04-24 05:16:322231
2232 if (!render_manager_.ShouldCloseTabOnUnresponsiveRenderer())
2233 return;
2234
2235 // If the tab hangs in the beforeunload/unload handler there's really
2236 // nothing we can do to recover. Pretend the unload listeners have
2237 // all fired and close the tab. If the hang is in the beforeunload handler
2238 // then the user will not have the option of cancelling the close.
2239 Close(rvh);
2240 return;
2241 }
2242
2243 if (render_view_host() && render_view_host()->IsRenderViewLive())
[email protected]57c6a652009-05-04 07:58:342244 HungRendererWarning::ShowForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:322245}
2246
2247void TabContents::RendererResponsive(RenderViewHost* render_view_host) {
[email protected]57c6a652009-05-04 07:58:342248 HungRendererWarning::HideForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:322249}
2250
2251void TabContents::LoadStateChanged(const GURL& url,
2252 net::LoadState load_state) {
2253 load_state_ = load_state;
2254 load_state_host_ = UTF8ToWide(url.host());
2255 if (load_state_ == net::LOAD_STATE_READING_RESPONSE)
2256 SetNotWaitingForResponse();
2257 if (is_loading())
[email protected]c9cd2222009-05-06 05:16:502258 NotifyNavigationStateChanged(INVALIDATE_LOAD | INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:322259}
2260
2261void TabContents::OnDidGetApplicationInfo(
2262 int32 page_id,
2263 const webkit_glue::WebApplicationInfo& info) {
2264 if (pending_install_.page_id != page_id)
2265 return; // The user clicked create on a separate page. Ignore this.
2266
2267 pending_install_.callback_functor =
2268 new GearsCreateShortcutCallbackFunctor(this);
2269 GearsCreateShortcut(
2270 info, pending_install_.title, pending_install_.url, pending_install_.icon,
2271 NewCallback(pending_install_.callback_functor,
2272 &GearsCreateShortcutCallbackFunctor::Run));
2273}
2274
2275void TabContents::OnEnterOrSpace() {
2276 // See comment in RenderViewHostDelegate::OnEnterOrSpace as to why we do this.
2277#if defined(OS_WIN)
2278 // TODO(port): this is stubbed in BrowserProcess
2279 DownloadRequestManager* drm = g_browser_process->download_request_manager();
2280 if (drm)
2281 drm->OnUserGesture(this);
2282#endif
2283}
2284
2285void TabContents::OnFindReply(int request_id,
2286 int number_of_matches,
2287 const gfx::Rect& selection_rect,
2288 int active_match_ordinal,
2289 bool final_update) {
2290 // Ignore responses for requests other than the one we have most recently
2291 // issued. That way we won't act on stale results when the user has
2292 // already typed in another query.
2293 if (request_id != current_find_request_id_)
2294 return;
2295
2296 if (number_of_matches == -1)
2297 number_of_matches = find_result_.number_of_matches();
2298 if (active_match_ordinal == -1)
2299 active_match_ordinal = find_result_.active_match_ordinal();
2300
2301 // Notify the UI, automation and any other observers that a find result was
2302 // found.
2303 find_result_ = FindNotificationDetails(request_id, number_of_matches,
2304 selection_rect, active_match_ordinal,
2305 final_update);
2306 NotificationService::current()->Notify(
2307 NotificationType::FIND_RESULT_AVAILABLE,
2308 Source<TabContents>(this),
2309 Details<FindNotificationDetails>(&find_result_));
2310}
2311
[email protected]829e7612009-04-25 01:15:112312bool TabContents::IsExternalTabContainer() const {
[email protected]420ae012009-04-24 05:16:322313 if (!delegate())
[email protected]829e7612009-04-25 01:15:112314 return false;
[email protected]420ae012009-04-24 05:16:322315
[email protected]829e7612009-04-25 01:15:112316 return delegate()->IsExternalTabContainer();
[email protected]420ae012009-04-24 05:16:322317}
2318
2319void TabContents::FileSelected(const FilePath& path,
2320 int index, void* params) {
2321 render_view_host()->FileSelected(path);
2322}
2323
2324void TabContents::MultiFilesSelected(const std::vector<FilePath>& files,
2325 void* params) {
2326 render_view_host()->MultiFilesSelected(files);
2327}
2328
2329void TabContents::FileSelectionCanceled(void* params) {
2330 // If the user cancels choosing a file to upload we pass back an
2331 // empty vector.
2332 render_view_host()->MultiFilesSelected(std::vector<FilePath>());
2333}
2334
2335void TabContents::BeforeUnloadFiredFromRenderManager(
2336 bool proceed,
2337 bool* proceed_to_fire_unload) {
2338 if (delegate())
2339 delegate()->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
2340}
2341
2342void TabContents::UpdateRenderViewSizeForRenderManager() {
2343 // TODO(brettw) this is a hack. See TabContentsView::SizeContents.
2344 view_->SizeContents(view_->GetContainerSize());
2345}
2346
2347DOMUI* TabContents::CreateDOMUIForRenderManager(const GURL& url) {
2348 return DOMUIFactory::CreateDOMUIForURL(AsWC(this), url);
2349}
2350
2351NavigationEntry*
2352TabContents::GetLastCommittedNavigationEntryForRenderManager() {
2353 return controller_.GetLastCommittedEntry();
2354}
2355
2356bool TabContents::CreateRenderViewForRenderManager(
2357 RenderViewHost* render_view_host) {
2358 // When we're running a DOM UI, the RenderViewHost needs to be put in DOM UI
2359 // mode before CreateRenderView is called. When we're asked to create a
2360 // RenderView, that means it's for the pending entry, so we have to use the
2361 // pending DOM UI.
2362 if (render_manager_.pending_dom_ui())
2363 render_view_host->AllowDOMUIBindings();
2364
2365 RenderWidgetHostView* rwh_view = view_->CreateViewForWidget(render_view_host);
2366 if (!render_view_host->CreateRenderView())
2367 return false;
2368
2369 // Now that the RenderView has been created, we need to tell it its size.
2370 rwh_view->SetSize(view_->GetContainerSize());
2371
2372 UpdateMaxPageIDIfNecessary(render_view_host->site_instance(),
2373 render_view_host);
2374 return true;
2375}
2376
2377void TabContents::Observe(NotificationType type,
2378 const NotificationSource& source,
2379 const NotificationDetails& details) {
2380 switch (type.value) {
2381 case NotificationType::BOOKMARK_MODEL_LOADED:
2382 // BookmarkModel finished loading, fall through to update starred state.
2383 case NotificationType::URLS_STARRED: {
2384 // Somewhere, a URL has been starred.
2385 // Ignore notifications for profiles other than our current one.
2386 Profile* source_profile = Source<Profile>(source).ptr();
2387 if (!source_profile || !source_profile->IsSameProfile(profile()))
2388 return;
2389
2390 UpdateStarredStateForCurrentURL();
2391 break;
2392 }
2393 case NotificationType::PREF_CHANGED: {
2394 std::wstring* pref_name_in = Details<std::wstring>(details).ptr();
2395 DCHECK(Source<PrefService>(source).ptr() == profile()->GetPrefs());
2396 if (*pref_name_in == prefs::kAlternateErrorPagesEnabled) {
2397 UpdateAlternateErrorPageURL();
2398 } else if (*pref_name_in == prefs::kDefaultCharset ||
2399 StartsWithASCII(WideToUTF8(*pref_name_in), "webkit.webprefs.", true)
2400 ) {
2401 UpdateWebPreferences();
2402 } else {
2403 NOTREACHED() << "unexpected pref change notification" << *pref_name_in;
2404 }
2405 break;
2406 }
2407 case NotificationType::RENDER_WIDGET_HOST_DESTROYED:
2408 view_->RenderWidgetHostDestroyed(Source<RenderWidgetHost>(source).ptr());
2409 break;
2410
2411 case NotificationType::NAV_ENTRY_COMMITTED: {
2412 DCHECK(&controller_ == Source<NavigationController>(source).ptr());
2413
2414 NavigationController::LoadCommittedDetails& committed_details =
2415 *(Details<NavigationController::LoadCommittedDetails>(details).ptr());
2416 ExpireInfoBars(committed_details);
2417 break;
2418 }
2419
2420 default:
2421 NOTREACHED();
2422 }
2423}