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