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