browser.cc revision 5821806d5e7f356e8fa4b058a389a808ea183019
1// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "chrome/browser/ui/browser.h"
6
7#if defined(OS_WIN)
8#include <windows.h>
9#include <shellapi.h>
10#endif  // defined(OS_WIN)
11
12#include <algorithm>
13#include <string>
14
15#include "base/base_paths.h"
16#include "base/bind.h"
17#include "base/command_line.h"
18#include "base/logging.h"
19#include "base/metrics/histogram.h"
20#include "base/path_service.h"
21#include "base/process_info.h"
22#include "base/string_number_conversions.h"
23#include "base/string_util.h"
24#include "base/stringprintf.h"
25#include "base/threading/thread.h"
26#include "base/threading/thread_restrictions.h"
27#include "base/time.h"
28#include "base/utf_string_conversions.h"
29#include "chrome/app/chrome_command_ids.h"
30#include "chrome/browser/api/infobars/simple_alert_infobar_delegate.h"
31#include "chrome/browser/autofill/personal_data_manager_factory.h"
32#include "chrome/browser/background/background_contents_service.h"
33#include "chrome/browser/background/background_contents_service_factory.h"
34#include "chrome/browser/bookmarks/bookmark_model.h"
35#include "chrome/browser/bookmarks/bookmark_utils.h"
36#include "chrome/browser/browser_process.h"
37#include "chrome/browser/browser_shutdown.h"
38#include "chrome/browser/character_encoding.h"
39#include "chrome/browser/chrome_page_zoom.h"
40#include "chrome/browser/content_settings/host_content_settings_map.h"
41#include "chrome/browser/content_settings/tab_specific_content_settings.h"
42#include "chrome/browser/custom_handlers/protocol_handler_registry.h"
43#include "chrome/browser/custom_handlers/register_protocol_handler_infobar_delegate.h"
44#include "chrome/browser/debugger/devtools_toggle_action.h"
45#include "chrome/browser/debugger/devtools_window.h"
46#include "chrome/browser/download/download_crx_util.h"
47#include "chrome/browser/download/download_item_model.h"
48#include "chrome/browser/download/download_service.h"
49#include "chrome/browser/download/download_service_factory.h"
50#include "chrome/browser/download/download_shelf.h"
51#include "chrome/browser/download/download_started_animation.h"
52#include "chrome/browser/download/download_util.h"
53#include "chrome/browser/extensions/browser_extension_window_controller.h"
54#include "chrome/browser/extensions/extension_prefs.h"
55#include "chrome/browser/extensions/extension_service.h"
56#include "chrome/browser/extensions/tab_helper.h"
57#include "chrome/browser/favicon/favicon_tab_helper.h"
58#include "chrome/browser/file_select_helper.h"
59#include "chrome/browser/first_run/first_run.h"
60#include "chrome/browser/google/google_url_tracker.h"
61#include "chrome/browser/infobars/infobar_tab_helper.h"
62#include "chrome/browser/intents/device_attached_intent_source.h"
63#include "chrome/browser/intents/register_intent_handler_infobar_delegate.h"
64#include "chrome/browser/intents/web_intents_reporting.h"
65#include "chrome/browser/intents/web_intents_util.h"
66#include "chrome/browser/lifetime/application_lifetime.h"
67#include "chrome/browser/media/media_stream_devices_controller.h"
68#include "chrome/browser/net/url_fixer_upper.h"
69#include "chrome/browser/notifications/notification_ui_manager.h"
70#include "chrome/browser/platform_util.h"
71#include "chrome/browser/prefs/incognito_mode_prefs.h"
72#include "chrome/browser/prefs/pref_service.h"
73#include "chrome/browser/printing/cloud_print/cloud_print_setup_flow.h"
74#include "chrome/browser/printing/print_preview_tab_controller.h"
75#include "chrome/browser/profiles/profile.h"
76#include "chrome/browser/profiles/profile_destroyer.h"
77#include "chrome/browser/profiles/profile_manager.h"
78#include "chrome/browser/profiles/profile_metrics.h"
79#include "chrome/browser/repost_form_warning_controller.h"
80#include "chrome/browser/sessions/session_service.h"
81#include "chrome/browser/sessions/session_service_factory.h"
82#include "chrome/browser/sessions/session_tab_helper.h"
83#include "chrome/browser/sessions/session_types.h"
84#include "chrome/browser/sessions/tab_restore_service.h"
85#include "chrome/browser/sessions/tab_restore_service_factory.h"
86#include "chrome/browser/sync/profile_sync_service.h"
87#include "chrome/browser/sync/profile_sync_service_factory.h"
88#include "chrome/browser/sync/sync_ui_util.h"
89#include "chrome/browser/tab_contents/background_contents.h"
90#include "chrome/browser/tab_contents/retargeting_details.h"
91#include "chrome/browser/tab_contents/tab_util.h"
92#include "chrome/browser/themes/theme_service.h"
93#include "chrome/browser/themes/theme_service_factory.h"
94#include "chrome/browser/ui/app_modal_dialogs/javascript_dialog_creator.h"
95#include "chrome/browser/ui/bookmarks/bookmark_tab_helper.h"
96#include "chrome/browser/ui/browser_command_controller.h"
97#include "chrome/browser/ui/browser_commands.h"
98#include "chrome/browser/ui/browser_content_setting_bubble_model_delegate.h"
99#include "chrome/browser/ui/browser_dialogs.h"
100#include "chrome/browser/ui/browser_finder.h"
101#include "chrome/browser/ui/browser_instant_controller.h"
102#include "chrome/browser/ui/browser_list.h"
103#include "chrome/browser/ui/browser_navigator.h"
104#include "chrome/browser/ui/browser_tab_restore_service_delegate.h"
105#include "chrome/browser/ui/browser_tab_strip_model_delegate.h"
106#include "chrome/browser/ui/browser_tabstrip.h"
107#include "chrome/browser/ui/browser_toolbar_model_delegate.h"
108#include "chrome/browser/ui/browser_ui_prefs.h"
109#include "chrome/browser/ui/browser_window.h"
110#include "chrome/browser/ui/chrome_pages.h"
111#include "chrome/browser/ui/chrome_select_file_policy.h"
112#include "chrome/browser/ui/extensions/shell_window.h"
113#include "chrome/browser/ui/find_bar/find_bar.h"
114#include "chrome/browser/ui/find_bar/find_bar_controller.h"
115#include "chrome/browser/ui/find_bar/find_tab_helper.h"
116#include "chrome/browser/ui/fullscreen/fullscreen_controller.h"
117#include "chrome/browser/ui/global_error/global_error.h"
118#include "chrome/browser/ui/global_error/global_error_service.h"
119#include "chrome/browser/ui/global_error/global_error_service_factory.h"
120#include "chrome/browser/ui/intents/web_intent_picker_controller.h"
121#include "chrome/browser/ui/media_stream_infobar_delegate.h"
122#include "chrome/browser/ui/omnibox/location_bar.h"
123#include "chrome/browser/ui/search/search.h"
124#include "chrome/browser/ui/search/search_delegate.h"
125#include "chrome/browser/ui/search/search_model.h"
126#include "chrome/browser/ui/search/search_types.h"
127#include "chrome/browser/ui/singleton_tabs.h"
128#include "chrome/browser/ui/status_bubble.h"
129#include "chrome/browser/ui/sync/browser_synced_window_delegate.h"
130#include "chrome/browser/ui/tab_contents/core_tab_helper.h"
131#include "chrome/browser/ui/tab_contents/tab_contents.h"
132#include "chrome/browser/ui/tab_modal_confirm_dialog.h"
133#include "chrome/browser/ui/tabs/dock_info.h"
134#include "chrome/browser/ui/tabs/tab_menu_model.h"
135#include "chrome/browser/ui/tabs/tab_strip_model.h"
136#include "chrome/browser/ui/toolbar/toolbar_model_impl.h"
137#include "chrome/browser/ui/unload_controller.h"
138#include "chrome/browser/ui/web_applications/web_app_ui.h"
139#include "chrome/browser/ui/webui/signin/login_ui_service.h"
140#include "chrome/browser/ui/webui/signin/login_ui_service_factory.h"
141#include "chrome/browser/ui/window_sizer/window_sizer.h"
142#include "chrome/browser/upgrade_detector.h"
143#include "chrome/browser/web_applications/web_app.h"
144#include "chrome/common/chrome_constants.h"
145#include "chrome/common/chrome_notification_types.h"
146#include "chrome/common/chrome_switches.h"
147#include "chrome/common/custom_handlers/protocol_handler.h"
148#include "chrome/common/extensions/extension.h"
149#include "chrome/common/extensions/extension_constants.h"
150#include "chrome/common/pref_names.h"
151#include "chrome/common/profiling.h"
152#include "chrome/common/startup_metric_utils.h"
153#include "chrome/common/url_constants.h"
154#include "chrome/common/web_apps.h"
155#include "content/public/browser/color_chooser.h"
156#include "content/public/browser/devtools_manager.h"
157#include "content/public/browser/download_item.h"
158#include "content/public/browser/download_manager.h"
159#include "content/public/browser/interstitial_page.h"
160#include "content/public/browser/invalidate_type.h"
161#include "content/public/browser/navigation_controller.h"
162#include "content/public/browser/navigation_entry.h"
163#include "content/public/browser/notification_details.h"
164#include "content/public/browser/notification_service.h"
165#include "content/public/browser/plugin_service.h"
166#include "content/public/browser/render_process_host.h"
167#include "content/public/browser/render_view_host.h"
168#include "content/public/browser/site_instance.h"
169#include "content/public/browser/user_metrics.h"
170#include "content/public/browser/web_contents.h"
171#include "content/public/browser/web_contents_view.h"
172#include "content/public/browser/web_intents_dispatcher.h"
173#include "content/public/common/content_restriction.h"
174#include "content/public/common/content_switches.h"
175#include "content/public/common/page_zoom.h"
176#include "content/public/common/renderer_preferences.h"
177#include "grit/chromium_strings.h"
178#include "grit/generated_resources.h"
179#include "grit/locale_settings.h"
180#include "grit/theme_resources.h"
181#include "net/base/net_util.h"
182#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
183#include "net/cookies/cookie_monster.h"
184#include "net/url_request/url_request_context.h"
185#include "ui/base/animation/animation.h"
186#include "ui/base/dialogs/selected_file_info.h"
187#include "ui/base/l10n/l10n_util.h"
188#include "ui/gfx/point.h"
189#include "webkit/glue/web_intent_data.h"
190#include "webkit/glue/web_intent_service_data.h"
191#include "webkit/glue/webkit_glue.h"
192#include "webkit/glue/window_open_disposition.h"
193#include "webkit/plugins/webplugininfo.h"
194
195#if defined(OS_WIN)
196#include "base/win/metro.h"
197#include "chrome/browser/autofill/autofill_ie_toolbar_import_win.h"
198#include "chrome/browser/shell_integration.h"
199#include "chrome/browser/ssl/ssl_error_info.h"
200#include "chrome/browser/task_manager/task_manager.h"
201#include "chrome/browser/ui/view_ids.h"
202#include "ui/base/win/shell.h"
203#endif  // OS_WIN
204
205#if defined(OS_CHROMEOS)
206#include "chrome/browser/chromeos/drive/drive_file_system_util.h"
207#endif
208
209#if defined(USE_ASH)
210#include "ash/ash_switches.h"
211#endif
212
213using base::TimeDelta;
214using content::NativeWebKeyboardEvent;
215using content::NavigationController;
216using content::NavigationEntry;
217using content::OpenURLParams;
218using content::PluginService;
219using content::Referrer;
220using content::SiteInstance;
221using content::UserMetricsAction;
222using content::WebContents;
223using extensions::Extension;
224using ui::WebDialogDelegate;
225
226///////////////////////////////////////////////////////////////////////////////
227
228namespace {
229
230// The URL to be loaded to display the "Report a broken page" form.
231const char kBrokenPageUrl[] =
232    "https://www.google.com/support/chrome/bin/request.py?contact_type="
233    "broken_website&format=inproduct&p.page_title=$1&p.page_url=$2";
234
235// How long we wait before updating the browser chrome while loading a page.
236const int kUIUpdateCoalescingTimeMS = 200;
237
238BrowserWindow* CreateBrowserWindow(Browser* browser) {
239  return BrowserWindow::CreateBrowserWindow(browser);
240}
241
242#if defined(OS_CHROMEOS)
243chrome::HostDesktopType kDefaultHostDesktopType = chrome::HOST_DESKTOP_TYPE_ASH;
244#else
245chrome::HostDesktopType kDefaultHostDesktopType =
246    chrome::HOST_DESKTOP_TYPE_NATIVE;
247#endif
248
249bool ShouldReloadCrashedTab(WebContents* contents) {
250  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
251  return (command_line.HasSwitch(switches::kReloadKilledTabs) &&
252      contents->IsCrashed());
253}
254
255}  // namespace
256
257////////////////////////////////////////////////////////////////////////////////
258// Browser, CreateParams:
259
260Browser::CreateParams::CreateParams()
261    : type(TYPE_TABBED),
262      profile(NULL),
263      host_desktop_type(kDefaultHostDesktopType),
264      app_type(APP_TYPE_HOST),
265      initial_show_state(ui::SHOW_STATE_DEFAULT),
266      is_session_restore(false),
267      window(NULL) {
268}
269
270Browser::CreateParams::CreateParams(Profile* profile)
271    : type(TYPE_TABBED),
272      profile(profile),
273      host_desktop_type(kDefaultHostDesktopType),
274      app_type(APP_TYPE_HOST),
275      initial_show_state(ui::SHOW_STATE_DEFAULT),
276      is_session_restore(false),
277      window(NULL) {
278}
279
280Browser::CreateParams::CreateParams(Type type, Profile* profile)
281    : type(type),
282      profile(profile),
283      host_desktop_type(kDefaultHostDesktopType),
284      app_type(APP_TYPE_HOST),
285      initial_show_state(ui::SHOW_STATE_DEFAULT),
286      is_session_restore(false),
287      window(NULL) {
288}
289
290Browser::CreateParams::CreateParams(Type type,
291                                    Profile* profile,
292                                    chrome::HostDesktopType host_desktop_type)
293    : type(type),
294      profile(profile),
295      host_desktop_type(host_desktop_type),
296      app_type(APP_TYPE_HOST),
297      initial_show_state(ui::SHOW_STATE_DEFAULT),
298      is_session_restore(false),
299      window(NULL) {
300}
301
302// static
303Browser::CreateParams Browser::CreateParams::CreateForApp(
304    Type type,
305    const std::string& app_name,
306    const gfx::Rect& window_bounds,
307    Profile* profile) {
308  DCHECK(type != TYPE_TABBED);
309  DCHECK(!app_name.empty());
310
311  CreateParams params(type, profile);
312  params.app_name = app_name;
313  params.app_type = APP_TYPE_CHILD;
314  params.initial_bounds = window_bounds;
315
316  return params;
317}
318
319// static
320Browser::CreateParams Browser::CreateParams::CreateForDevTools(
321    Profile* profile) {
322  CreateParams params(TYPE_POPUP, profile);
323  params.app_name = DevToolsWindow::kDevToolsApp;
324  return params;
325}
326
327///////////////////////////////////////////////////////////////////////////////
328// Browser, Constructors, Creation, Showing:
329
330Browser::Browser(const CreateParams& params)
331    : type_(params.type),
332      profile_(params.profile),
333      window_(NULL),
334      ALLOW_THIS_IN_INITIALIZER_LIST(
335          tab_strip_model_delegate_(
336            new chrome::BrowserTabStripModelDelegate(this))),
337      tab_strip_model_(new TabStripModel(tab_strip_model_delegate_.get(),
338                                         params.profile)),
339      app_name_(params.app_name),
340      app_type_(params.app_type),
341      chrome_updater_factory_(this),
342      cancel_download_confirmation_state_(NOT_PROMPTED),
343      override_bounds_(params.initial_bounds),
344      initial_show_state_(params.initial_show_state),
345      is_session_restore_(params.is_session_restore),
346      host_desktop_type_(params.host_desktop_type),
347      ALLOW_THIS_IN_INITIALIZER_LIST(
348          unload_controller_(new chrome::UnloadController(this))),
349      weak_factory_(this),
350      ALLOW_THIS_IN_INITIALIZER_LIST(
351          content_setting_bubble_model_delegate_(
352              new BrowserContentSettingBubbleModelDelegate(this))),
353      ALLOW_THIS_IN_INITIALIZER_LIST(
354          toolbar_model_delegate_(
355              new BrowserToolbarModelDelegate(this))),
356      ALLOW_THIS_IN_INITIALIZER_LIST(
357          tab_restore_service_delegate_(
358              new BrowserTabRestoreServiceDelegate(this))),
359      ALLOW_THIS_IN_INITIALIZER_LIST(
360          synced_window_delegate_(
361              new BrowserSyncedWindowDelegate(this))),
362      bookmark_bar_state_(BookmarkBar::HIDDEN),
363      ALLOW_THIS_IN_INITIALIZER_LIST(
364          command_controller_(new chrome::BrowserCommandController(this))),
365      window_has_shown_(false) {
366  if (!app_name_.empty())
367    chrome::RegisterAppPrefs(app_name_, profile_);
368  tab_strip_model_->AddObserver(this);
369
370  toolbar_model_.reset(new ToolbarModelImpl(toolbar_model_delegate_.get()));
371  search_model_.reset(new chrome::search::SearchModel(NULL));
372  search_delegate_.reset(
373      new chrome::search::SearchDelegate(search_model_.get(),
374                                         toolbar_model_.get()));
375
376  registrar_.Add(this, content::NOTIFICATION_SSL_VISIBLE_STATE_CHANGED,
377                 content::NotificationService::AllSources());
378  registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_LOADED,
379                 content::Source<Profile>(profile_->GetOriginalProfile()));
380  registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UNLOADED,
381                 content::Source<Profile>(profile_->GetOriginalProfile()));
382  registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UNINSTALLED,
383                 content::Source<Profile>(profile_->GetOriginalProfile()));
384  registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
385                 content::NotificationService::AllSources());
386#if defined(ENABLE_THEMES)
387  registrar_.Add(
388      this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED,
389      content::Source<ThemeService>(
390          ThemeServiceFactory::GetForProfile(profile_)));
391#endif
392  registrar_.Add(this, chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED,
393                 content::NotificationService::AllSources());
394
395  profile_pref_registrar_.Init(profile_->GetPrefs());
396  profile_pref_registrar_.Add(prefs::kDevToolsDisabled, this);
397  profile_pref_registrar_.Add(prefs::kShowBookmarkBar, this);
398  profile_pref_registrar_.Add(prefs::kHomePage, this);
399
400  BrowserList::AddBrowser(this);
401
402  // NOTE: These prefs all need to be explicitly destroyed in the destructor
403  // or you'll get a nasty surprise when you run the incognito tests.
404  encoding_auto_detect_.Init(prefs::kWebKitUsesUniversalDetector,
405                             profile_->GetPrefs(), NULL);
406
407  instant_controller_.reset(new chrome::BrowserInstantController(this));
408
409#if 0
410  // Disabled for M22. See http://crbug.com/144326.
411  device_attached_intent_source_.reset(
412      new DeviceAttachedIntentSource(this, (this)));
413#endif
414
415  UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_INIT);
416
417  FilePath profile_path = profile_->GetPath();
418  ProfileMetrics::LogProfileLaunch(profile_path);
419
420  window_ = params.window ? params.window : CreateBrowserWindow(this);
421
422  // TODO(beng): move to BrowserFrameWin.
423#if defined(OS_WIN) && !defined(USE_AURA)
424  // Set the app user model id for this application to that of the application
425  // name.  See http://crbug.com/7028.
426  ui::win::SetAppIdForWindow(
427      is_app() && !is_type_panel() ?
428      ShellIntegration::GetAppModelIdForProfile(UTF8ToWide(app_name_),
429                                                profile_->GetPath()) :
430      ShellIntegration::GetChromiumModelIdForProfile(profile_->GetPath()),
431      window()->GetNativeWindow());
432
433  if (is_type_panel()) {
434    ui::win::SetAppIconForWindow(ShellIntegration::GetChromiumIconPath(),
435                                 window()->GetNativeWindow());
436  }
437#endif
438
439  // Create the extension window controller before sending notifications.
440  extension_window_controller_.reset(
441      new BrowserExtensionWindowController(this));
442
443  // TODO(beng): Move BrowserList::AddBrowser() to the end of this function and
444  //             replace uses of this with BL's notifications.
445  content::NotificationService::current()->Notify(
446      chrome::NOTIFICATION_BROWSER_WINDOW_READY,
447      content::Source<Browser>(this),
448      content::NotificationService::NoDetails());
449
450  // TODO(beng): move to ChromeBrowserMain:
451  PrefService* local_state = g_browser_process->local_state();
452  if (local_state && local_state->FindPreference(
453      prefs::kAutofillPersonalDataManagerFirstRun) &&
454      local_state->GetBoolean(prefs::kAutofillPersonalDataManagerFirstRun)) {
455    // Notify PDM that this is a first run.
456#if defined(OS_WIN)
457    ImportAutofillDataWin(PersonalDataManagerFactory::GetForProfile(profile_));
458#endif  // defined(OS_WIN)
459    // Reset the preference so we don't call it again for subsequent windows.
460    local_state->ClearPref(prefs::kAutofillPersonalDataManagerFirstRun);
461  }
462
463  fullscreen_controller_.reset(new FullscreenController(this));
464  search_model_->AddObserver(this);
465}
466
467Browser::~Browser() {
468  // The tab strip should not have any tabs at this point.
469  if (!browser_shutdown::ShuttingDownWithoutClosingBrowsers())
470    DCHECK(tab_strip_model_->empty());
471
472  search_model_->RemoveObserver(this);
473  tab_strip_model_->RemoveObserver(this);
474
475  BrowserList::RemoveBrowser(this);
476
477  SessionService* session_service =
478      SessionServiceFactory::GetForProfile(profile_);
479  if (session_service)
480    session_service->WindowClosed(session_id_);
481
482  TabRestoreService* tab_restore_service =
483      TabRestoreServiceFactory::GetForProfile(profile());
484  if (tab_restore_service)
485    tab_restore_service->BrowserClosed(tab_restore_service_delegate());
486
487#if !defined(OS_MACOSX)
488  if (!chrome::GetBrowserCount(profile_)) {
489    // We're the last browser window with this profile. We need to nuke the
490    // TabRestoreService, which will start the shutdown of the
491    // NavigationControllers and allow for proper shutdown. If we don't do this
492    // chrome won't shutdown cleanly, and may end up crashing when some
493    // thread tries to use the IO thread (or another thread) that is no longer
494    // valid.
495    // This isn't a valid assumption for Mac OS, as it stays running after
496    // the last browser has closed. The Mac equivalent is in its app
497    // controller.
498    TabRestoreServiceFactory::ResetForProfile(profile_);
499  }
500#endif
501
502  profile_pref_registrar_.RemoveAll();
503
504  encoding_auto_detect_.Destroy();
505
506  command_controller_.reset();
507
508  if (profile_->IsOffTheRecord() &&
509      !BrowserList::IsOffTheRecordSessionActiveForProfile(profile_)) {
510    // An incognito profile is no longer needed, this indirectly frees
511    // its cache and cookies once it gets destroyed at the appropriate time.
512    ProfileDestroyer::DestroyProfileWhenAppropriate(profile_);
513  }
514
515  // There may be pending file dialogs, we need to tell them that we've gone
516  // away so they don't try and call back to us.
517  if (select_file_dialog_.get())
518    select_file_dialog_->ListenerDestroyed();
519}
520
521///////////////////////////////////////////////////////////////////////////////
522// Getters & Setters
523
524FindBarController* Browser::GetFindBarController() {
525  if (!find_bar_controller_.get()) {
526    FindBar* find_bar = window_->CreateFindBar();
527    find_bar_controller_.reset(new FindBarController(find_bar));
528    find_bar->SetFindBarController(find_bar_controller_.get());
529    find_bar_controller_->ChangeWebContents(chrome::GetActiveWebContents(this));
530    find_bar_controller_->find_bar()->MoveWindowIfNecessary(gfx::Rect(), true);
531  }
532  return find_bar_controller_.get();
533}
534
535bool Browser::HasFindBarController() const {
536  return find_bar_controller_.get() != NULL;
537}
538
539bool Browser::is_app() const {
540  return !app_name_.empty();
541}
542
543bool Browser::is_devtools() const {
544  return app_name_ == DevToolsWindow::kDevToolsApp;
545}
546
547///////////////////////////////////////////////////////////////////////////////
548// Browser, State Storage and Retrieval for UI:
549
550gfx::Image Browser::GetCurrentPageIcon() const {
551  WebContents* web_contents = chrome::GetActiveWebContents(this);
552  // |web_contents| can be NULL since GetCurrentPageIcon() is called by the
553  // window during the window's creation (before tabs have been added).
554  FaviconTabHelper* favicon_tab_helper =
555      web_contents ? FaviconTabHelper::FromWebContents(web_contents) : NULL;
556  return favicon_tab_helper ? favicon_tab_helper->GetFavicon() : gfx::Image();
557}
558
559string16 Browser::GetWindowTitleForCurrentTab() const {
560  WebContents* contents = chrome::GetActiveWebContents(this);
561  string16 title;
562
563  // |contents| can be NULL because GetWindowTitleForCurrentTab is called by the
564  // window during the window's creation (before tabs have been added).
565  if (contents) {
566    title = contents->GetTitle();
567    FormatTitleForDisplay(&title);
568  }
569  if (title.empty())
570    title = CoreTabHelper::GetDefaultTitle();
571
572#if defined(OS_MACOSX) || defined(USE_ASH)
573  // On Mac or Ash, we don't want to suffix the page title with
574  // the application name.
575  return title;
576#else
577  // Don't append the app name to window titles on app frames and app popups
578  return is_app() ?
579      title :
580      l10n_util::GetStringFUTF16(IDS_BROWSER_WINDOW_TITLE_FORMAT, title);
581#endif
582}
583
584// static
585void Browser::FormatTitleForDisplay(string16* title) {
586  size_t current_index = 0;
587  size_t match_index;
588  while ((match_index = title->find(L'\n', current_index)) != string16::npos) {
589    title->replace(match_index, 1, string16());
590    current_index = match_index;
591  }
592}
593
594///////////////////////////////////////////////////////////////////////////////
595// Browser, OnBeforeUnload handling:
596
597bool Browser::ShouldCloseWindow() {
598  if (!CanCloseWithInProgressDownloads())
599    return false;
600
601  return unload_controller_->ShouldCloseWindow();
602}
603
604bool Browser::IsAttemptingToCloseBrowser() const {
605  return unload_controller_->is_attempting_to_close_browser();
606}
607
608void Browser::OnWindowClosing() {
609  if (!ShouldCloseWindow())
610    return;
611
612  // Application should shutdown on last window close if the user is explicitly
613  // trying to quit, or if there is nothing keeping the browser alive (such as
614  // AppController on the Mac, or BackgroundContentsService for background
615  // pages).
616  bool should_quit_if_last_browser =
617      browser_shutdown::IsTryingToQuit() || !browser::WillKeepAlive();
618
619  if (should_quit_if_last_browser && BrowserList::size() == 1)
620    browser_shutdown::OnShutdownStarting(browser_shutdown::WINDOW_CLOSE);
621
622  // Don't use GetForProfileIfExisting here, we want to force creation of the
623  // session service so that user can restore what was open.
624  SessionService* session_service =
625      SessionServiceFactory::GetForProfile(profile());
626  if (session_service)
627    session_service->WindowClosing(session_id());
628
629  TabRestoreService* tab_restore_service =
630      TabRestoreServiceFactory::GetForProfile(profile());
631
632#if defined(USE_AURA)
633  if (tab_restore_service && is_app())
634    tab_restore_service->BrowserClosing(tab_restore_service_delegate());
635#endif
636
637  if (tab_restore_service && is_type_tabbed() && tab_count())
638    tab_restore_service->BrowserClosing(tab_restore_service_delegate());
639
640  // TODO(sky): convert session/tab restore to use notification.
641  content::NotificationService::current()->Notify(
642      chrome::NOTIFICATION_BROWSER_CLOSING,
643      content::Source<Browser>(this),
644      content::NotificationService::NoDetails());
645
646  chrome::CloseAllTabs(this);
647}
648
649void Browser::OnWindowActivated() {
650  // On some platforms we want to automatically reload tabs that are
651  // killed when the user selects them.
652  WebContents* contents = chrome::GetActiveWebContents(this);
653  if (contents && ShouldReloadCrashedTab(contents))
654    chrome::Reload(this, CURRENT_TAB);
655}
656
657////////////////////////////////////////////////////////////////////////////////
658// In-progress download termination handling:
659
660void Browser::InProgressDownloadResponse(bool cancel_downloads) {
661  if (cancel_downloads) {
662    cancel_download_confirmation_state_ = RESPONSE_RECEIVED;
663    chrome::CloseWindow(this);
664    return;
665  }
666
667  // Sets the confirmation state to NOT_PROMPTED so that if the user tries to
668  // close again we'll show the warning again.
669  cancel_download_confirmation_state_ = NOT_PROMPTED;
670
671  // Show the download page so the user can figure-out what downloads are still
672  // in-progress.
673  chrome::ShowDownloads(this);
674}
675
676Browser::DownloadClosePreventionType Browser::OkToCloseWithInProgressDownloads(
677    int* num_downloads_blocking) const {
678  DCHECK(num_downloads_blocking);
679  *num_downloads_blocking = 0;
680
681  if (IsAttemptingToCloseBrowser())
682    return DOWNLOAD_CLOSE_OK;
683
684  // If we're not running a full browser process with a profile manager
685  // (testing), it's ok to close the browser.
686  if (!g_browser_process->profile_manager())
687    return DOWNLOAD_CLOSE_OK;
688
689  int total_download_count = DownloadService::DownloadCountAllProfiles();
690  if (total_download_count == 0)
691    return DOWNLOAD_CLOSE_OK;   // No downloads; can definitely close.
692
693  // Figure out how many windows are open total, and associated with this
694  // profile, that are relevant for the ok-to-close decision.
695  int profile_window_count = 0;
696  int total_window_count = 0;
697  for (BrowserList::const_iterator iter = BrowserList::begin();
698       iter != BrowserList::end(); ++iter) {
699    // Don't count this browser window or any other in the process of closing.
700    Browser* const browser = *iter;
701    // Window closing may be delayed, and windows that are in the process of
702    // closing don't count against our totals.
703    if (browser == this || browser->IsAttemptingToCloseBrowser())
704      continue;
705
706    if ((*iter)->profile() == profile())
707      profile_window_count++;
708    total_window_count++;
709  }
710
711  // If there aren't any other windows, we're at browser shutdown,
712  // which would cancel all current downloads.
713  if (total_window_count == 0) {
714    *num_downloads_blocking = total_download_count;
715    return DOWNLOAD_CLOSE_BROWSER_SHUTDOWN;
716  }
717
718  // If there aren't any other windows on our profile, and we're an incognito
719  // profile, and there are downloads associated with that profile,
720  // those downloads would be cancelled by our window (-> profile) close.
721  DownloadService* download_service =
722      DownloadServiceFactory::GetForProfile(profile());
723  if (profile_window_count == 0 && download_service->DownloadCount() > 0 &&
724      profile()->IsOffTheRecord()) {
725    *num_downloads_blocking = download_service->DownloadCount();
726    return DOWNLOAD_CLOSE_LAST_WINDOW_IN_INCOGNITO_PROFILE;
727  }
728
729  // Those are the only conditions under which we will block shutdown.
730  return DOWNLOAD_CLOSE_OK;
731}
732
733////////////////////////////////////////////////////////////////////////////////
734// Browser, TabStripModel pass-thrus:
735
736int Browser::tab_count() const {
737  return tab_strip_model_->count();
738}
739
740int Browser::active_index() const {
741  return tab_strip_model_->active_index();
742}
743
744////////////////////////////////////////////////////////////////////////////////
745// Browser, Tab adding/showing functions:
746
747void Browser::WindowFullscreenStateChanged() {
748  fullscreen_controller_->WindowFullscreenStateChanged();
749  command_controller_->FullscreenStateChanged();
750  UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TOGGLE_FULLSCREEN);
751}
752
753///////////////////////////////////////////////////////////////////////////////
754// Browser, Assorted browser commands:
755
756void Browser::ToggleFullscreenModeWithExtension(const GURL& extension_url) {
757  fullscreen_controller_->ToggleFullscreenModeWithExtension(extension_url);
758}
759
760#if defined(OS_MACOSX)
761void Browser::TogglePresentationMode() {
762  fullscreen_controller_->TogglePresentationMode();
763}
764#endif
765
766bool Browser::SupportsWindowFeature(WindowFeature feature) const {
767  return SupportsWindowFeatureImpl(feature, true);
768}
769
770bool Browser::CanSupportWindowFeature(WindowFeature feature) const {
771  return SupportsWindowFeatureImpl(feature, false);
772}
773
774void Browser::ToggleEncodingAutoDetect() {
775  content::RecordAction(UserMetricsAction("AutoDetectChange"));
776  encoding_auto_detect_.SetValue(!encoding_auto_detect_.GetValue());
777  // If "auto detect" is turned on, then any current override encoding
778  // is cleared. This also implicitly performs a reload.
779  // OTOH, if "auto detect" is turned off, we don't change the currently
780  // active encoding.
781  if (encoding_auto_detect_.GetValue()) {
782    WebContents* contents = chrome::GetActiveWebContents(this);
783    if (contents)
784      contents->ResetOverrideEncoding();
785  }
786}
787
788void Browser::OverrideEncoding(int encoding_id) {
789  content::RecordAction(UserMetricsAction("OverrideEncoding"));
790  const std::string selected_encoding =
791      CharacterEncoding::GetCanonicalEncodingNameByCommandId(encoding_id);
792  WebContents* contents = chrome::GetActiveWebContents(this);
793  if (!selected_encoding.empty() && contents)
794     contents->SetOverrideEncoding(selected_encoding);
795  // Update the list of recently selected encodings.
796  std::string new_selected_encoding_list;
797  if (CharacterEncoding::UpdateRecentlySelectedEncoding(
798        profile_->GetPrefs()->GetString(prefs::kRecentlySelectedEncoding),
799        encoding_id,
800        &new_selected_encoding_list)) {
801    profile_->GetPrefs()->SetString(prefs::kRecentlySelectedEncoding,
802                                    new_selected_encoding_list);
803  }
804}
805
806void Browser::OpenFile() {
807  content::RecordAction(UserMetricsAction("OpenFile"));
808  select_file_dialog_ = ui::SelectFileDialog::Create(
809      this, new ChromeSelectFilePolicy(
810          chrome::GetActiveWebContents(this)));
811
812  const FilePath directory = profile_->last_selected_directory();
813
814  // TODO(beng): figure out how to juggle this.
815  gfx::NativeWindow parent_window = window_->GetNativeWindow();
816  ui::SelectFileDialog::FileTypeInfo file_types;
817  file_types.support_gdata = true;
818  select_file_dialog_->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE,
819                                  string16(), directory,
820                                  &file_types, 0, FILE_PATH_LITERAL(""),
821                                  parent_window, NULL);
822}
823
824void Browser::UpdateDownloadShelfVisibility(bool visible) {
825  if (GetStatusBubble())
826    GetStatusBubble()->UpdateDownloadShelfVisibility(visible);
827}
828
829///////////////////////////////////////////////////////////////////////////////
830
831// static
832bool Browser::RunUnloadEventsHelper(WebContents* contents) {
833  // If the WebContents is not connected yet, then there's no unload
834  // handler we can fire even if the WebContents has an unload listener.
835  // One case where we hit this is in a tab that has an infinite loop
836  // before load.
837  if (contents->NeedToFireBeforeUnload()) {
838    // If the page has unload listeners, then we tell the renderer to fire
839    // them. Once they have fired, we'll get a message back saying whether
840    // to proceed closing the page or not, which sends us back to this method
841    // with the NeedToFireBeforeUnload bit cleared.
842    contents->GetRenderViewHost()->FirePageBeforeUnload(false);
843    return true;
844  }
845  return false;
846}
847
848// static
849void Browser::JSOutOfMemoryHelper(WebContents* web_contents) {
850  InfoBarTabHelper* infobar_helper =
851      InfoBarTabHelper::FromWebContents(web_contents);
852  if (!infobar_helper)
853    return;
854
855  infobar_helper->AddInfoBar(new SimpleAlertInfoBarDelegate(
856      infobar_helper,
857      NULL,
858      l10n_util::GetStringUTF16(IDS_JS_OUT_OF_MEMORY_PROMPT),
859      true));
860}
861
862// static
863void Browser::RegisterProtocolHandlerHelper(WebContents* web_contents,
864                                            const std::string& protocol,
865                                            const GURL& url,
866                                            const string16& title,
867                                            bool user_gesture,
868                                            BrowserWindow* window) {
869  TabContents* tab_contents = TabContents::FromWebContents(web_contents);
870  if (!tab_contents || tab_contents->profile()->IsOffTheRecord())
871    return;
872
873  ProtocolHandler handler =
874      ProtocolHandler::CreateProtocolHandler(protocol, url, title);
875
876  ProtocolHandlerRegistry* registry =
877      tab_contents->profile()->GetProtocolHandlerRegistry();
878  TabSpecificContentSettings* tab_content_settings =
879      TabSpecificContentSettings::FromWebContents(web_contents);
880
881  if (registry->SilentlyHandleRegisterHandlerRequest(handler))
882    return;
883
884  if (!user_gesture && window) {
885    tab_content_settings->set_pending_protocol_handler(handler);
886    tab_content_settings->set_previous_protocol_handler(
887        registry->GetHandlerFor(handler.protocol()));
888    window->GetLocationBar()->UpdateContentSettingsIcons();
889    return;
890  }
891
892  // Make sure content-setting icon is turned off in case the page does
893  // ungestured and gestured RPH calls.
894  if (window) {
895    tab_content_settings->ClearPendingProtocolHandler();
896    window->GetLocationBar()->UpdateContentSettingsIcons();
897  }
898
899  content::RecordAction(
900      UserMetricsAction("RegisterProtocolHandler.InfoBar_Shown"));
901  InfoBarTabHelper* infobar_helper =
902      InfoBarTabHelper::FromWebContents(web_contents);
903
904  RegisterProtocolHandlerInfoBarDelegate* rph_delegate =
905      new RegisterProtocolHandlerInfoBarDelegate(infobar_helper,
906                                                 registry,
907                                                 handler);
908
909  for (size_t i = 0; i < infobar_helper->GetInfoBarCount(); i++) {
910    InfoBarDelegate* delegate = infobar_helper->GetInfoBarDelegateAt(i);
911    RegisterProtocolHandlerInfoBarDelegate* cast_delegate =
912        delegate->AsRegisterProtocolHandlerInfoBarDelegate();
913    if (cast_delegate != NULL && cast_delegate->IsReplacedBy(rph_delegate)) {
914      infobar_helper->ReplaceInfoBar(cast_delegate, rph_delegate);
915      rph_delegate = NULL;
916      break;
917    }
918  }
919
920  if (rph_delegate != NULL)
921    infobar_helper->AddInfoBar(rph_delegate);
922}
923
924// static
925void Browser::FindReplyHelper(WebContents* web_contents,
926                              int request_id,
927                              int number_of_matches,
928                              const gfx::Rect& selection_rect,
929                              int active_match_ordinal,
930                              bool final_update) {
931  FindTabHelper* find_tab_helper = FindTabHelper::FromWebContents(web_contents);
932  if (!find_tab_helper)
933    return;
934
935  find_tab_helper->HandleFindReply(request_id,
936                                   number_of_matches,
937                                   selection_rect,
938                                   active_match_ordinal,
939                                   final_update);
940}
941
942// static
943void Browser::RequestMediaAccessPermissionHelper(
944    content::WebContents* web_contents,
945    const content::MediaStreamRequest* request,
946    const content::MediaResponseCallback& callback) {
947  TabContents* tab = TabContents::FromWebContents(web_contents);
948
949  scoped_ptr<MediaStreamDevicesController>
950      controller(new MediaStreamDevicesController(tab->profile(),
951                                                  request,
952                                                  callback));
953  if (!controller->DismissInfoBarAndTakeActionOnSettings()) {
954  InfoBarTabHelper* infobar_helper =
955      InfoBarTabHelper::FromWebContents(web_contents);
956    InfoBarDelegate* old_infobar = NULL;
957    for (size_t i = 0; i < infobar_helper->GetInfoBarCount(); ++i) {
958      old_infobar = infobar_helper->GetInfoBarDelegateAt(i)->
959          AsMediaStreamInfoBarDelegate();
960      if (old_infobar)
961        break;
962    }
963
964    InfoBarDelegate* infobar =
965        new MediaStreamInfoBarDelegate(infobar_helper, controller.release());
966    if (old_infobar)
967      infobar_helper->ReplaceInfoBar(old_infobar, infobar);
968    else
969      infobar_helper->AddInfoBar(infobar);
970  }
971}
972
973void Browser::UpdateUIForNavigationInTab(TabContents* contents,
974                                         content::PageTransition transition,
975                                         bool user_initiated) {
976  tab_strip_model_->TabNavigating(contents, transition);
977
978  bool contents_is_selected = contents == chrome::GetActiveTabContents(this);
979  if (user_initiated && contents_is_selected && window()->GetLocationBar()) {
980    // Forcibly reset the location bar if the url is going to change in the
981    // current tab, since otherwise it won't discard any ongoing user edits,
982    // since it doesn't realize this is a user-initiated action.
983    window()->GetLocationBar()->Revert();
984  }
985
986  if (GetStatusBubble())
987    GetStatusBubble()->Hide();
988
989  // Update the location bar. This is synchronous. We specifically don't
990  // update the load state since the load hasn't started yet and updating it
991  // will put it out of sync with the actual state like whether we're
992  // displaying a favicon, which controls the throbber. If we updated it here,
993  // the throbber will show the default favicon for a split second when
994  // navigating away from the new tab page.
995  ScheduleUIUpdate(contents->web_contents(), content::INVALIDATE_TYPE_URL);
996
997  if (contents_is_selected)
998    contents->web_contents()->Focus();
999}
1000
1001///////////////////////////////////////////////////////////////////////////////
1002// Browser, PageNavigator implementation:
1003
1004WebContents* Browser::OpenURL(const OpenURLParams& params) {
1005  return OpenURLFromTab(NULL, params);
1006}
1007
1008///////////////////////////////////////////////////////////////////////////////
1009// Browser, TabStripModelObserver implementation:
1010
1011void Browser::TabInsertedAt(WebContents* contents,
1012                            int index,
1013                            bool foreground) {
1014  SetAsDelegate(contents, this);
1015  SessionTabHelper* session_tab_helper =
1016      SessionTabHelper::FromWebContents(contents);
1017  session_tab_helper->SetWindowID(session_id());
1018
1019  content::NotificationService::current()->Notify(
1020      chrome::NOTIFICATION_TAB_PARENTED,
1021      content::Source<content::WebContents>(contents),
1022      content::NotificationService::NoDetails());
1023
1024  SyncHistoryWithTabs(index);
1025
1026  // Make sure the loading state is updated correctly, otherwise the throbber
1027  // won't start if the page is loading.
1028  LoadingStateChanged(contents);
1029
1030  registrar_.Add(this, content::NOTIFICATION_INTERSTITIAL_ATTACHED,
1031                 content::Source<WebContents>(contents));
1032
1033  registrar_.Add(this, content::NOTIFICATION_INTERSTITIAL_DETACHED,
1034                 content::Source<WebContents>(contents));
1035  SessionService* session_service =
1036      SessionServiceFactory::GetForProfile(profile_);
1037  if (session_service)
1038    session_service->TabInserted(contents);
1039}
1040
1041void Browser::TabClosingAt(TabStripModel* tab_strip_model,
1042                           WebContents* contents,
1043                           int index) {
1044  fullscreen_controller_->OnTabClosing(contents);
1045  SessionService* session_service =
1046      SessionServiceFactory::GetForProfile(profile_);
1047  if (session_service)
1048    session_service->TabClosing(contents);
1049  content::NotificationService::current()->Notify(
1050      chrome::NOTIFICATION_TAB_CLOSING,
1051      content::Source<NavigationController>(&contents->GetController()),
1052      content::NotificationService::NoDetails());
1053
1054  // Sever the WebContents' connection back to us.
1055  SetAsDelegate(contents, NULL);
1056}
1057
1058void Browser::TabDetachedAt(WebContents* contents, int index) {
1059  TabDetachedAtImpl(contents, index, DETACH_TYPE_DETACH);
1060}
1061
1062void Browser::TabDeactivated(TabContents* contents) {
1063  fullscreen_controller_->OnTabDeactivated(contents);
1064  search_delegate_->OnTabDeactivated(contents->web_contents());
1065
1066  // Save what the user's currently typing, so it can be restored when we
1067  // switch back to this tab.
1068  window_->GetLocationBar()->SaveStateToContents(contents->web_contents());
1069}
1070
1071void Browser::ActiveTabChanged(TabContents* old_contents,
1072                               TabContents* new_contents,
1073                               int index,
1074                               bool user_gesture) {
1075  // On some platforms we want to automatically reload tabs that are
1076  // killed when the user selects them.
1077  bool did_reload = false;
1078  if (user_gesture && ShouldReloadCrashedTab(new_contents->web_contents())) {
1079    LOG(WARNING) << "Reloading killed tab at " << index;
1080    static int reload_count = 0;
1081    UMA_HISTOGRAM_CUSTOM_COUNTS(
1082        "Tabs.SadTab.ReloadCount", ++reload_count, 1, 1000, 50);
1083    chrome::Reload(this, CURRENT_TAB);
1084    did_reload = true;
1085  }
1086
1087  // Discarded tabs always get reloaded.
1088  if (!did_reload && tab_strip_model_->IsTabDiscarded(index)) {
1089    LOG(WARNING) << "Reloading discarded tab at " << index;
1090    static int reload_count = 0;
1091    UMA_HISTOGRAM_CUSTOM_COUNTS(
1092        "Tabs.Discard.ReloadCount", ++reload_count, 1, 1000, 50);
1093    chrome::Reload(this, CURRENT_TAB);
1094  }
1095
1096  // If we have any update pending, do it now.
1097  if (chrome_updater_factory_.HasWeakPtrs() && old_contents)
1098    ProcessPendingUIUpdates();
1099
1100  // Propagate the profile to the location bar.
1101  UpdateToolbar(true);
1102
1103  // Propagate tab state to toolbar, tab-strip, etc.
1104  UpdateSearchState(new_contents);
1105
1106  // Update reload/stop state.
1107  command_controller_->LoadingStateChanged(
1108      new_contents->web_contents()->IsLoading(), true);
1109
1110  // Update commands to reflect current state.
1111  command_controller_->TabStateChanged();
1112
1113  // Reset the status bubble.
1114  StatusBubble* status_bubble = GetStatusBubble();
1115  if (status_bubble) {
1116    status_bubble->Hide();
1117
1118    // Show the loading state (if any).
1119    status_bubble->SetStatus(
1120        CoreTabHelper::FromWebContents(chrome::GetActiveWebContents(this))->
1121            GetStatusText());
1122  }
1123
1124  if (HasFindBarController()) {
1125    find_bar_controller_->ChangeWebContents(new_contents->web_contents());
1126    find_bar_controller_->find_bar()->MoveWindowIfNecessary(gfx::Rect(), true);
1127  }
1128
1129  // Update sessions. Don't force creation of sessions. If sessions doesn't
1130  // exist, the change will be picked up by sessions when created.
1131  SessionService* session_service =
1132      SessionServiceFactory::GetForProfileIfExisting(profile_);
1133  if (session_service && !tab_strip_model_->closing_all()) {
1134    session_service->SetSelectedTabInWindow(session_id(), active_index());
1135  }
1136
1137  UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH);
1138}
1139
1140void Browser::TabMoved(TabContents* contents,
1141                       int from_index,
1142                       int to_index) {
1143  DCHECK(from_index >= 0 && to_index >= 0);
1144  // Notify the history service.
1145  SyncHistoryWithTabs(std::min(from_index, to_index));
1146}
1147
1148void Browser::TabReplacedAt(TabStripModel* tab_strip_model,
1149                            TabContents* old_contents,
1150                            TabContents* new_contents,
1151                            int index) {
1152  TabDetachedAtImpl(old_contents->web_contents(), index, DETACH_TYPE_REPLACE);
1153  SessionService* session_service =
1154      SessionServiceFactory::GetForProfile(profile_);
1155  if (session_service)
1156    session_service->TabClosing(old_contents->web_contents());
1157  TabInsertedAt(new_contents->web_contents(), index, (index == active_index()));
1158
1159  int entry_count =
1160      new_contents->web_contents()->GetController().GetEntryCount();
1161  if (entry_count > 0) {
1162    // Send out notification so that observers are updated appropriately.
1163    new_contents->web_contents()->GetController().NotifyEntryChanged(
1164        new_contents->web_contents()->GetController().GetEntryAtIndex(
1165            entry_count - 1),
1166        entry_count - 1);
1167  }
1168
1169  if (session_service) {
1170    // The new_contents may end up with a different navigation stack. Force
1171    // the session service to update itself.
1172    session_service->TabRestored(new_contents,
1173                                 tab_strip_model_->IsTabPinned(index));
1174  }
1175
1176  content::DevToolsManager::GetInstance()->ContentsReplaced(
1177      old_contents->web_contents(), new_contents->web_contents());
1178}
1179
1180void Browser::TabPinnedStateChanged(WebContents* contents, int index) {
1181  SessionService* session_service =
1182      SessionServiceFactory::GetForProfileIfExisting(profile());
1183  if (session_service) {
1184    SessionTabHelper* session_tab_helper =
1185        SessionTabHelper::FromWebContents(contents);
1186    session_service->SetPinnedState(session_id(),
1187                                    session_tab_helper->session_id(),
1188                                    tab_strip_model_->IsTabPinned(index));
1189  }
1190}
1191
1192void Browser::TabStripEmpty() {
1193  // Close the frame after we return to the message loop (not immediately,
1194  // otherwise it will destroy this object before the stack has a chance to
1195  // cleanly unwind.)
1196  // Note: This will be called several times if TabStripEmpty is called several
1197  //       times. This is because it does not close the window if tabs are
1198  //       still present.
1199  MessageLoop::current()->PostTask(
1200      FROM_HERE, base::Bind(&Browser::CloseFrame, weak_factory_.GetWeakPtr()));
1201}
1202
1203bool Browser::PreHandleKeyboardEvent(content::WebContents* source,
1204                                     const NativeWebKeyboardEvent& event,
1205                                     bool* is_keyboard_shortcut) {
1206  // Escape exits tabbed fullscreen mode.
1207  // TODO(koz): Write a test for this http://crbug.com/100441.
1208  if (event.windowsKeyCode == 27 &&
1209      fullscreen_controller_->HandleUserPressedEscape()) {
1210    return true;
1211  }
1212  return window()->PreHandleKeyboardEvent(event, is_keyboard_shortcut);
1213}
1214
1215void Browser::HandleKeyboardEvent(content::WebContents* source,
1216                                  const NativeWebKeyboardEvent& event) {
1217  window()->HandleKeyboardEvent(event);
1218}
1219
1220bool Browser::TabsNeedBeforeUnloadFired() {
1221  return unload_controller_->TabsNeedBeforeUnloadFired();
1222}
1223
1224bool Browser::IsMouseLocked() const {
1225  return fullscreen_controller_->IsMouseLocked();
1226}
1227
1228void Browser::OnWindowDidShow() {
1229  if (window_has_shown_)
1230    return;
1231  window_has_shown_ = true;
1232
1233// CurrentProcessInfo::CreationTime() is currently only implemented on Mac and
1234// Windows.
1235#if defined(OS_MACOSX) || defined(OS_WIN)
1236  // Measure the latency from startup till the first browser window becomes
1237  // visible.
1238  static bool is_first_browser_window = true;
1239  if (is_first_browser_window &&
1240      !startup_metric_utils::WasNonBrowserUIDisplayed()) {
1241    is_first_browser_window = false;
1242    const base::Time* process_creation_time =
1243        base::CurrentProcessInfo::CreationTime();
1244
1245    if (process_creation_time) {
1246      UMA_HISTOGRAM_LONG_TIMES(
1247          "Startup.BrowserWindowDisplay",
1248          base::Time::Now() - *process_creation_time);
1249    }
1250  }
1251#endif  // defined(OS_MACOSX) || defined(OS_WIN)
1252
1253  // Nothing to do for non-tabbed windows.
1254  if (!is_type_tabbed())
1255    return;
1256
1257  // Show any pending global error bubble.
1258  GlobalErrorService* service =
1259      GlobalErrorServiceFactory::GetForProfile(profile());
1260  GlobalError* error = service->GetFirstGlobalErrorWithBubbleView();
1261  if (error)
1262    error->ShowBubbleView(this);
1263}
1264
1265void Browser::ShowFirstRunBubble() {
1266  window()->GetLocationBar()->ShowFirstRunBubble();
1267}
1268
1269///////////////////////////////////////////////////////////////////////////////
1270// Browser, content::WebContentsDelegate implementation:
1271
1272WebContents* Browser::OpenURLFromTab(WebContents* source,
1273                                     const OpenURLParams& params) {
1274  chrome::NavigateParams nav_params(this, params.url, params.transition);
1275  nav_params.source_contents = chrome::GetTabContentsAt(this,
1276      tab_strip_model_->GetIndexOfWebContents(source));
1277  nav_params.referrer = params.referrer;
1278  nav_params.extra_headers = params.extra_headers;
1279  nav_params.disposition = params.disposition;
1280  nav_params.tabstrip_add_types = TabStripModel::ADD_NONE;
1281  nav_params.window_action = chrome::NavigateParams::SHOW_WINDOW;
1282  nav_params.user_gesture = true;
1283  nav_params.override_encoding = params.override_encoding;
1284  nav_params.is_renderer_initiated = params.is_renderer_initiated;
1285  nav_params.transferred_global_request_id =
1286      params.transferred_global_request_id;
1287  chrome::Navigate(&nav_params);
1288
1289  return nav_params.target_contents ?
1290      nav_params.target_contents->web_contents() : NULL;
1291}
1292
1293void Browser::NavigationStateChanged(const WebContents* source,
1294                                     unsigned changed_flags) {
1295  // Only update the UI when something visible has changed.
1296  if (changed_flags)
1297    ScheduleUIUpdate(source, changed_flags);
1298
1299  // We can synchronously update commands since they will only change once per
1300  // navigation, so we don't have to worry about flickering. We do, however,
1301  // need to update the command state early on load to always present usable
1302  // actions in the face of slow-to-commit pages.
1303  if (changed_flags & (content::INVALIDATE_TYPE_URL |
1304                       content::INVALIDATE_TYPE_LOAD))
1305    command_controller_->TabStateChanged();
1306}
1307
1308void Browser::AddNewContents(WebContents* source,
1309                             WebContents* new_contents,
1310                             WindowOpenDisposition disposition,
1311                             const gfx::Rect& initial_pos,
1312                             bool user_gesture,
1313                             bool* was_blocked) {
1314  chrome::AddWebContents(this, source, new_contents, disposition, initial_pos,
1315                         user_gesture, was_blocked);
1316}
1317
1318void Browser::ActivateContents(WebContents* contents) {
1319  chrome::ActivateTabAt(this, tab_strip_model_->GetIndexOfWebContents(contents),
1320                        false);
1321  window_->Activate();
1322}
1323
1324void Browser::DeactivateContents(WebContents* contents) {
1325  window_->Deactivate();
1326}
1327
1328void Browser::LoadingStateChanged(WebContents* source) {
1329  window_->UpdateLoadingAnimations(tab_strip_model_->TabsAreLoading());
1330  window_->UpdateTitleBar();
1331
1332  WebContents* selected_contents = chrome::GetActiveWebContents(this);
1333  if (source == selected_contents) {
1334    bool is_loading = source->IsLoading();
1335    command_controller_->LoadingStateChanged(is_loading, false);
1336    if (GetStatusBubble()) {
1337      GetStatusBubble()->SetStatus(
1338          CoreTabHelper::FromWebContents(chrome::GetActiveWebContents(this))->
1339              GetStatusText());
1340    }
1341  }
1342}
1343
1344void Browser::CloseContents(WebContents* source) {
1345  if (unload_controller_->CanCloseContents(source))
1346    chrome::CloseWebContents(this, source);
1347}
1348
1349void Browser::MoveContents(WebContents* source, const gfx::Rect& pos) {
1350  if (!IsPopupOrPanel(source)) {
1351    NOTREACHED() << "moving invalid browser type";
1352    return;
1353  }
1354  window_->SetBounds(pos);
1355}
1356
1357bool Browser::IsPopupOrPanel(const WebContents* source) const {
1358  // A non-tabbed BROWSER is an unconstrained popup.
1359  return is_type_popup() || is_type_panel();
1360}
1361
1362void Browser::UpdateTargetURL(WebContents* source, int32 page_id,
1363                              const GURL& url) {
1364  if (!GetStatusBubble())
1365    return;
1366
1367  if (source == chrome::GetActiveWebContents(this)) {
1368    PrefService* prefs = profile_->GetPrefs();
1369    GetStatusBubble()->SetURL(url, prefs->GetString(prefs::kAcceptLanguages));
1370  }
1371}
1372
1373void Browser::ContentsMouseEvent(
1374    WebContents* source, const gfx::Point& location, bool motion) {
1375  if (!GetStatusBubble())
1376    return;
1377
1378  if (source == chrome::GetActiveWebContents(this)) {
1379    GetStatusBubble()->MouseMoved(location, !motion);
1380    if (!motion)
1381      GetStatusBubble()->SetURL(GURL(), std::string());
1382  }
1383}
1384
1385void Browser::ContentsZoomChange(bool zoom_in) {
1386  chrome::ExecuteCommand(this, zoom_in ? IDC_ZOOM_PLUS : IDC_ZOOM_MINUS);
1387}
1388
1389void Browser::WebContentsFocused(WebContents* contents) {
1390  window_->WebContentsFocused(contents);
1391}
1392
1393bool Browser::TakeFocus(content::WebContents* source,
1394                        bool reverse) {
1395  content::NotificationService::current()->Notify(
1396      chrome::NOTIFICATION_FOCUS_RETURNED_TO_BROWSER,
1397      content::Source<Browser>(this),
1398      content::NotificationService::NoDetails());
1399  return false;
1400}
1401
1402gfx::Rect Browser::GetRootWindowResizerRect() const {
1403  return window_->GetRootWindowResizerRect();
1404}
1405
1406void Browser::BeforeUnloadFired(WebContents* web_contents,
1407                                bool proceed,
1408                                bool* proceed_to_fire_unload) {
1409  *proceed_to_fire_unload =
1410      unload_controller_->BeforeUnloadFired(web_contents, proceed);
1411}
1412
1413void Browser::SetFocusToLocationBar(bool select_all) {
1414  // Two differences between this and FocusLocationBar():
1415  // (1) This doesn't get recorded in user metrics, since it's called
1416  //     internally.
1417  // (2) This checks whether the location bar can be focused, and if not, clears
1418  //     the focus.  FocusLocationBar() is only reached when the location bar is
1419  //     focusable, but this may be reached at other times, e.g. while in
1420  //     fullscreen mode, where we need to leave focus in a consistent state.
1421  window_->SetFocusToLocationBar(select_all);
1422}
1423
1424void Browser::RenderWidgetShowing() {
1425  window_->DisableInactiveFrame();
1426}
1427
1428int Browser::GetExtraRenderViewHeight() const {
1429  return window_->GetExtraRenderViewHeight();
1430}
1431
1432void Browser::OnStartDownload(WebContents* source,
1433                              content::DownloadItem* download) {
1434  if (!download_util::ShouldShowInShelf(download))
1435    return;
1436
1437  WebContents* constrained = GetConstrainingWebContents(source);
1438  if (constrained != source) {
1439    // Download in a constrained popup is shown in the tab that opened it.
1440    constrained->GetDelegate()->OnStartDownload(constrained, download);
1441    return;
1442  }
1443
1444  if (!window())
1445    return;
1446
1447  // GetDownloadShelf creates the download shelf if it was not yet created.
1448  DownloadShelf* shelf = window()->GetDownloadShelf();
1449  shelf->AddDownload(new DownloadItemModel(download));
1450  // Don't show the animation for "Save file" downloads.
1451  // For non-theme extensions, we don't show the download animation.
1452  // Show animation in same window as the download shelf. Download shelf
1453  // may not be in the same window that initiated the download.
1454  // Don't show the animation if the selected tab is not visible (i.e. the
1455  // window is minimized, we're in a unit test, etc.).
1456  WebContents* shelf_tab = chrome::GetActiveWebContents(shelf->browser());
1457  if ((download->GetTotalBytes() > 0) &&
1458      !download_crx_util::IsExtensionDownload(*download) &&
1459      platform_util::IsVisible(shelf_tab->GetNativeView()) &&
1460      ui::Animation::ShouldRenderRichAnimation()) {
1461    DownloadStartedAnimation::Show(shelf_tab);
1462  }
1463
1464  // If the download occurs in a new tab, and it's not a save page
1465  // download (started before initial navigation completed) close it.
1466  if (source->GetController().IsInitialNavigation() && tab_count() > 1 &&
1467      !download->IsSavePackageDownload())
1468    CloseContents(source);
1469}
1470
1471void Browser::ViewSourceForTab(WebContents* source, const GURL& page_url) {
1472  DCHECK(source);
1473  TabContents* tab_contents = chrome::GetTabContentsAt(this,
1474      tab_strip_model_->GetIndexOfWebContents(source));
1475  chrome::ViewSource(this, tab_contents);
1476}
1477
1478void Browser::ViewSourceForFrame(WebContents* source,
1479                                 const GURL& frame_url,
1480                                 const std::string& frame_content_state) {
1481  DCHECK(source);
1482  TabContents* tab_contents = chrome::GetTabContentsAt(this,
1483      tab_strip_model_->GetIndexOfWebContents(source));
1484  chrome::ViewSource(this, tab_contents, frame_url, frame_content_state);
1485}
1486
1487void Browser::ShowRepostFormWarningDialog(WebContents* source) {
1488  TabModalConfirmDialog::Create(new RepostFormWarningController(source),
1489                                source);
1490}
1491
1492bool Browser::ShouldCreateWebContents(
1493    WebContents* web_contents,
1494    int route_id,
1495    WindowContainerType window_container_type,
1496    const string16& frame_name,
1497    const GURL& target_url) {
1498  if (window_container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {
1499    // If a BackgroundContents is created, suppress the normal WebContents.
1500    return !MaybeCreateBackgroundContents(
1501        route_id, web_contents, frame_name, target_url);
1502  }
1503
1504  return true;
1505}
1506
1507void Browser::WebContentsCreated(WebContents* source_contents,
1508                                 int64 source_frame_id,
1509                                 const GURL& target_url,
1510                                 WebContents* new_contents) {
1511  // Adopt the WebContents now, so all observers are in place, as the network
1512  // requests for its initial navigation will start immediately. The WebContents
1513  // will later be inserted into this browser using Browser::Navigate via
1514  // AddNewContents.
1515  AdoptAsTabContents(new_contents);
1516
1517  // Notify.
1518  RetargetingDetails details;
1519  details.source_web_contents = source_contents;
1520  details.source_frame_id = source_frame_id;
1521  details.target_url = target_url;
1522  details.target_web_contents = new_contents;
1523  details.not_yet_in_tabstrip = true;
1524  content::NotificationService::current()->Notify(
1525      chrome::NOTIFICATION_RETARGETING,
1526      content::Source<Profile>(profile_),
1527      content::Details<RetargetingDetails>(&details));
1528}
1529
1530void Browser::ContentRestrictionsChanged(WebContents* source) {
1531  command_controller_->ContentRestrictionsChanged();
1532}
1533
1534void Browser::RendererUnresponsive(WebContents* source) {
1535  // Ignore hangs if print preview is open.
1536  TabContents* tab_contents = TabContents::FromWebContents(source);
1537  if (tab_contents) {
1538    printing::PrintPreviewTabController* controller =
1539        printing::PrintPreviewTabController::GetInstance();
1540    if (controller) {
1541      TabContents* preview_tab =
1542          controller->GetPrintPreviewForTab(tab_contents);
1543      if (preview_tab && preview_tab != tab_contents) {
1544        return;
1545      }
1546    }
1547  }
1548
1549  chrome::ShowHungRendererDialog(source);
1550}
1551
1552void Browser::RendererResponsive(WebContents* source) {
1553  chrome::HideHungRendererDialog(source);
1554}
1555
1556void Browser::WorkerCrashed(WebContents* source) {
1557  InfoBarTabHelper* infobar_helper =
1558      InfoBarTabHelper::FromWebContents(source);
1559  infobar_helper->AddInfoBar(new SimpleAlertInfoBarDelegate(
1560      infobar_helper,
1561      NULL,
1562      l10n_util::GetStringUTF16(IDS_WEBWORKER_CRASHED_PROMPT),
1563      true));
1564}
1565
1566void Browser::DidNavigateMainFramePostCommit(WebContents* web_contents) {
1567  if (web_contents == chrome::GetActiveWebContents(this))
1568    UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
1569}
1570
1571void Browser::DidNavigateToPendingEntry(WebContents* web_contents) {
1572  if (web_contents == chrome::GetActiveWebContents(this))
1573    UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
1574}
1575
1576content::JavaScriptDialogCreator* Browser::GetJavaScriptDialogCreator() {
1577  return GetJavaScriptDialogCreatorInstance();
1578}
1579
1580content::ColorChooser* Browser::OpenColorChooser(WebContents* web_contents,
1581                                                 int color_chooser_id,
1582                                                 SkColor color) {
1583#if defined(OS_WIN)
1584  // On Windows, only create a color chooser if one doesn't exist, because we
1585  // can't close the old color chooser dialog.
1586  if (!color_chooser_.get())
1587    color_chooser_.reset(content::ColorChooser::Create(color_chooser_id,
1588                                                       web_contents,
1589                                                       color));
1590#else
1591  if (color_chooser_.get())
1592    color_chooser_->End();
1593  color_chooser_.reset(content::ColorChooser::Create(color_chooser_id,
1594                                                     web_contents,
1595                                                     color));
1596#endif
1597  return color_chooser_.get();
1598}
1599
1600void Browser::DidEndColorChooser() {
1601  color_chooser_.reset();
1602}
1603
1604void Browser::RunFileChooser(WebContents* web_contents,
1605                             const content::FileChooserParams& params) {
1606  FileSelectHelper::RunFileChooser(web_contents, params);
1607}
1608
1609void Browser::EnumerateDirectory(WebContents* web_contents,
1610                                 int request_id,
1611                                 const FilePath& path) {
1612  FileSelectHelper::EnumerateDirectory(web_contents, request_id, path);
1613}
1614
1615void Browser::ToggleFullscreenModeForTab(WebContents* web_contents,
1616                                         bool enter_fullscreen) {
1617  fullscreen_controller_->ToggleFullscreenModeForTab(web_contents,
1618                                                     enter_fullscreen);
1619}
1620
1621bool Browser::IsFullscreenForTabOrPending(
1622    const WebContents* web_contents) const {
1623  return fullscreen_controller_->IsFullscreenForTabOrPending(web_contents);
1624}
1625
1626void Browser::JSOutOfMemory(WebContents* web_contents) {
1627  JSOutOfMemoryHelper(web_contents);
1628}
1629
1630void Browser::RegisterProtocolHandler(WebContents* web_contents,
1631                                      const std::string& protocol,
1632                                      const GURL& url,
1633                                      const string16& title,
1634                                      bool user_gesture) {
1635  RegisterProtocolHandlerHelper(
1636      web_contents, protocol, url, title, user_gesture, window());
1637}
1638
1639void Browser::RegisterIntentHandler(
1640    WebContents* web_contents,
1641    const webkit_glue::WebIntentServiceData& data,
1642    bool user_gesture) {
1643  RegisterIntentHandlerHelper(web_contents, data, user_gesture);
1644}
1645
1646void Browser::WebIntentDispatch(
1647    WebContents* web_contents,
1648    content::WebIntentsDispatcher* intents_dispatcher) {
1649  if (!web_intents::IsWebIntentsEnabledForProfile(profile_)) {
1650    web_intents::RecordIntentsDispatchDisabled();
1651    delete intents_dispatcher;
1652    return;
1653  }
1654
1655  // Make sure the requester is coming from an extension/app page.
1656  // Internal dispatches set |web_contents| to NULL.
1657#if !defined(OS_CHROMEOS)
1658  if (web_contents &&
1659      !CommandLine::ForCurrentProcess()->HasSwitch(
1660          switches::kWebIntentsInvocationEnabled)) {
1661    ExtensionService* extensions_service = profile_->GetExtensionService();
1662    if (!extensions_service ||
1663        extensions_service->extensions()->GetExtensionOrAppByURL(
1664            ExtensionURLInfo(web_contents->GetURL())) == NULL) {
1665      web_intents::RecordIntentsDispatchDisabled();
1666      intents_dispatcher->SendReplyMessage(
1667          webkit_glue::WEB_INTENT_REPLY_FAILURE,
1668          ASCIIToUTF16("Intents may only be invoked from extensions/apps."));
1669      return;
1670    }
1671  }
1672#else
1673  // ChromeOS currently uses a couple specific intent actions.
1674  // TODO(gbillock): delete this when we find good alternatives for those uses.
1675  if (intents_dispatcher->GetIntent().action !=
1676      ASCIIToUTF16(web_intents::kActionCrosEcho) &&
1677      intents_dispatcher->GetIntent().action !=
1678      ASCIIToUTF16(web_intents::kActionView)) {
1679    web_intents::RecordIntentsDispatchDisabled();
1680    intents_dispatcher->SendReplyMessage(
1681        webkit_glue::WEB_INTENT_REPLY_FAILURE,
1682        ASCIIToUTF16("Intents may only be invoked from extensions/apps."));
1683    return;
1684  }
1685#endif
1686
1687  web_intents::RecordIntentDispatchRequested();
1688
1689  if (!web_contents) {
1690    // Intent is system-caused and the picker will show over the currently
1691    // active web contents.
1692    web_contents = chrome::GetActiveWebContents(this);
1693  }
1694  WebIntentPickerController* web_intent_picker_controller =
1695      WebIntentPickerController::FromWebContents(web_contents);
1696  web_intent_picker_controller->SetIntentsDispatcher(intents_dispatcher);
1697  web_intent_picker_controller->ShowDialog(
1698      intents_dispatcher->GetIntent().action,
1699      intents_dispatcher->GetIntent().type);
1700}
1701
1702void Browser::UpdatePreferredSize(WebContents* source,
1703                                  const gfx::Size& pref_size) {
1704  window_->UpdatePreferredSize(source, pref_size);
1705}
1706
1707void Browser::ResizeDueToAutoResize(WebContents* source,
1708                                    const gfx::Size& new_size) {
1709  window_->ResizeDueToAutoResize(source, new_size);
1710}
1711
1712void Browser::FindReply(WebContents* web_contents,
1713                        int request_id,
1714                        int number_of_matches,
1715                        const gfx::Rect& selection_rect,
1716                        int active_match_ordinal,
1717                        bool final_update) {
1718  FindReplyHelper(web_contents, request_id, number_of_matches, selection_rect,
1719                  active_match_ordinal, final_update);
1720}
1721
1722void Browser::RequestToLockMouse(WebContents* web_contents,
1723                                 bool user_gesture,
1724                                 bool last_unlocked_by_target) {
1725  fullscreen_controller_->RequestToLockMouse(web_contents,
1726                                             user_gesture,
1727                                             last_unlocked_by_target);
1728}
1729
1730void Browser::LostMouseLock() {
1731  fullscreen_controller_->LostMouseLock();
1732}
1733
1734void Browser::RequestMediaAccessPermission(
1735    content::WebContents* web_contents,
1736    const content::MediaStreamRequest* request,
1737    const content::MediaResponseCallback& callback) {
1738  RequestMediaAccessPermissionHelper(web_contents, request, callback);
1739}
1740
1741///////////////////////////////////////////////////////////////////////////////
1742// Browser, CoreTabHelperDelegate implementation:
1743
1744void Browser::SwapTabContents(content::WebContents* old_contents,
1745                              content::WebContents* new_contents) {
1746  int index = tab_strip_model_->GetIndexOfWebContents(old_contents);
1747  DCHECK_NE(TabStripModel::kNoTab, index);
1748  TabContents* new_tab_contents = TabContents::FromWebContents(new_contents);
1749  tab_strip_model_->ReplaceTabContentsAt(index, new_tab_contents);
1750}
1751
1752bool Browser::CanReloadContents(content::WebContents* web_contents) const {
1753  return chrome::CanReload(this);
1754}
1755
1756bool Browser::CanSaveContents(content::WebContents* web_contents) const {
1757  return chrome::CanSavePage(this);
1758}
1759
1760///////////////////////////////////////////////////////////////////////////////
1761// Browser, SearchEngineTabHelperDelegate implementation:
1762
1763void Browser::ConfirmAddSearchProvider(TemplateURL* template_url,
1764                                       Profile* profile) {
1765  window()->ConfirmAddSearchProvider(template_url, profile);
1766}
1767
1768///////////////////////////////////////////////////////////////////////////////
1769// Browser, ConstrainedWindowTabHelperDelegate implementation:
1770
1771void Browser::SetTabContentBlocked(content::WebContents* web_contents,
1772                                   bool blocked) {
1773  int index = tab_strip_model_->GetIndexOfWebContents(web_contents);
1774  if (index == TabStripModel::kNoTab) {
1775    NOTREACHED();
1776    return;
1777  }
1778  tab_strip_model_->SetTabBlocked(index, blocked);
1779  command_controller_->PrintingStateChanged();
1780  command_controller_->FullscreenStateChanged();
1781  if (!blocked && chrome::GetActiveWebContents(this) == web_contents)
1782    web_contents->Focus();
1783}
1784
1785bool Browser::GetConstrainedWindowTopCenter(gfx::Point* point) {
1786  int y = 0;
1787  if (window_->GetConstrainedWindowTopY(&y)) {
1788    *point = gfx::Point(window_->GetBounds().width() / 2, y);
1789    return true;
1790  }
1791
1792  return false;
1793}
1794
1795///////////////////////////////////////////////////////////////////////////////
1796// Browser, BlockedContentTabHelperDelegate implementation:
1797
1798content::WebContents* Browser::GetConstrainingWebContents(
1799    content::WebContents* source) {
1800  return source;
1801}
1802
1803///////////////////////////////////////////////////////////////////////////////
1804// Browser, BookmarkTabHelperDelegate implementation:
1805
1806void Browser::URLStarredChanged(content::WebContents* web_contents,
1807                                bool starred) {
1808  if (web_contents == chrome::GetActiveWebContents(this))
1809    window_->SetStarredState(starred);
1810}
1811
1812///////////////////////////////////////////////////////////////////////////////
1813// Browser, ZoomObserver implementation:
1814
1815void Browser::OnZoomChanged(content::WebContents* source,
1816                            bool can_show_bubble) {
1817  if (source == chrome::GetActiveWebContents(this)) {
1818    // Only show the zoom bubble for zoom changes in the active window.
1819    window_->ZoomChangedForActiveTab(can_show_bubble && window_->IsActive());
1820  }
1821}
1822
1823///////////////////////////////////////////////////////////////////////////////
1824// Browser, ui::SelectFileDialog::Listener implementation:
1825
1826void Browser::FileSelected(const FilePath& path, int index, void* params) {
1827  FileSelectedWithExtraInfo(ui::SelectedFileInfo(path, path), index, params);
1828}
1829
1830void Browser::FileSelectedWithExtraInfo(
1831    const ui::SelectedFileInfo& file_info,
1832    int index,
1833    void* params) {
1834  profile_->set_last_selected_directory(file_info.file_path.DirName());
1835
1836  const FilePath& path = file_info.local_path;
1837  GURL file_url = net::FilePathToFileURL(path);
1838
1839#if defined(OS_CHROMEOS)
1840  drive::util::ModifyDriveFileResourceUrl(profile_, path, &file_url);
1841#endif
1842
1843  if (file_url.is_empty())
1844    return;
1845
1846  OpenURL(OpenURLParams(
1847      file_url, Referrer(), CURRENT_TAB, content::PAGE_TRANSITION_TYPED,
1848      false));
1849}
1850
1851///////////////////////////////////////////////////////////////////////////////
1852// Browser, content::NotificationObserver implementation:
1853
1854void Browser::Observe(int type,
1855                      const content::NotificationSource& source,
1856                      const content::NotificationDetails& details) {
1857  switch (type) {
1858    case content::NOTIFICATION_SSL_VISIBLE_STATE_CHANGED:
1859      // When the current tab's SSL state changes, we need to update the URL
1860      // bar to reflect the new state. Note that it's possible for the selected
1861      // tab contents to be NULL. This is because we listen for all sources
1862      // (NavigationControllers) for convenience, so the notification could
1863      // actually be for a different window while we're doing asynchronous
1864      // closing of this one.
1865      if (chrome::GetActiveWebContents(this) &&
1866          &chrome::GetActiveWebContents(this)->GetController() ==
1867          content::Source<NavigationController>(source).ptr())
1868        UpdateToolbar(false);
1869      break;
1870
1871    case chrome::NOTIFICATION_EXTENSION_UNLOADED: {
1872      if (window()->GetLocationBar())
1873        window()->GetLocationBar()->UpdatePageActions();
1874
1875      // Close any tabs from the unloaded extension, unless it's terminated,
1876      // in which case let the sad tabs remain.
1877      if (content::Details<extensions::UnloadedExtensionInfo>(
1878            details)->reason != extension_misc::UNLOAD_REASON_TERMINATE) {
1879        const Extension* extension =
1880            content::Details<extensions::UnloadedExtensionInfo>(
1881                details)->extension;
1882        for (int i = tab_strip_model_->count() - 1; i >= 0; --i) {
1883          WebContents* tc = chrome::GetTabContentsAt(this, i)->web_contents();
1884          if (tc->GetURL().SchemeIs(chrome::kExtensionScheme) &&
1885              tc->GetURL().host() == extension->id())
1886            chrome::CloseWebContents(this, tc);
1887        }
1888      }
1889      break;
1890    }
1891
1892    case chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED: {
1893      Profile* profile = content::Source<Profile>(source).ptr();
1894      if (profile_->IsSameProfile(profile) && window()->GetLocationBar())
1895        window()->GetLocationBar()->InvalidatePageActions();
1896      break;
1897    }
1898
1899    case chrome::NOTIFICATION_EXTENSION_UNINSTALLED:
1900    case chrome::NOTIFICATION_EXTENSION_LOADED:
1901      // During window creation on Windows we may end up calling into
1902      // SHAppBarMessage, which internally spawns a nested message loop. This
1903      // makes it possible for us to end up here before window creation has
1904      // completed,at which point window_ is NULL. See 94752 for details.
1905      if (window() && window()->GetLocationBar())
1906        window()->GetLocationBar()->UpdatePageActions();
1907      break;
1908
1909#if defined(ENABLE_THEMES)
1910    case chrome::NOTIFICATION_BROWSER_THEME_CHANGED:
1911      window()->UserChangedTheme();
1912      break;
1913#endif
1914
1915    case chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED: {
1916      WebContents* web_contents = content::Source<WebContents>(source).ptr();
1917      if (web_contents == chrome::GetActiveWebContents(this)) {
1918        LocationBar* location_bar = window()->GetLocationBar();
1919        if (location_bar)
1920          location_bar->UpdateContentSettingsIcons();
1921      }
1922      break;
1923    }
1924
1925    case content::NOTIFICATION_INTERSTITIAL_ATTACHED:
1926      UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
1927      break;
1928
1929    case content::NOTIFICATION_INTERSTITIAL_DETACHED:
1930      UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
1931      break;
1932
1933    default:
1934      NOTREACHED() << "Got a notification we didn't register for.";
1935  }
1936}
1937
1938void Browser::OnPreferenceChanged(PrefServiceBase* service,
1939                                  const std::string& pref_name) {
1940  if (pref_name == prefs::kDevToolsDisabled) {
1941    if (profile_->GetPrefs()->GetBoolean(prefs::kDevToolsDisabled))
1942      content::DevToolsManager::GetInstance()->CloseAllClientHosts();
1943  } else if (pref_name == prefs::kShowBookmarkBar) {
1944    UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE);
1945  } else if (pref_name == prefs::kHomePage) {
1946    MarkHomePageAsChanged(static_cast<PrefService*>(service));
1947  } else {
1948    NOTREACHED();
1949  }
1950}
1951
1952void Browser::ModeChanged(const chrome::search::Mode& old_mode,
1953                          const chrome::search::Mode& new_mode) {
1954  UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE);
1955}
1956
1957///////////////////////////////////////////////////////////////////////////////
1958// Browser, Command and state updating (private):
1959
1960void Browser::MarkHomePageAsChanged(PrefService* pref_service) {
1961  pref_service->SetBoolean(prefs::kHomePageChanged, true);
1962}
1963
1964///////////////////////////////////////////////////////////////////////////////
1965// Browser, UI update coalescing and handling (private):
1966
1967void Browser::UpdateToolbar(bool should_restore_state) {
1968  window_->UpdateToolbar(chrome::GetActiveTabContents(this),
1969                         should_restore_state);
1970}
1971
1972void Browser::UpdateSearchState(TabContents* contents) {
1973  if (chrome::search::IsInstantExtendedAPIEnabled(profile_))
1974    search_delegate_->OnTabActivated(contents->web_contents());
1975}
1976
1977void Browser::ScheduleUIUpdate(const WebContents* source,
1978                               unsigned changed_flags) {
1979  if (!source)
1980    return;
1981
1982  // Do some synchronous updates.
1983  if (changed_flags & content::INVALIDATE_TYPE_URL &&
1984      source == chrome::GetActiveWebContents(this)) {
1985    // Only update the URL for the current tab. Note that we do not update
1986    // the navigation commands since those would have already been updated
1987    // synchronously by NavigationStateChanged.
1988    UpdateToolbar(false);
1989    changed_flags &= ~content::INVALIDATE_TYPE_URL;
1990  }
1991  if (changed_flags & content::INVALIDATE_TYPE_LOAD) {
1992    // Update the loading state synchronously. This is so the throbber will
1993    // immediately start/stop, which gives a more snappy feel. We want to do
1994    // this for any tab so they start & stop quickly.
1995    tab_strip_model_->UpdateTabContentsStateAt(
1996        chrome::GetIndexOfTab(this, source),
1997        TabStripModelObserver::LOADING_ONLY);
1998    // The status bubble needs to be updated during INVALIDATE_TYPE_LOAD too,
1999    // but we do that asynchronously by not stripping INVALIDATE_TYPE_LOAD from
2000    // changed_flags.
2001  }
2002
2003  if (changed_flags & content::INVALIDATE_TYPE_TITLE && !source->IsLoading()) {
2004    // To correctly calculate whether the title changed while not loading
2005    // we need to process the update synchronously. This state only matters for
2006    // the TabStripModel, so we notify the TabStripModel now and notify others
2007    // asynchronously.
2008    tab_strip_model_->UpdateTabContentsStateAt(
2009        chrome::GetIndexOfTab(this, source),
2010        TabStripModelObserver::TITLE_NOT_LOADING);
2011  }
2012
2013  // If the only updates were synchronously handled above, we're done.
2014  if (changed_flags == 0)
2015    return;
2016
2017  // Save the dirty bits.
2018  scheduled_updates_[source] |= changed_flags;
2019
2020  if (!chrome_updater_factory_.HasWeakPtrs()) {
2021    // No task currently scheduled, start another.
2022    MessageLoop::current()->PostDelayedTask(
2023        FROM_HERE,
2024        base::Bind(&Browser::ProcessPendingUIUpdates,
2025                   chrome_updater_factory_.GetWeakPtr()),
2026        base::TimeDelta::FromMilliseconds(kUIUpdateCoalescingTimeMS));
2027  }
2028}
2029
2030void Browser::ProcessPendingUIUpdates() {
2031#ifndef NDEBUG
2032  // Validate that all tabs we have pending updates for exist. This is scary
2033  // because the pending list must be kept in sync with any detached or
2034  // deleted tabs.
2035  for (UpdateMap::const_iterator i = scheduled_updates_.begin();
2036       i != scheduled_updates_.end(); ++i) {
2037    bool found = false;
2038    for (int tab = 0; tab < tab_count(); tab++) {
2039      if (chrome::GetWebContentsAt(this, tab) == i->first) {
2040        found = true;
2041        break;
2042      }
2043    }
2044    DCHECK(found);
2045  }
2046#endif
2047
2048  chrome_updater_factory_.InvalidateWeakPtrs();
2049
2050  for (UpdateMap::const_iterator i = scheduled_updates_.begin();
2051       i != scheduled_updates_.end(); ++i) {
2052    // Do not dereference |contents|, it may be out-of-date!
2053    const WebContents* contents = i->first;
2054    unsigned flags = i->second;
2055
2056    if (contents == chrome::GetActiveWebContents(this)) {
2057      // Updates that only matter when the tab is selected go here.
2058
2059      if (flags & content::INVALIDATE_TYPE_PAGE_ACTIONS) {
2060        LocationBar* location_bar = window()->GetLocationBar();
2061        if (location_bar)
2062          location_bar->UpdatePageActions();
2063      }
2064      // Updating the URL happens synchronously in ScheduleUIUpdate.
2065      if (flags & content::INVALIDATE_TYPE_LOAD && GetStatusBubble()) {
2066        GetStatusBubble()->SetStatus(
2067            CoreTabHelper::FromWebContents(chrome::GetActiveWebContents(this))->
2068                GetStatusText());
2069      }
2070
2071      if (flags & (content::INVALIDATE_TYPE_TAB |
2072                   content::INVALIDATE_TYPE_TITLE)) {
2073        window_->UpdateTitleBar();
2074      }
2075    }
2076
2077    // Updates that don't depend upon the selected state go here.
2078    if (flags &
2079        (content::INVALIDATE_TYPE_TAB | content::INVALIDATE_TYPE_TITLE)) {
2080      tab_strip_model_->UpdateTabContentsStateAt(
2081          tab_strip_model_->GetIndexOfWebContents(contents),
2082          TabStripModelObserver::ALL);
2083    }
2084
2085    // We don't need to process INVALIDATE_STATE, since that's not visible.
2086  }
2087
2088  scheduled_updates_.clear();
2089}
2090
2091void Browser::RemoveScheduledUpdatesFor(WebContents* contents) {
2092  if (!contents)
2093    return;
2094
2095  UpdateMap::iterator i = scheduled_updates_.find(contents);
2096  if (i != scheduled_updates_.end())
2097    scheduled_updates_.erase(i);
2098}
2099
2100
2101///////////////////////////////////////////////////////////////////////////////
2102// Browser, Getters for UI (private):
2103
2104StatusBubble* Browser::GetStatusBubble() {
2105  // In kiosk mode, we want to always hide the status bubble.
2106  if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kKioskMode))
2107    return NULL;
2108  return window_ ? window_->GetStatusBubble() : NULL;
2109}
2110
2111///////////////////////////////////////////////////////////////////////////////
2112// Browser, Session restore functions (private):
2113
2114void Browser::SyncHistoryWithTabs(int index) {
2115  SessionService* session_service =
2116      SessionServiceFactory::GetForProfileIfExisting(profile());
2117  if (session_service) {
2118    for (int i = index; i < tab_count(); ++i) {
2119      WebContents* web_contents = chrome::GetWebContentsAt(this, i);
2120      if (web_contents) {
2121        SessionTabHelper* session_tab_helper =
2122            SessionTabHelper::FromWebContents(web_contents);
2123        session_service->SetTabIndexInWindow(
2124            session_id(), session_tab_helper->session_id(), i);
2125        session_service->SetPinnedState(
2126            session_id(),
2127            session_tab_helper->session_id(),
2128            tab_strip_model_->IsTabPinned(i));
2129      }
2130    }
2131  }
2132}
2133
2134///////////////////////////////////////////////////////////////////////////////
2135// Browser, In-progress download termination handling (private):
2136
2137bool Browser::CanCloseWithInProgressDownloads() {
2138  // If we've prompted, we need to hear from the user before we
2139  // can close.
2140  if (cancel_download_confirmation_state_ != NOT_PROMPTED)
2141    return cancel_download_confirmation_state_ != WAITING_FOR_RESPONSE;
2142
2143  int num_downloads_blocking;
2144  if (DOWNLOAD_CLOSE_OK ==
2145      OkToCloseWithInProgressDownloads(&num_downloads_blocking))
2146    return true;
2147
2148  // Closing this window will kill some downloads; prompt to make sure
2149  // that's ok.
2150  cancel_download_confirmation_state_ = WAITING_FOR_RESPONSE;
2151  window_->ConfirmBrowserCloseWithPendingDownloads();
2152
2153  // Return false so the browser does not close.  We'll close if the user
2154  // confirms in the dialog.
2155  return false;
2156}
2157
2158///////////////////////////////////////////////////////////////////////////////
2159// Browser, Assorted utility functions (private):
2160
2161void Browser::CloseFrame() {
2162  window_->Close();
2163}
2164
2165void Browser::TabDetachedAtImpl(content::WebContents* contents,
2166                                int index,
2167                                DetachType type) {
2168  if (type == DETACH_TYPE_DETACH) {
2169    // Save the current location bar state, but only if the tab being detached
2170    // is the selected tab.  Because saving state can conditionally revert the
2171    // location bar, saving the current tab's location bar state to a
2172    // non-selected tab can corrupt both tabs.
2173    if (contents == chrome::GetActiveWebContents(this)) {
2174      LocationBar* location_bar = window()->GetLocationBar();
2175      if (location_bar)
2176        location_bar->SaveStateToContents(contents);
2177    }
2178
2179    if (!tab_strip_model_->closing_all())
2180      SyncHistoryWithTabs(0);
2181  }
2182
2183  SetAsDelegate(contents, NULL);
2184  RemoveScheduledUpdatesFor(contents);
2185
2186  if (find_bar_controller_.get() && index == active_index()) {
2187    find_bar_controller_->ChangeWebContents(NULL);
2188  }
2189
2190  // Stop observing search model changes for this tab.
2191  search_delegate_->OnTabDetached(contents);
2192
2193  registrar_.Remove(this, content::NOTIFICATION_INTERSTITIAL_ATTACHED,
2194                    content::Source<WebContents>(contents));
2195  registrar_.Remove(this, content::NOTIFICATION_INTERSTITIAL_DETACHED,
2196                    content::Source<WebContents>(contents));
2197}
2198
2199bool Browser::SupportsWindowFeatureImpl(WindowFeature feature,
2200                                        bool check_fullscreen) const {
2201  // On Mac, fullscreen mode has most normal things (in a slide-down panel). On
2202  // other platforms, we hide some controls when in fullscreen mode.
2203  bool hide_ui_for_fullscreen = false;
2204#if !defined(OS_MACOSX)
2205  hide_ui_for_fullscreen = check_fullscreen && window_ &&
2206      window_->IsFullscreen();
2207#endif
2208
2209  unsigned int features = FEATURE_INFOBAR | FEATURE_DOWNLOADSHELF;
2210
2211  if (is_type_tabbed())
2212    features |= FEATURE_BOOKMARKBAR;
2213
2214  if (!hide_ui_for_fullscreen) {
2215    if (!is_type_tabbed())
2216      features |= FEATURE_TITLEBAR;
2217
2218    if (is_type_tabbed())
2219      features |= FEATURE_TABSTRIP;
2220
2221    if (is_type_tabbed())
2222      features |= FEATURE_TOOLBAR;
2223
2224    if (!is_app())
2225      features |= FEATURE_LOCATIONBAR;
2226  }
2227  return !!(features & feature);
2228}
2229
2230void Browser::UpdateBookmarkBarState(BookmarkBarStateChangeReason reason) {
2231  BookmarkBar::State state;
2232  // The bookmark bar is hidden in fullscreen mode, unless on the new tab page.
2233  if (browser_defaults::bookmarks_enabled &&
2234      profile_->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar) &&
2235      (!window_ || !window_->IsFullscreen())) {
2236    // Always show detached mode if search mode is |NTP|.
2237    state = search_model_->mode().is_ntp() ?
2238        BookmarkBar::DETACHED : BookmarkBar::SHOW;
2239  } else {
2240    WebContents* web_contents = chrome::GetActiveWebContents(this);
2241    BookmarkTabHelper* bookmark_tab_helper =
2242        web_contents ? BookmarkTabHelper::FromWebContents(web_contents) : NULL;
2243    if (bookmark_tab_helper && bookmark_tab_helper->ShouldShowBookmarkBar())
2244      state = BookmarkBar::DETACHED;
2245    else
2246      state = BookmarkBar::HIDDEN;
2247  }
2248
2249  // Don't allow the bookmark bar to be shown in suggestions mode.
2250  if (search_model_->mode().is_search_suggestions())
2251    state = BookmarkBar::HIDDEN;
2252
2253  if (state == bookmark_bar_state_)
2254    return;
2255
2256  bookmark_bar_state_ = state;
2257
2258  if (!window_)
2259    return;  // This is called from the constructor when window_ is NULL.
2260
2261  if (reason == BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH) {
2262    // Don't notify BrowserWindow on a tab switch as at the time this is invoked
2263    // BrowserWindow hasn't yet switched tabs. The BrowserWindow implementations
2264    // end up querying state once they process the tab switch.
2265    return;
2266  }
2267
2268  BookmarkBar::AnimateChangeType animate_type =
2269      (reason == BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE) ?
2270      BookmarkBar::ANIMATE_STATE_CHANGE :
2271      BookmarkBar::DONT_ANIMATE_STATE_CHANGE;
2272  window_->BookmarkBarStateChanged(animate_type);
2273}
2274
2275bool Browser::MaybeCreateBackgroundContents(int route_id,
2276                                            WebContents* opener_web_contents,
2277                                            const string16& frame_name,
2278                                            const GURL& target_url) {
2279  GURL opener_url = opener_web_contents->GetURL();
2280  ExtensionService* extensions_service = profile_->GetExtensionService();
2281
2282  if (!opener_url.is_valid() ||
2283      frame_name.empty() ||
2284      !extensions_service ||
2285      !extensions_service->is_ready())
2286    return false;
2287
2288  // Only hosted apps have web extents, so this ensures that only hosted apps
2289  // can create BackgroundContents. We don't have to check for background
2290  // permission as that is checked in RenderMessageFilter when the CreateWindow
2291  // message is processed.
2292  const Extension* extension =
2293      extensions_service->extensions()->GetHostedAppByURL(
2294          ExtensionURLInfo(opener_url));
2295  if (!extension)
2296    return false;
2297
2298  // No BackgroundContents allowed if BackgroundContentsService doesn't exist.
2299  BackgroundContentsService* service =
2300      BackgroundContentsServiceFactory::GetForProfile(profile_);
2301  if (!service)
2302    return false;
2303
2304  // Ensure that we're trying to open this from the extension's process.
2305  SiteInstance* opener_site_instance = opener_web_contents->GetSiteInstance();
2306  extensions::ProcessMap* process_map = extensions_service->process_map();
2307  if (!opener_site_instance->GetProcess() ||
2308      !process_map->Contains(
2309          extension->id(), opener_site_instance->GetProcess()->GetID())) {
2310    return false;
2311  }
2312
2313  // Only allow a single background contents per app.
2314  bool allow_js_access = extension->allow_background_js_access();
2315  BackgroundContents* existing =
2316      service->GetAppBackgroundContents(ASCIIToUTF16(extension->id()));
2317  if (existing) {
2318    // For non-scriptable background contents, ignore the request altogether,
2319    // (returning true, so that a regular WebContents isn't created either).
2320    if (!allow_js_access)
2321      return true;
2322    // For scriptable background pages, if one already exists, close it (even
2323    // if it was specified in the manifest).
2324    DLOG(INFO) << "Closing existing BackgroundContents for " << opener_url;
2325    delete existing;
2326  }
2327
2328  // If script access is not allowed, create the the background contents in a
2329  // new SiteInstance, so that a separate process is used.
2330  scoped_refptr<content::SiteInstance> site_instance =
2331      allow_js_access ?
2332      opener_site_instance :
2333      content::SiteInstance::Create(opener_web_contents->GetBrowserContext());
2334
2335  // Passed all the checks, so this should be created as a BackgroundContents.
2336  BackgroundContents* contents = service->CreateBackgroundContents(
2337      site_instance,
2338      route_id,
2339      profile_,
2340      frame_name,
2341      ASCIIToUTF16(extension->id()));
2342
2343  // When a separate process is used, the original renderer cannot access the
2344  // new window later, thus we need to navigate the window now.
2345  if (contents && !allow_js_access) {
2346    contents->web_contents()->GetController().LoadURL(
2347        target_url,
2348        content::Referrer(),
2349        content::PAGE_TRANSITION_LINK,
2350        std::string());  // No extra headers.
2351  }
2352
2353  return contents != NULL;
2354}
2355