blob: 557d2a6667e38bc644fb961074f8352f7706eafe [file] [log] [blame]
[email protected]ce5c4502009-05-06 16:46:111// Copyright (c) 2009 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
[email protected]f3ec7742009-01-15 00:59:165#include "chrome/browser/tab_contents/tab_contents.h"
initial.commit09911bf2008-07-26 23:55:296
[email protected]a92b8642009-05-05 23:38:567#include "app/l10n_util.h"
[email protected]9929da92009-05-05 02:05:118#include "app/resource_bundle.h"
[email protected]420ae012009-04-24 05:16:329#include "base/file_version_info.h"
10#include "base/process_util.h"
[email protected]96d185d2009-04-24 03:28:5411#include "base/string16.h"
12#include "base/time.h"
[email protected]fdd61c62009-04-22 19:22:5713#include "chrome/browser/autofill_manager.h"
[email protected]66ba4932009-06-04 19:22:1314#include "chrome/browser/blocked_popup_container.h"
[email protected]420ae012009-04-24 05:16:3215#include "chrome/browser/bookmarks/bookmark_model.h"
[email protected]96d185d2009-04-24 03:28:5416#include "chrome/browser/browser_process.h"
initial.commit09911bf2008-07-26 23:55:2917#include "chrome/browser/cert_store.h"
[email protected]96d185d2009-04-24 03:28:5418#include "chrome/browser/debugger/devtools_manager.h"
[email protected]420ae012009-04-24 05:16:3219#include "chrome/browser/dom_operation_notification_details.h"
[email protected]96d185d2009-04-24 03:28:5420#include "chrome/browser/dom_ui/dom_ui.h"
21#include "chrome/browser/dom_ui/dom_ui_factory.h"
[email protected]bcef0dc02009-02-28 00:35:0222#include "chrome/browser/download/download_item_model.h"
[email protected]420ae012009-04-24 05:16:3223#include "chrome/browser/download/download_manager.h"
24#include "chrome/browser/download/download_request_manager.h"
[email protected]420ae012009-04-24 05:16:3225#include "chrome/browser/gears_integration.h"
26#include "chrome/browser/google_util.h"
[email protected]8897c382009-05-06 17:53:2627#include "chrome/browser/hung_renderer_dialog.h"
[email protected]420ae012009-04-24 05:16:3228#include "chrome/browser/jsmessage_box_handler.h"
29#include "chrome/browser/load_from_memory_cache_details.h"
30#include "chrome/browser/load_notification_details.h"
[email protected]fdd61c62009-04-22 19:22:5731#include "chrome/browser/password_manager/password_manager.h"
32#include "chrome/browser/plugin_installer.h"
[email protected]ce560f82009-06-03 09:39:4433#include "chrome/browser/profile.h"
[email protected]96d185d2009-04-24 03:28:5434#include "chrome/browser/renderer_host/render_widget_host_view.h"
35#include "chrome/browser/renderer_host/web_cache_manager.h"
[email protected]bd1ad682009-05-15 22:19:1736#include "chrome/browser/tab_contents/infobar_delegate.h"
[email protected]7e383692009-06-12 19:14:5437#include "chrome/browser/tab_contents/interstitial_page.h"
[email protected]f3ec7742009-01-15 00:59:1638#include "chrome/browser/tab_contents/navigation_entry.h"
39#include "chrome/browser/tab_contents/tab_contents_delegate.h"
[email protected]fdd61c62009-04-22 19:22:5740#include "chrome/browser/tab_contents/tab_contents_view.h"
[email protected]58dca552009-06-17 00:35:0241#include "chrome/browser/tab_contents/thumbnail_generator.h"
[email protected]449478302009-06-09 20:04:2842#include "chrome/browser/thumbnail_store.h"
[email protected]420ae012009-04-24 05:16:3243#include "chrome/browser/search_engines/template_url_fetcher.h"
44#include "chrome/browser/search_engines/template_url_model.h"
[email protected]35f7d212009-04-29 21:19:2745#include "chrome/common/chrome_switches.h"
[email protected]bfd04a62009-02-01 18:16:5646#include "chrome/common/notification_service.h"
[email protected]ce5c4502009-05-06 16:46:1147#include "chrome/common/page_action.h"
initial.commit09911bf2008-07-26 23:55:2948#include "chrome/common/pref_names.h"
[email protected]1eb89e82008-08-15 12:27:0349#include "chrome/common/pref_service.h"
[email protected]420ae012009-04-24 05:16:3250#include "chrome/common/render_messages.h"
[email protected]96d185d2009-04-24 03:28:5451#include "chrome/common/url_constants.h"
[email protected]8897c382009-05-06 17:53:2652#include "grit/generated_resources.h"
[email protected]420ae012009-04-24 05:16:3253#include "grit/locale_settings.h"
54#include "net/base/mime_util.h"
55#include "net/base/net_errors.h"
[email protected]d686e812009-06-03 19:10:2956#include "net/base/net_util.h"
[email protected]420ae012009-04-24 05:16:3257#include "net/base/registry_controlled_domain.h"
[email protected]3e45ba92009-02-20 21:09:0058
59#if defined(OS_WIN)
[email protected]66ba4932009-06-04 19:22:1360// For CRect
[email protected]9041a302009-06-04 19:36:3361#include <atlbase.h>
[email protected]326f7112009-06-04 19:30:2962#include <atlapp.h>
[email protected]66ba4932009-06-04 19:22:1363#include <atlmisc.h>
[email protected]3e45ba92009-02-20 21:09:0064// TODO(port): some of these headers should be ported.
[email protected]420ae012009-04-24 05:16:3265#include "chrome/browser/modal_html_dialog_delegate.h"
[email protected]2362e4f2009-05-08 00:34:0566#include "views/controls/scrollbar/native_scroll_bar.h"
[email protected]3e45ba92009-02-20 21:09:0067#endif
initial.commit09911bf2008-07-26 23:55:2968
[email protected]420ae012009-04-24 05:16:3269// Cross-Site Navigations
70//
71// If a TabContents is told to navigate to a different web site (as determined
72// by SiteInstance), it will replace its current RenderViewHost with a new
73// RenderViewHost dedicated to the new SiteInstance. This works as follows:
74//
75// - Navigate determines whether the destination is cross-site, and if so,
76// it creates a pending_render_view_host_ and moves into the PENDING
77// RendererState.
78// - The pending RVH is "suspended," so that no navigation messages are sent to
79// its renderer until the onbeforeunload JavaScript handler has a chance to
80// run in the current RVH.
81// - The pending RVH tells CrossSiteRequestManager (a thread-safe singleton)
82// that it has a pending cross-site request. ResourceDispatcherHost will
83// check for this when the response arrives.
84// - The current RVH runs its onbeforeunload handler. If it returns false, we
85// cancel all the pending logic and go back to NORMAL. Otherwise we allow
86// the pending RVH to send the navigation request to its renderer.
87// - ResourceDispatcherHost receives a ResourceRequest on the IO thread. It
88// checks CrossSiteRequestManager to see that the RVH responsible has a
89// pending cross-site request, and then installs a CrossSiteEventHandler.
90// - When RDH receives a response, the BufferedEventHandler determines whether
91// it is a download. If so, it sends a message to the new renderer causing
92// it to cancel the request, and the download proceeds in the download
93// thread. For now, we stay in a PENDING state (with a pending RVH) until
[email protected]57c6a652009-05-04 07:58:3494// the next DidNavigate event for this TabContents. This isn't ideal, but it
[email protected]420ae012009-04-24 05:16:3295// doesn't affect any functionality.
96// - After RDH receives a response and determines that it is safe and not a
97// download, it pauses the response to first run the old page's onunload
98// handler. It does this by asynchronously calling the OnCrossSiteResponse
[email protected]57c6a652009-05-04 07:58:3499// method of TabContents on the UI thread, which sends a ClosePage message
[email protected]420ae012009-04-24 05:16:32100// to the current RVH.
101// - Once the onunload handler is finished, a ClosePage_ACK message is sent to
102// the ResourceDispatcherHost, who unpauses the response. Data is then sent
103// to the pending RVH.
104// - The pending renderer sends a FrameNavigate message that invokes the
105// DidNavigate method. This replaces the current RVH with the
106// pending RVH and goes back to the NORMAL RendererState.
107
108namespace {
109
110// Amount of time we wait between when a key event is received and the renderer
111// is queried for its state and pushed to the NavigationEntry.
112const int kQueryStateDelay = 5000;
113
114const int kSyncWaitDelay = 40;
115
116// If another javascript message box is displayed within
117// kJavascriptMessageExpectedDelay of a previous javascript message box being
118// dismissed, display an option to suppress future message boxes from this
119// contents.
120const int kJavascriptMessageExpectedDelay = 1000;
121
[email protected]420ae012009-04-24 05:16:32122const char kLinkDoctorBaseURL[] =
123 "http://linkhelp.clients.google.com/tbproxy/lh/fixurl";
124
[email protected]420ae012009-04-24 05:16:32125// The list of prefs we want to observe.
126const wchar_t* kPrefsToObserve[] = {
127 prefs::kAlternateErrorPagesEnabled,
128 prefs::kWebKitJavaEnabled,
129 prefs::kWebKitJavascriptEnabled,
130 prefs::kWebKitLoadsImagesAutomatically,
131 prefs::kWebKitPluginsEnabled,
132 prefs::kWebKitUsesUniversalDetector,
133 prefs::kWebKitSerifFontFamily,
134 prefs::kWebKitSansSerifFontFamily,
135 prefs::kWebKitFixedFontFamily,
136 prefs::kWebKitDefaultFontSize,
137 prefs::kWebKitDefaultFixedFontSize,
138 prefs::kDefaultCharset
139 // kWebKitStandardFontIsSerif needs to be added
140 // if we let users pick which font to use, serif or sans-serif when
141 // no font is specified or a CSS generic family (serif or sans-serif)
142 // is not specified.
143};
144
145const int kPrefsToObserveLength = arraysize(kPrefsToObserve);
146
147// Limit on the number of suggestions to appear in the pop-up menu under an
148// text input element in a form.
149const int kMaxAutofillMenuItems = 6;
150
151// Returns true if the entry's transition type is FORM_SUBMIT.
152bool IsFormSubmit(const NavigationEntry* entry) {
153 return (PageTransition::StripQualifier(entry->transition_type()) ==
154 PageTransition::FORM_SUBMIT);
155}
156
157#if defined(OS_WIN)
158
159BOOL CALLBACK InvalidateWindow(HWND hwnd, LPARAM lparam) {
160 // Note: erase is required to properly paint some widgets borders. This can
161 // be seen with textfields.
162 InvalidateRect(hwnd, NULL, TRUE);
163 return TRUE;
164}
165#endif
166
[email protected]420ae012009-04-24 05:16:32167} // namespace
168
169// -----------------------------------------------------------------------------
170
[email protected]fdd61c62009-04-22 19:22:57171// static
172int TabContents::find_request_id_counter_ = -1;
173
[email protected]420ae012009-04-24 05:16:32174class TabContents::GearsCreateShortcutCallbackFunctor {
175 public:
176 explicit GearsCreateShortcutCallbackFunctor(TabContents* contents)
177 : contents_(contents) {}
178
179 void Run(const GearsShortcutData2& shortcut_data, bool success) {
180 if (contents_)
181 contents_->OnGearsCreateShortcutDone(shortcut_data, success);
182 delete this;
183 }
184 void Cancel() {
185 contents_ = NULL;
186 }
187
188 private:
189 TabContents* contents_;
190};
191
[email protected]420ae012009-04-24 05:16:32192TabContents::TabContents(Profile* profile,
193 SiteInstance* site_instance,
194 int routing_id,
195 base::WaitableEvent* modal_dialog_event)
[email protected]b680ad22009-04-15 23:19:42196 : delegate_(NULL),
[email protected]66ba4932009-06-04 19:22:13197 ALLOW_THIS_IN_INITIALIZER_LIST(controller_(this, profile)),
198 ALLOW_THIS_IN_INITIALIZER_LIST(view_(
[email protected]d82ed61e2009-06-16 02:46:22199 TabContentsView::Create(this))),
200 ALLOW_THIS_IN_INITIALIZER_LIST(render_manager_(this, this)),
[email protected]fdd61c62009-04-22 19:22:57201 property_bag_(),
202 registrar_(),
[email protected]d82ed61e2009-06-16 02:46:22203 ALLOW_THIS_IN_INITIALIZER_LIST(printing_(*this)),
[email protected]fdd61c62009-04-22 19:22:57204 save_package_(),
205 cancelable_consumer_(),
206 autofill_manager_(),
207 password_manager_(),
208 plugin_installer_(),
[email protected]d82ed61e2009-06-16 02:46:22209 ALLOW_THIS_IN_INITIALIZER_LIST(fav_icon_helper_(this)),
[email protected]fdd61c62009-04-22 19:22:57210 select_file_dialog_(),
211 pending_install_(),
[email protected]d5f942ba2008-09-26 19:30:34212 is_loading_(false),
initial.commit09911bf2008-07-26 23:55:29213 is_crashed_(false),
[email protected]d5f942ba2008-09-26 19:30:34214 waiting_for_response_(false),
[email protected]d5f942ba2008-09-26 19:30:34215 max_page_id_(-1),
[email protected]fdd61c62009-04-22 19:22:57216 current_load_start_(),
217 load_state_(net::LOAD_STATE_IDLE),
218 load_state_host_(),
219 received_page_title_(false),
220 is_starred_(false),
221 contents_mime_type_(),
222 encoding_(),
[email protected]332af7732009-03-11 13:21:35223 blocked_popups_(NULL),
[email protected]fdd61c62009-04-22 19:22:57224 infobar_delegates_(),
[email protected]fdd61c62009-04-22 19:22:57225 find_ui_active_(false),
226 find_op_aborted_(false),
227 current_find_request_id_(find_request_id_counter_++),
228 find_text_(),
[email protected]e491f1c2009-05-22 20:28:12229 last_search_case_sensitive_(false),
230 last_search_prepopulate_text_(NULL),
231 last_search_result_(),
[email protected]fdd61c62009-04-22 19:22:57232 capturing_contents_(false),
233 is_being_destroyed_(false),
234 notify_disconnection_(false),
235 history_requests_(),
236#if defined(OS_WIN)
237 message_box_active_(CreateEvent(NULL, TRUE, FALSE, NULL)),
238#endif
239 last_javascript_message_dismissal_(),
240 suppress_javascript_messages_(false) {
[email protected]420ae012009-04-24 05:16:32241 pending_install_.page_id = 0;
242 pending_install_.callback_functor = NULL;
243
[email protected]58dca552009-06-17 00:35:02244#if defined(LINUX2)
245 // Make sure the thumbnailer is started before starting the render manager.
246 // The thumbnailer will want to listen for RVH creations, one of which will
247 // happen in RVHManager::Init.
248 ThumbnailGenerator* generator = g_browser_process->GetThumbnailGenerator();
249 if (generator)
250 generator->StartThumbnailing();
251#endif
252
[email protected]420ae012009-04-24 05:16:32253 render_manager_.Init(profile, site_instance, routing_id, modal_dialog_event);
254
255 view_->CreateView();
256
257 // Register for notifications about all interested prefs change.
258 PrefService* prefs = profile->GetPrefs();
259 if (prefs) {
260 for (int i = 0; i < kPrefsToObserveLength; ++i)
261 prefs->AddPrefObserver(kPrefsToObserve[i], this);
262 }
263
264 // Register for notifications about URL starredness changing on any profile.
265 registrar_.Add(this, NotificationType::URLS_STARRED,
266 NotificationService::AllSources());
267 registrar_.Add(this, NotificationType::BOOKMARK_MODEL_LOADED,
268 NotificationService::AllSources());
269 registrar_.Add(this, NotificationType::RENDER_WIDGET_HOST_DESTROYED,
270 NotificationService::AllSources());
271
272 // Keep a global copy of the previous search string (if any).
273 static string16 global_last_search = string16();
[email protected]e491f1c2009-05-22 20:28:12274 last_search_prepopulate_text_ = &global_last_search;
[email protected]332af7732009-03-11 13:21:35275}
initial.commit09911bf2008-07-26 23:55:29276
277TabContents::~TabContents() {
[email protected]420ae012009-04-24 05:16:32278 is_being_destroyed_ = true;
279
280 // We don't want any notifications while we're runnign our destructor.
281 registrar_.RemoveAll();
282
283 // Unregister the notifications of all observed prefs change.
284 PrefService* prefs = profile()->GetPrefs();
285 if (prefs) {
286 for (int i = 0; i < kPrefsToObserveLength; ++i)
287 prefs->RemovePrefObserver(kPrefsToObserve[i], this);
288 }
289
290 // Clean up subwindows like plugins and the find in page bar.
291 view_->OnContentsDestroy();
292
293 NotifyDisconnected();
[email protected]d82ed61e2009-06-16 02:46:22294 HungRendererDialog::HideForTabContents(this);
[email protected]420ae012009-04-24 05:16:32295
296 if (pending_install_.callback_functor)
297 pending_install_.callback_functor->Cancel();
298
299 // First cleanly close all child windows.
300 // TODO(mpcomplete): handle case if MaybeCloseChildWindows() already asked
301 // some of these to close. CloseWindows is async, so it might get called
302 // twice before it runs.
303 int size = static_cast<int>(child_windows_.size());
304 for (int i = size - 1; i >= 0; --i) {
305 ConstrainedWindow* window = child_windows_[i];
306 if (window)
307 window->CloseConstrainedWindow();
308 }
309
[email protected]66ba4932009-06-04 19:22:13310 if (blocked_popups_)
311 blocked_popups_->Destroy();
312
[email protected]420ae012009-04-24 05:16:32313 // Notify any observer that have a reference on this tab contents.
314 NotificationService::current()->Notify(
315 NotificationType::TAB_CONTENTS_DESTROYED,
316 Source<TabContents>(this),
317 NotificationService::NoDetails());
318
[email protected]1e5e74f2009-05-27 20:55:12319 // Notify any lasting InfobarDelegates that have not yet been removed that
320 // whatever infobar they were handling in this TabContents has closed,
321 // because the TabContents is going away entirely.
322 // This must happen after the TAB_CONTENTS_DESTROYED notification as the
323 // notification may trigger infobars calls that access their delegate. (and
324 // some implementations of InfoBarDelegate do delete themselves on
325 // InfoBarClosed()).
326 for (int i = 0; i < infobar_delegate_count(); ++i) {
327 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
328 delegate->InfoBarClosed();
329 }
330 infobar_delegates_.clear();
331
[email protected]420ae012009-04-24 05:16:32332 // TODO(brettw) this should be moved to the view.
333#if defined(OS_WIN)
334 // If we still have a window handle, destroy it. GetNativeView can return
335 // NULL if this contents was part of a window that closed.
336 if (GetNativeView())
337 ::DestroyWindow(GetNativeView());
338#endif
initial.commit09911bf2008-07-26 23:55:29339}
340
[email protected]d5f942ba2008-09-26 19:30:34341// static
342void TabContents::RegisterUserPrefs(PrefService* prefs) {
[email protected]420ae012009-04-24 05:16:32343 prefs->RegisterBooleanPref(prefs::kAlternateErrorPagesEnabled, true);
344
345 WebPreferences pref_defaults;
346 prefs->RegisterBooleanPref(prefs::kWebKitJavascriptEnabled,
347 pref_defaults.javascript_enabled);
348 prefs->RegisterBooleanPref(prefs::kWebKitWebSecurityEnabled,
349 pref_defaults.web_security_enabled);
350 prefs->RegisterBooleanPref(
351 prefs::kWebKitJavascriptCanOpenWindowsAutomatically, true);
352 prefs->RegisterBooleanPref(prefs::kWebKitLoadsImagesAutomatically,
353 pref_defaults.loads_images_automatically);
354 prefs->RegisterBooleanPref(prefs::kWebKitPluginsEnabled,
355 pref_defaults.plugins_enabled);
356 prefs->RegisterBooleanPref(prefs::kWebKitDomPasteEnabled,
357 pref_defaults.dom_paste_enabled);
358 prefs->RegisterBooleanPref(prefs::kWebKitShrinksStandaloneImagesToFit,
359 pref_defaults.shrinks_standalone_images_to_fit);
[email protected]0df30122009-06-03 12:13:08360 prefs->RegisterStringPref(prefs::kWebKitInspectorSettings,
361 pref_defaults.inspector_settings);
[email protected]420ae012009-04-24 05:16:32362 prefs->RegisterBooleanPref(prefs::kWebKitTextAreasAreResizable,
363 pref_defaults.text_areas_are_resizable);
364 prefs->RegisterBooleanPref(prefs::kWebKitJavaEnabled,
365 pref_defaults.java_enabled);
366
367 prefs->RegisterLocalizedStringPref(prefs::kAcceptLanguages,
368 IDS_ACCEPT_LANGUAGES);
369 prefs->RegisterLocalizedStringPref(prefs::kDefaultCharset,
370 IDS_DEFAULT_ENCODING);
371 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitStandardFontIsSerif,
372 IDS_STANDARD_FONT_IS_SERIF);
373 prefs->RegisterLocalizedStringPref(prefs::kWebKitFixedFontFamily,
374 IDS_FIXED_FONT_FAMILY);
375 prefs->RegisterLocalizedStringPref(prefs::kWebKitSerifFontFamily,
376 IDS_SERIF_FONT_FAMILY);
377 prefs->RegisterLocalizedStringPref(prefs::kWebKitSansSerifFontFamily,
378 IDS_SANS_SERIF_FONT_FAMILY);
379 prefs->RegisterLocalizedStringPref(prefs::kWebKitCursiveFontFamily,
380 IDS_CURSIVE_FONT_FAMILY);
381 prefs->RegisterLocalizedStringPref(prefs::kWebKitFantasyFontFamily,
382 IDS_FANTASY_FONT_FAMILY);
383 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFontSize,
384 IDS_DEFAULT_FONT_SIZE);
385 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFixedFontSize,
386 IDS_DEFAULT_FIXED_FONT_SIZE);
387 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumFontSize,
388 IDS_MINIMUM_FONT_SIZE);
389 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumLogicalFontSize,
390 IDS_MINIMUM_LOGICAL_FONT_SIZE);
391 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitUsesUniversalDetector,
392 IDS_USES_UNIVERSAL_DETECTOR);
393 prefs->RegisterLocalizedStringPref(prefs::kStaticEncodings,
394 IDS_STATIC_ENCODING_LIST);
initial.commit09911bf2008-07-26 23:55:29395}
396
[email protected]d5f942ba2008-09-26 19:30:34397bool TabContents::SupportsURL(GURL* url) {
[email protected]6e95706d2009-04-23 22:55:01398 // TODO(brettw) remove this function.
[email protected]9423d9412009-04-14 22:13:55399 return true;
[email protected]d5f942ba2008-09-26 19:30:34400}
401
[email protected]6e95706d2009-04-23 22:55:01402AutofillManager* TabContents::GetAutofillManager() {
403 if (autofill_manager_.get() == NULL)
404 autofill_manager_.reset(new AutofillManager(this));
405 return autofill_manager_.get();
406}
407
408PasswordManager* TabContents::GetPasswordManager() {
409 if (password_manager_.get() == NULL)
410 password_manager_.reset(new PasswordManager(this));
411 return password_manager_.get();
412}
413
414PluginInstaller* TabContents::GetPluginInstaller() {
415 if (plugin_installer_.get() == NULL)
416 plugin_installer_.reset(new PluginInstaller(this));
417 return plugin_installer_.get();
418}
419
[email protected]d5f942ba2008-09-26 19:30:34420const GURL& TabContents::GetURL() const {
421 // We may not have a navigation entry yet
[email protected]ce3fa3c2009-04-20 19:55:57422 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34423 return entry ? entry->display_url() : GURL::EmptyGURL();
424}
425
[email protected]96d185d2009-04-24 03:28:54426const string16& TabContents::GetTitle() const {
[email protected]4c6092c5b2009-06-06 00:23:55427 // Transient entries take precedence. They are used for interstitial pages
428 // that are shown on top of existing pages.
429 NavigationEntry* entry = controller_.GetTransientEntry();
430 if (entry)
431 return entry->GetTitleForDisplay(&controller_);
432
[email protected]96d185d2009-04-24 03:28:54433 DOMUI* our_dom_ui = render_manager_.pending_dom_ui() ?
434 render_manager_.pending_dom_ui() : render_manager_.dom_ui();
435 if (our_dom_ui) {
436 // Don't override the title in view source mode.
[email protected]4c6092c5b2009-06-06 00:23:55437 entry = controller_.GetActiveEntry();
[email protected]96d185d2009-04-24 03:28:54438 if (!(entry && entry->IsViewSourceMode())) {
439 // Give the DOM UI the chance to override our title.
440 const string16& title = our_dom_ui->overridden_title();
441 if (!title.empty())
442 return title;
443 }
444 }
445
446 // We use the title for the last committed entry rather than a pending
447 // navigation entry. For example, when the user types in a URL, we want to
448 // keep the old page's title until the new load has committed and we get a new
449 // title.
[email protected]96d185d2009-04-24 03:28:54450 entry = controller_.GetLastCommittedEntry();
451 if (entry)
452 return entry->GetTitleForDisplay(&controller_);
453 else if (controller_.LoadingURLLazily())
454 return controller_.GetLazyTitle();
455 return EmptyString16();
456}
457
[email protected]d5f942ba2008-09-26 19:30:34458int32 TabContents::GetMaxPageID() {
459 if (GetSiteInstance())
460 return GetSiteInstance()->max_page_id();
461 else
462 return max_page_id_;
463}
464
465void TabContents::UpdateMaxPageID(int32 page_id) {
466 // Ensure both the SiteInstance and RenderProcessHost update their max page
[email protected]57c6a652009-05-04 07:58:34467 // IDs in sync. Only TabContents will also have site instances, except during
[email protected]d5f942ba2008-09-26 19:30:34468 // testing.
469 if (GetSiteInstance())
470 GetSiteInstance()->UpdateMaxPageID(page_id);
[email protected]57c6a652009-05-04 07:58:34471 process()->UpdateMaxPageID(page_id);
[email protected]d5f942ba2008-09-26 19:30:34472}
473
[email protected]96d185d2009-04-24 03:28:54474SiteInstance* TabContents::GetSiteInstance() const {
475 return render_manager_.current_host()->site_instance();
476}
477
[email protected]d5f942ba2008-09-26 19:30:34478const std::wstring TabContents::GetDefaultTitle() const {
479 return l10n_util::GetString(IDS_DEFAULT_TAB_TITLE);
480}
481
[email protected]96d185d2009-04-24 03:28:54482bool TabContents::ShouldDisplayURL() {
483 // Don't hide the url in view source mode.
484 NavigationEntry* entry = controller_.GetActiveEntry();
485 if (entry && entry->IsViewSourceMode())
486 return true;
[email protected]83e3895b2009-06-11 00:07:16487
488 // Hide the URL in chrome-extension://.
489 if (GetURL().SchemeIs(chrome::kExtensionScheme))
490 return false;
491
[email protected]96d185d2009-04-24 03:28:54492 DOMUI* dom_ui = GetDOMUIForCurrentState();
493 if (dom_ui)
494 return !dom_ui->should_hide_url();
495 return true;
496}
497
[email protected]d5f942ba2008-09-26 19:30:34498SkBitmap TabContents::GetFavIcon() const {
499 // Like GetTitle(), we also want to use the favicon for the last committed
500 // entry rather than a pending navigation entry.
[email protected]ce3fa3c2009-04-20 19:55:57501 NavigationEntry* entry = controller_.GetTransientEntry();
[email protected]cbab76d2008-10-13 22:42:47502 if (entry)
503 return entry->favicon().bitmap();
504
[email protected]ce3fa3c2009-04-20 19:55:57505 entry = controller_.GetLastCommittedEntry();
[email protected]d5f942ba2008-09-26 19:30:34506 if (entry)
507 return entry->favicon().bitmap();
[email protected]ce3fa3c2009-04-20 19:55:57508 else if (controller_.LoadingURLLazily())
509 return controller_.GetLazyFavIcon();
[email protected]d5f942ba2008-09-26 19:30:34510 return SkBitmap();
511}
512
[email protected]96d185d2009-04-24 03:28:54513bool TabContents::ShouldDisplayFavIcon() {
514 // Always display a throbber during pending loads.
515 if (controller_.GetLastCommittedEntry() && controller_.pending_entry())
516 return true;
517
518 DOMUI* dom_ui = GetDOMUIForCurrentState();
519 if (dom_ui)
520 return !dom_ui->hide_favicon();
521 return true;
522}
523
[email protected]96d185d2009-04-24 03:28:54524std::wstring TabContents::GetStatusText() const {
525 if (!is_loading() || load_state_ == net::LOAD_STATE_IDLE)
526 return std::wstring();
527
528 switch (load_state_) {
529 case net::LOAD_STATE_WAITING_FOR_CACHE:
530 return l10n_util::GetString(IDS_LOAD_STATE_WAITING_FOR_CACHE);
531 case net::LOAD_STATE_RESOLVING_PROXY_FOR_URL:
532 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_PROXY_FOR_URL);
533 case net::LOAD_STATE_RESOLVING_HOST:
534 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_HOST);
535 case net::LOAD_STATE_CONNECTING:
536 return l10n_util::GetString(IDS_LOAD_STATE_CONNECTING);
537 case net::LOAD_STATE_SENDING_REQUEST:
538 return l10n_util::GetString(IDS_LOAD_STATE_SENDING_REQUEST);
539 case net::LOAD_STATE_WAITING_FOR_RESPONSE:
540 return l10n_util::GetStringF(IDS_LOAD_STATE_WAITING_FOR_RESPONSE,
541 load_state_host_);
542 // Ignore net::LOAD_STATE_READING_RESPONSE and net::LOAD_STATE_IDLE
543 case net::LOAD_STATE_IDLE:
544 case net::LOAD_STATE_READING_RESPONSE:
545 break;
546 }
547
548 return std::wstring();
549}
550
[email protected]d5f942ba2008-09-26 19:30:34551void TabContents::SetIsCrashed(bool state) {
552 if (state == is_crashed_)
553 return;
554
555 is_crashed_ = state;
[email protected]c9cd2222009-05-06 05:16:50556 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]d5f942ba2008-09-26 19:30:34557}
558
[email protected]ce5c4502009-05-06 16:46:11559void TabContents::EnablePageAction(const PageAction* page_action) {
560 DCHECK(page_action);
561
562 if (IsPageActionEnabled(page_action))
563 return; // Already enabled.
564
565 enabled_page_actions_.insert(page_action);
566}
567
568bool TabContents::IsPageActionEnabled(const PageAction* page_action) {
569 DCHECK(page_action);
570 return enabled_page_actions_.end() != enabled_page_actions_.find(page_action);
571}
572
573
[email protected]d5f942ba2008-09-26 19:30:34574void TabContents::NotifyNavigationStateChanged(unsigned changed_flags) {
575 if (delegate_)
576 delegate_->NavigationStateChanged(this, changed_flags);
577}
578
[email protected]96d185d2009-04-24 03:28:54579void TabContents::DidBecomeSelected() {
580 controller_.SetActive(true);
581
582 if (render_widget_host_view())
583 render_widget_host_view()->DidBecomeSelected();
584
585 // If pid() is -1, that means the RenderProcessHost still hasn't been
586 // initialized. It'll register with CacheManagerHost when it is.
587 if (process()->pid() != -1)
588 WebCacheManager::GetInstance()->ObserveActivity(process()->pid());
589}
590
591void TabContents::WasHidden() {
592 if (!capturing_contents()) {
593 // |render_view_host()| can be NULL if the user middle clicks a link to open
594 // a tab in then background, then closes the tab before selecting it. This
595 // is because closing the tab calls TabContents::Destroy(), which removes
596 // the |render_view_host()|; then when we actually destroy the window,
597 // OnWindowPosChanged() notices and calls HideContents() (which calls us).
598 if (render_widget_host_view())
599 render_widget_host_view()->WasHidden();
[email protected]96d185d2009-04-24 03:28:54600 }
601
602 NotificationService::current()->Notify(
603 NotificationType::TAB_CONTENTS_HIDDEN,
604 Source<TabContents>(this),
605 NotificationService::NoDetails());
606}
607
[email protected]d5f942ba2008-09-26 19:30:34608void TabContents::Activate() {
609 if (delegate_)
610 delegate_->ActivateContents(this);
611}
612
[email protected]96d185d2009-04-24 03:28:54613void TabContents::ShowContents() {
614 if (render_widget_host_view())
615 render_widget_host_view()->DidBecomeSelected();
[email protected]96d185d2009-04-24 03:28:54616}
617
618void TabContents::HideContents() {
619 // TODO(pkasting): http://b/1239839 Right now we purposefully don't call
620 // our superclass HideContents(), because some callers want to be very picky
621 // about the order in which these get called. In addition to making the code
622 // here practically impossible to understand, this also means we end up
623 // calling TabContents::WasHidden() twice if callers call both versions of
[email protected]57c6a652009-05-04 07:58:34624 // HideContents() on a TabContents.
[email protected]96d185d2009-04-24 03:28:54625 WasHidden();
626}
627
[email protected]c0588052008-10-27 23:01:50628void TabContents::OpenURL(const GURL& url, const GURL& referrer,
[email protected]d5f942ba2008-09-26 19:30:34629 WindowOpenDisposition disposition,
630 PageTransition::Type transition) {
631 if (delegate_)
[email protected]c0588052008-10-27 23:01:50632 delegate_->OpenURLFromTab(this, url, referrer, disposition, transition);
[email protected]d5f942ba2008-09-26 19:30:34633}
634
635bool TabContents::NavigateToPendingEntry(bool reload) {
[email protected]96d185d2009-04-24 03:28:54636 const NavigationEntry& entry = *controller_.pending_entry();
637
638 RenderViewHost* dest_render_view_host = render_manager_.Navigate(entry);
639 if (!dest_render_view_host)
640 return false; // Unable to create the desired render view host.
641
642 // Tell DevTools agent that it is attached prior to the navigation.
[email protected]684b4ba22009-05-07 06:27:41643 DevToolsManager* devtools_manager = g_browser_process->devtools_manager();
[email protected]7e8e6b62009-05-08 11:28:32644 if (devtools_manager) { // NULL in unit tests.
[email protected]684b4ba22009-05-07 06:27:41645 devtools_manager->OnNavigatingToPendingEntry(
646 render_view_host(),
647 dest_render_view_host,
648 controller_.pending_entry()->url());
[email protected]7e8e6b62009-05-08 11:28:32649 }
[email protected]96d185d2009-04-24 03:28:54650
651 // Used for page load time metrics.
652 current_load_start_ = base::TimeTicks::Now();
653
654 // Navigate in the desired RenderViewHost.
655 dest_render_view_host->NavigateToEntry(entry, reload);
656
657 if (entry.page_id() == -1) {
658 // HACK!! This code suppresses javascript: URLs from being added to
659 // session history, which is what we want to do for javascript: URLs that
660 // do not generate content. What we really need is a message from the
661 // renderer telling us that a new page was not created. The same message
662 // could be used for mailto: URLs and the like.
663 if (entry.url().SchemeIs(chrome::kJavaScriptScheme))
664 return false;
665 }
666
667 // Clear any provisional password saves - this stops password infobars
668 // showing up on pages the user navigates to while the right page is
669 // loading.
670 GetPasswordManager()->ClearProvisionalSave();
671
672 if (reload && !profile()->IsOffTheRecord()) {
673 HistoryService* history =
674 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
675 if (history)
676 history->SetFavIconOutOfDateForPage(entry.url());
677 }
678
[email protected]d5f942ba2008-09-26 19:30:34679 return true;
680}
681
[email protected]96d185d2009-04-24 03:28:54682void TabContents::Stop() {
683 render_manager_.Stop();
684 printing_.Stop();
685}
686
687void TabContents::Cut() {
688 render_view_host()->Cut();
689}
690
691void TabContents::Copy() {
692 render_view_host()->Copy();
693}
694
695void TabContents::Paste() {
696 render_view_host()->Paste();
697}
698
699void TabContents::DisassociateFromPopupCount() {
700 render_view_host()->DisassociateFromPopupCount();
701}
702
703TabContents* TabContents::Clone() {
704 // We create a new SiteInstance so that the new tab won't share processes
705 // with the old one. This can be changed in the future if we need it to share
706 // processes for some reason.
[email protected]420ae012009-04-24 05:16:32707 TabContents* tc = new TabContents(profile(),
[email protected]96d185d2009-04-24 03:28:54708 SiteInstance::CreateSiteInstance(profile()),
709 MSG_ROUTING_NONE, NULL);
710 tc->controller().CopyStateFrom(controller_);
711 return tc;
712}
713
[email protected]420ae012009-04-24 05:16:32714void TabContents::CreateShortcut() {
715 NavigationEntry* entry = controller_.GetLastCommittedEntry();
716 if (!entry)
717 return;
718
719 // We only allow one pending install request. By resetting the page id we
720 // effectively cancel the pending install request.
721 pending_install_.page_id = entry->page_id();
722 pending_install_.icon = GetFavIcon();
723 pending_install_.title = UTF16ToWideHack(GetTitle());
724 pending_install_.url = GetURL();
725 if (pending_install_.callback_functor) {
726 pending_install_.callback_functor->Cancel();
727 pending_install_.callback_functor = NULL;
728 }
729 DCHECK(!pending_install_.icon.isNull()) << "Menu item should be disabled.";
730 if (pending_install_.title.empty())
731 pending_install_.title = UTF8ToWide(GetURL().spec());
732
733 // Request the application info. When done OnDidGetApplicationInfo is invoked
734 // and we'll create the shortcut.
735 render_view_host()->GetApplicationInfo(pending_install_.page_id);
736}
737
[email protected]76f68dc2009-03-10 20:31:32738#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29739ConstrainedWindow* TabContents::CreateConstrainedDialog(
[email protected]effb25d2009-06-17 16:48:11740 views::WindowDelegate* window_delegate) {
initial.commit09911bf2008-07-26 23:55:29741 ConstrainedWindow* window =
742 ConstrainedWindow::CreateConstrainedDialog(
[email protected]effb25d2009-06-17 16:48:11743 this, window_delegate);
initial.commit09911bf2008-07-26 23:55:29744 child_windows_.push_back(window);
745 return window;
746}
[email protected]f3332e12009-03-23 15:28:57747#endif
initial.commit09911bf2008-07-26 23:55:29748
749void TabContents::AddNewContents(TabContents* new_contents,
750 WindowOpenDisposition disposition,
751 const gfx::Rect& initial_pos,
[email protected]c88a70fe2009-05-05 20:00:22752 bool user_gesture,
753 const GURL& creator_url) {
initial.commit09911bf2008-07-26 23:55:29754 if (!delegate_)
755 return;
756
[email protected]ce494a312009-06-10 23:54:20757#if defined(OS_WIN) || defined(OS_LINUX)
[email protected]35f7d212009-04-29 21:19:27758 if ((disposition == NEW_POPUP) && !user_gesture &&
759 !CommandLine::ForCurrentProcess()->HasSwitch(
760 switches::kDisablePopupBlocking)) {
[email protected]2c4410d2009-05-06 23:46:22761 // Unrequested popups from normal pages are constrained unless they're in
[email protected]b6c874582009-05-08 19:38:31762 // the whitelist. The popup owner will handle checking this.
763 delegate_->GetConstrainingContents(this)->AddPopup(new_contents,
764 initial_pos,
765 creator_url.is_valid() ? creator_url.host() : std::string());
766 } else {
[email protected]0aa55312008-10-17 21:53:08767 new_contents->DisassociateFromPopupCount();
initial.commit09911bf2008-07-26 23:55:29768 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
769 user_gesture);
770 }
[email protected]b6c874582009-05-08 19:38:31771 PopupNotificationVisibilityChanged(ShowingBlockedPopupNotification());
[email protected]f3332e12009-03-23 15:28:57772#else
773 // TODO(port): implement the popup blocker stuff
774 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
775 user_gesture);
776#endif
initial.commit09911bf2008-07-26 23:55:29777}
778
initial.commit09911bf2008-07-26 23:55:29779void TabContents::CloseAllSuppressedPopups() {
[email protected]d6598c052008-11-05 19:03:25780 if (blocked_popups_)
[email protected]2c4410d2009-05-06 23:46:22781 blocked_popups_->CloseAll();
initial.commit09911bf2008-07-26 23:55:29782}
783
[email protected]96d185d2009-04-24 03:28:54784void TabContents::PopupNotificationVisibilityChanged(bool visible) {
785 render_view_host()->PopupNotificationVisibilityChanged(visible);
786}
787
788gfx::NativeView TabContents::GetContentNativeView() {
789 return view_->GetContentNativeView();
790}
791
792gfx::NativeView TabContents::GetNativeView() const {
793 return view_->GetNativeView();
794}
795
796void TabContents::GetContainerBounds(gfx::Rect *out) const {
797 view_->GetContainerBounds(out);
798}
799
800void TabContents::Focus() {
801 view_->Focus();
802}
803
[email protected]90daadb42009-06-08 21:27:28804void TabContents::FocusThroughTabTraversal(bool reverse) {
[email protected]7e383692009-06-12 19:14:54805 if (showing_interstitial_page()) {
806 render_manager_.interstitial_page()->FocusThroughTabTraversal(reverse);
807 return;
808 }
[email protected]96d185d2009-04-24 03:28:54809 render_view_host()->SetInitialFocus(reverse);
810}
811
812bool TabContents::FocusLocationBarByDefault() {
813 DOMUI* dom_ui = GetDOMUIForCurrentState();
814 if (dom_ui)
815 return dom_ui->focus_location_bar_by_default();
816 return false;
817}
818
[email protected]616ed5a2008-11-21 22:27:24819void TabContents::AddInfoBar(InfoBarDelegate* delegate) {
820 // Look through the existing InfoBarDelegates we have for a match. If we've
821 // already got one that matches, then we don't add the new one.
[email protected]f86a07022008-11-25 01:06:05822 for (int i = 0; i < infobar_delegate_count(); ++i) {
[email protected]616ed5a2008-11-21 22:27:24823 if (GetInfoBarDelegateAt(i)->EqualsDelegate(delegate))
824 return;
825 }
826
827 infobar_delegates_.push_back(delegate);
[email protected]bfd04a62009-02-01 18:16:56828 NotificationService::current()->Notify(
829 NotificationType::TAB_CONTENTS_INFOBAR_ADDED,
830 Source<TabContents>(this),
831 Details<InfoBarDelegate>(delegate));
[email protected]616ed5a2008-11-21 22:27:24832
833 // Add ourselves as an observer for navigations the first time a delegate is
834 // added. We use this notification to expire InfoBars that need to expire on
835 // page transitions.
836 if (infobar_delegates_.size() == 1) {
[email protected]bfd04a62009-02-01 18:16:56837 registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57838 Source<NavigationController>(&controller_));
[email protected]616ed5a2008-11-21 22:27:24839 }
840}
841
842void TabContents::RemoveInfoBar(InfoBarDelegate* delegate) {
843 std::vector<InfoBarDelegate*>::iterator it =
844 find(infobar_delegates_.begin(), infobar_delegates_.end(), delegate);
845 if (it != infobar_delegates_.end()) {
846 InfoBarDelegate* delegate = *it;
[email protected]bfd04a62009-02-01 18:16:56847 NotificationService::current()->Notify(
848 NotificationType::TAB_CONTENTS_INFOBAR_REMOVED,
849 Source<TabContents>(this),
850 Details<InfoBarDelegate>(delegate));
[email protected]f86a07022008-11-25 01:06:05851 infobar_delegates_.erase(it);
[email protected]616ed5a2008-11-21 22:27:24852
[email protected]6a02963e2009-01-06 16:58:03853 // Remove ourselves as an observer if we are tracking no more InfoBars.
854 if (infobar_delegates_.empty()) {
[email protected]bfd04a62009-02-01 18:16:56855 registrar_.Remove(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57856 Source<NavigationController>(&controller_));
[email protected]6a02963e2009-01-06 16:58:03857 }
[email protected]616ed5a2008-11-21 22:27:24858 }
859}
[email protected]3edd9522009-03-04 22:19:41860
[email protected]96d185d2009-04-24 03:28:54861bool TabContents::IsBookmarkBarAlwaysVisible() {
862 // See GetDOMUIForCurrentState() comment for more info. This case is very
863 // similar, but for non-first loads, we want to use the committed entry. This
864 // is so the bookmarks bar disappears at the same time the page does.
865 if (controller_.GetLastCommittedEntry()) {
866 // Not the first load, always use the committed DOM UI.
867 if (render_manager_.dom_ui())
868 return render_manager_.dom_ui()->force_bookmark_bar_visible();
869 return false; // Default.
870 }
871
872 // When it's the first load, we know either the pending one or the committed
873 // one will have the DOM UI in it (see GetDOMUIForCurrentState), and only one
874 // of them will be valid, so we can just check both.
875 if (render_manager_.pending_dom_ui())
876 return render_manager_.pending_dom_ui()->force_bookmark_bar_visible();
877 if (render_manager_.dom_ui())
878 return render_manager_.dom_ui()->force_bookmark_bar_visible();
879 return false; // Default.
880}
881
[email protected]3edd9522009-03-04 22:19:41882void TabContents::ToolbarSizeChanged(bool is_animating) {
883 TabContentsDelegate* d = delegate();
884 if (d)
885 d->ToolbarSizeChanged(this, is_animating);
886}
[email protected]616ed5a2008-11-21 22:27:24887
[email protected]d5f942ba2008-09-26 19:30:34888void TabContents::OnStartDownload(DownloadItem* download) {
889 DCHECK(download);
[email protected]d5f942ba2008-09-26 19:30:34890
891 // Download in a constrained popup is shown in the tab that opened it.
[email protected]b6c874582009-05-08 19:38:31892 TabContents* tab_contents = delegate()->GetConstrainingContents(this);
[email protected]d5f942ba2008-09-26 19:30:34893
[email protected]59560e0b2009-06-04 03:30:22894 if (tab_contents && tab_contents->delegate())
895 tab_contents->delegate()->OnStartDownload(download);
[email protected]19347f6f2009-06-19 04:24:20896
897 // Update the URL display.
898 // If the download is caused by typing in a downloadable URL, e.g.,
899 // http://example.com/somefile.zip, into the omnibox, the previous URL
900 // will reappear.
901 if (delegate())
902 delegate()->NavigationStateChanged(this, TabContents::INVALIDATE_URL);
[email protected]3edd9522009-03-04 22:19:41903}
[email protected]3edd9522009-03-04 22:19:41904
[email protected]d5f942ba2008-09-26 19:30:34905void TabContents::WillClose(ConstrainedWindow* window) {
906 ConstrainedWindowList::iterator it =
907 find(child_windows_.begin(), child_windows_.end(), window);
908 if (it != child_windows_.end())
909 child_windows_.erase(it);
[email protected]66ba4932009-06-04 19:22:13910}
[email protected]d5f942ba2008-09-26 19:30:34911
[email protected]66ba4932009-06-04 19:22:13912void TabContents::WillCloseBlockedPopupContainer(
913 BlockedPopupContainer* container) {
914 DCHECK(blocked_popups_ == container);
915 blocked_popups_ = NULL;
[email protected]d5f942ba2008-09-26 19:30:34916}
917
[email protected]d5f942ba2008-09-26 19:30:34918void TabContents::DidMoveOrResize(ConstrainedWindow* window) {
[email protected]332af7732009-03-11 13:21:35919#if defined(OS_WIN)
[email protected]92edc472009-02-10 20:32:06920 UpdateWindow(GetNativeView());
[email protected]332af7732009-03-11 13:21:35921#endif
[email protected]d5f942ba2008-09-26 19:30:34922}
923
[email protected]e491f1c2009-05-22 20:28:12924void TabContents::StartFinding(string16 find_text,
925 bool forward_direction,
926 bool case_sensitive) {
[email protected]6e95706d2009-04-23 22:55:01927 // If find_text is empty, it means FindNext was pressed with a keyboard
928 // shortcut so unless we have something to search for we return early.
[email protected]e491f1c2009-05-22 20:28:12929 if (find_text.empty() && find_text_.empty()) {
930 if (last_search_prepopulate_text_->empty())
931 return;
932 // Try whatever we searched for last in any tab.
933 find_text = *last_search_prepopulate_text_;
934 }
[email protected]6e95706d2009-04-23 22:55:01935
936 // This is a FindNext operation if we are searching for the same text again,
937 // or if the passed in search text is empty (FindNext keyboard shortcut). The
938 // exception to this is if the Find was aborted (then we don't want FindNext
939 // because the highlighting has been cleared and we need it to reappear). We
940 // therefore treat FindNext after an aborted Find operation as a full fledged
941 // Find.
942 bool find_next = (find_text_ == find_text || find_text.empty()) &&
[email protected]e491f1c2009-05-22 20:28:12943 (last_search_case_sensitive_ == case_sensitive) &&
[email protected]6e95706d2009-04-23 22:55:01944 !find_op_aborted_;
945 if (!find_next)
946 current_find_request_id_ = find_request_id_counter_++;
947
948 if (!find_text.empty())
949 find_text_ = find_text;
[email protected]e491f1c2009-05-22 20:28:12950 last_search_case_sensitive_ = case_sensitive;
[email protected]6e95706d2009-04-23 22:55:01951
952 find_op_aborted_ = false;
953
954 // Keep track of what the last search was across the tabs.
[email protected]e491f1c2009-05-22 20:28:12955 *last_search_prepopulate_text_ = find_text;
[email protected]6e95706d2009-04-23 22:55:01956
957 render_view_host()->StartFinding(current_find_request_id_,
958 find_text_,
959 forward_direction,
[email protected]e491f1c2009-05-22 20:28:12960 case_sensitive,
[email protected]6e95706d2009-04-23 22:55:01961 find_next);
962}
963
964void TabContents::StopFinding(bool clear_selection) {
[email protected]2d2dffc2009-06-09 21:41:00965 // When |clear_selection| is true, it means the find string has been cleared
966 // by the user, but the UI has not been dismissed.
967 if (!clear_selection)
968 find_ui_active_ = false;
[email protected]6e95706d2009-04-23 22:55:01969 find_op_aborted_ = true;
[email protected]e491f1c2009-05-22 20:28:12970 last_search_result_ = FindNotificationDetails();
[email protected]6e95706d2009-04-23 22:55:01971 render_view_host()->StopFinding(clear_selection);
972}
973
[email protected]420ae012009-04-24 05:16:32974void TabContents::OnJavaScriptMessageBoxClosed(IPC::Message* reply_msg,
975 bool success,
976 const std::wstring& prompt) {
977 last_javascript_message_dismissal_ = base::TimeTicks::Now();
978 render_manager_.OnJavaScriptMessageBoxClosed(reply_msg, success, prompt);
979}
980
[email protected]571e31152009-05-15 19:34:02981void TabContents::OnJavaScriptMessageBoxWindowDestroyed() {
982 render_manager_.OnJavaScriptMessageBoxWindowDestroyed();
983}
984
[email protected]420ae012009-04-24 05:16:32985void TabContents::OnSavePage() {
986 // If we can not save the page, try to download it.
987 if (!SavePackage::IsSavableContents(contents_mime_type())) {
988 DownloadManager* dlm = profile()->GetDownloadManager();
989 const GURL& current_page_url = GetURL();
990 if (dlm && current_page_url.is_valid())
[email protected]d82ed61e2009-06-16 02:46:22991 dlm->DownloadUrl(current_page_url, GURL(), "", this);
[email protected]420ae012009-04-24 05:16:32992 return;
993 }
994
995 Stop();
996
997 // Create the save package and possibly prompt the user for the name to save
998 // the page as. The user prompt is an asynchronous operation that runs on
999 // another thread.
[email protected]d82ed61e2009-06-16 02:46:221000 save_package_ = new SavePackage(this);
[email protected]420ae012009-04-24 05:16:321001 save_package_->GetSaveInfo();
1002}
1003
1004// Used in automated testing to bypass prompting the user for file names.
1005// Instead, the names and paths are hard coded rather than running them through
1006// file name sanitation and extension / mime checking.
1007void TabContents::SavePage(const std::wstring& main_file,
1008 const std::wstring& dir_path,
1009 SavePackage::SavePackageType save_type) {
1010 // Stop the page from navigating.
1011 Stop();
1012
[email protected]d82ed61e2009-06-16 02:46:221013 save_package_ = new SavePackage(this, save_type,
[email protected]420ae012009-04-24 05:16:321014 FilePath::FromWStringHack(main_file),
1015 FilePath::FromWStringHack(dir_path));
1016 save_package_->Init();
1017}
1018
1019void TabContents::PrintPreview() {
1020 // We don't show the print preview yet, only the print dialog.
1021 PrintNow();
1022}
1023
1024bool TabContents::PrintNow() {
1025 // We can't print interstitial page for now.
1026 if (showing_interstitial_page())
1027 return false;
1028
1029 return render_view_host()->PrintPages();
1030}
1031
[email protected]82270452009-06-19 15:58:011032void TabContents::PrintingDone(int document_cookie, bool success) {
1033 render_view_host()->PrintingDone(document_cookie, success);
1034}
1035
[email protected]420ae012009-04-24 05:16:321036bool TabContents::IsActiveEntry(int32 page_id) {
1037 NavigationEntry* active_entry = controller_.GetActiveEntry();
1038 return (active_entry != NULL &&
1039 active_entry->site_instance() == GetSiteInstance() &&
1040 active_entry->page_id() == page_id);
1041}
1042
[email protected]96d185d2009-04-24 03:28:541043// Notifies the RenderWidgetHost instance about the fact that the page is
1044// loading, or done loading and calls the base implementation.
1045void TabContents::SetIsLoading(bool is_loading,
1046 LoadNotificationDetails* details) {
1047 if (is_loading == is_loading_)
1048 return;
1049
1050 if (!is_loading) {
1051 load_state_ = net::LOAD_STATE_IDLE;
1052 load_state_host_.clear();
1053 }
1054
1055 render_manager_.SetIsLoading(is_loading);
1056
1057 is_loading_ = is_loading;
1058 waiting_for_response_ = is_loading;
1059
1060 if (delegate_)
1061 delegate_->LoadingStateChanged(this);
[email protected]329581b2009-04-28 06:52:351062 NotifyNavigationStateChanged(INVALIDATE_LOAD);
[email protected]96d185d2009-04-24 03:28:541063
1064 NotificationType type = is_loading ? NotificationType::LOAD_START :
1065 NotificationType::LOAD_STOP;
[email protected]ce5c4502009-05-06 16:46:111066 NotificationDetails det = NotificationService::NoDetails();
[email protected]96d185d2009-04-24 03:28:541067 if (details)
1068 det = Details<LoadNotificationDetails>(details);
1069 NotificationService::current()->Notify(type,
1070 Source<NavigationController>(&controller_),
1071 det);
1072}
1073
[email protected]ce494a312009-06-10 23:54:201074#if defined(OS_WIN) || defined(OS_LINUX)
[email protected]2c4410d2009-05-06 23:46:221075void TabContents::CreateBlockedPopupContainerIfNecessary() {
1076 if (blocked_popups_)
1077 return;
1078
[email protected]4d4c0b92009-06-08 23:13:011079 blocked_popups_ = BlockedPopupContainer::Create(this, profile());
[email protected]2c4410d2009-05-06 23:46:221080}
1081
[email protected]b6c874582009-05-08 19:38:311082void TabContents::AddPopup(TabContents* new_contents,
1083 const gfx::Rect& initial_pos,
1084 const std::string& host) {
[email protected]2c4410d2009-05-06 23:46:221085 CreateBlockedPopupContainerIfNecessary();
1086 blocked_popups_->AddTabContents(new_contents, initial_pos, host);
[email protected]2c4410d2009-05-06 23:46:221087}
[email protected]66ba4932009-06-04 19:22:131088#endif
[email protected]2c4410d2009-05-06 23:46:221089
[email protected]e69bce3dd2009-04-20 22:05:121090// TODO(brettw) This should be on the TabContentsView.
[email protected]66ba4932009-06-04 19:22:131091void TabContents::RepositionSupressedPopupsToFit() {
[email protected]d6598c052008-11-05 19:03:251092 if (blocked_popups_)
[email protected]4d4c0b92009-06-08 23:13:011093 blocked_popups_->RepositionBlockedPopupContainer();
[email protected]d5f942ba2008-09-26 19:30:341094}
1095
[email protected]b9681312008-11-07 00:08:261096bool TabContents::ShowingBlockedPopupNotification() const {
1097 return blocked_popups_ != NULL &&
[email protected]2c4410d2009-05-06 23:46:221098 blocked_popups_->GetBlockedPopupCount() != 0;
[email protected]b9681312008-11-07 00:08:261099}
[email protected]616ed5a2008-11-21 22:27:241100
1101namespace {
1102bool TransitionIsReload(PageTransition::Type transition) {
1103 return PageTransition::StripQualifier(transition) == PageTransition::RELOAD;
1104}
1105}
1106
1107void TabContents::ExpireInfoBars(
1108 const NavigationController::LoadCommittedDetails& details) {
1109 // Only hide InfoBars when the user has done something that makes the main
1110 // frame load. We don't want various automatic or subframe navigations making
1111 // it disappear.
1112 if (!details.is_user_initiated_main_frame_load())
1113 return;
1114
[email protected]f86a07022008-11-25 01:06:051115 for (int i = infobar_delegate_count() - 1; i >= 0; --i) {
[email protected]616ed5a2008-11-21 22:27:241116 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
[email protected]f86a07022008-11-25 01:06:051117 if (delegate->ShouldExpire(details))
[email protected]616ed5a2008-11-21 22:27:241118 RemoveInfoBar(delegate);
[email protected]616ed5a2008-11-21 22:27:241119 }
1120}
[email protected]fdd61c62009-04-22 19:22:571121
1122void TabContents::OnGearsCreateShortcutDone(
1123 const GearsShortcutData2& shortcut_data, bool success) {
1124 NavigationEntry* current_entry = controller_.GetLastCommittedEntry();
1125 bool same_page =
1126 current_entry && pending_install_.page_id == current_entry->page_id();
1127
1128 if (success && same_page) {
1129 // Only switch to app mode if the user chose to create a shortcut and
1130 // we're still on the same page that it corresponded to.
1131 if (delegate())
1132 delegate()->ConvertContentsToApplication(this);
1133 }
1134
1135 // Reset the page id to indicate no requests are pending.
1136 pending_install_.page_id = 0;
1137 pending_install_.callback_functor = NULL;
1138}
[email protected]96d185d2009-04-24 03:28:541139
1140DOMUI* TabContents::GetDOMUIForCurrentState() {
1141 // When there is a pending navigation entry, we want to use the pending DOMUI
1142 // that goes along with it to control the basic flags. For example, we want to
1143 // show the pending URL in the URL bar, so we want the display_url flag to
1144 // be from the pending entry.
1145 //
1146 // The confusion comes because there are multiple possibilities for the
1147 // initial load in a tab as a side effect of the way the RenderViewHostManager
1148 // works.
1149 //
1150 // - For the very first tab the load looks "normal". The new tab DOM UI is
1151 // the pending one, and we want it to apply here.
1152 //
1153 // - For subsequent new tabs, they'll get a new SiteInstance which will then
1154 // get switched to the one previously associated with the new tab pages.
1155 // This switching will cause the manager to commit the RVH/DOMUI. So we'll
1156 // have a committed DOM UI in this case.
1157 //
1158 // This condition handles all of these cases:
1159 //
1160 // - First load in first tab: no committed nav entry + pending nav entry +
1161 // pending dom ui:
1162 // -> Use pending DOM UI if any.
1163 //
1164 // - First load in second tab: no committed nav entry + pending nav entry +
1165 // no pending DOM UI:
1166 // -> Use the committed DOM UI if any.
1167 //
1168 // - Second navigation in any tab: committed nav entry + pending nav entry:
1169 // -> Use pending DOM UI if any.
1170 //
1171 // - Normal state with no load: committed nav entry + no pending nav entry:
1172 // -> Use committed DOM UI.
1173 if (controller_.pending_entry() &&
1174 (controller_.GetLastCommittedEntry() ||
1175 render_manager_.pending_dom_ui()))
1176 return render_manager_.pending_dom_ui();
1177 return render_manager_.dom_ui();
1178}
[email protected]420ae012009-04-24 05:16:321179
1180void TabContents::DidNavigateMainFramePostCommit(
1181 const NavigationController::LoadCommittedDetails& details,
1182 const ViewHostMsg_FrameNavigate_Params& params) {
[email protected]420ae012009-04-24 05:16:321183 if (details.is_user_initiated_main_frame_load()) {
1184 // Clear the status bubble. This is a workaround for a bug where WebKit
1185 // doesn't let us know that the cursor left an element during a
1186 // transition (this is also why the mouse cursor remains as a hand after
1187 // clicking on a link); see bugs 1184641 and 980803. We don't want to
1188 // clear the bubble when a user navigates to a named anchor in the same
1189 // page.
1190 UpdateTargetURL(details.entry->page_id(), GURL());
1191
1192 // UpdateHelpersForDidNavigate will handle the case where the password_form
1193 // origin is valid.
1194 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1195 // cleaned up and covered by tests.
1196 if (!params.password_form.origin.is_valid())
1197 GetPasswordManager()->DidNavigate();
1198 }
1199
1200 // The keyword generator uses the navigation entries, so must be called after
1201 // the commit.
1202 GenerateKeywordIfNecessary(params);
1203
1204 // Allow the new page to set the title again.
1205 received_page_title_ = false;
1206
1207 // Get the favicon, either from history or request it from the net.
1208 fav_icon_helper_.FetchFavIcon(details.entry->url());
1209
[email protected]ce5c4502009-05-06 16:46:111210 // Disable all page actions.
1211 enabled_page_actions_.clear();
1212
[email protected]420ae012009-04-24 05:16:321213 // Close constrained popups if necessary.
1214 MaybeCloseChildWindows(details.previous_url, details.entry->url());
1215
1216 // Update the starred state.
1217 UpdateStarredStateForCurrentURL();
1218}
1219
1220void TabContents::DidNavigateAnyFramePostCommit(
1221 RenderViewHost* render_view_host,
1222 const NavigationController::LoadCommittedDetails& details,
1223 const ViewHostMsg_FrameNavigate_Params& params) {
1224 // If we navigate, start showing messages again. This does nothing to prevent
1225 // a malicious script from spamming messages, since the script could just
1226 // reload the page to stop blocking.
1227 suppress_javascript_messages_ = false;
1228
1229 // Update history. Note that this needs to happen after the entry is complete,
1230 // which WillNavigate[Main,Sub]Frame will do before this function is called.
1231 if (params.should_update_history) {
1232 // Most of the time, the displayURL matches the loaded URL, but for about:
1233 // URLs, we use a data: URL as the real value. We actually want to save
1234 // the about: URL to the history db and keep the data: URL hidden. This is
1235 // what the TabContents' URL getter does.
1236 UpdateHistoryForNavigation(GetURL(), params);
1237 }
1238
1239 // Notify the password manager of the navigation or form submit.
1240 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1241 // cleaned up and covered by tests.
1242 if (params.password_form.origin.is_valid())
1243 GetPasswordManager()->ProvisionallySavePassword(params.password_form);
1244}
1245
1246void TabContents::MaybeCloseChildWindows(const GURL& previous_url,
1247 const GURL& current_url) {
1248 if (net::RegistryControlledDomainService::SameDomainOrHost(
1249 previous_url, current_url))
1250 return;
1251
1252 // Clear out any child windows since we are leaving this page entirely.
1253 // We use indices instead of iterators in case CloseWindow does something
1254 // that may invalidate an iterator.
1255 int size = static_cast<int>(child_windows_.size());
1256 for (int i = size - 1; i >= 0; --i) {
1257 ConstrainedWindow* window = child_windows_[i];
1258 if (window)
1259 window->CloseConstrainedWindow();
1260 }
1261}
1262
1263void TabContents::UpdateStarredStateForCurrentURL() {
1264 BookmarkModel* model = profile()->GetBookmarkModel();
1265 const bool old_state = is_starred_;
1266 is_starred_ = (model && model->IsBookmarked(GetURL()));
1267
1268 if (is_starred_ != old_state && delegate())
1269 delegate()->URLStarredChanged(this, is_starred_);
1270}
1271
1272void TabContents::UpdateAlternateErrorPageURL() {
1273 GURL url = GetAlternateErrorPageURL();
1274 render_view_host()->SetAlternateErrorPageURL(url);
1275}
1276
1277void TabContents::UpdateWebPreferences() {
1278 render_view_host()->UpdateWebPreferences(GetWebkitPrefs());
1279}
1280
1281void TabContents::UpdateMaxPageIDIfNecessary(SiteInstance* site_instance,
1282 RenderViewHost* rvh) {
1283 // If we are creating a RVH for a restored controller, then we might
1284 // have more page IDs than the SiteInstance's current max page ID. We must
1285 // make sure that the max page ID is larger than any restored page ID.
1286 // Note that it is ok for conflicting page IDs to exist in another tab
1287 // (i.e., NavigationController), but if any page ID is larger than the max,
1288 // the back/forward list will get confused.
1289 int max_restored_page_id = controller_.max_restored_page_id();
1290 if (max_restored_page_id > 0) {
1291 int curr_max_page_id = site_instance->max_page_id();
1292 if (max_restored_page_id > curr_max_page_id) {
1293 // Need to update the site instance immediately.
1294 site_instance->UpdateMaxPageID(max_restored_page_id);
1295
1296 // Also tell the renderer to update its internal representation. We
1297 // need to reserve enough IDs to make all restored page IDs less than
1298 // the max.
1299 if (curr_max_page_id < 0)
1300 curr_max_page_id = 0;
1301 rvh->ReservePageIDRange(max_restored_page_id - curr_max_page_id);
1302 }
1303 }
1304}
1305
1306void TabContents::UpdateHistoryForNavigation(
1307 const GURL& display_url,
1308 const ViewHostMsg_FrameNavigate_Params& params) {
1309 if (profile()->IsOffTheRecord())
1310 return;
1311
1312 // Add to history service.
1313 HistoryService* hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1314 if (hs) {
1315 if (PageTransition::IsMainFrame(params.transition) &&
1316 display_url != params.url) {
1317 // Hack on the "display" URL so that it will appear in history. For some
1318 // types of URLs, we will display a magic URL that is different from where
1319 // the page is actually navigated. We want the user to see in history
1320 // what they saw in the URL bar, so we add the display URL as a redirect.
1321 // This only applies to the main frame, as the display URL doesn't apply
1322 // to sub-frames.
1323 std::vector<GURL> redirects = params.redirects;
1324 if (!redirects.empty())
1325 redirects.back() = display_url;
1326 hs->AddPage(display_url, this, params.page_id, params.referrer,
1327 params.transition, redirects);
1328 } else {
1329 hs->AddPage(params.url, this, params.page_id, params.referrer,
1330 params.transition, params.redirects);
1331 }
1332 }
1333}
1334
1335bool TabContents::UpdateTitleForEntry(NavigationEntry* entry,
1336 const std::wstring& title) {
1337 // For file URLs without a title, use the pathname instead. In the case of a
1338 // synthesized title, we don't want the update to count toward the "one set
1339 // per page of the title to history."
1340 std::wstring final_title;
1341 bool explicit_set;
1342 if (entry->url().SchemeIsFile() && title.empty()) {
1343 final_title = UTF8ToWide(entry->url().ExtractFileName());
1344 explicit_set = false; // Don't count synthetic titles toward the set limit.
1345 } else {
1346 TrimWhitespace(title, TRIM_ALL, &final_title);
1347 explicit_set = true;
1348 }
1349
1350 if (final_title == UTF16ToWideHack(entry->title()))
1351 return false; // Nothing changed, don't bother.
1352
1353 entry->set_title(WideToUTF16Hack(final_title));
1354
1355 // Update the history system for this page.
1356 if (!profile()->IsOffTheRecord() && !received_page_title_) {
1357 HistoryService* hs =
1358 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1359 if (hs)
1360 hs->SetPageTitle(entry->display_url(), final_title);
1361
1362 // Don't allow the title to be saved again for explicitly set ones.
1363 received_page_title_ = explicit_set;
1364 }
1365
1366 // Lastly, set the title for the view.
1367 view_->SetPageTitle(final_title);
1368
1369 return true;
1370}
1371
1372void TabContents::NotifySwapped() {
1373 // After sending out a swap notification, we need to send a disconnect
1374 // notification so that clients that pick up a pointer to |this| can NULL the
1375 // pointer. See Bug 1230284.
1376 notify_disconnection_ = true;
1377 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341378 NotificationType::TAB_CONTENTS_SWAPPED,
[email protected]d82ed61e2009-06-16 02:46:221379 Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321380 NotificationService::NoDetails());
1381}
1382
1383void TabContents::NotifyConnected() {
1384 notify_disconnection_ = true;
1385 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341386 NotificationType::TAB_CONTENTS_CONNECTED,
[email protected]d82ed61e2009-06-16 02:46:221387 Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321388 NotificationService::NoDetails());
1389}
1390
1391void TabContents::NotifyDisconnected() {
1392 if (!notify_disconnection_)
1393 return;
1394
1395 notify_disconnection_ = false;
1396 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341397 NotificationType::TAB_CONTENTS_DISCONNECTED,
[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::GenerateKeywordIfNecessary(
1403 const ViewHostMsg_FrameNavigate_Params& params) {
1404 if (!params.searchable_form_url.is_valid())
1405 return;
1406
1407 if (profile()->IsOffTheRecord())
1408 return;
1409
1410 int last_index = controller_.last_committed_entry_index();
1411 // When there was no previous page, the last index will be 0. This is
1412 // normally due to a form submit that opened in a new tab.
1413 // TODO(brettw) bug 916126: we should support keywords when form submits
1414 // happen in new tabs.
1415 if (last_index <= 0)
1416 return;
1417 const NavigationEntry* previous_entry =
1418 controller_.GetEntryAtIndex(last_index - 1);
1419 if (IsFormSubmit(previous_entry)) {
1420 // Only generate a keyword if the previous page wasn't itself a form
1421 // submit.
1422 return;
1423 }
1424
1425 GURL keyword_url = previous_entry->user_typed_url().is_valid() ?
1426 previous_entry->user_typed_url() : previous_entry->url();
1427 std::wstring keyword =
1428 TemplateURLModel::GenerateKeyword(keyword_url, true); // autodetected
1429 if (keyword.empty())
1430 return;
1431
1432 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
1433 if (!url_model)
1434 return;
1435
1436 if (!url_model->loaded()) {
1437 url_model->Load();
1438 return;
1439 }
1440
1441 const TemplateURL* current_url;
1442 std::wstring url = UTF8ToWide(params.searchable_form_url.spec());
1443 if (!url_model->CanReplaceKeyword(keyword, url, &current_url))
1444 return;
1445
1446 if (current_url) {
1447 if (current_url->originating_url().is_valid()) {
1448 // The existing keyword was generated from an OpenSearch description
1449 // document, don't regenerate.
1450 return;
1451 }
1452 url_model->Remove(current_url);
1453 }
1454 TemplateURL* new_url = new TemplateURL();
1455 new_url->set_keyword(keyword);
1456 new_url->set_short_name(keyword);
1457 new_url->SetURL(url, 0, 0);
1458 new_url->add_input_encoding(params.searchable_form_encoding);
1459 DCHECK(controller_.GetLastCommittedEntry());
1460 const GURL& favicon_url =
1461 controller_.GetLastCommittedEntry()->favicon().url();
1462 if (favicon_url.is_valid()) {
1463 new_url->SetFavIconURL(favicon_url);
1464 } else {
1465 // The favicon url isn't valid. This means there really isn't a favicon,
1466 // or the favicon url wasn't obtained before the load started. This assumes
1467 // the later.
1468 // TODO(sky): Need a way to set the favicon that doesn't involve generating
1469 // its url.
1470 new_url->SetFavIconURL(TemplateURL::GenerateFaviconURL(params.referrer));
1471 }
1472 new_url->set_safe_for_autoreplace(true);
1473 url_model->Add(new_url);
1474}
1475
1476RenderViewHostDelegate::View* TabContents::GetViewDelegate() const {
1477 return view_.get();
1478}
1479
1480RenderViewHostDelegate::Save* TabContents::GetSaveDelegate() const {
1481 return save_package_.get(); // May be NULL, but we can return NULL.
1482}
1483
[email protected]80d96fa2009-06-10 22:34:511484RendererPreferences TabContents::GetRendererPrefs() const {
1485 if (delegate())
1486 return delegate()->GetRendererPrefs();
1487 else
1488 return RendererPreferences();
1489}
1490
[email protected]6dfed102009-04-28 03:09:531491ExtensionFunctionDispatcher* TabContents::CreateExtensionFunctionDispatcher(
1492 RenderViewHost* render_view_host,
1493 const std::string& extension_id) {
1494 return delegate()->CreateExtensionFunctionDispatcher(render_view_host,
1495 extension_id);
1496}
1497
[email protected]57c6a652009-05-04 07:58:341498TabContents* TabContents::GetAsTabContents() {
1499 return this;
1500}
1501
[email protected]420ae012009-04-24 05:16:321502void TabContents::RenderViewCreated(RenderViewHost* render_view_host) {
1503 NavigationEntry* entry = controller_.GetActiveEntry();
1504 if (!entry)
1505 return;
1506
1507 // When we're creating views, we're still doing initial setup, so we always
1508 // use the pending DOM UI rather than any possibly existing committed one.
1509 if (render_manager_.pending_dom_ui()) {
1510 render_manager_.pending_dom_ui()->RenderViewCreated(render_view_host);
1511 }
1512
1513 if (entry->IsViewSourceMode()) {
1514 // Put the renderer in view source mode.
1515 render_view_host->Send(
1516 new ViewMsg_EnableViewSourceMode(render_view_host->routing_id()));
1517 }
[email protected]0666aef2009-05-13 19:48:081518
1519 view()->RenderViewCreated(render_view_host);
[email protected]420ae012009-04-24 05:16:321520}
1521
1522void TabContents::RenderViewReady(RenderViewHost* rvh) {
1523 if (rvh != render_view_host()) {
1524 // Don't notify the world, since this came from a renderer in the
1525 // background.
1526 return;
1527 }
1528
1529 NotifyConnected();
1530 SetIsCrashed(false);
1531}
1532
1533void TabContents::RenderViewGone(RenderViewHost* rvh) {
1534 // Ask the print preview if this renderer was valuable.
1535 if (!printing_.OnRenderViewGone(rvh))
1536 return;
1537 if (rvh != render_view_host()) {
1538 // The pending page's RenderViewHost is gone.
1539 return;
1540 }
1541
1542 SetIsLoading(false, NULL);
1543 NotifyDisconnected();
1544 SetIsCrashed(true);
1545
[email protected]8e537302009-06-10 21:19:581546 // Tell the view that we've crashed so it can prepare the sad tab page.
1547 view_->OnTabCrashed();
[email protected]420ae012009-04-24 05:16:321548
1549 // Hide any visible hung renderer warning for this web contents' process.
[email protected]d82ed61e2009-06-16 02:46:221550 HungRendererDialog::HideForTabContents(this);
[email protected]420ae012009-04-24 05:16:321551}
1552
1553void TabContents::DidNavigate(RenderViewHost* rvh,
1554 const ViewHostMsg_FrameNavigate_Params& params) {
1555 if (PageTransition::IsMainFrame(params.transition))
1556 render_manager_.DidNavigateMainFrame(rvh);
1557
1558 // Update the site of the SiteInstance if it doesn't have one yet.
1559 if (!GetSiteInstance()->has_site())
1560 GetSiteInstance()->SetSite(params.url);
1561
1562 // Need to update MIME type here because it's referred to in
1563 // UpdateNavigationCommands() called by RendererDidNavigate() to
1564 // determine whether or not to enable the encoding menu.
1565 // It's updated only for the main frame. For a subframe,
1566 // RenderView::UpdateURL does not set params.contents_mime_type.
1567 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
1568 // TODO(jungshik): Add a test for the encoding menu to avoid
1569 // regressing it again.
1570 if (PageTransition::IsMainFrame(params.transition))
1571 contents_mime_type_ = params.contents_mime_type;
1572
1573 NavigationController::LoadCommittedDetails details;
1574 if (!controller_.RendererDidNavigate(params, &details))
1575 return; // No navigation happened.
1576
1577 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
1578 // for the appropriate notification (best) or you can add it to
1579 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
1580 // necessary, please).
1581
1582 // Run post-commit tasks.
1583 if (details.is_main_frame)
1584 DidNavigateMainFramePostCommit(details, params);
1585 DidNavigateAnyFramePostCommit(rvh, details, params);
1586}
1587
1588void TabContents::UpdateState(RenderViewHost* rvh,
1589 int32 page_id,
1590 const std::string& state) {
1591 DCHECK(rvh == render_view_host());
1592
1593 // We must be prepared to handle state updates for any page, these occur
1594 // when the user is scrolling and entering form data, as well as when we're
1595 // leaving a page, in which case our state may have already been moved to
1596 // the next page. The navigation controller will look up the appropriate
1597 // NavigationEntry and update it when it is notified via the delegate.
1598
1599 int entry_index = controller_.GetEntryIndexWithPageID(
1600 GetSiteInstance(), page_id);
1601 if (entry_index < 0)
1602 return;
1603 NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
1604
1605 if (state == entry->content_state())
1606 return; // Nothing to update.
1607 entry->set_content_state(state);
1608 controller_.NotifyEntryChanged(entry, entry_index);
1609}
1610
1611void TabContents::UpdateTitle(RenderViewHost* rvh,
1612 int32 page_id, const std::wstring& title) {
1613 // If we have a title, that's a pretty good indication that we've started
1614 // getting useful data.
1615 SetNotWaitingForResponse();
1616
1617 DCHECK(rvh == render_view_host());
1618 NavigationEntry* entry = controller_.GetEntryWithPageID(GetSiteInstance(),
1619 page_id);
1620 if (!entry || !UpdateTitleForEntry(entry, title))
1621 return;
1622
1623 // Broadcast notifications when the UI should be updated.
1624 if (entry == controller_.GetEntryAtOffset(0))
[email protected]c9cd2222009-05-06 05:16:501625 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:321626}
1627
[email protected]420ae012009-04-24 05:16:321628void TabContents::UpdateEncoding(RenderViewHost* render_view_host,
1629 const std::wstring& encoding) {
1630 set_encoding(encoding);
1631}
1632
1633void TabContents::UpdateTargetURL(int32 page_id, const GURL& url) {
1634 if (delegate())
1635 delegate()->UpdateTargetURL(this, url);
1636}
1637
1638void TabContents::UpdateThumbnail(const GURL& url,
1639 const SkBitmap& bitmap,
1640 const ThumbnailScore& score) {
1641 // Tell History about this thumbnail
[email protected]449478302009-06-09 20:04:281642 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kThumbnailStore)) {
1643 profile()->GetThumbnailStore()->
1644 SetPageThumbnail(url, bitmap, score, !profile()->IsOffTheRecord());
1645 } else {
1646 HistoryService* hs;
1647 if (!profile()->IsOffTheRecord() &&
1648 (hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS))) {
1649 hs->SetPageThumbnail(url, bitmap, score);
1650 }
[email protected]420ae012009-04-24 05:16:321651 }
1652}
1653
[email protected]0df30122009-06-03 12:13:081654void TabContents::UpdateInspectorSettings(const std::wstring& raw_settings) {
1655 profile()->GetPrefs()->SetString(prefs::kWebKitInspectorSettings,
1656 raw_settings);
1657}
1658
[email protected]420ae012009-04-24 05:16:321659void TabContents::Close(RenderViewHost* rvh) {
1660 // Ignore this if it comes from a RenderViewHost that we aren't showing.
1661 if (delegate() && rvh == render_view_host())
1662 delegate()->CloseContents(this);
1663}
1664
1665void TabContents::RequestMove(const gfx::Rect& new_bounds) {
1666 if (delegate() && delegate()->IsPopup(this))
1667 delegate()->MoveContents(this, new_bounds);
1668}
1669
[email protected]329581b2009-04-28 06:52:351670void TabContents::DidStartLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321671 SetIsLoading(true, NULL);
1672}
1673
[email protected]329581b2009-04-28 06:52:351674void TabContents::DidStopLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321675 scoped_ptr<LoadNotificationDetails> details;
1676
1677 NavigationEntry* entry = controller_.GetActiveEntry();
1678 // An entry may not exist for a stop when loading an initial blank page or
1679 // if an iframe injected by script into a blank page finishes loading.
1680 if (entry) {
1681 scoped_ptr<base::ProcessMetrics> metrics(
1682 base::ProcessMetrics::CreateProcessMetrics(
1683 process()->process().handle()));
1684
1685 base::TimeDelta elapsed = base::TimeTicks::Now() - current_load_start_;
1686
1687 details.reset(new LoadNotificationDetails(
1688 entry->display_url(),
1689 entry->transition_type(),
1690 elapsed,
1691 &controller_,
1692 controller_.GetCurrentEntryIndex()));
1693 }
1694
1695 // Tell PasswordManager we've finished a page load, which serves as a
1696 // green light to save pending passwords and reset itself.
1697 GetPasswordManager()->DidStopLoading();
1698
1699 SetIsLoading(false, details.get());
1700}
1701
1702void TabContents::DidStartProvisionalLoadForFrame(
1703 RenderViewHost* render_view_host,
1704 bool is_main_frame,
1705 const GURL& url) {
1706 ProvisionalLoadDetails details(is_main_frame,
1707 controller_.IsURLInPageNavigation(url),
1708 url, std::string(), false);
1709 NotificationService::current()->Notify(
1710 NotificationType::FRAME_PROVISIONAL_LOAD_START,
1711 Source<NavigationController>(&controller_),
1712 Details<ProvisionalLoadDetails>(&details));
1713}
1714
1715void TabContents::DidRedirectProvisionalLoad(int32 page_id,
1716 const GURL& source_url,
1717 const GURL& target_url) {
1718 NavigationEntry* entry;
1719 if (page_id == -1)
1720 entry = controller_.pending_entry();
1721 else
1722 entry = controller_.GetEntryWithPageID(GetSiteInstance(), page_id);
1723 if (!entry || entry->url() != source_url)
1724 return;
1725 entry->set_url(target_url);
1726}
1727
1728void TabContents::DidLoadResourceFromMemoryCache(
1729 const GURL& url,
1730 const std::string& frame_origin,
1731 const std::string& main_frame_origin,
1732 const std::string& security_info) {
1733 // Send out a notification that we loaded a resource from our memory cache.
1734 int cert_id = 0, cert_status = 0, security_bits = 0;
1735 SSLManager::DeserializeSecurityInfo(security_info,
1736 &cert_id, &cert_status,
1737 &security_bits);
1738 LoadFromMemoryCacheDetails details(url, frame_origin, main_frame_origin,
[email protected]9ae66cbf2009-05-12 16:21:031739 process()->pid(), cert_id, cert_status);
[email protected]420ae012009-04-24 05:16:321740
1741 NotificationService::current()->Notify(
1742 NotificationType::LOAD_FROM_MEMORY_CACHE,
1743 Source<NavigationController>(&controller_),
1744 Details<LoadFromMemoryCacheDetails>(&details));
1745}
1746
1747void TabContents::DidFailProvisionalLoadWithError(
1748 RenderViewHost* render_view_host,
1749 bool is_main_frame,
1750 int error_code,
1751 const GURL& url,
1752 bool showing_repost_interstitial) {
1753 if (net::ERR_ABORTED == error_code) {
1754 // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
1755 // This means that the interstitial won't be torn down properly, which is
1756 // bad. But if we have an interstitial, go back to another tab type, and
1757 // then load the same interstitial again, we could end up getting the first
1758 // interstitial's "failed" message (as a result of the cancel) when we're on
1759 // the second one.
1760 //
1761 // We can't tell this apart, so we think we're tearing down the current page
1762 // which will cause a crash later one. There is also some code in
1763 // RenderViewHostManager::RendererAbortedProvisionalLoad that is commented
1764 // out because of this problem.
1765 //
1766 // http://code.google.com/p/chromium/issues/detail?id=2855
1767 // Because this will not tear down the interstitial properly, if "back" is
1768 // back to another tab type, the interstitial will still be somewhat alive
1769 // in the previous tab type. If you navigate somewhere that activates the
1770 // tab with the interstitial again, you'll see a flash before the new load
1771 // commits of the interstitial page.
1772 if (showing_interstitial_page()) {
1773 LOG(WARNING) << "Discarding message during interstitial.";
1774 return;
1775 }
1776
1777 // This will discard our pending entry if we cancelled the load (e.g., if we
1778 // decided to download the file instead of load it). Only discard the
1779 // pending entry if the URLs match, otherwise the user initiated a navigate
1780 // before the page loaded so that the discard would discard the wrong entry.
1781 NavigationEntry* pending_entry = controller_.pending_entry();
1782 if (pending_entry && pending_entry->url() == url)
1783 controller_.DiscardNonCommittedEntries();
1784
1785 render_manager_.RendererAbortedProvisionalLoad(render_view_host);
1786 }
1787
1788 // Send out a notification that we failed a provisional load with an error.
1789 ProvisionalLoadDetails details(is_main_frame,
1790 controller_.IsURLInPageNavigation(url),
1791 url, std::string(), false);
1792 details.set_error_code(error_code);
1793
1794 NotificationService::current()->Notify(
1795 NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR,
1796 Source<NavigationController>(&controller_),
1797 Details<ProvisionalLoadDetails>(&details));
1798}
1799
1800void TabContents::UpdateFavIconURL(RenderViewHost* render_view_host,
1801 int32 page_id,
1802 const GURL& icon_url) {
1803 fav_icon_helper_.SetFavIconURL(icon_url);
1804}
1805
1806void TabContents::DidDownloadImage(
1807 RenderViewHost* render_view_host,
1808 int id,
1809 const GURL& image_url,
1810 bool errored,
1811 const SkBitmap& image) {
1812 // A notification for downloading would be more flexible, but for now I'm
1813 // forwarding to the two places that could possibly have initiated the
1814 // request. If we end up with another place invoking DownloadImage, probably
1815 // best to refactor out into notification service, or something similar.
1816 if (errored)
1817 fav_icon_helper_.FavIconDownloadFailed(id);
1818 else
1819 fav_icon_helper_.SetFavIcon(id, image_url, image);
1820}
1821
1822void TabContents::RequestOpenURL(const GURL& url, const GURL& referrer,
1823 WindowOpenDisposition disposition) {
1824 if (render_manager_.dom_ui()) {
1825 // When we're a DOM UI, it will provide a page transition type for us (this
1826 // is so the new tab page can specify AUTO_BOOKMARK for automatically
1827 // generated suggestions).
1828 //
1829 // Note also that we hide the referrer for DOM UI pages. We don't really
[email protected]60e448982009-05-06 04:21:161830 // want web sites to see a referrer of "chrome://blah" (and some
1831 // chrome: URLs might have search terms or other stuff we don't want to
[email protected]420ae012009-04-24 05:16:321832 // send to the site), so we send no referrer.
1833 OpenURL(url, GURL(), disposition,
1834 render_manager_.dom_ui()->link_transition_type());
1835 } else {
1836 OpenURL(url, referrer, disposition, PageTransition::LINK);
1837 }
1838}
1839
1840void TabContents::DomOperationResponse(const std::string& json_string,
1841 int automation_id) {
1842 DomOperationNotificationDetails details(json_string, automation_id);
1843 NotificationService::current()->Notify(
[email protected]d82ed61e2009-06-16 02:46:221844 NotificationType::DOM_OPERATION_RESPONSE, Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321845 Details<DomOperationNotificationDetails>(&details));
1846}
1847
1848void TabContents::ProcessDOMUIMessage(const std::string& message,
1849 const std::string& content) {
1850 if (!render_manager_.dom_ui()) {
1851 // We shouldn't get a DOM UI message when we haven't enabled the DOM UI.
1852 // Because the renderer might be owned and sending random messages, we need
1853 // to ignore these inproper ones.
1854 NOTREACHED();
1855 return;
1856 }
1857 render_manager_.dom_ui()->ProcessDOMUIMessage(message, content);
1858}
1859
[email protected]09b8f82f2009-06-16 20:22:111860void TabContents::DocumentLoadedInFrame() {
1861 controller_.DocumentLoadedInFrame();
1862}
1863
[email protected]420ae012009-04-24 05:16:321864void TabContents::ProcessExternalHostMessage(const std::string& message,
1865 const std::string& origin,
1866 const std::string& target) {
1867 if (delegate())
1868 delegate()->ForwardMessageToExternalHost(message, origin, target);
1869}
1870
1871void TabContents::GoToEntryAtOffset(int offset) {
1872 controller_.GoToOffset(offset);
1873}
1874
1875void TabContents::GetHistoryListCount(int* back_list_count,
1876 int* forward_list_count) {
1877 int current_index = controller_.last_committed_entry_index();
1878 *back_list_count = current_index;
1879 *forward_list_count = controller_.entry_count() - current_index - 1;
1880}
1881
1882void TabContents::RunFileChooser(bool multiple_files,
1883 const string16& title,
1884 const FilePath& default_file) {
1885 if (!select_file_dialog_.get())
1886 select_file_dialog_ = SelectFileDialog::Create(this);
1887 SelectFileDialog::Type dialog_type =
1888 multiple_files ? SelectFileDialog::SELECT_OPEN_MULTI_FILE :
1889 SelectFileDialog::SELECT_OPEN_FILE;
1890 select_file_dialog_->SelectFile(dialog_type, title, default_file,
1891 NULL, 0, FILE_PATH_LITERAL(""),
1892 view_->GetTopLevelNativeWindow(), NULL);
1893}
1894
1895void TabContents::RunJavaScriptMessage(
1896 const std::wstring& message,
1897 const std::wstring& default_prompt,
1898 const GURL& frame_url,
1899 const int flags,
1900 IPC::Message* reply_msg,
1901 bool* did_suppress_message) {
1902 // Suppress javascript messages when requested and when inside a constrained
1903 // popup window (because that activates them and breaks them out of the
1904 // constrained window jail).
1905 bool suppress_this_message = suppress_javascript_messages_;
1906 if (delegate())
1907 suppress_this_message |=
[email protected]b6c874582009-05-08 19:38:311908 (delegate()->GetConstrainingContents(this) != this);
[email protected]420ae012009-04-24 05:16:321909
1910 *did_suppress_message = suppress_this_message;
1911
1912 if (!suppress_this_message) {
1913 base::TimeDelta time_since_last_message(
1914 base::TimeTicks::Now() - last_javascript_message_dismissal_);
1915 bool show_suppress_checkbox = false;
1916 // Show a checkbox offering to suppress further messages if this message is
1917 // being displayed within kJavascriptMessageExpectedDelay of the last one.
1918 if (time_since_last_message <
1919 base::TimeDelta::FromMilliseconds(kJavascriptMessageExpectedDelay))
1920 show_suppress_checkbox = true;
1921
[email protected]d82ed61e2009-06-16 02:46:221922 RunJavascriptMessageBox(this, frame_url, flags, message, default_prompt,
[email protected]420ae012009-04-24 05:16:321923 show_suppress_checkbox, reply_msg);
1924 } else {
1925 // If we are suppressing messages, just reply as is if the user immediately
1926 // pressed "Cancel".
1927 OnJavaScriptMessageBoxClosed(reply_msg, false, std::wstring());
1928 }
1929}
1930
1931void TabContents::RunBeforeUnloadConfirm(const std::wstring& message,
1932 IPC::Message* reply_msg) {
[email protected]d82ed61e2009-06-16 02:46:221933 RunBeforeUnloadDialog(this, message, reply_msg);
[email protected]420ae012009-04-24 05:16:321934}
1935
1936void TabContents::ShowModalHTMLDialog(const GURL& url, int width, int height,
1937 const std::string& json_arguments,
1938 IPC::Message* reply_msg) {
1939 if (delegate()) {
1940 HtmlDialogUIDelegate* dialog_delegate =
1941 new ModalHtmlDialogDelegate(url, width, height, json_arguments,
[email protected]d82ed61e2009-06-16 02:46:221942 reply_msg, this);
[email protected]420ae012009-04-24 05:16:321943 delegate()->ShowHtmlDialog(dialog_delegate, NULL);
1944 }
1945}
1946
1947void TabContents::PasswordFormsSeen(
[email protected]ed3fb032009-06-16 19:50:561948 const std::vector<webkit_glue::PasswordForm>& forms) {
[email protected]420ae012009-04-24 05:16:321949 GetPasswordManager()->PasswordFormsSeen(forms);
1950}
1951
1952void TabContents::AutofillFormSubmitted(
[email protected]daa8c58e2009-06-15 17:21:101953 const webkit_glue::AutofillForm& form) {
[email protected]420ae012009-04-24 05:16:321954 GetAutofillManager()->AutofillFormSubmitted(form);
1955}
1956
1957void TabContents::GetAutofillSuggestions(const std::wstring& field_name,
1958 const std::wstring& user_text, int64 node_id, int request_id) {
1959 GetAutofillManager()->FetchValuesForName(field_name, user_text,
1960 kMaxAutofillMenuItems, node_id, request_id);
1961}
1962
1963void TabContents::RemoveAutofillEntry(const std::wstring& field_name,
1964 const std::wstring& value) {
1965 GetAutofillManager()->RemoveValueForName(field_name, value);
1966}
1967
1968// Checks to see if we should generate a keyword based on the OSDD, and if
1969// necessary uses TemplateURLFetcher to download the OSDD and create a keyword.
1970void TabContents::PageHasOSDD(RenderViewHost* render_view_host,
1971 int32 page_id, const GURL& url,
1972 bool autodetected) {
1973 // Make sure page_id is the current page, and the TemplateURLModel is loaded.
1974 DCHECK(url.is_valid());
1975 if (!IsActiveEntry(page_id))
1976 return;
1977 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
1978 if (!url_model)
1979 return;
1980 if (!url_model->loaded()) {
1981 url_model->Load();
1982 return;
1983 }
1984 if (!profile()->GetTemplateURLFetcher())
1985 return;
1986
1987 if (profile()->IsOffTheRecord())
1988 return;
1989
1990 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
1991 DCHECK(entry);
1992
1993 const NavigationEntry* base_entry = entry;
1994 if (IsFormSubmit(base_entry)) {
1995 // If the current page is a form submit, find the last page that was not
1996 // a form submit and use its url to generate the keyword from.
1997 int index = controller_.last_committed_entry_index() - 1;
1998 while (index >= 0 && IsFormSubmit(controller_.GetEntryAtIndex(index)))
1999 index--;
2000 if (index >= 0)
2001 base_entry = controller_.GetEntryAtIndex(index);
2002 else
2003 base_entry = NULL;
2004 }
2005
2006 // We want to use the user typed URL if available since that represents what
2007 // the user typed to get here, and fall back on the regular URL if not.
2008 if (!base_entry)
2009 return;
2010 GURL keyword_url = base_entry->user_typed_url().is_valid() ?
2011 base_entry->user_typed_url() : base_entry->url();
2012 if (!keyword_url.is_valid())
2013 return;
2014 std::wstring keyword = TemplateURLModel::GenerateKeyword(keyword_url,
2015 autodetected);
2016 if (keyword.empty())
2017 return;
2018 const TemplateURL* template_url =
2019 url_model->GetTemplateURLForKeyword(keyword);
2020 if (template_url && (!template_url->safe_for_autoreplace() ||
2021 template_url->originating_url() == url)) {
2022 // Either there is a user created TemplateURL for this keyword, or the
2023 // keyword has the same OSDD url and we've parsed it.
2024 return;
2025 }
2026
2027 // Download the OpenSearch description document. If this is successful a
2028 // new keyword will be created when done.
[email protected]fbb959c2009-06-17 23:19:562029 gfx::NativeWindow ancestor = view_->GetTopLevelNativeWindow();
[email protected]420ae012009-04-24 05:16:322030 profile()->GetTemplateURLFetcher()->ScheduleDownload(
2031 keyword,
2032 url,
2033 base_entry->favicon().url(),
2034 ancestor,
2035 autodetected);
2036}
2037
2038void TabContents::InspectElementReply(int num_resources) {
2039 // We have received reply from inspect element request. Notify the
2040 // automation provider in case we need to notify automation client.
2041 NotificationService::current()->Notify(
[email protected]d82ed61e2009-06-16 02:46:222042 NotificationType::DOM_INSPECT_ELEMENT_RESPONSE, Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:322043 Details<int>(&num_resources));
2044}
2045
2046void TabContents::DidGetPrintedPagesCount(int cookie, int number_pages) {
2047 printing_.DidGetPrintedPagesCount(cookie, number_pages);
2048}
2049
2050void TabContents::DidPrintPage(const ViewHostMsg_DidPrintPage_Params& params) {
2051 printing_.DidPrintPage(params);
2052}
2053
2054GURL TabContents::GetAlternateErrorPageURL() const {
2055 GURL url;
2056 // Disable alternate error pages when in OffTheRecord/Incognito mode.
2057 if (profile()->IsOffTheRecord())
2058 return url;
2059
2060 PrefService* prefs = profile()->GetPrefs();
2061 DCHECK(prefs);
2062 if (prefs->GetBoolean(prefs::kAlternateErrorPagesEnabled)) {
2063 url = google_util::AppendGoogleLocaleParam(GURL(kLinkDoctorBaseURL));
2064 url = google_util::AppendGoogleTLDParam(url);
2065 }
2066 return url;
2067}
2068
2069WebPreferences TabContents::GetWebkitPrefs() {
2070 PrefService* prefs = render_view_host()->process()->profile()->GetPrefs();
2071 bool isDomUI = false;
2072 return RenderViewHostDelegateHelper::GetWebkitPrefs(prefs, isDomUI);
2073}
2074
2075void TabContents::OnMissingPluginStatus(int status) {
2076#if defined(OS_WIN)
2077// TODO(PORT): pull in when plug-ins work
2078 GetPluginInstaller()->OnMissingPluginStatus(status);
2079#endif
2080}
2081
2082void TabContents::OnCrashedPlugin(const FilePath& plugin_path) {
2083#if defined(OS_WIN)
2084// TODO(PORT): pull in when plug-ins work
2085 DCHECK(!plugin_path.value().empty());
2086
2087 std::wstring plugin_name = plugin_path.ToWStringHack();
2088 scoped_ptr<FileVersionInfo> version_info(
2089 FileVersionInfo::CreateFileVersionInfo(plugin_path));
2090 if (version_info.get()) {
2091 const std::wstring& product_name = version_info->product_name();
2092 if (!product_name.empty())
2093 plugin_name = product_name;
2094 }
2095 AddInfoBar(new SimpleAlertInfoBarDelegate(
2096 this, l10n_util::GetStringF(IDS_PLUGIN_CRASHED_PROMPT, plugin_name),
2097 NULL));
2098#endif
2099}
2100
2101void TabContents::OnCrashedWorker() {
2102 AddInfoBar(new SimpleAlertInfoBarDelegate(
2103 this, l10n_util::GetString(IDS_WEBWORKER_CRASHED_PROMPT),
2104 NULL));
2105}
2106
2107void TabContents::OnJSOutOfMemory() {
2108 AddInfoBar(new SimpleAlertInfoBarDelegate(
2109 this, l10n_util::GetString(IDS_JS_OUT_OF_MEMORY_PROMPT), NULL));
2110}
2111
2112void TabContents::ShouldClosePage(bool proceed) {
2113 render_manager_.ShouldClosePage(proceed);
2114}
2115
2116void TabContents::OnCrossSiteResponse(int new_render_process_host_id,
2117 int new_request_id) {
[email protected]57c6a652009-05-04 07:58:342118 // Allows the TabContents to react when a cross-site response is ready to be
[email protected]420ae012009-04-24 05:16:322119 // delivered to a pending RenderViewHost. We must first run the onunload
2120 // handler of the old RenderViewHost before we can allow it to proceed.
2121 render_manager_.OnCrossSiteResponse(new_render_process_host_id,
2122 new_request_id);
2123}
2124
2125bool TabContents::CanBlur() const {
2126 return delegate() ? delegate()->CanBlur() : true;
2127}
2128
2129gfx::Rect TabContents::GetRootWindowResizerRect() const {
2130 if (delegate())
2131 return delegate()->GetRootWindowResizerRect();
2132 return gfx::Rect();
2133}
2134
2135void TabContents::RendererUnresponsive(RenderViewHost* rvh,
2136 bool is_during_unload) {
2137 if (is_during_unload) {
2138 // Hang occurred while firing the beforeunload/unload handler.
2139 // Pretend the handler fired so tab closing continues as if it had.
[email protected]829e7612009-04-25 01:15:112140 rvh->set_sudden_termination_allowed(true);
[email protected]420ae012009-04-24 05:16:322141
2142 if (!render_manager_.ShouldCloseTabOnUnresponsiveRenderer())
2143 return;
2144
2145 // If the tab hangs in the beforeunload/unload handler there's really
2146 // nothing we can do to recover. Pretend the unload listeners have
2147 // all fired and close the tab. If the hang is in the beforeunload handler
2148 // then the user will not have the option of cancelling the close.
2149 Close(rvh);
2150 return;
2151 }
2152
2153 if (render_view_host() && render_view_host()->IsRenderViewLive())
[email protected]d82ed61e2009-06-16 02:46:222154 HungRendererDialog::ShowForTabContents(this);
[email protected]420ae012009-04-24 05:16:322155}
2156
2157void TabContents::RendererResponsive(RenderViewHost* render_view_host) {
[email protected]d82ed61e2009-06-16 02:46:222158 HungRendererDialog::HideForTabContents(this);
[email protected]420ae012009-04-24 05:16:322159}
2160
2161void TabContents::LoadStateChanged(const GURL& url,
2162 net::LoadState load_state) {
2163 load_state_ = load_state;
[email protected]d686e812009-06-03 19:10:292164 std::wstring languages =
2165 profile()->GetPrefs()->GetString(prefs::kAcceptLanguages);
2166 load_state_host_.clear();
2167 std::string host = url.host();
2168 net::IDNToUnicode(host.c_str(), host.size(), languages, &load_state_host_);
[email protected]420ae012009-04-24 05:16:322169 if (load_state_ == net::LOAD_STATE_READING_RESPONSE)
2170 SetNotWaitingForResponse();
2171 if (is_loading())
[email protected]c9cd2222009-05-06 05:16:502172 NotifyNavigationStateChanged(INVALIDATE_LOAD | INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:322173}
2174
2175void TabContents::OnDidGetApplicationInfo(
2176 int32 page_id,
2177 const webkit_glue::WebApplicationInfo& info) {
2178 if (pending_install_.page_id != page_id)
2179 return; // The user clicked create on a separate page. Ignore this.
2180
2181 pending_install_.callback_functor =
2182 new GearsCreateShortcutCallbackFunctor(this);
2183 GearsCreateShortcut(
2184 info, pending_install_.title, pending_install_.url, pending_install_.icon,
2185 NewCallback(pending_install_.callback_functor,
2186 &GearsCreateShortcutCallbackFunctor::Run));
2187}
2188
[email protected]14ce83f2009-05-28 18:35:242189void TabContents::OnUserGesture() {
2190 // See comment in RenderViewHostDelegate::OnUserGesture as to why we do this.
2191#if defined(OS_WIN) || defined(OS_LINUX)
[email protected]420ae012009-04-24 05:16:322192 DownloadRequestManager* drm = g_browser_process->download_request_manager();
2193 if (drm)
2194 drm->OnUserGesture(this);
2195#endif
[email protected]09b8f82f2009-06-16 20:22:112196 controller_.OnUserGesture();
[email protected]420ae012009-04-24 05:16:322197}
2198
2199void TabContents::OnFindReply(int request_id,
2200 int number_of_matches,
2201 const gfx::Rect& selection_rect,
2202 int active_match_ordinal,
2203 bool final_update) {
2204 // Ignore responses for requests other than the one we have most recently
2205 // issued. That way we won't act on stale results when the user has
2206 // already typed in another query.
2207 if (request_id != current_find_request_id_)
2208 return;
2209
2210 if (number_of_matches == -1)
[email protected]e491f1c2009-05-22 20:28:122211 number_of_matches = last_search_result_.number_of_matches();
[email protected]420ae012009-04-24 05:16:322212 if (active_match_ordinal == -1)
[email protected]e491f1c2009-05-22 20:28:122213 active_match_ordinal = last_search_result_.active_match_ordinal();
[email protected]420ae012009-04-24 05:16:322214
[email protected]2c355c282009-05-21 23:24:432215 gfx::Rect selection = selection_rect;
2216 if (selection.IsEmpty())
[email protected]e491f1c2009-05-22 20:28:122217 selection = last_search_result_.selection_rect();
[email protected]2c355c282009-05-21 23:24:432218
[email protected]420ae012009-04-24 05:16:322219 // Notify the UI, automation and any other observers that a find result was
2220 // found.
[email protected]e491f1c2009-05-22 20:28:122221 last_search_result_ = FindNotificationDetails(request_id, number_of_matches,
2222 selection, active_match_ordinal,
2223 final_update);
[email protected]420ae012009-04-24 05:16:322224 NotificationService::current()->Notify(
2225 NotificationType::FIND_RESULT_AVAILABLE,
2226 Source<TabContents>(this),
[email protected]e491f1c2009-05-22 20:28:122227 Details<FindNotificationDetails>(&last_search_result_));
[email protected]420ae012009-04-24 05:16:322228}
2229
[email protected]829e7612009-04-25 01:15:112230bool TabContents::IsExternalTabContainer() const {
[email protected]420ae012009-04-24 05:16:322231 if (!delegate())
[email protected]829e7612009-04-25 01:15:112232 return false;
[email protected]420ae012009-04-24 05:16:322233
[email protected]829e7612009-04-25 01:15:112234 return delegate()->IsExternalTabContainer();
[email protected]420ae012009-04-24 05:16:322235}
2236
2237void TabContents::FileSelected(const FilePath& path,
2238 int index, void* params) {
2239 render_view_host()->FileSelected(path);
2240}
2241
2242void TabContents::MultiFilesSelected(const std::vector<FilePath>& files,
2243 void* params) {
2244 render_view_host()->MultiFilesSelected(files);
2245}
2246
2247void TabContents::FileSelectionCanceled(void* params) {
2248 // If the user cancels choosing a file to upload we pass back an
2249 // empty vector.
2250 render_view_host()->MultiFilesSelected(std::vector<FilePath>());
2251}
2252
2253void TabContents::BeforeUnloadFiredFromRenderManager(
2254 bool proceed,
2255 bool* proceed_to_fire_unload) {
2256 if (delegate())
2257 delegate()->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
2258}
2259
2260void TabContents::UpdateRenderViewSizeForRenderManager() {
2261 // TODO(brettw) this is a hack. See TabContentsView::SizeContents.
2262 view_->SizeContents(view_->GetContainerSize());
2263}
2264
2265DOMUI* TabContents::CreateDOMUIForRenderManager(const GURL& url) {
[email protected]d82ed61e2009-06-16 02:46:222266 return DOMUIFactory::CreateDOMUIForURL(this, url);
[email protected]420ae012009-04-24 05:16:322267}
2268
2269NavigationEntry*
2270TabContents::GetLastCommittedNavigationEntryForRenderManager() {
2271 return controller_.GetLastCommittedEntry();
2272}
2273
2274bool TabContents::CreateRenderViewForRenderManager(
2275 RenderViewHost* render_view_host) {
2276 // When we're running a DOM UI, the RenderViewHost needs to be put in DOM UI
2277 // mode before CreateRenderView is called. When we're asked to create a
2278 // RenderView, that means it's for the pending entry, so we have to use the
2279 // pending DOM UI.
2280 if (render_manager_.pending_dom_ui())
2281 render_view_host->AllowDOMUIBindings();
2282
[email protected]1adff062009-06-02 18:39:552283 // Ditto for extension bindings.
2284 if (controller().pending_entry()->url().SchemeIs(chrome::kExtensionScheme))
2285 render_view_host->AllowExtensionBindings();
2286
[email protected]420ae012009-04-24 05:16:322287 RenderWidgetHostView* rwh_view = view_->CreateViewForWidget(render_view_host);
2288 if (!render_view_host->CreateRenderView())
2289 return false;
2290
2291 // Now that the RenderView has been created, we need to tell it its size.
2292 rwh_view->SetSize(view_->GetContainerSize());
2293
2294 UpdateMaxPageIDIfNecessary(render_view_host->site_instance(),
2295 render_view_host);
2296 return true;
2297}
2298
2299void TabContents::Observe(NotificationType type,
2300 const NotificationSource& source,
2301 const NotificationDetails& details) {
2302 switch (type.value) {
2303 case NotificationType::BOOKMARK_MODEL_LOADED:
2304 // BookmarkModel finished loading, fall through to update starred state.
2305 case NotificationType::URLS_STARRED: {
2306 // Somewhere, a URL has been starred.
2307 // Ignore notifications for profiles other than our current one.
2308 Profile* source_profile = Source<Profile>(source).ptr();
2309 if (!source_profile || !source_profile->IsSameProfile(profile()))
2310 return;
2311
2312 UpdateStarredStateForCurrentURL();
2313 break;
2314 }
2315 case NotificationType::PREF_CHANGED: {
2316 std::wstring* pref_name_in = Details<std::wstring>(details).ptr();
2317 DCHECK(Source<PrefService>(source).ptr() == profile()->GetPrefs());
2318 if (*pref_name_in == prefs::kAlternateErrorPagesEnabled) {
2319 UpdateAlternateErrorPageURL();
2320 } else if (*pref_name_in == prefs::kDefaultCharset ||
2321 StartsWithASCII(WideToUTF8(*pref_name_in), "webkit.webprefs.", true)
2322 ) {
2323 UpdateWebPreferences();
2324 } else {
2325 NOTREACHED() << "unexpected pref change notification" << *pref_name_in;
2326 }
2327 break;
2328 }
2329 case NotificationType::RENDER_WIDGET_HOST_DESTROYED:
2330 view_->RenderWidgetHostDestroyed(Source<RenderWidgetHost>(source).ptr());
2331 break;
2332
2333 case NotificationType::NAV_ENTRY_COMMITTED: {
2334 DCHECK(&controller_ == Source<NavigationController>(source).ptr());
2335
2336 NavigationController::LoadCommittedDetails& committed_details =
2337 *(Details<NavigationController::LoadCommittedDetails>(details).ptr());
2338 ExpireInfoBars(committed_details);
2339 break;
2340 }
2341
2342 default:
2343 NOTREACHED();
2344 }
2345}