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