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