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