blob: 08843172a260cf08764aeada648a23792b642923 [file] [log] [blame]
[email protected]ce5c4502009-05-06 16:46:111// Copyright (c) 2009 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
[email protected]f3ec7742009-01-15 00:59:165#include "chrome/browser/tab_contents/tab_contents.h"
initial.commit09911bf2008-07-26 23:55:296
[email protected]a92b8642009-05-05 23:38:567#include "app/l10n_util.h"
[email protected]9929da92009-05-05 02:05:118#include "app/resource_bundle.h"
[email protected]420ae012009-04-24 05:16:329#include "base/file_version_info.h"
10#include "base/process_util.h"
[email protected]96d185d2009-04-24 03:28:5411#include "base/string16.h"
12#include "base/time.h"
[email protected]fdd61c62009-04-22 19:22:5713#include "chrome/browser/autofill_manager.h"
[email protected]66ba4932009-06-04 19:22:1314#include "chrome/browser/blocked_popup_container.h"
[email protected]420ae012009-04-24 05:16:3215#include "chrome/browser/bookmarks/bookmark_model.h"
[email protected]96d185d2009-04-24 03:28:5416#include "chrome/browser/browser_process.h"
initial.commit09911bf2008-07-26 23:55:2917#include "chrome/browser/cert_store.h"
[email protected]96d185d2009-04-24 03:28:5418#include "chrome/browser/debugger/devtools_manager.h"
[email protected]420ae012009-04-24 05:16:3219#include "chrome/browser/dom_operation_notification_details.h"
[email protected]96d185d2009-04-24 03:28:5420#include "chrome/browser/dom_ui/dom_ui.h"
21#include "chrome/browser/dom_ui/dom_ui_factory.h"
[email protected]bcef0dc02009-02-28 00:35:0222#include "chrome/browser/download/download_item_model.h"
[email protected]420ae012009-04-24 05:16:3223#include "chrome/browser/download/download_manager.h"
24#include "chrome/browser/download/download_request_manager.h"
[email protected]420ae012009-04-24 05:16:3225#include "chrome/browser/gears_integration.h"
26#include "chrome/browser/google_util.h"
[email protected]8897c382009-05-06 17:53:2627#include "chrome/browser/hung_renderer_dialog.h"
[email protected]420ae012009-04-24 05:16:3228#include "chrome/browser/jsmessage_box_handler.h"
29#include "chrome/browser/load_from_memory_cache_details.h"
30#include "chrome/browser/load_notification_details.h"
[email protected]fdd61c62009-04-22 19:22:5731#include "chrome/browser/password_manager/password_manager.h"
32#include "chrome/browser/plugin_installer.h"
[email protected]ce560f82009-06-03 09:39:4433#include "chrome/browser/profile.h"
[email protected]96d185d2009-04-24 03:28:5434#include "chrome/browser/renderer_host/render_widget_host_view.h"
35#include "chrome/browser/renderer_host/web_cache_manager.h"
[email protected]bd1ad682009-05-15 22:19:1736#include "chrome/browser/tab_contents/infobar_delegate.h"
[email protected]7e383692009-06-12 19:14:5437#include "chrome/browser/tab_contents/interstitial_page.h"
[email protected]f3ec7742009-01-15 00:59:1638#include "chrome/browser/tab_contents/navigation_entry.h"
[email protected]de34a962009-06-26 23:22:4339#include "chrome/browser/tab_contents/provisional_load_details.h"
[email protected]f3ec7742009-01-15 00:59:1640#include "chrome/browser/tab_contents/tab_contents_delegate.h"
[email protected]fdd61c62009-04-22 19:22:5741#include "chrome/browser/tab_contents/tab_contents_view.h"
[email protected]58dca552009-06-17 00:35:0242#include "chrome/browser/tab_contents/thumbnail_generator.h"
[email protected]449478302009-06-09 20:04:2843#include "chrome/browser/thumbnail_store.h"
[email protected]420ae012009-04-24 05:16:3244#include "chrome/browser/search_engines/template_url_fetcher.h"
45#include "chrome/browser/search_engines/template_url_model.h"
[email protected]35f7d212009-04-29 21:19:2746#include "chrome/common/chrome_switches.h"
[email protected]bfd04a62009-02-01 18:16:5647#include "chrome/common/notification_service.h"
[email protected]ce5c4502009-05-06 16:46:1148#include "chrome/common/page_action.h"
initial.commit09911bf2008-07-26 23:55:2949#include "chrome/common/pref_names.h"
[email protected]1eb89e82008-08-15 12:27:0350#include "chrome/common/pref_service.h"
[email protected]420ae012009-04-24 05:16:3251#include "chrome/common/render_messages.h"
[email protected]96d185d2009-04-24 03:28:5452#include "chrome/common/url_constants.h"
[email protected]8897c382009-05-06 17:53:2653#include "grit/generated_resources.h"
[email protected]420ae012009-04-24 05:16:3254#include "grit/locale_settings.h"
55#include "net/base/mime_util.h"
56#include "net/base/net_errors.h"
[email protected]d686e812009-06-03 19:10:2957#include "net/base/net_util.h"
[email protected]420ae012009-04-24 05:16:3258#include "net/base/registry_controlled_domain.h"
[email protected]3e45ba92009-02-20 21:09:0059
60#if defined(OS_WIN)
[email protected]66ba4932009-06-04 19:22:1361// For CRect
[email protected]9041a302009-06-04 19:36:3362#include <atlbase.h>
[email protected]326f7112009-06-04 19:30:2963#include <atlapp.h>
[email protected]66ba4932009-06-04 19:22:1364#include <atlmisc.h>
[email protected]3e45ba92009-02-20 21:09:0065// TODO(port): some of these headers should be ported.
[email protected]420ae012009-04-24 05:16:3266#include "chrome/browser/modal_html_dialog_delegate.h"
[email protected]2362e4f2009-05-08 00:34:0567#include "views/controls/scrollbar/native_scroll_bar.h"
[email protected]3e45ba92009-02-20 21:09:0068#endif
initial.commit09911bf2008-07-26 23:55:2969
[email protected]420ae012009-04-24 05:16:3270// Cross-Site Navigations
71//
72// If a TabContents is told to navigate to a different web site (as determined
73// by SiteInstance), it will replace its current RenderViewHost with a new
74// RenderViewHost dedicated to the new SiteInstance. This works as follows:
75//
76// - Navigate determines whether the destination is cross-site, and if so,
77// it creates a pending_render_view_host_ and moves into the PENDING
78// RendererState.
79// - The pending RVH is "suspended," so that no navigation messages are sent to
80// its renderer until the onbeforeunload JavaScript handler has a chance to
81// run in the current RVH.
82// - The pending RVH tells CrossSiteRequestManager (a thread-safe singleton)
83// that it has a pending cross-site request. ResourceDispatcherHost will
84// check for this when the response arrives.
85// - The current RVH runs its onbeforeunload handler. If it returns false, we
86// cancel all the pending logic and go back to NORMAL. Otherwise we allow
87// the pending RVH to send the navigation request to its renderer.
88// - ResourceDispatcherHost receives a ResourceRequest on the IO thread. It
89// checks CrossSiteRequestManager to see that the RVH responsible has a
90// pending cross-site request, and then installs a CrossSiteEventHandler.
91// - When RDH receives a response, the BufferedEventHandler determines whether
92// it is a download. If so, it sends a message to the new renderer causing
93// it to cancel the request, and the download proceeds in the download
94// thread. For now, we stay in a PENDING state (with a pending RVH) until
[email protected]57c6a652009-05-04 07:58:3495// the next DidNavigate event for this TabContents. This isn't ideal, but it
[email protected]420ae012009-04-24 05:16:3296// doesn't affect any functionality.
97// - After RDH receives a response and determines that it is safe and not a
98// download, it pauses the response to first run the old page's onunload
99// handler. It does this by asynchronously calling the OnCrossSiteResponse
[email protected]57c6a652009-05-04 07:58:34100// method of TabContents on the UI thread, which sends a ClosePage message
[email protected]420ae012009-04-24 05:16:32101// to the current RVH.
102// - Once the onunload handler is finished, a ClosePage_ACK message is sent to
103// the ResourceDispatcherHost, who unpauses the response. Data is then sent
104// to the pending RVH.
105// - The pending renderer sends a FrameNavigate message that invokes the
106// DidNavigate method. This replaces the current RVH with the
107// pending RVH and goes back to the NORMAL RendererState.
108
109namespace {
110
111// Amount of time we wait between when a key event is received and the renderer
112// is queried for its state and pushed to the NavigationEntry.
113const int kQueryStateDelay = 5000;
114
115const int kSyncWaitDelay = 40;
116
117// If another javascript message box is displayed within
118// kJavascriptMessageExpectedDelay of a previous javascript message box being
119// dismissed, display an option to suppress future message boxes from this
120// contents.
121const int kJavascriptMessageExpectedDelay = 1000;
122
[email protected]420ae012009-04-24 05:16:32123const char kLinkDoctorBaseURL[] =
124 "http://linkhelp.clients.google.com/tbproxy/lh/fixurl";
125
[email protected]420ae012009-04-24 05:16:32126// The list of prefs we want to observe.
127const wchar_t* kPrefsToObserve[] = {
128 prefs::kAlternateErrorPagesEnabled,
129 prefs::kWebKitJavaEnabled,
130 prefs::kWebKitJavascriptEnabled,
131 prefs::kWebKitLoadsImagesAutomatically,
132 prefs::kWebKitPluginsEnabled,
133 prefs::kWebKitUsesUniversalDetector,
134 prefs::kWebKitSerifFontFamily,
135 prefs::kWebKitSansSerifFontFamily,
136 prefs::kWebKitFixedFontFamily,
137 prefs::kWebKitDefaultFontSize,
138 prefs::kWebKitDefaultFixedFontSize,
139 prefs::kDefaultCharset
140 // kWebKitStandardFontIsSerif needs to be added
141 // if we let users pick which font to use, serif or sans-serif when
142 // no font is specified or a CSS generic family (serif or sans-serif)
143 // is not specified.
144};
145
146const int kPrefsToObserveLength = arraysize(kPrefsToObserve);
147
148// Limit on the number of suggestions to appear in the pop-up menu under an
149// text input element in a form.
150const int kMaxAutofillMenuItems = 6;
151
152// Returns true if the entry's transition type is FORM_SUBMIT.
153bool IsFormSubmit(const NavigationEntry* entry) {
154 return (PageTransition::StripQualifier(entry->transition_type()) ==
155 PageTransition::FORM_SUBMIT);
156}
157
158#if defined(OS_WIN)
159
160BOOL CALLBACK InvalidateWindow(HWND hwnd, LPARAM lparam) {
161 // Note: erase is required to properly paint some widgets borders. This can
162 // be seen with textfields.
163 InvalidateRect(hwnd, NULL, TRUE);
164 return TRUE;
165}
166#endif
167
[email protected]056de2d2009-06-26 16:41:34168void MakeNavigateParams(const NavigationEntry& entry, bool reload,
169 ViewMsg_Navigate_Params* params) {
170 params->page_id = entry.page_id();
171 params->url = entry.url();
172 params->referrer = entry.referrer();
173 params->transition = entry.transition_type();
174 params->state = entry.content_state();
175 params->reload = reload;
176 params->request_time = base::Time::Now();
177}
178
[email protected]420ae012009-04-24 05:16:32179} // namespace
180
181// -----------------------------------------------------------------------------
182
[email protected]fdd61c62009-04-22 19:22:57183// static
184int TabContents::find_request_id_counter_ = -1;
185
[email protected]420ae012009-04-24 05:16:32186class TabContents::GearsCreateShortcutCallbackFunctor {
187 public:
188 explicit GearsCreateShortcutCallbackFunctor(TabContents* contents)
189 : contents_(contents) {}
190
191 void Run(const GearsShortcutData2& shortcut_data, bool success) {
192 if (contents_)
193 contents_->OnGearsCreateShortcutDone(shortcut_data, success);
194 delete this;
195 }
196 void Cancel() {
197 contents_ = NULL;
198 }
199
200 private:
201 TabContents* contents_;
202};
203
[email protected]420ae012009-04-24 05:16:32204TabContents::TabContents(Profile* profile,
205 SiteInstance* site_instance,
206 int routing_id,
207 base::WaitableEvent* modal_dialog_event)
[email protected]b680ad22009-04-15 23:19:42208 : delegate_(NULL),
[email protected]66ba4932009-06-04 19:22:13209 ALLOW_THIS_IN_INITIALIZER_LIST(controller_(this, profile)),
210 ALLOW_THIS_IN_INITIALIZER_LIST(view_(
[email protected]d82ed61e2009-06-16 02:46:22211 TabContentsView::Create(this))),
212 ALLOW_THIS_IN_INITIALIZER_LIST(render_manager_(this, this)),
[email protected]fdd61c62009-04-22 19:22:57213 property_bag_(),
214 registrar_(),
[email protected]d82ed61e2009-06-16 02:46:22215 ALLOW_THIS_IN_INITIALIZER_LIST(printing_(*this)),
[email protected]fdd61c62009-04-22 19:22:57216 save_package_(),
217 cancelable_consumer_(),
218 autofill_manager_(),
219 password_manager_(),
220 plugin_installer_(),
[email protected]d82ed61e2009-06-16 02:46:22221 ALLOW_THIS_IN_INITIALIZER_LIST(fav_icon_helper_(this)),
[email protected]fdd61c62009-04-22 19:22:57222 select_file_dialog_(),
223 pending_install_(),
[email protected]d5f942ba2008-09-26 19:30:34224 is_loading_(false),
initial.commit09911bf2008-07-26 23:55:29225 is_crashed_(false),
[email protected]d5f942ba2008-09-26 19:30:34226 waiting_for_response_(false),
[email protected]d5f942ba2008-09-26 19:30:34227 max_page_id_(-1),
[email protected]fdd61c62009-04-22 19:22:57228 current_load_start_(),
229 load_state_(net::LOAD_STATE_IDLE),
230 load_state_host_(),
231 received_page_title_(false),
232 is_starred_(false),
233 contents_mime_type_(),
234 encoding_(),
[email protected]332af7732009-03-11 13:21:35235 blocked_popups_(NULL),
[email protected]fdd61c62009-04-22 19:22:57236 infobar_delegates_(),
[email protected]fdd61c62009-04-22 19:22:57237 find_ui_active_(false),
238 find_op_aborted_(false),
239 current_find_request_id_(find_request_id_counter_++),
240 find_text_(),
[email protected]e491f1c2009-05-22 20:28:12241 last_search_case_sensitive_(false),
242 last_search_prepopulate_text_(NULL),
243 last_search_result_(),
[email protected]fdd61c62009-04-22 19:22:57244 capturing_contents_(false),
245 is_being_destroyed_(false),
246 notify_disconnection_(false),
247 history_requests_(),
248#if defined(OS_WIN)
249 message_box_active_(CreateEvent(NULL, TRUE, FALSE, NULL)),
250#endif
251 last_javascript_message_dismissal_(),
252 suppress_javascript_messages_(false) {
[email protected]420ae012009-04-24 05:16:32253 pending_install_.page_id = 0;
254 pending_install_.callback_functor = NULL;
255
[email protected]58dca552009-06-17 00:35:02256#if defined(LINUX2)
257 // Make sure the thumbnailer is started before starting the render manager.
258 // The thumbnailer will want to listen for RVH creations, one of which will
259 // happen in RVHManager::Init.
260 ThumbnailGenerator* generator = g_browser_process->GetThumbnailGenerator();
261 if (generator)
262 generator->StartThumbnailing();
263#endif
264
[email protected]420ae012009-04-24 05:16:32265 render_manager_.Init(profile, site_instance, routing_id, modal_dialog_event);
266
267 view_->CreateView();
268
269 // Register for notifications about all interested prefs change.
270 PrefService* prefs = profile->GetPrefs();
271 if (prefs) {
272 for (int i = 0; i < kPrefsToObserveLength; ++i)
273 prefs->AddPrefObserver(kPrefsToObserve[i], this);
274 }
275
276 // Register for notifications about URL starredness changing on any profile.
277 registrar_.Add(this, NotificationType::URLS_STARRED,
278 NotificationService::AllSources());
279 registrar_.Add(this, NotificationType::BOOKMARK_MODEL_LOADED,
280 NotificationService::AllSources());
281 registrar_.Add(this, NotificationType::RENDER_WIDGET_HOST_DESTROYED,
282 NotificationService::AllSources());
283
284 // Keep a global copy of the previous search string (if any).
285 static string16 global_last_search = string16();
[email protected]e491f1c2009-05-22 20:28:12286 last_search_prepopulate_text_ = &global_last_search;
[email protected]332af7732009-03-11 13:21:35287}
initial.commit09911bf2008-07-26 23:55:29288
289TabContents::~TabContents() {
[email protected]420ae012009-04-24 05:16:32290 is_being_destroyed_ = true;
291
292 // We don't want any notifications while we're runnign our destructor.
293 registrar_.RemoveAll();
294
295 // Unregister the notifications of all observed prefs change.
296 PrefService* prefs = profile()->GetPrefs();
297 if (prefs) {
298 for (int i = 0; i < kPrefsToObserveLength; ++i)
299 prefs->RemovePrefObserver(kPrefsToObserve[i], this);
300 }
301
302 // Clean up subwindows like plugins and the find in page bar.
303 view_->OnContentsDestroy();
304
305 NotifyDisconnected();
[email protected]d82ed61e2009-06-16 02:46:22306 HungRendererDialog::HideForTabContents(this);
[email protected]420ae012009-04-24 05:16:32307
308 if (pending_install_.callback_functor)
309 pending_install_.callback_functor->Cancel();
310
311 // First cleanly close all child windows.
312 // TODO(mpcomplete): handle case if MaybeCloseChildWindows() already asked
313 // some of these to close. CloseWindows is async, so it might get called
314 // twice before it runs.
315 int size = static_cast<int>(child_windows_.size());
316 for (int i = size - 1; i >= 0; --i) {
317 ConstrainedWindow* window = child_windows_[i];
318 if (window)
319 window->CloseConstrainedWindow();
320 }
321
[email protected]66ba4932009-06-04 19:22:13322 if (blocked_popups_)
323 blocked_popups_->Destroy();
324
[email protected]420ae012009-04-24 05:16:32325 // Notify any observer that have a reference on this tab contents.
326 NotificationService::current()->Notify(
327 NotificationType::TAB_CONTENTS_DESTROYED,
328 Source<TabContents>(this),
329 NotificationService::NoDetails());
330
[email protected]1e5e74f2009-05-27 20:55:12331 // Notify any lasting InfobarDelegates that have not yet been removed that
332 // whatever infobar they were handling in this TabContents has closed,
333 // because the TabContents is going away entirely.
334 // This must happen after the TAB_CONTENTS_DESTROYED notification as the
335 // notification may trigger infobars calls that access their delegate. (and
336 // some implementations of InfoBarDelegate do delete themselves on
337 // InfoBarClosed()).
338 for (int i = 0; i < infobar_delegate_count(); ++i) {
339 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
340 delegate->InfoBarClosed();
341 }
342 infobar_delegates_.clear();
343
[email protected]420ae012009-04-24 05:16:32344 // TODO(brettw) this should be moved to the view.
345#if defined(OS_WIN)
346 // If we still have a window handle, destroy it. GetNativeView can return
347 // NULL if this contents was part of a window that closed.
348 if (GetNativeView())
349 ::DestroyWindow(GetNativeView());
350#endif
initial.commit09911bf2008-07-26 23:55:29351}
352
[email protected]d5f942ba2008-09-26 19:30:34353// static
354void TabContents::RegisterUserPrefs(PrefService* prefs) {
[email protected]420ae012009-04-24 05:16:32355 prefs->RegisterBooleanPref(prefs::kAlternateErrorPagesEnabled, true);
356
357 WebPreferences pref_defaults;
358 prefs->RegisterBooleanPref(prefs::kWebKitJavascriptEnabled,
359 pref_defaults.javascript_enabled);
360 prefs->RegisterBooleanPref(prefs::kWebKitWebSecurityEnabled,
361 pref_defaults.web_security_enabled);
362 prefs->RegisterBooleanPref(
363 prefs::kWebKitJavascriptCanOpenWindowsAutomatically, true);
364 prefs->RegisterBooleanPref(prefs::kWebKitLoadsImagesAutomatically,
365 pref_defaults.loads_images_automatically);
366 prefs->RegisterBooleanPref(prefs::kWebKitPluginsEnabled,
367 pref_defaults.plugins_enabled);
368 prefs->RegisterBooleanPref(prefs::kWebKitDomPasteEnabled,
369 pref_defaults.dom_paste_enabled);
370 prefs->RegisterBooleanPref(prefs::kWebKitShrinksStandaloneImagesToFit,
371 pref_defaults.shrinks_standalone_images_to_fit);
[email protected]0df30122009-06-03 12:13:08372 prefs->RegisterStringPref(prefs::kWebKitInspectorSettings,
373 pref_defaults.inspector_settings);
[email protected]420ae012009-04-24 05:16:32374 prefs->RegisterBooleanPref(prefs::kWebKitTextAreasAreResizable,
375 pref_defaults.text_areas_are_resizable);
376 prefs->RegisterBooleanPref(prefs::kWebKitJavaEnabled,
377 pref_defaults.java_enabled);
378
379 prefs->RegisterLocalizedStringPref(prefs::kAcceptLanguages,
380 IDS_ACCEPT_LANGUAGES);
381 prefs->RegisterLocalizedStringPref(prefs::kDefaultCharset,
382 IDS_DEFAULT_ENCODING);
383 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitStandardFontIsSerif,
384 IDS_STANDARD_FONT_IS_SERIF);
385 prefs->RegisterLocalizedStringPref(prefs::kWebKitFixedFontFamily,
386 IDS_FIXED_FONT_FAMILY);
387 prefs->RegisterLocalizedStringPref(prefs::kWebKitSerifFontFamily,
388 IDS_SERIF_FONT_FAMILY);
389 prefs->RegisterLocalizedStringPref(prefs::kWebKitSansSerifFontFamily,
390 IDS_SANS_SERIF_FONT_FAMILY);
391 prefs->RegisterLocalizedStringPref(prefs::kWebKitCursiveFontFamily,
392 IDS_CURSIVE_FONT_FAMILY);
393 prefs->RegisterLocalizedStringPref(prefs::kWebKitFantasyFontFamily,
394 IDS_FANTASY_FONT_FAMILY);
395 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFontSize,
396 IDS_DEFAULT_FONT_SIZE);
397 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFixedFontSize,
398 IDS_DEFAULT_FIXED_FONT_SIZE);
399 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumFontSize,
400 IDS_MINIMUM_FONT_SIZE);
401 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumLogicalFontSize,
402 IDS_MINIMUM_LOGICAL_FONT_SIZE);
403 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitUsesUniversalDetector,
404 IDS_USES_UNIVERSAL_DETECTOR);
405 prefs->RegisterLocalizedStringPref(prefs::kStaticEncodings,
406 IDS_STATIC_ENCODING_LIST);
initial.commit09911bf2008-07-26 23:55:29407}
408
[email protected]d5f942ba2008-09-26 19:30:34409bool TabContents::SupportsURL(GURL* url) {
[email protected]6e95706d2009-04-23 22:55:01410 // TODO(brettw) remove this function.
[email protected]9423d9412009-04-14 22:13:55411 return true;
[email protected]d5f942ba2008-09-26 19:30:34412}
413
[email protected]6e95706d2009-04-23 22:55:01414AutofillManager* TabContents::GetAutofillManager() {
415 if (autofill_manager_.get() == NULL)
416 autofill_manager_.reset(new AutofillManager(this));
417 return autofill_manager_.get();
418}
419
420PasswordManager* TabContents::GetPasswordManager() {
421 if (password_manager_.get() == NULL)
422 password_manager_.reset(new PasswordManager(this));
423 return password_manager_.get();
424}
425
426PluginInstaller* TabContents::GetPluginInstaller() {
427 if (plugin_installer_.get() == NULL)
428 plugin_installer_.reset(new PluginInstaller(this));
429 return plugin_installer_.get();
430}
431
[email protected]d5f942ba2008-09-26 19:30:34432const GURL& TabContents::GetURL() const {
433 // We may not have a navigation entry yet
[email protected]ce3fa3c2009-04-20 19:55:57434 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34435 return entry ? entry->display_url() : GURL::EmptyGURL();
436}
437
[email protected]96d185d2009-04-24 03:28:54438const string16& TabContents::GetTitle() const {
[email protected]4c6092c5b2009-06-06 00:23:55439 // Transient entries take precedence. They are used for interstitial pages
440 // that are shown on top of existing pages.
441 NavigationEntry* entry = controller_.GetTransientEntry();
442 if (entry)
443 return entry->GetTitleForDisplay(&controller_);
444
[email protected]96d185d2009-04-24 03:28:54445 DOMUI* our_dom_ui = render_manager_.pending_dom_ui() ?
446 render_manager_.pending_dom_ui() : render_manager_.dom_ui();
447 if (our_dom_ui) {
448 // Don't override the title in view source mode.
[email protected]4c6092c5b2009-06-06 00:23:55449 entry = controller_.GetActiveEntry();
[email protected]96d185d2009-04-24 03:28:54450 if (!(entry && entry->IsViewSourceMode())) {
451 // Give the DOM UI the chance to override our title.
452 const string16& title = our_dom_ui->overridden_title();
453 if (!title.empty())
454 return title;
455 }
456 }
457
458 // We use the title for the last committed entry rather than a pending
459 // navigation entry. For example, when the user types in a URL, we want to
460 // keep the old page's title until the new load has committed and we get a new
461 // title.
[email protected]96d185d2009-04-24 03:28:54462 entry = controller_.GetLastCommittedEntry();
463 if (entry)
464 return entry->GetTitleForDisplay(&controller_);
465 else if (controller_.LoadingURLLazily())
466 return controller_.GetLazyTitle();
467 return EmptyString16();
468}
469
[email protected]d5f942ba2008-09-26 19:30:34470int32 TabContents::GetMaxPageID() {
471 if (GetSiteInstance())
472 return GetSiteInstance()->max_page_id();
473 else
474 return max_page_id_;
475}
476
477void TabContents::UpdateMaxPageID(int32 page_id) {
478 // Ensure both the SiteInstance and RenderProcessHost update their max page
[email protected]57c6a652009-05-04 07:58:34479 // IDs in sync. Only TabContents will also have site instances, except during
[email protected]d5f942ba2008-09-26 19:30:34480 // testing.
481 if (GetSiteInstance())
482 GetSiteInstance()->UpdateMaxPageID(page_id);
[email protected]57c6a652009-05-04 07:58:34483 process()->UpdateMaxPageID(page_id);
[email protected]d5f942ba2008-09-26 19:30:34484}
485
[email protected]96d185d2009-04-24 03:28:54486SiteInstance* TabContents::GetSiteInstance() const {
487 return render_manager_.current_host()->site_instance();
488}
489
[email protected]d5f942ba2008-09-26 19:30:34490const std::wstring TabContents::GetDefaultTitle() const {
491 return l10n_util::GetString(IDS_DEFAULT_TAB_TITLE);
492}
493
[email protected]96d185d2009-04-24 03:28:54494bool TabContents::ShouldDisplayURL() {
495 // Don't hide the url in view source mode.
496 NavigationEntry* entry = controller_.GetActiveEntry();
497 if (entry && entry->IsViewSourceMode())
498 return true;
[email protected]83e3895b2009-06-11 00:07:16499
[email protected]96d185d2009-04-24 03:28:54500 DOMUI* dom_ui = GetDOMUIForCurrentState();
501 if (dom_ui)
502 return !dom_ui->should_hide_url();
503 return true;
504}
505
[email protected]d5f942ba2008-09-26 19:30:34506SkBitmap TabContents::GetFavIcon() const {
507 // Like GetTitle(), we also want to use the favicon for the last committed
508 // entry rather than a pending navigation entry.
[email protected]ce3fa3c2009-04-20 19:55:57509 NavigationEntry* entry = controller_.GetTransientEntry();
[email protected]cbab76d2008-10-13 22:42:47510 if (entry)
511 return entry->favicon().bitmap();
512
[email protected]ce3fa3c2009-04-20 19:55:57513 entry = controller_.GetLastCommittedEntry();
[email protected]d5f942ba2008-09-26 19:30:34514 if (entry)
515 return entry->favicon().bitmap();
[email protected]ce3fa3c2009-04-20 19:55:57516 else if (controller_.LoadingURLLazily())
517 return controller_.GetLazyFavIcon();
[email protected]d5f942ba2008-09-26 19:30:34518 return SkBitmap();
519}
520
[email protected]96d185d2009-04-24 03:28:54521bool TabContents::ShouldDisplayFavIcon() {
522 // Always display a throbber during pending loads.
523 if (controller_.GetLastCommittedEntry() && controller_.pending_entry())
524 return true;
525
526 DOMUI* dom_ui = GetDOMUIForCurrentState();
527 if (dom_ui)
528 return !dom_ui->hide_favicon();
529 return true;
530}
531
[email protected]96d185d2009-04-24 03:28:54532std::wstring TabContents::GetStatusText() const {
533 if (!is_loading() || load_state_ == net::LOAD_STATE_IDLE)
534 return std::wstring();
535
536 switch (load_state_) {
537 case net::LOAD_STATE_WAITING_FOR_CACHE:
538 return l10n_util::GetString(IDS_LOAD_STATE_WAITING_FOR_CACHE);
539 case net::LOAD_STATE_RESOLVING_PROXY_FOR_URL:
540 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_PROXY_FOR_URL);
541 case net::LOAD_STATE_RESOLVING_HOST:
542 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_HOST);
543 case net::LOAD_STATE_CONNECTING:
544 return l10n_util::GetString(IDS_LOAD_STATE_CONNECTING);
545 case net::LOAD_STATE_SENDING_REQUEST:
546 return l10n_util::GetString(IDS_LOAD_STATE_SENDING_REQUEST);
547 case net::LOAD_STATE_WAITING_FOR_RESPONSE:
548 return l10n_util::GetStringF(IDS_LOAD_STATE_WAITING_FOR_RESPONSE,
549 load_state_host_);
550 // Ignore net::LOAD_STATE_READING_RESPONSE and net::LOAD_STATE_IDLE
551 case net::LOAD_STATE_IDLE:
552 case net::LOAD_STATE_READING_RESPONSE:
553 break;
554 }
555
556 return std::wstring();
557}
558
[email protected]d5f942ba2008-09-26 19:30:34559void TabContents::SetIsCrashed(bool state) {
560 if (state == is_crashed_)
561 return;
562
563 is_crashed_ = state;
[email protected]c9cd2222009-05-06 05:16:50564 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]d5f942ba2008-09-26 19:30:34565}
566
[email protected]f9b1a7b2009-06-22 17:26:38567void TabContents::SetPageActionEnabled(const PageAction* page_action,
[email protected]d7eaf572009-07-01 21:57:00568 bool enable,
569 const std::string& title,
570 int icon_id) {
[email protected]ce5c4502009-05-06 16:46:11571 DCHECK(page_action);
572
[email protected]d7eaf572009-07-01 21:57:00573 if (!enable &&
574 enabled_page_actions_.end() == enabled_page_actions_.find(page_action)) {
575 return; // Don't need to disable twice.
576 }
[email protected]ce5c4502009-05-06 16:46:11577
[email protected]d7eaf572009-07-01 21:57:00578 if (enable) {
579 enabled_page_actions_[page_action].reset(
580 new PageActionState(title, icon_id));
581 } else {
[email protected]f9b1a7b2009-06-22 17:26:38582 enabled_page_actions_.erase(page_action);
[email protected]d7eaf572009-07-01 21:57:00583 }
[email protected]ce5c4502009-05-06 16:46:11584}
585
[email protected]d7eaf572009-07-01 21:57:00586const PageActionState* TabContents::GetPageActionState(
587 const PageAction* page_action) {
588 if (enabled_page_actions_.end() == enabled_page_actions_.find(page_action))
589 return NULL;
[email protected]ce5c4502009-05-06 16:46:11590
[email protected]d7eaf572009-07-01 21:57:00591 return enabled_page_actions_[page_action].get();
592}
[email protected]ce5c4502009-05-06 16:46:11593
[email protected]d5f942ba2008-09-26 19:30:34594void TabContents::NotifyNavigationStateChanged(unsigned changed_flags) {
595 if (delegate_)
596 delegate_->NavigationStateChanged(this, changed_flags);
597}
598
[email protected]96d185d2009-04-24 03:28:54599void TabContents::DidBecomeSelected() {
600 controller_.SetActive(true);
601
602 if (render_widget_host_view())
603 render_widget_host_view()->DidBecomeSelected();
604
605 // If pid() is -1, that means the RenderProcessHost still hasn't been
606 // initialized. It'll register with CacheManagerHost when it is.
607 if (process()->pid() != -1)
608 WebCacheManager::GetInstance()->ObserveActivity(process()->pid());
609}
610
611void TabContents::WasHidden() {
612 if (!capturing_contents()) {
613 // |render_view_host()| can be NULL if the user middle clicks a link to open
614 // a tab in then background, then closes the tab before selecting it. This
615 // is because closing the tab calls TabContents::Destroy(), which removes
616 // the |render_view_host()|; then when we actually destroy the window,
617 // OnWindowPosChanged() notices and calls HideContents() (which calls us).
618 if (render_widget_host_view())
619 render_widget_host_view()->WasHidden();
[email protected]96d185d2009-04-24 03:28:54620 }
621
622 NotificationService::current()->Notify(
623 NotificationType::TAB_CONTENTS_HIDDEN,
624 Source<TabContents>(this),
625 NotificationService::NoDetails());
626}
627
[email protected]d5f942ba2008-09-26 19:30:34628void TabContents::Activate() {
629 if (delegate_)
630 delegate_->ActivateContents(this);
631}
632
[email protected]96d185d2009-04-24 03:28:54633void TabContents::ShowContents() {
634 if (render_widget_host_view())
635 render_widget_host_view()->DidBecomeSelected();
[email protected]96d185d2009-04-24 03:28:54636}
637
638void TabContents::HideContents() {
639 // TODO(pkasting): http://b/1239839 Right now we purposefully don't call
640 // our superclass HideContents(), because some callers want to be very picky
641 // about the order in which these get called. In addition to making the code
642 // here practically impossible to understand, this also means we end up
643 // calling TabContents::WasHidden() twice if callers call both versions of
[email protected]57c6a652009-05-04 07:58:34644 // HideContents() on a TabContents.
[email protected]96d185d2009-04-24 03:28:54645 WasHidden();
646}
647
[email protected]c0588052008-10-27 23:01:50648void TabContents::OpenURL(const GURL& url, const GURL& referrer,
[email protected]d5f942ba2008-09-26 19:30:34649 WindowOpenDisposition disposition,
650 PageTransition::Type transition) {
651 if (delegate_)
[email protected]c0588052008-10-27 23:01:50652 delegate_->OpenURLFromTab(this, url, referrer, disposition, transition);
[email protected]d5f942ba2008-09-26 19:30:34653}
654
655bool TabContents::NavigateToPendingEntry(bool reload) {
[email protected]96d185d2009-04-24 03:28:54656 const NavigationEntry& entry = *controller_.pending_entry();
657
658 RenderViewHost* dest_render_view_host = render_manager_.Navigate(entry);
659 if (!dest_render_view_host)
660 return false; // Unable to create the desired render view host.
661
662 // Tell DevTools agent that it is attached prior to the navigation.
[email protected]d9f9b792009-06-24 13:17:12663 DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
[email protected]7e8e6b62009-05-08 11:28:32664 if (devtools_manager) { // NULL in unit tests.
[email protected]684b4ba22009-05-07 06:27:41665 devtools_manager->OnNavigatingToPendingEntry(
666 render_view_host(),
667 dest_render_view_host,
668 controller_.pending_entry()->url());
[email protected]7e8e6b62009-05-08 11:28:32669 }
[email protected]96d185d2009-04-24 03:28:54670
671 // Used for page load time metrics.
672 current_load_start_ = base::TimeTicks::Now();
673
674 // Navigate in the desired RenderViewHost.
[email protected]056de2d2009-06-26 16:41:34675 ViewMsg_Navigate_Params navigate_params;
676 MakeNavigateParams(entry, reload, &navigate_params);
677 dest_render_view_host->Navigate(navigate_params);
[email protected]96d185d2009-04-24 03:28:54678
679 if (entry.page_id() == -1) {
680 // HACK!! This code suppresses javascript: URLs from being added to
681 // session history, which is what we want to do for javascript: URLs that
682 // do not generate content. What we really need is a message from the
683 // renderer telling us that a new page was not created. The same message
684 // could be used for mailto: URLs and the like.
685 if (entry.url().SchemeIs(chrome::kJavaScriptScheme))
686 return false;
687 }
688
689 // Clear any provisional password saves - this stops password infobars
690 // showing up on pages the user navigates to while the right page is
691 // loading.
692 GetPasswordManager()->ClearProvisionalSave();
693
694 if (reload && !profile()->IsOffTheRecord()) {
695 HistoryService* history =
696 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
697 if (history)
698 history->SetFavIconOutOfDateForPage(entry.url());
699 }
700
[email protected]d5f942ba2008-09-26 19:30:34701 return true;
702}
703
[email protected]96d185d2009-04-24 03:28:54704void TabContents::Stop() {
705 render_manager_.Stop();
706 printing_.Stop();
707}
708
709void TabContents::Cut() {
710 render_view_host()->Cut();
711}
712
713void TabContents::Copy() {
714 render_view_host()->Copy();
715}
716
717void TabContents::Paste() {
718 render_view_host()->Paste();
719}
720
721void TabContents::DisassociateFromPopupCount() {
722 render_view_host()->DisassociateFromPopupCount();
723}
724
725TabContents* TabContents::Clone() {
726 // We create a new SiteInstance so that the new tab won't share processes
727 // with the old one. This can be changed in the future if we need it to share
728 // processes for some reason.
[email protected]420ae012009-04-24 05:16:32729 TabContents* tc = new TabContents(profile(),
[email protected]96d185d2009-04-24 03:28:54730 SiteInstance::CreateSiteInstance(profile()),
731 MSG_ROUTING_NONE, NULL);
732 tc->controller().CopyStateFrom(controller_);
733 return tc;
734}
735
[email protected]420ae012009-04-24 05:16:32736void TabContents::CreateShortcut() {
737 NavigationEntry* entry = controller_.GetLastCommittedEntry();
738 if (!entry)
739 return;
740
741 // We only allow one pending install request. By resetting the page id we
742 // effectively cancel the pending install request.
743 pending_install_.page_id = entry->page_id();
744 pending_install_.icon = GetFavIcon();
745 pending_install_.title = UTF16ToWideHack(GetTitle());
746 pending_install_.url = GetURL();
747 if (pending_install_.callback_functor) {
748 pending_install_.callback_functor->Cancel();
749 pending_install_.callback_functor = NULL;
750 }
751 DCHECK(!pending_install_.icon.isNull()) << "Menu item should be disabled.";
752 if (pending_install_.title.empty())
753 pending_install_.title = UTF8ToWide(GetURL().spec());
754
755 // Request the application info. When done OnDidGetApplicationInfo is invoked
756 // and we'll create the shortcut.
757 render_view_host()->GetApplicationInfo(pending_install_.page_id);
758}
759
[email protected]e8382172009-06-19 22:16:28760#if defined(OS_WIN) || defined(OS_LINUX)
initial.commit09911bf2008-07-26 23:55:29761ConstrainedWindow* TabContents::CreateConstrainedDialog(
[email protected]e8382172009-06-19 22:16:28762 ConstrainedWindowDelegate* delegate) {
initial.commit09911bf2008-07-26 23:55:29763 ConstrainedWindow* window =
[email protected]e8382172009-06-19 22:16:28764 ConstrainedWindow::CreateConstrainedDialog(this, delegate);
initial.commit09911bf2008-07-26 23:55:29765 child_windows_.push_back(window);
766 return window;
767}
[email protected]f3332e12009-03-23 15:28:57768#endif
initial.commit09911bf2008-07-26 23:55:29769
770void TabContents::AddNewContents(TabContents* new_contents,
771 WindowOpenDisposition disposition,
772 const gfx::Rect& initial_pos,
[email protected]c88a70fe2009-05-05 20:00:22773 bool user_gesture,
774 const GURL& creator_url) {
initial.commit09911bf2008-07-26 23:55:29775 if (!delegate_)
776 return;
777
[email protected]35f7d212009-04-29 21:19:27778 if ((disposition == NEW_POPUP) && !user_gesture &&
779 !CommandLine::ForCurrentProcess()->HasSwitch(
780 switches::kDisablePopupBlocking)) {
[email protected]2c4410d2009-05-06 23:46:22781 // Unrequested popups from normal pages are constrained unless they're in
[email protected]b6c874582009-05-08 19:38:31782 // the whitelist. The popup owner will handle checking this.
783 delegate_->GetConstrainingContents(this)->AddPopup(new_contents,
784 initial_pos,
785 creator_url.is_valid() ? creator_url.host() : std::string());
786 } else {
[email protected]0aa55312008-10-17 21:53:08787 new_contents->DisassociateFromPopupCount();
initial.commit09911bf2008-07-26 23:55:29788 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
789 user_gesture);
790 }
[email protected]b6c874582009-05-08 19:38:31791 PopupNotificationVisibilityChanged(ShowingBlockedPopupNotification());
initial.commit09911bf2008-07-26 23:55:29792}
793
initial.commit09911bf2008-07-26 23:55:29794void TabContents::CloseAllSuppressedPopups() {
[email protected]d6598c052008-11-05 19:03:25795 if (blocked_popups_)
[email protected]2c4410d2009-05-06 23:46:22796 blocked_popups_->CloseAll();
initial.commit09911bf2008-07-26 23:55:29797}
798
[email protected]96d185d2009-04-24 03:28:54799void TabContents::PopupNotificationVisibilityChanged(bool visible) {
800 render_view_host()->PopupNotificationVisibilityChanged(visible);
801}
802
803gfx::NativeView TabContents::GetContentNativeView() {
804 return view_->GetContentNativeView();
805}
806
807gfx::NativeView TabContents::GetNativeView() const {
808 return view_->GetNativeView();
809}
810
811void TabContents::GetContainerBounds(gfx::Rect *out) const {
812 view_->GetContainerBounds(out);
813}
814
815void TabContents::Focus() {
816 view_->Focus();
817}
818
[email protected]90daadb42009-06-08 21:27:28819void TabContents::FocusThroughTabTraversal(bool reverse) {
[email protected]7e383692009-06-12 19:14:54820 if (showing_interstitial_page()) {
821 render_manager_.interstitial_page()->FocusThroughTabTraversal(reverse);
822 return;
823 }
[email protected]96d185d2009-04-24 03:28:54824 render_view_host()->SetInitialFocus(reverse);
825}
826
827bool TabContents::FocusLocationBarByDefault() {
828 DOMUI* dom_ui = GetDOMUIForCurrentState();
829 if (dom_ui)
830 return dom_ui->focus_location_bar_by_default();
[email protected]3e3f0eb2009-06-22 18:33:43831 NavigationEntry* entry = controller_.GetActiveEntry();
832 if (entry && entry->url() == GURL("about:blank"))
833 return true;
[email protected]96d185d2009-04-24 03:28:54834 return false;
835}
836
[email protected]616ed5a2008-11-21 22:27:24837void TabContents::AddInfoBar(InfoBarDelegate* delegate) {
838 // Look through the existing InfoBarDelegates we have for a match. If we've
839 // already got one that matches, then we don't add the new one.
[email protected]f86a07022008-11-25 01:06:05840 for (int i = 0; i < infobar_delegate_count(); ++i) {
[email protected]616ed5a2008-11-21 22:27:24841 if (GetInfoBarDelegateAt(i)->EqualsDelegate(delegate))
842 return;
843 }
844
845 infobar_delegates_.push_back(delegate);
[email protected]bfd04a62009-02-01 18:16:56846 NotificationService::current()->Notify(
847 NotificationType::TAB_CONTENTS_INFOBAR_ADDED,
848 Source<TabContents>(this),
849 Details<InfoBarDelegate>(delegate));
[email protected]616ed5a2008-11-21 22:27:24850
851 // Add ourselves as an observer for navigations the first time a delegate is
852 // added. We use this notification to expire InfoBars that need to expire on
853 // page transitions.
854 if (infobar_delegates_.size() == 1) {
[email protected]bfd04a62009-02-01 18:16:56855 registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57856 Source<NavigationController>(&controller_));
[email protected]616ed5a2008-11-21 22:27:24857 }
858}
859
860void TabContents::RemoveInfoBar(InfoBarDelegate* delegate) {
861 std::vector<InfoBarDelegate*>::iterator it =
862 find(infobar_delegates_.begin(), infobar_delegates_.end(), delegate);
863 if (it != infobar_delegates_.end()) {
864 InfoBarDelegate* delegate = *it;
[email protected]bfd04a62009-02-01 18:16:56865 NotificationService::current()->Notify(
866 NotificationType::TAB_CONTENTS_INFOBAR_REMOVED,
867 Source<TabContents>(this),
868 Details<InfoBarDelegate>(delegate));
[email protected]f86a07022008-11-25 01:06:05869 infobar_delegates_.erase(it);
[email protected]616ed5a2008-11-21 22:27:24870
[email protected]6a02963e2009-01-06 16:58:03871 // Remove ourselves as an observer if we are tracking no more InfoBars.
872 if (infobar_delegates_.empty()) {
[email protected]bfd04a62009-02-01 18:16:56873 registrar_.Remove(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57874 Source<NavigationController>(&controller_));
[email protected]6a02963e2009-01-06 16:58:03875 }
[email protected]616ed5a2008-11-21 22:27:24876 }
877}
[email protected]3edd9522009-03-04 22:19:41878
[email protected]96d185d2009-04-24 03:28:54879bool TabContents::IsBookmarkBarAlwaysVisible() {
880 // See GetDOMUIForCurrentState() comment for more info. This case is very
881 // similar, but for non-first loads, we want to use the committed entry. This
882 // is so the bookmarks bar disappears at the same time the page does.
883 if (controller_.GetLastCommittedEntry()) {
884 // Not the first load, always use the committed DOM UI.
885 if (render_manager_.dom_ui())
886 return render_manager_.dom_ui()->force_bookmark_bar_visible();
887 return false; // Default.
888 }
889
890 // When it's the first load, we know either the pending one or the committed
891 // one will have the DOM UI in it (see GetDOMUIForCurrentState), and only one
892 // of them will be valid, so we can just check both.
893 if (render_manager_.pending_dom_ui())
894 return render_manager_.pending_dom_ui()->force_bookmark_bar_visible();
895 if (render_manager_.dom_ui())
896 return render_manager_.dom_ui()->force_bookmark_bar_visible();
897 return false; // Default.
898}
899
[email protected]3edd9522009-03-04 22:19:41900void TabContents::ToolbarSizeChanged(bool is_animating) {
901 TabContentsDelegate* d = delegate();
902 if (d)
903 d->ToolbarSizeChanged(this, is_animating);
904}
[email protected]616ed5a2008-11-21 22:27:24905
[email protected]d5f942ba2008-09-26 19:30:34906void TabContents::OnStartDownload(DownloadItem* download) {
907 DCHECK(download);
[email protected]d5f942ba2008-09-26 19:30:34908
909 // Download in a constrained popup is shown in the tab that opened it.
[email protected]b6c874582009-05-08 19:38:31910 TabContents* tab_contents = delegate()->GetConstrainingContents(this);
[email protected]d5f942ba2008-09-26 19:30:34911
[email protected]59560e0b2009-06-04 03:30:22912 if (tab_contents && tab_contents->delegate())
913 tab_contents->delegate()->OnStartDownload(download);
[email protected]3edd9522009-03-04 22:19:41914}
[email protected]3edd9522009-03-04 22:19:41915
[email protected]d5f942ba2008-09-26 19:30:34916void TabContents::WillClose(ConstrainedWindow* window) {
917 ConstrainedWindowList::iterator it =
918 find(child_windows_.begin(), child_windows_.end(), window);
919 if (it != child_windows_.end())
920 child_windows_.erase(it);
[email protected]66ba4932009-06-04 19:22:13921}
[email protected]d5f942ba2008-09-26 19:30:34922
[email protected]66ba4932009-06-04 19:22:13923void TabContents::WillCloseBlockedPopupContainer(
924 BlockedPopupContainer* container) {
925 DCHECK(blocked_popups_ == container);
926 blocked_popups_ = NULL;
[email protected]d5f942ba2008-09-26 19:30:34927}
928
[email protected]d5f942ba2008-09-26 19:30:34929void TabContents::DidMoveOrResize(ConstrainedWindow* window) {
[email protected]332af7732009-03-11 13:21:35930#if defined(OS_WIN)
[email protected]92edc472009-02-10 20:32:06931 UpdateWindow(GetNativeView());
[email protected]332af7732009-03-11 13:21:35932#endif
[email protected]d5f942ba2008-09-26 19:30:34933}
934
[email protected]e491f1c2009-05-22 20:28:12935void TabContents::StartFinding(string16 find_text,
936 bool forward_direction,
937 bool case_sensitive) {
[email protected]6e95706d2009-04-23 22:55:01938 // If find_text is empty, it means FindNext was pressed with a keyboard
939 // shortcut so unless we have something to search for we return early.
[email protected]e491f1c2009-05-22 20:28:12940 if (find_text.empty() && find_text_.empty()) {
941 if (last_search_prepopulate_text_->empty())
942 return;
943 // Try whatever we searched for last in any tab.
944 find_text = *last_search_prepopulate_text_;
945 }
[email protected]6e95706d2009-04-23 22:55:01946
947 // This is a FindNext operation if we are searching for the same text again,
948 // or if the passed in search text is empty (FindNext keyboard shortcut). The
949 // exception to this is if the Find was aborted (then we don't want FindNext
950 // because the highlighting has been cleared and we need it to reappear). We
951 // therefore treat FindNext after an aborted Find operation as a full fledged
952 // Find.
953 bool find_next = (find_text_ == find_text || find_text.empty()) &&
[email protected]e491f1c2009-05-22 20:28:12954 (last_search_case_sensitive_ == case_sensitive) &&
[email protected]6e95706d2009-04-23 22:55:01955 !find_op_aborted_;
956 if (!find_next)
957 current_find_request_id_ = find_request_id_counter_++;
958
959 if (!find_text.empty())
960 find_text_ = find_text;
[email protected]e491f1c2009-05-22 20:28:12961 last_search_case_sensitive_ = case_sensitive;
[email protected]6e95706d2009-04-23 22:55:01962
963 find_op_aborted_ = false;
964
965 // Keep track of what the last search was across the tabs.
[email protected]e491f1c2009-05-22 20:28:12966 *last_search_prepopulate_text_ = find_text;
[email protected]6e95706d2009-04-23 22:55:01967
968 render_view_host()->StartFinding(current_find_request_id_,
969 find_text_,
970 forward_direction,
[email protected]e491f1c2009-05-22 20:28:12971 case_sensitive,
[email protected]6e95706d2009-04-23 22:55:01972 find_next);
973}
974
975void TabContents::StopFinding(bool clear_selection) {
[email protected]2d2dffc2009-06-09 21:41:00976 // When |clear_selection| is true, it means the find string has been cleared
977 // by the user, but the UI has not been dismissed.
978 if (!clear_selection)
979 find_ui_active_ = false;
[email protected]6e95706d2009-04-23 22:55:01980 find_op_aborted_ = true;
[email protected]e491f1c2009-05-22 20:28:12981 last_search_result_ = FindNotificationDetails();
[email protected]6e95706d2009-04-23 22:55:01982 render_view_host()->StopFinding(clear_selection);
983}
984
[email protected]420ae012009-04-24 05:16:32985void TabContents::OnJavaScriptMessageBoxClosed(IPC::Message* reply_msg,
986 bool success,
987 const std::wstring& prompt) {
988 last_javascript_message_dismissal_ = base::TimeTicks::Now();
989 render_manager_.OnJavaScriptMessageBoxClosed(reply_msg, success, prompt);
990}
991
[email protected]571e31152009-05-15 19:34:02992void TabContents::OnJavaScriptMessageBoxWindowDestroyed() {
993 render_manager_.OnJavaScriptMessageBoxWindowDestroyed();
994}
995
[email protected]420ae012009-04-24 05:16:32996void TabContents::OnSavePage() {
997 // If we can not save the page, try to download it.
998 if (!SavePackage::IsSavableContents(contents_mime_type())) {
999 DownloadManager* dlm = profile()->GetDownloadManager();
1000 const GURL& current_page_url = GetURL();
1001 if (dlm && current_page_url.is_valid())
[email protected]d82ed61e2009-06-16 02:46:221002 dlm->DownloadUrl(current_page_url, GURL(), "", this);
[email protected]420ae012009-04-24 05:16:321003 return;
1004 }
1005
1006 Stop();
1007
1008 // Create the save package and possibly prompt the user for the name to save
1009 // the page as. The user prompt is an asynchronous operation that runs on
1010 // another thread.
[email protected]d82ed61e2009-06-16 02:46:221011 save_package_ = new SavePackage(this);
[email protected]420ae012009-04-24 05:16:321012 save_package_->GetSaveInfo();
1013}
1014
1015// Used in automated testing to bypass prompting the user for file names.
1016// Instead, the names and paths are hard coded rather than running them through
1017// file name sanitation and extension / mime checking.
1018void TabContents::SavePage(const std::wstring& main_file,
1019 const std::wstring& dir_path,
1020 SavePackage::SavePackageType save_type) {
1021 // Stop the page from navigating.
1022 Stop();
1023
[email protected]d82ed61e2009-06-16 02:46:221024 save_package_ = new SavePackage(this, save_type,
[email protected]420ae012009-04-24 05:16:321025 FilePath::FromWStringHack(main_file),
1026 FilePath::FromWStringHack(dir_path));
1027 save_package_->Init();
1028}
1029
1030void TabContents::PrintPreview() {
1031 // We don't show the print preview yet, only the print dialog.
1032 PrintNow();
1033}
1034
1035bool TabContents::PrintNow() {
1036 // We can't print interstitial page for now.
1037 if (showing_interstitial_page())
1038 return false;
1039
1040 return render_view_host()->PrintPages();
1041}
1042
[email protected]82270452009-06-19 15:58:011043void TabContents::PrintingDone(int document_cookie, bool success) {
1044 render_view_host()->PrintingDone(document_cookie, success);
1045}
1046
[email protected]420ae012009-04-24 05:16:321047bool TabContents::IsActiveEntry(int32 page_id) {
1048 NavigationEntry* active_entry = controller_.GetActiveEntry();
1049 return (active_entry != NULL &&
1050 active_entry->site_instance() == GetSiteInstance() &&
1051 active_entry->page_id() == page_id);
1052}
1053
[email protected]96d185d2009-04-24 03:28:541054// Notifies the RenderWidgetHost instance about the fact that the page is
1055// loading, or done loading and calls the base implementation.
1056void TabContents::SetIsLoading(bool is_loading,
1057 LoadNotificationDetails* details) {
1058 if (is_loading == is_loading_)
1059 return;
1060
1061 if (!is_loading) {
1062 load_state_ = net::LOAD_STATE_IDLE;
1063 load_state_host_.clear();
1064 }
1065
1066 render_manager_.SetIsLoading(is_loading);
1067
1068 is_loading_ = is_loading;
1069 waiting_for_response_ = is_loading;
1070
1071 if (delegate_)
1072 delegate_->LoadingStateChanged(this);
[email protected]329581b2009-04-28 06:52:351073 NotifyNavigationStateChanged(INVALIDATE_LOAD);
[email protected]96d185d2009-04-24 03:28:541074
1075 NotificationType type = is_loading ? NotificationType::LOAD_START :
1076 NotificationType::LOAD_STOP;
[email protected]ce5c4502009-05-06 16:46:111077 NotificationDetails det = NotificationService::NoDetails();
[email protected]96d185d2009-04-24 03:28:541078 if (details)
1079 det = Details<LoadNotificationDetails>(details);
1080 NotificationService::current()->Notify(type,
1081 Source<NavigationController>(&controller_),
1082 det);
1083}
1084
[email protected]2c4410d2009-05-06 23:46:221085void TabContents::CreateBlockedPopupContainerIfNecessary() {
1086 if (blocked_popups_)
1087 return;
1088
[email protected]4d4c0b92009-06-08 23:13:011089 blocked_popups_ = BlockedPopupContainer::Create(this, profile());
[email protected]2c4410d2009-05-06 23:46:221090}
1091
[email protected]b6c874582009-05-08 19:38:311092void TabContents::AddPopup(TabContents* new_contents,
1093 const gfx::Rect& initial_pos,
1094 const std::string& host) {
[email protected]2c4410d2009-05-06 23:46:221095 CreateBlockedPopupContainerIfNecessary();
1096 blocked_popups_->AddTabContents(new_contents, initial_pos, host);
[email protected]2c4410d2009-05-06 23:46:221097}
1098
[email protected]e69bce3dd2009-04-20 22:05:121099// TODO(brettw) This should be on the TabContentsView.
[email protected]66ba4932009-06-04 19:22:131100void TabContents::RepositionSupressedPopupsToFit() {
[email protected]d6598c052008-11-05 19:03:251101 if (blocked_popups_)
[email protected]4d4c0b92009-06-08 23:13:011102 blocked_popups_->RepositionBlockedPopupContainer();
[email protected]d5f942ba2008-09-26 19:30:341103}
1104
[email protected]b9681312008-11-07 00:08:261105bool TabContents::ShowingBlockedPopupNotification() const {
1106 return blocked_popups_ != NULL &&
[email protected]2c4410d2009-05-06 23:46:221107 blocked_popups_->GetBlockedPopupCount() != 0;
[email protected]b9681312008-11-07 00:08:261108}
[email protected]616ed5a2008-11-21 22:27:241109
1110namespace {
1111bool TransitionIsReload(PageTransition::Type transition) {
1112 return PageTransition::StripQualifier(transition) == PageTransition::RELOAD;
1113}
1114}
1115
1116void TabContents::ExpireInfoBars(
1117 const NavigationController::LoadCommittedDetails& details) {
1118 // Only hide InfoBars when the user has done something that makes the main
1119 // frame load. We don't want various automatic or subframe navigations making
1120 // it disappear.
1121 if (!details.is_user_initiated_main_frame_load())
1122 return;
1123
[email protected]f86a07022008-11-25 01:06:051124 for (int i = infobar_delegate_count() - 1; i >= 0; --i) {
[email protected]616ed5a2008-11-21 22:27:241125 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
[email protected]f86a07022008-11-25 01:06:051126 if (delegate->ShouldExpire(details))
[email protected]616ed5a2008-11-21 22:27:241127 RemoveInfoBar(delegate);
[email protected]616ed5a2008-11-21 22:27:241128 }
1129}
[email protected]fdd61c62009-04-22 19:22:571130
1131void TabContents::OnGearsCreateShortcutDone(
1132 const GearsShortcutData2& shortcut_data, bool success) {
1133 NavigationEntry* current_entry = controller_.GetLastCommittedEntry();
1134 bool same_page =
1135 current_entry && pending_install_.page_id == current_entry->page_id();
1136
1137 if (success && same_page) {
1138 // Only switch to app mode if the user chose to create a shortcut and
1139 // we're still on the same page that it corresponded to.
1140 if (delegate())
1141 delegate()->ConvertContentsToApplication(this);
1142 }
1143
1144 // Reset the page id to indicate no requests are pending.
1145 pending_install_.page_id = 0;
1146 pending_install_.callback_functor = NULL;
1147}
[email protected]96d185d2009-04-24 03:28:541148
1149DOMUI* TabContents::GetDOMUIForCurrentState() {
1150 // When there is a pending navigation entry, we want to use the pending DOMUI
1151 // that goes along with it to control the basic flags. For example, we want to
1152 // show the pending URL in the URL bar, so we want the display_url flag to
1153 // be from the pending entry.
1154 //
1155 // The confusion comes because there are multiple possibilities for the
1156 // initial load in a tab as a side effect of the way the RenderViewHostManager
1157 // works.
1158 //
1159 // - For the very first tab the load looks "normal". The new tab DOM UI is
1160 // the pending one, and we want it to apply here.
1161 //
1162 // - For subsequent new tabs, they'll get a new SiteInstance which will then
1163 // get switched to the one previously associated with the new tab pages.
1164 // This switching will cause the manager to commit the RVH/DOMUI. So we'll
1165 // have a committed DOM UI in this case.
1166 //
1167 // This condition handles all of these cases:
1168 //
1169 // - First load in first tab: no committed nav entry + pending nav entry +
1170 // pending dom ui:
1171 // -> Use pending DOM UI if any.
1172 //
1173 // - First load in second tab: no committed nav entry + pending nav entry +
1174 // no pending DOM UI:
1175 // -> Use the committed DOM UI if any.
1176 //
1177 // - Second navigation in any tab: committed nav entry + pending nav entry:
1178 // -> Use pending DOM UI if any.
1179 //
1180 // - Normal state with no load: committed nav entry + no pending nav entry:
1181 // -> Use committed DOM UI.
1182 if (controller_.pending_entry() &&
1183 (controller_.GetLastCommittedEntry() ||
1184 render_manager_.pending_dom_ui()))
1185 return render_manager_.pending_dom_ui();
1186 return render_manager_.dom_ui();
1187}
[email protected]420ae012009-04-24 05:16:321188
1189void TabContents::DidNavigateMainFramePostCommit(
1190 const NavigationController::LoadCommittedDetails& details,
1191 const ViewHostMsg_FrameNavigate_Params& params) {
[email protected]420ae012009-04-24 05:16:321192 if (details.is_user_initiated_main_frame_load()) {
1193 // Clear the status bubble. This is a workaround for a bug where WebKit
1194 // doesn't let us know that the cursor left an element during a
1195 // transition (this is also why the mouse cursor remains as a hand after
1196 // clicking on a link); see bugs 1184641 and 980803. We don't want to
1197 // clear the bubble when a user navigates to a named anchor in the same
1198 // page.
1199 UpdateTargetURL(details.entry->page_id(), GURL());
1200
1201 // UpdateHelpersForDidNavigate will handle the case where the password_form
1202 // origin is valid.
1203 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1204 // cleaned up and covered by tests.
1205 if (!params.password_form.origin.is_valid())
1206 GetPasswordManager()->DidNavigate();
1207 }
1208
1209 // The keyword generator uses the navigation entries, so must be called after
1210 // the commit.
1211 GenerateKeywordIfNecessary(params);
1212
1213 // Allow the new page to set the title again.
1214 received_page_title_ = false;
1215
1216 // Get the favicon, either from history or request it from the net.
1217 fav_icon_helper_.FetchFavIcon(details.entry->url());
1218
[email protected]ce5c4502009-05-06 16:46:111219 // Disable all page actions.
1220 enabled_page_actions_.clear();
1221
[email protected]420ae012009-04-24 05:16:321222 // Close constrained popups if necessary.
1223 MaybeCloseChildWindows(details.previous_url, details.entry->url());
1224
1225 // Update the starred state.
1226 UpdateStarredStateForCurrentURL();
1227}
1228
1229void TabContents::DidNavigateAnyFramePostCommit(
1230 RenderViewHost* render_view_host,
1231 const NavigationController::LoadCommittedDetails& details,
1232 const ViewHostMsg_FrameNavigate_Params& params) {
1233 // If we navigate, start showing messages again. This does nothing to prevent
1234 // a malicious script from spamming messages, since the script could just
1235 // reload the page to stop blocking.
1236 suppress_javascript_messages_ = false;
1237
1238 // Update history. Note that this needs to happen after the entry is complete,
1239 // which WillNavigate[Main,Sub]Frame will do before this function is called.
1240 if (params.should_update_history) {
1241 // Most of the time, the displayURL matches the loaded URL, but for about:
1242 // URLs, we use a data: URL as the real value. We actually want to save
1243 // the about: URL to the history db and keep the data: URL hidden. This is
1244 // what the TabContents' URL getter does.
[email protected]befd8d822009-07-01 04:51:471245 UpdateHistoryForNavigation(GetURL(), details, params);
[email protected]420ae012009-04-24 05:16:321246 }
1247
1248 // Notify the password manager of the navigation or form submit.
1249 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1250 // cleaned up and covered by tests.
1251 if (params.password_form.origin.is_valid())
1252 GetPasswordManager()->ProvisionallySavePassword(params.password_form);
1253}
1254
1255void TabContents::MaybeCloseChildWindows(const GURL& previous_url,
1256 const GURL& current_url) {
1257 if (net::RegistryControlledDomainService::SameDomainOrHost(
1258 previous_url, current_url))
1259 return;
1260
1261 // Clear out any child windows since we are leaving this page entirely.
1262 // We use indices instead of iterators in case CloseWindow does something
1263 // that may invalidate an iterator.
1264 int size = static_cast<int>(child_windows_.size());
1265 for (int i = size - 1; i >= 0; --i) {
1266 ConstrainedWindow* window = child_windows_[i];
1267 if (window)
1268 window->CloseConstrainedWindow();
1269 }
1270}
1271
1272void TabContents::UpdateStarredStateForCurrentURL() {
1273 BookmarkModel* model = profile()->GetBookmarkModel();
1274 const bool old_state = is_starred_;
1275 is_starred_ = (model && model->IsBookmarked(GetURL()));
1276
1277 if (is_starred_ != old_state && delegate())
1278 delegate()->URLStarredChanged(this, is_starred_);
1279}
1280
1281void TabContents::UpdateAlternateErrorPageURL() {
1282 GURL url = GetAlternateErrorPageURL();
1283 render_view_host()->SetAlternateErrorPageURL(url);
1284}
1285
1286void TabContents::UpdateWebPreferences() {
1287 render_view_host()->UpdateWebPreferences(GetWebkitPrefs());
1288}
1289
1290void TabContents::UpdateMaxPageIDIfNecessary(SiteInstance* site_instance,
1291 RenderViewHost* rvh) {
1292 // If we are creating a RVH for a restored controller, then we might
1293 // have more page IDs than the SiteInstance's current max page ID. We must
1294 // make sure that the max page ID is larger than any restored page ID.
1295 // Note that it is ok for conflicting page IDs to exist in another tab
1296 // (i.e., NavigationController), but if any page ID is larger than the max,
1297 // the back/forward list will get confused.
1298 int max_restored_page_id = controller_.max_restored_page_id();
1299 if (max_restored_page_id > 0) {
1300 int curr_max_page_id = site_instance->max_page_id();
1301 if (max_restored_page_id > curr_max_page_id) {
1302 // Need to update the site instance immediately.
1303 site_instance->UpdateMaxPageID(max_restored_page_id);
1304
1305 // Also tell the renderer to update its internal representation. We
1306 // need to reserve enough IDs to make all restored page IDs less than
1307 // the max.
1308 if (curr_max_page_id < 0)
1309 curr_max_page_id = 0;
1310 rvh->ReservePageIDRange(max_restored_page_id - curr_max_page_id);
1311 }
1312 }
1313}
1314
1315void TabContents::UpdateHistoryForNavigation(
1316 const GURL& display_url,
[email protected]befd8d822009-07-01 04:51:471317 const NavigationController::LoadCommittedDetails& details,
[email protected]420ae012009-04-24 05:16:321318 const ViewHostMsg_FrameNavigate_Params& params) {
1319 if (profile()->IsOffTheRecord())
1320 return;
1321
1322 // Add to history service.
1323 HistoryService* hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1324 if (hs) {
1325 if (PageTransition::IsMainFrame(params.transition) &&
1326 display_url != params.url) {
1327 // Hack on the "display" URL so that it will appear in history. For some
1328 // types of URLs, we will display a magic URL that is different from where
1329 // the page is actually navigated. We want the user to see in history
1330 // what they saw in the URL bar, so we add the display URL as a redirect.
1331 // This only applies to the main frame, as the display URL doesn't apply
1332 // to sub-frames.
1333 std::vector<GURL> redirects = params.redirects;
1334 if (!redirects.empty())
1335 redirects.back() = display_url;
1336 hs->AddPage(display_url, this, params.page_id, params.referrer,
[email protected]befd8d822009-07-01 04:51:471337 params.transition, redirects, details.did_replace_entry);
[email protected]420ae012009-04-24 05:16:321338 } else {
1339 hs->AddPage(params.url, this, params.page_id, params.referrer,
[email protected]befd8d822009-07-01 04:51:471340 params.transition, params.redirects,
1341 details.did_replace_entry);
[email protected]420ae012009-04-24 05:16:321342 }
1343 }
1344}
1345
1346bool TabContents::UpdateTitleForEntry(NavigationEntry* entry,
1347 const std::wstring& title) {
1348 // For file URLs without a title, use the pathname instead. In the case of a
1349 // synthesized title, we don't want the update to count toward the "one set
1350 // per page of the title to history."
1351 std::wstring final_title;
1352 bool explicit_set;
1353 if (entry->url().SchemeIsFile() && title.empty()) {
1354 final_title = UTF8ToWide(entry->url().ExtractFileName());
1355 explicit_set = false; // Don't count synthetic titles toward the set limit.
1356 } else {
1357 TrimWhitespace(title, TRIM_ALL, &final_title);
1358 explicit_set = true;
1359 }
1360
1361 if (final_title == UTF16ToWideHack(entry->title()))
1362 return false; // Nothing changed, don't bother.
1363
1364 entry->set_title(WideToUTF16Hack(final_title));
1365
1366 // Update the history system for this page.
1367 if (!profile()->IsOffTheRecord() && !received_page_title_) {
1368 HistoryService* hs =
1369 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1370 if (hs)
1371 hs->SetPageTitle(entry->display_url(), final_title);
1372
1373 // Don't allow the title to be saved again for explicitly set ones.
1374 received_page_title_ = explicit_set;
1375 }
1376
1377 // Lastly, set the title for the view.
1378 view_->SetPageTitle(final_title);
1379
1380 return true;
1381}
1382
1383void TabContents::NotifySwapped() {
1384 // After sending out a swap notification, we need to send a disconnect
1385 // notification so that clients that pick up a pointer to |this| can NULL the
1386 // pointer. See Bug 1230284.
1387 notify_disconnection_ = true;
1388 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341389 NotificationType::TAB_CONTENTS_SWAPPED,
[email protected]d82ed61e2009-06-16 02:46:221390 Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321391 NotificationService::NoDetails());
1392}
1393
1394void TabContents::NotifyConnected() {
1395 notify_disconnection_ = true;
1396 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341397 NotificationType::TAB_CONTENTS_CONNECTED,
[email protected]d82ed61e2009-06-16 02:46:221398 Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321399 NotificationService::NoDetails());
1400}
1401
1402void TabContents::NotifyDisconnected() {
1403 if (!notify_disconnection_)
1404 return;
1405
1406 notify_disconnection_ = false;
1407 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341408 NotificationType::TAB_CONTENTS_DISCONNECTED,
[email protected]d82ed61e2009-06-16 02:46:221409 Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321410 NotificationService::NoDetails());
1411}
1412
1413void TabContents::GenerateKeywordIfNecessary(
1414 const ViewHostMsg_FrameNavigate_Params& params) {
1415 if (!params.searchable_form_url.is_valid())
1416 return;
1417
1418 if (profile()->IsOffTheRecord())
1419 return;
1420
1421 int last_index = controller_.last_committed_entry_index();
1422 // When there was no previous page, the last index will be 0. This is
1423 // normally due to a form submit that opened in a new tab.
1424 // TODO(brettw) bug 916126: we should support keywords when form submits
1425 // happen in new tabs.
1426 if (last_index <= 0)
1427 return;
1428 const NavigationEntry* previous_entry =
1429 controller_.GetEntryAtIndex(last_index - 1);
1430 if (IsFormSubmit(previous_entry)) {
1431 // Only generate a keyword if the previous page wasn't itself a form
1432 // submit.
1433 return;
1434 }
1435
1436 GURL keyword_url = previous_entry->user_typed_url().is_valid() ?
1437 previous_entry->user_typed_url() : previous_entry->url();
1438 std::wstring keyword =
1439 TemplateURLModel::GenerateKeyword(keyword_url, true); // autodetected
1440 if (keyword.empty())
1441 return;
1442
1443 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
1444 if (!url_model)
1445 return;
1446
1447 if (!url_model->loaded()) {
1448 url_model->Load();
1449 return;
1450 }
1451
1452 const TemplateURL* current_url;
1453 std::wstring url = UTF8ToWide(params.searchable_form_url.spec());
1454 if (!url_model->CanReplaceKeyword(keyword, url, &current_url))
1455 return;
1456
1457 if (current_url) {
1458 if (current_url->originating_url().is_valid()) {
1459 // The existing keyword was generated from an OpenSearch description
1460 // document, don't regenerate.
1461 return;
1462 }
1463 url_model->Remove(current_url);
1464 }
1465 TemplateURL* new_url = new TemplateURL();
1466 new_url->set_keyword(keyword);
1467 new_url->set_short_name(keyword);
1468 new_url->SetURL(url, 0, 0);
1469 new_url->add_input_encoding(params.searchable_form_encoding);
1470 DCHECK(controller_.GetLastCommittedEntry());
1471 const GURL& favicon_url =
1472 controller_.GetLastCommittedEntry()->favicon().url();
1473 if (favicon_url.is_valid()) {
1474 new_url->SetFavIconURL(favicon_url);
1475 } else {
1476 // The favicon url isn't valid. This means there really isn't a favicon,
1477 // or the favicon url wasn't obtained before the load started. This assumes
1478 // the later.
1479 // TODO(sky): Need a way to set the favicon that doesn't involve generating
1480 // its url.
1481 new_url->SetFavIconURL(TemplateURL::GenerateFaviconURL(params.referrer));
1482 }
1483 new_url->set_safe_for_autoreplace(true);
1484 url_model->Add(new_url);
1485}
1486
1487RenderViewHostDelegate::View* TabContents::GetViewDelegate() const {
1488 return view_.get();
1489}
1490
1491RenderViewHostDelegate::Save* TabContents::GetSaveDelegate() const {
1492 return save_package_.get(); // May be NULL, but we can return NULL.
1493}
1494
[email protected]80d96fa2009-06-10 22:34:511495RendererPreferences TabContents::GetRendererPrefs() const {
1496 if (delegate())
1497 return delegate()->GetRendererPrefs();
1498 else
1499 return RendererPreferences();
1500}
1501
[email protected]57c6a652009-05-04 07:58:341502TabContents* TabContents::GetAsTabContents() {
1503 return this;
1504}
1505
[email protected]420ae012009-04-24 05:16:321506void TabContents::RenderViewCreated(RenderViewHost* render_view_host) {
1507 NavigationEntry* entry = controller_.GetActiveEntry();
1508 if (!entry)
1509 return;
1510
1511 // When we're creating views, we're still doing initial setup, so we always
1512 // use the pending DOM UI rather than any possibly existing committed one.
1513 if (render_manager_.pending_dom_ui()) {
1514 render_manager_.pending_dom_ui()->RenderViewCreated(render_view_host);
1515 }
1516
1517 if (entry->IsViewSourceMode()) {
1518 // Put the renderer in view source mode.
1519 render_view_host->Send(
1520 new ViewMsg_EnableViewSourceMode(render_view_host->routing_id()));
1521 }
[email protected]0666aef2009-05-13 19:48:081522
1523 view()->RenderViewCreated(render_view_host);
[email protected]420ae012009-04-24 05:16:321524}
1525
1526void TabContents::RenderViewReady(RenderViewHost* rvh) {
1527 if (rvh != render_view_host()) {
1528 // Don't notify the world, since this came from a renderer in the
1529 // background.
1530 return;
1531 }
1532
1533 NotifyConnected();
1534 SetIsCrashed(false);
1535}
1536
1537void TabContents::RenderViewGone(RenderViewHost* rvh) {
1538 // Ask the print preview if this renderer was valuable.
1539 if (!printing_.OnRenderViewGone(rvh))
1540 return;
1541 if (rvh != render_view_host()) {
1542 // The pending page's RenderViewHost is gone.
1543 return;
1544 }
1545
1546 SetIsLoading(false, NULL);
1547 NotifyDisconnected();
1548 SetIsCrashed(true);
1549
[email protected]8e537302009-06-10 21:19:581550 // Tell the view that we've crashed so it can prepare the sad tab page.
1551 view_->OnTabCrashed();
[email protected]420ae012009-04-24 05:16:321552
1553 // Hide any visible hung renderer warning for this web contents' process.
[email protected]d82ed61e2009-06-16 02:46:221554 HungRendererDialog::HideForTabContents(this);
[email protected]420ae012009-04-24 05:16:321555}
1556
1557void TabContents::DidNavigate(RenderViewHost* rvh,
1558 const ViewHostMsg_FrameNavigate_Params& params) {
1559 if (PageTransition::IsMainFrame(params.transition))
1560 render_manager_.DidNavigateMainFrame(rvh);
1561
1562 // Update the site of the SiteInstance if it doesn't have one yet.
1563 if (!GetSiteInstance()->has_site())
1564 GetSiteInstance()->SetSite(params.url);
1565
1566 // Need to update MIME type here because it's referred to in
1567 // UpdateNavigationCommands() called by RendererDidNavigate() to
1568 // determine whether or not to enable the encoding menu.
1569 // It's updated only for the main frame. For a subframe,
1570 // RenderView::UpdateURL does not set params.contents_mime_type.
1571 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
1572 // TODO(jungshik): Add a test for the encoding menu to avoid
1573 // regressing it again.
1574 if (PageTransition::IsMainFrame(params.transition))
1575 contents_mime_type_ = params.contents_mime_type;
1576
1577 NavigationController::LoadCommittedDetails details;
1578 if (!controller_.RendererDidNavigate(params, &details))
1579 return; // No navigation happened.
1580
1581 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
1582 // for the appropriate notification (best) or you can add it to
1583 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
1584 // necessary, please).
1585
1586 // Run post-commit tasks.
1587 if (details.is_main_frame)
1588 DidNavigateMainFramePostCommit(details, params);
1589 DidNavigateAnyFramePostCommit(rvh, details, params);
1590}
1591
1592void TabContents::UpdateState(RenderViewHost* rvh,
1593 int32 page_id,
1594 const std::string& state) {
1595 DCHECK(rvh == render_view_host());
1596
1597 // We must be prepared to handle state updates for any page, these occur
1598 // when the user is scrolling and entering form data, as well as when we're
1599 // leaving a page, in which case our state may have already been moved to
1600 // the next page. The navigation controller will look up the appropriate
1601 // NavigationEntry and update it when it is notified via the delegate.
1602
1603 int entry_index = controller_.GetEntryIndexWithPageID(
1604 GetSiteInstance(), page_id);
1605 if (entry_index < 0)
1606 return;
1607 NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
1608
1609 if (state == entry->content_state())
1610 return; // Nothing to update.
1611 entry->set_content_state(state);
1612 controller_.NotifyEntryChanged(entry, entry_index);
1613}
1614
1615void TabContents::UpdateTitle(RenderViewHost* rvh,
1616 int32 page_id, const std::wstring& title) {
1617 // If we have a title, that's a pretty good indication that we've started
1618 // getting useful data.
1619 SetNotWaitingForResponse();
1620
1621 DCHECK(rvh == render_view_host());
1622 NavigationEntry* entry = controller_.GetEntryWithPageID(GetSiteInstance(),
1623 page_id);
1624 if (!entry || !UpdateTitleForEntry(entry, title))
1625 return;
1626
1627 // Broadcast notifications when the UI should be updated.
1628 if (entry == controller_.GetEntryAtOffset(0))
[email protected]c9cd2222009-05-06 05:16:501629 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:321630}
1631
[email protected]420ae012009-04-24 05:16:321632void TabContents::UpdateEncoding(RenderViewHost* render_view_host,
1633 const std::wstring& encoding) {
1634 set_encoding(encoding);
1635}
1636
1637void TabContents::UpdateTargetURL(int32 page_id, const GURL& url) {
1638 if (delegate())
1639 delegate()->UpdateTargetURL(this, url);
1640}
1641
1642void TabContents::UpdateThumbnail(const GURL& url,
1643 const SkBitmap& bitmap,
1644 const ThumbnailScore& score) {
1645 // Tell History about this thumbnail
[email protected]449478302009-06-09 20:04:281646 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kThumbnailStore)) {
1647 profile()->GetThumbnailStore()->
1648 SetPageThumbnail(url, bitmap, score, !profile()->IsOffTheRecord());
1649 } else {
1650 HistoryService* hs;
1651 if (!profile()->IsOffTheRecord() &&
1652 (hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS))) {
1653 hs->SetPageThumbnail(url, bitmap, score);
1654 }
[email protected]420ae012009-04-24 05:16:321655 }
1656}
1657
[email protected]0df30122009-06-03 12:13:081658void TabContents::UpdateInspectorSettings(const std::wstring& raw_settings) {
1659 profile()->GetPrefs()->SetString(prefs::kWebKitInspectorSettings,
1660 raw_settings);
1661}
1662
[email protected]420ae012009-04-24 05:16:321663void TabContents::Close(RenderViewHost* rvh) {
1664 // Ignore this if it comes from a RenderViewHost that we aren't showing.
1665 if (delegate() && rvh == render_view_host())
1666 delegate()->CloseContents(this);
1667}
1668
1669void TabContents::RequestMove(const gfx::Rect& new_bounds) {
1670 if (delegate() && delegate()->IsPopup(this))
1671 delegate()->MoveContents(this, new_bounds);
1672}
1673
[email protected]329581b2009-04-28 06:52:351674void TabContents::DidStartLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321675 SetIsLoading(true, NULL);
1676}
1677
[email protected]329581b2009-04-28 06:52:351678void TabContents::DidStopLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321679 scoped_ptr<LoadNotificationDetails> details;
1680
1681 NavigationEntry* entry = controller_.GetActiveEntry();
1682 // An entry may not exist for a stop when loading an initial blank page or
1683 // if an iframe injected by script into a blank page finishes loading.
1684 if (entry) {
1685 scoped_ptr<base::ProcessMetrics> metrics(
1686 base::ProcessMetrics::CreateProcessMetrics(
1687 process()->process().handle()));
1688
1689 base::TimeDelta elapsed = base::TimeTicks::Now() - current_load_start_;
1690
1691 details.reset(new LoadNotificationDetails(
1692 entry->display_url(),
1693 entry->transition_type(),
1694 elapsed,
1695 &controller_,
1696 controller_.GetCurrentEntryIndex()));
1697 }
1698
1699 // Tell PasswordManager we've finished a page load, which serves as a
1700 // green light to save pending passwords and reset itself.
1701 GetPasswordManager()->DidStopLoading();
1702
1703 SetIsLoading(false, details.get());
1704}
1705
1706void TabContents::DidStartProvisionalLoadForFrame(
1707 RenderViewHost* render_view_host,
1708 bool is_main_frame,
1709 const GURL& url) {
1710 ProvisionalLoadDetails details(is_main_frame,
1711 controller_.IsURLInPageNavigation(url),
1712 url, std::string(), false);
1713 NotificationService::current()->Notify(
1714 NotificationType::FRAME_PROVISIONAL_LOAD_START,
1715 Source<NavigationController>(&controller_),
1716 Details<ProvisionalLoadDetails>(&details));
1717}
1718
1719void TabContents::DidRedirectProvisionalLoad(int32 page_id,
1720 const GURL& source_url,
1721 const GURL& target_url) {
1722 NavigationEntry* entry;
1723 if (page_id == -1)
1724 entry = controller_.pending_entry();
1725 else
1726 entry = controller_.GetEntryWithPageID(GetSiteInstance(), page_id);
1727 if (!entry || entry->url() != source_url)
1728 return;
1729 entry->set_url(target_url);
1730}
1731
1732void TabContents::DidLoadResourceFromMemoryCache(
1733 const GURL& url,
1734 const std::string& frame_origin,
1735 const std::string& main_frame_origin,
1736 const std::string& security_info) {
1737 // Send out a notification that we loaded a resource from our memory cache.
1738 int cert_id = 0, cert_status = 0, security_bits = 0;
1739 SSLManager::DeserializeSecurityInfo(security_info,
1740 &cert_id, &cert_status,
1741 &security_bits);
1742 LoadFromMemoryCacheDetails details(url, frame_origin, main_frame_origin,
[email protected]9ae66cbf2009-05-12 16:21:031743 process()->pid(), cert_id, cert_status);
[email protected]420ae012009-04-24 05:16:321744
1745 NotificationService::current()->Notify(
1746 NotificationType::LOAD_FROM_MEMORY_CACHE,
1747 Source<NavigationController>(&controller_),
1748 Details<LoadFromMemoryCacheDetails>(&details));
1749}
1750
1751void TabContents::DidFailProvisionalLoadWithError(
1752 RenderViewHost* render_view_host,
1753 bool is_main_frame,
1754 int error_code,
1755 const GURL& url,
1756 bool showing_repost_interstitial) {
1757 if (net::ERR_ABORTED == error_code) {
1758 // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
1759 // This means that the interstitial won't be torn down properly, which is
1760 // bad. But if we have an interstitial, go back to another tab type, and
1761 // then load the same interstitial again, we could end up getting the first
1762 // interstitial's "failed" message (as a result of the cancel) when we're on
1763 // the second one.
1764 //
1765 // We can't tell this apart, so we think we're tearing down the current page
1766 // which will cause a crash later one. There is also some code in
1767 // RenderViewHostManager::RendererAbortedProvisionalLoad that is commented
1768 // out because of this problem.
1769 //
1770 // http://code.google.com/p/chromium/issues/detail?id=2855
1771 // Because this will not tear down the interstitial properly, if "back" is
1772 // back to another tab type, the interstitial will still be somewhat alive
1773 // in the previous tab type. If you navigate somewhere that activates the
1774 // tab with the interstitial again, you'll see a flash before the new load
1775 // commits of the interstitial page.
1776 if (showing_interstitial_page()) {
1777 LOG(WARNING) << "Discarding message during interstitial.";
1778 return;
1779 }
1780
1781 // This will discard our pending entry if we cancelled the load (e.g., if we
1782 // decided to download the file instead of load it). Only discard the
1783 // pending entry if the URLs match, otherwise the user initiated a navigate
1784 // before the page loaded so that the discard would discard the wrong entry.
1785 NavigationEntry* pending_entry = controller_.pending_entry();
[email protected]e684a312009-06-24 02:30:591786 if (pending_entry && pending_entry->url() == url) {
[email protected]420ae012009-04-24 05:16:321787 controller_.DiscardNonCommittedEntries();
[email protected]e684a312009-06-24 02:30:591788 // Update the URL display.
1789 NotifyNavigationStateChanged(TabContents::INVALIDATE_URL);
1790 }
[email protected]420ae012009-04-24 05:16:321791
1792 render_manager_.RendererAbortedProvisionalLoad(render_view_host);
1793 }
1794
1795 // Send out a notification that we failed a provisional load with an error.
1796 ProvisionalLoadDetails details(is_main_frame,
1797 controller_.IsURLInPageNavigation(url),
1798 url, std::string(), false);
1799 details.set_error_code(error_code);
1800
1801 NotificationService::current()->Notify(
1802 NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR,
1803 Source<NavigationController>(&controller_),
1804 Details<ProvisionalLoadDetails>(&details));
1805}
1806
1807void TabContents::UpdateFavIconURL(RenderViewHost* render_view_host,
1808 int32 page_id,
1809 const GURL& icon_url) {
1810 fav_icon_helper_.SetFavIconURL(icon_url);
1811}
1812
1813void TabContents::DidDownloadImage(
1814 RenderViewHost* render_view_host,
1815 int id,
1816 const GURL& image_url,
1817 bool errored,
1818 const SkBitmap& image) {
1819 // A notification for downloading would be more flexible, but for now I'm
1820 // forwarding to the two places that could possibly have initiated the
1821 // request. If we end up with another place invoking DownloadImage, probably
1822 // best to refactor out into notification service, or something similar.
1823 if (errored)
1824 fav_icon_helper_.FavIconDownloadFailed(id);
1825 else
1826 fav_icon_helper_.SetFavIcon(id, image_url, image);
1827}
1828
1829void TabContents::RequestOpenURL(const GURL& url, const GURL& referrer,
1830 WindowOpenDisposition disposition) {
1831 if (render_manager_.dom_ui()) {
1832 // When we're a DOM UI, it will provide a page transition type for us (this
1833 // is so the new tab page can specify AUTO_BOOKMARK for automatically
1834 // generated suggestions).
1835 //
1836 // Note also that we hide the referrer for DOM UI pages. We don't really
[email protected]60e448982009-05-06 04:21:161837 // want web sites to see a referrer of "chrome://blah" (and some
1838 // chrome: URLs might have search terms or other stuff we don't want to
[email protected]420ae012009-04-24 05:16:321839 // send to the site), so we send no referrer.
1840 OpenURL(url, GURL(), disposition,
1841 render_manager_.dom_ui()->link_transition_type());
1842 } else {
1843 OpenURL(url, referrer, disposition, PageTransition::LINK);
1844 }
1845}
1846
1847void TabContents::DomOperationResponse(const std::string& json_string,
1848 int automation_id) {
1849 DomOperationNotificationDetails details(json_string, automation_id);
1850 NotificationService::current()->Notify(
[email protected]d82ed61e2009-06-16 02:46:221851 NotificationType::DOM_OPERATION_RESPONSE, Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321852 Details<DomOperationNotificationDetails>(&details));
1853}
1854
1855void TabContents::ProcessDOMUIMessage(const std::string& message,
[email protected]811bfe32009-07-01 08:46:251856 const std::string& content,
1857 int request_id,
1858 bool has_callback) {
[email protected]420ae012009-04-24 05:16:321859 if (!render_manager_.dom_ui()) {
1860 // We shouldn't get a DOM UI message when we haven't enabled the DOM UI.
1861 // Because the renderer might be owned and sending random messages, we need
1862 // to ignore these inproper ones.
1863 NOTREACHED();
1864 return;
1865 }
[email protected]811bfe32009-07-01 08:46:251866 render_manager_.dom_ui()->ProcessDOMUIMessage(message, content, request_id,
1867 has_callback);
[email protected]420ae012009-04-24 05:16:321868}
1869
[email protected]09b8f82f2009-06-16 20:22:111870void TabContents::DocumentLoadedInFrame() {
1871 controller_.DocumentLoadedInFrame();
1872}
1873
[email protected]420ae012009-04-24 05:16:321874void TabContents::ProcessExternalHostMessage(const std::string& message,
1875 const std::string& origin,
1876 const std::string& target) {
1877 if (delegate())
1878 delegate()->ForwardMessageToExternalHost(message, origin, target);
1879}
1880
1881void TabContents::GoToEntryAtOffset(int offset) {
1882 controller_.GoToOffset(offset);
1883}
1884
1885void TabContents::GetHistoryListCount(int* back_list_count,
1886 int* forward_list_count) {
1887 int current_index = controller_.last_committed_entry_index();
1888 *back_list_count = current_index;
1889 *forward_list_count = controller_.entry_count() - current_index - 1;
1890}
1891
1892void TabContents::RunFileChooser(bool multiple_files,
1893 const string16& title,
1894 const FilePath& default_file) {
1895 if (!select_file_dialog_.get())
1896 select_file_dialog_ = SelectFileDialog::Create(this);
1897 SelectFileDialog::Type dialog_type =
1898 multiple_files ? SelectFileDialog::SELECT_OPEN_MULTI_FILE :
1899 SelectFileDialog::SELECT_OPEN_FILE;
1900 select_file_dialog_->SelectFile(dialog_type, title, default_file,
1901 NULL, 0, FILE_PATH_LITERAL(""),
1902 view_->GetTopLevelNativeWindow(), NULL);
1903}
1904
1905void TabContents::RunJavaScriptMessage(
1906 const std::wstring& message,
1907 const std::wstring& default_prompt,
1908 const GURL& frame_url,
1909 const int flags,
1910 IPC::Message* reply_msg,
1911 bool* did_suppress_message) {
1912 // Suppress javascript messages when requested and when inside a constrained
1913 // popup window (because that activates them and breaks them out of the
1914 // constrained window jail).
1915 bool suppress_this_message = suppress_javascript_messages_;
1916 if (delegate())
1917 suppress_this_message |=
[email protected]b6c874582009-05-08 19:38:311918 (delegate()->GetConstrainingContents(this) != this);
[email protected]420ae012009-04-24 05:16:321919
1920 *did_suppress_message = suppress_this_message;
1921
1922 if (!suppress_this_message) {
1923 base::TimeDelta time_since_last_message(
1924 base::TimeTicks::Now() - last_javascript_message_dismissal_);
1925 bool show_suppress_checkbox = false;
1926 // Show a checkbox offering to suppress further messages if this message is
1927 // being displayed within kJavascriptMessageExpectedDelay of the last one.
1928 if (time_since_last_message <
1929 base::TimeDelta::FromMilliseconds(kJavascriptMessageExpectedDelay))
1930 show_suppress_checkbox = true;
1931
[email protected]d82ed61e2009-06-16 02:46:221932 RunJavascriptMessageBox(this, frame_url, flags, message, default_prompt,
[email protected]420ae012009-04-24 05:16:321933 show_suppress_checkbox, reply_msg);
1934 } else {
1935 // If we are suppressing messages, just reply as is if the user immediately
1936 // pressed "Cancel".
1937 OnJavaScriptMessageBoxClosed(reply_msg, false, std::wstring());
1938 }
1939}
1940
1941void TabContents::RunBeforeUnloadConfirm(const std::wstring& message,
1942 IPC::Message* reply_msg) {
[email protected]d82ed61e2009-06-16 02:46:221943 RunBeforeUnloadDialog(this, message, reply_msg);
[email protected]420ae012009-04-24 05:16:321944}
1945
1946void TabContents::ShowModalHTMLDialog(const GURL& url, int width, int height,
1947 const std::string& json_arguments,
1948 IPC::Message* reply_msg) {
1949 if (delegate()) {
1950 HtmlDialogUIDelegate* dialog_delegate =
1951 new ModalHtmlDialogDelegate(url, width, height, json_arguments,
[email protected]d82ed61e2009-06-16 02:46:221952 reply_msg, this);
[email protected]420ae012009-04-24 05:16:321953 delegate()->ShowHtmlDialog(dialog_delegate, NULL);
1954 }
1955}
1956
1957void TabContents::PasswordFormsSeen(
[email protected]ed3fb032009-06-16 19:50:561958 const std::vector<webkit_glue::PasswordForm>& forms) {
[email protected]420ae012009-04-24 05:16:321959 GetPasswordManager()->PasswordFormsSeen(forms);
1960}
1961
1962void TabContents::AutofillFormSubmitted(
[email protected]daa8c58e2009-06-15 17:21:101963 const webkit_glue::AutofillForm& form) {
[email protected]420ae012009-04-24 05:16:321964 GetAutofillManager()->AutofillFormSubmitted(form);
1965}
1966
1967void TabContents::GetAutofillSuggestions(const std::wstring& field_name,
1968 const std::wstring& user_text, int64 node_id, int request_id) {
1969 GetAutofillManager()->FetchValuesForName(field_name, user_text,
1970 kMaxAutofillMenuItems, node_id, request_id);
1971}
1972
1973void TabContents::RemoveAutofillEntry(const std::wstring& field_name,
1974 const std::wstring& value) {
1975 GetAutofillManager()->RemoveValueForName(field_name, value);
1976}
1977
1978// Checks to see if we should generate a keyword based on the OSDD, and if
1979// necessary uses TemplateURLFetcher to download the OSDD and create a keyword.
1980void TabContents::PageHasOSDD(RenderViewHost* render_view_host,
1981 int32 page_id, const GURL& url,
1982 bool autodetected) {
1983 // Make sure page_id is the current page, and the TemplateURLModel is loaded.
1984 DCHECK(url.is_valid());
1985 if (!IsActiveEntry(page_id))
1986 return;
1987 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
1988 if (!url_model)
1989 return;
1990 if (!url_model->loaded()) {
1991 url_model->Load();
1992 return;
1993 }
1994 if (!profile()->GetTemplateURLFetcher())
1995 return;
1996
1997 if (profile()->IsOffTheRecord())
1998 return;
1999
2000 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
2001 DCHECK(entry);
2002
2003 const NavigationEntry* base_entry = entry;
2004 if (IsFormSubmit(base_entry)) {
2005 // If the current page is a form submit, find the last page that was not
2006 // a form submit and use its url to generate the keyword from.
2007 int index = controller_.last_committed_entry_index() - 1;
2008 while (index >= 0 && IsFormSubmit(controller_.GetEntryAtIndex(index)))
2009 index--;
2010 if (index >= 0)
2011 base_entry = controller_.GetEntryAtIndex(index);
2012 else
2013 base_entry = NULL;
2014 }
2015
2016 // We want to use the user typed URL if available since that represents what
2017 // the user typed to get here, and fall back on the regular URL if not.
2018 if (!base_entry)
2019 return;
2020 GURL keyword_url = base_entry->user_typed_url().is_valid() ?
2021 base_entry->user_typed_url() : base_entry->url();
2022 if (!keyword_url.is_valid())
2023 return;
2024 std::wstring keyword = TemplateURLModel::GenerateKeyword(keyword_url,
2025 autodetected);
2026 if (keyword.empty())
2027 return;
2028 const TemplateURL* template_url =
2029 url_model->GetTemplateURLForKeyword(keyword);
2030 if (template_url && (!template_url->safe_for_autoreplace() ||
2031 template_url->originating_url() == url)) {
2032 // Either there is a user created TemplateURL for this keyword, or the
2033 // keyword has the same OSDD url and we've parsed it.
2034 return;
2035 }
2036
2037 // Download the OpenSearch description document. If this is successful a
2038 // new keyword will be created when done.
[email protected]420ae012009-04-24 05:16:322039 profile()->GetTemplateURLFetcher()->ScheduleDownload(
2040 keyword,
2041 url,
2042 base_entry->favicon().url(),
[email protected]d0cc9fb52009-06-23 02:26:162043 this,
[email protected]420ae012009-04-24 05:16:322044 autodetected);
2045}
2046
[email protected]420ae012009-04-24 05:16:322047void TabContents::DidGetPrintedPagesCount(int cookie, int number_pages) {
2048 printing_.DidGetPrintedPagesCount(cookie, number_pages);
2049}
2050
2051void TabContents::DidPrintPage(const ViewHostMsg_DidPrintPage_Params& params) {
2052 printing_.DidPrintPage(params);
2053}
2054
2055GURL TabContents::GetAlternateErrorPageURL() const {
2056 GURL url;
2057 // Disable alternate error pages when in OffTheRecord/Incognito mode.
2058 if (profile()->IsOffTheRecord())
2059 return url;
2060
2061 PrefService* prefs = profile()->GetPrefs();
2062 DCHECK(prefs);
2063 if (prefs->GetBoolean(prefs::kAlternateErrorPagesEnabled)) {
2064 url = google_util::AppendGoogleLocaleParam(GURL(kLinkDoctorBaseURL));
2065 url = google_util::AppendGoogleTLDParam(url);
2066 }
2067 return url;
2068}
2069
2070WebPreferences TabContents::GetWebkitPrefs() {
2071 PrefService* prefs = render_view_host()->process()->profile()->GetPrefs();
2072 bool isDomUI = false;
2073 return RenderViewHostDelegateHelper::GetWebkitPrefs(prefs, isDomUI);
2074}
2075
2076void TabContents::OnMissingPluginStatus(int status) {
2077#if defined(OS_WIN)
2078// TODO(PORT): pull in when plug-ins work
2079 GetPluginInstaller()->OnMissingPluginStatus(status);
2080#endif
2081}
2082
2083void TabContents::OnCrashedPlugin(const FilePath& plugin_path) {
2084#if defined(OS_WIN)
2085// TODO(PORT): pull in when plug-ins work
2086 DCHECK(!plugin_path.value().empty());
2087
2088 std::wstring plugin_name = plugin_path.ToWStringHack();
2089 scoped_ptr<FileVersionInfo> version_info(
2090 FileVersionInfo::CreateFileVersionInfo(plugin_path));
2091 if (version_info.get()) {
2092 const std::wstring& product_name = version_info->product_name();
2093 if (!product_name.empty())
2094 plugin_name = product_name;
2095 }
2096 AddInfoBar(new SimpleAlertInfoBarDelegate(
2097 this, l10n_util::GetStringF(IDS_PLUGIN_CRASHED_PROMPT, plugin_name),
2098 NULL));
2099#endif
2100}
2101
2102void TabContents::OnCrashedWorker() {
2103 AddInfoBar(new SimpleAlertInfoBarDelegate(
2104 this, l10n_util::GetString(IDS_WEBWORKER_CRASHED_PROMPT),
2105 NULL));
2106}
2107
2108void TabContents::OnJSOutOfMemory() {
2109 AddInfoBar(new SimpleAlertInfoBarDelegate(
2110 this, l10n_util::GetString(IDS_JS_OUT_OF_MEMORY_PROMPT), NULL));
2111}
2112
2113void TabContents::ShouldClosePage(bool proceed) {
2114 render_manager_.ShouldClosePage(proceed);
2115}
2116
2117void TabContents::OnCrossSiteResponse(int new_render_process_host_id,
2118 int new_request_id) {
[email protected]57c6a652009-05-04 07:58:342119 // Allows the TabContents to react when a cross-site response is ready to be
[email protected]420ae012009-04-24 05:16:322120 // delivered to a pending RenderViewHost. We must first run the onunload
2121 // handler of the old RenderViewHost before we can allow it to proceed.
2122 render_manager_.OnCrossSiteResponse(new_render_process_host_id,
2123 new_request_id);
2124}
2125
2126bool TabContents::CanBlur() const {
2127 return delegate() ? delegate()->CanBlur() : true;
2128}
2129
2130gfx::Rect TabContents::GetRootWindowResizerRect() const {
2131 if (delegate())
2132 return delegate()->GetRootWindowResizerRect();
2133 return gfx::Rect();
2134}
2135
2136void TabContents::RendererUnresponsive(RenderViewHost* rvh,
2137 bool is_during_unload) {
2138 if (is_during_unload) {
2139 // Hang occurred while firing the beforeunload/unload handler.
2140 // Pretend the handler fired so tab closing continues as if it had.
[email protected]829e7612009-04-25 01:15:112141 rvh->set_sudden_termination_allowed(true);
[email protected]420ae012009-04-24 05:16:322142
2143 if (!render_manager_.ShouldCloseTabOnUnresponsiveRenderer())
2144 return;
2145
2146 // If the tab hangs in the beforeunload/unload handler there's really
2147 // nothing we can do to recover. Pretend the unload listeners have
2148 // all fired and close the tab. If the hang is in the beforeunload handler
2149 // then the user will not have the option of cancelling the close.
2150 Close(rvh);
2151 return;
2152 }
2153
2154 if (render_view_host() && render_view_host()->IsRenderViewLive())
[email protected]d82ed61e2009-06-16 02:46:222155 HungRendererDialog::ShowForTabContents(this);
[email protected]420ae012009-04-24 05:16:322156}
2157
2158void TabContents::RendererResponsive(RenderViewHost* render_view_host) {
[email protected]d82ed61e2009-06-16 02:46:222159 HungRendererDialog::HideForTabContents(this);
[email protected]420ae012009-04-24 05:16:322160}
2161
2162void TabContents::LoadStateChanged(const GURL& url,
2163 net::LoadState load_state) {
2164 load_state_ = load_state;
[email protected]d686e812009-06-03 19:10:292165 std::wstring languages =
2166 profile()->GetPrefs()->GetString(prefs::kAcceptLanguages);
2167 load_state_host_.clear();
2168 std::string host = url.host();
2169 net::IDNToUnicode(host.c_str(), host.size(), languages, &load_state_host_);
[email protected]420ae012009-04-24 05:16:322170 if (load_state_ == net::LOAD_STATE_READING_RESPONSE)
2171 SetNotWaitingForResponse();
2172 if (is_loading())
[email protected]c9cd2222009-05-06 05:16:502173 NotifyNavigationStateChanged(INVALIDATE_LOAD | INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:322174}
2175
2176void TabContents::OnDidGetApplicationInfo(
2177 int32 page_id,
2178 const webkit_glue::WebApplicationInfo& info) {
2179 if (pending_install_.page_id != page_id)
2180 return; // The user clicked create on a separate page. Ignore this.
2181
2182 pending_install_.callback_functor =
2183 new GearsCreateShortcutCallbackFunctor(this);
2184 GearsCreateShortcut(
2185 info, pending_install_.title, pending_install_.url, pending_install_.icon,
2186 NewCallback(pending_install_.callback_functor,
2187 &GearsCreateShortcutCallbackFunctor::Run));
2188}
2189
[email protected]14ce83f2009-05-28 18:35:242190void TabContents::OnUserGesture() {
2191 // See comment in RenderViewHostDelegate::OnUserGesture as to why we do this.
[email protected]420ae012009-04-24 05:16:322192 DownloadRequestManager* drm = g_browser_process->download_request_manager();
2193 if (drm)
2194 drm->OnUserGesture(this);
[email protected]09b8f82f2009-06-16 20:22:112195 controller_.OnUserGesture();
[email protected]420ae012009-04-24 05:16:322196}
2197
2198void TabContents::OnFindReply(int request_id,
2199 int number_of_matches,
2200 const gfx::Rect& selection_rect,
2201 int active_match_ordinal,
2202 bool final_update) {
2203 // Ignore responses for requests other than the one we have most recently
2204 // issued. That way we won't act on stale results when the user has
2205 // already typed in another query.
2206 if (request_id != current_find_request_id_)
2207 return;
2208
2209 if (number_of_matches == -1)
[email protected]e491f1c2009-05-22 20:28:122210 number_of_matches = last_search_result_.number_of_matches();
[email protected]420ae012009-04-24 05:16:322211 if (active_match_ordinal == -1)
[email protected]e491f1c2009-05-22 20:28:122212 active_match_ordinal = last_search_result_.active_match_ordinal();
[email protected]420ae012009-04-24 05:16:322213
[email protected]2c355c282009-05-21 23:24:432214 gfx::Rect selection = selection_rect;
2215 if (selection.IsEmpty())
[email protected]e491f1c2009-05-22 20:28:122216 selection = last_search_result_.selection_rect();
[email protected]2c355c282009-05-21 23:24:432217
[email protected]420ae012009-04-24 05:16:322218 // Notify the UI, automation and any other observers that a find result was
2219 // found.
[email protected]e491f1c2009-05-22 20:28:122220 last_search_result_ = FindNotificationDetails(request_id, number_of_matches,
2221 selection, active_match_ordinal,
2222 final_update);
[email protected]420ae012009-04-24 05:16:322223 NotificationService::current()->Notify(
2224 NotificationType::FIND_RESULT_AVAILABLE,
2225 Source<TabContents>(this),
[email protected]e491f1c2009-05-22 20:28:122226 Details<FindNotificationDetails>(&last_search_result_));
[email protected]420ae012009-04-24 05:16:322227}
2228
[email protected]829e7612009-04-25 01:15:112229bool TabContents::IsExternalTabContainer() const {
[email protected]420ae012009-04-24 05:16:322230 if (!delegate())
[email protected]829e7612009-04-25 01:15:112231 return false;
[email protected]420ae012009-04-24 05:16:322232
[email protected]829e7612009-04-25 01:15:112233 return delegate()->IsExternalTabContainer();
[email protected]420ae012009-04-24 05:16:322234}
2235
2236void TabContents::FileSelected(const FilePath& path,
2237 int index, void* params) {
2238 render_view_host()->FileSelected(path);
2239}
2240
2241void TabContents::MultiFilesSelected(const std::vector<FilePath>& files,
2242 void* params) {
2243 render_view_host()->MultiFilesSelected(files);
2244}
2245
2246void TabContents::FileSelectionCanceled(void* params) {
2247 // If the user cancels choosing a file to upload we pass back an
2248 // empty vector.
2249 render_view_host()->MultiFilesSelected(std::vector<FilePath>());
2250}
2251
2252void TabContents::BeforeUnloadFiredFromRenderManager(
2253 bool proceed,
2254 bool* proceed_to_fire_unload) {
2255 if (delegate())
2256 delegate()->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
2257}
2258
2259void TabContents::UpdateRenderViewSizeForRenderManager() {
2260 // TODO(brettw) this is a hack. See TabContentsView::SizeContents.
2261 view_->SizeContents(view_->GetContainerSize());
2262}
2263
2264DOMUI* TabContents::CreateDOMUIForRenderManager(const GURL& url) {
[email protected]d82ed61e2009-06-16 02:46:222265 return DOMUIFactory::CreateDOMUIForURL(this, url);
[email protected]420ae012009-04-24 05:16:322266}
2267
2268NavigationEntry*
2269TabContents::GetLastCommittedNavigationEntryForRenderManager() {
2270 return controller_.GetLastCommittedEntry();
2271}
2272
2273bool TabContents::CreateRenderViewForRenderManager(
2274 RenderViewHost* render_view_host) {
[email protected]811bfe32009-07-01 08:46:252275 // If the pending navigation is to a DOMUI, tell the RenderView about any
2276 // bindings it will need enabled.
[email protected]420ae012009-04-24 05:16:322277 if (render_manager_.pending_dom_ui())
[email protected]811bfe32009-07-01 08:46:252278 render_view_host->AllowBindings(
2279 render_manager_.pending_dom_ui()->bindings());
[email protected]1adff062009-06-02 18:39:552280
[email protected]420ae012009-04-24 05:16:322281 RenderWidgetHostView* rwh_view = view_->CreateViewForWidget(render_view_host);
2282 if (!render_view_host->CreateRenderView())
2283 return false;
2284
2285 // Now that the RenderView has been created, we need to tell it its size.
2286 rwh_view->SetSize(view_->GetContainerSize());
2287
2288 UpdateMaxPageIDIfNecessary(render_view_host->site_instance(),
2289 render_view_host);
2290 return true;
2291}
2292
2293void TabContents::Observe(NotificationType type,
2294 const NotificationSource& source,
2295 const NotificationDetails& details) {
2296 switch (type.value) {
2297 case NotificationType::BOOKMARK_MODEL_LOADED:
2298 // BookmarkModel finished loading, fall through to update starred state.
2299 case NotificationType::URLS_STARRED: {
2300 // Somewhere, a URL has been starred.
2301 // Ignore notifications for profiles other than our current one.
2302 Profile* source_profile = Source<Profile>(source).ptr();
2303 if (!source_profile || !source_profile->IsSameProfile(profile()))
2304 return;
2305
2306 UpdateStarredStateForCurrentURL();
2307 break;
2308 }
2309 case NotificationType::PREF_CHANGED: {
2310 std::wstring* pref_name_in = Details<std::wstring>(details).ptr();
2311 DCHECK(Source<PrefService>(source).ptr() == profile()->GetPrefs());
2312 if (*pref_name_in == prefs::kAlternateErrorPagesEnabled) {
2313 UpdateAlternateErrorPageURL();
2314 } else if (*pref_name_in == prefs::kDefaultCharset ||
2315 StartsWithASCII(WideToUTF8(*pref_name_in), "webkit.webprefs.", true)
2316 ) {
2317 UpdateWebPreferences();
2318 } else {
2319 NOTREACHED() << "unexpected pref change notification" << *pref_name_in;
2320 }
2321 break;
2322 }
2323 case NotificationType::RENDER_WIDGET_HOST_DESTROYED:
2324 view_->RenderWidgetHostDestroyed(Source<RenderWidgetHost>(source).ptr());
2325 break;
2326
2327 case NotificationType::NAV_ENTRY_COMMITTED: {
2328 DCHECK(&controller_ == Source<NavigationController>(source).ptr());
2329
2330 NavigationController::LoadCommittedDetails& committed_details =
2331 *(Details<NavigationController::LoadCommittedDetails>(details).ptr());
2332 ExpireInfoBars(committed_details);
2333 break;
2334 }
2335
2336 default:
2337 NOTREACHED();
2338 }
2339}