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