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.
5 #include "chrome/browser/ui/browser.h"
10 #endif // defined(OS_WIN)
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/custom_handlers/register_protocol_handler_permission_request.h"
48 #include "chrome/browser/defaults.h"
49 #include "chrome/browser/devtools/devtools_toggle_action.h"
50 #include "chrome/browser/devtools/devtools_window.h"
51 #include "chrome/browser/download/download_item_model.h"
52 #include "chrome/browser/download/download_service.h"
53 #include "chrome/browser/download/download_service_factory.h"
54 #include "chrome/browser/download/download_shelf.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/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/translate/translate_tab_helper.h"
89 #include "chrome/browser/ui/app_modal_dialogs/javascript_dialog_manager.h"
90 #include "chrome/browser/ui/autofill/tab_autofill_manager_delegate.h"
91 #include "chrome/browser/ui/blocked_content/popup_blocker_tab_helper.h"
92 #include "chrome/browser/ui/bookmarks/bookmark_tab_helper.h"
93 #include "chrome/browser/ui/browser_command_controller.h"
94 #include "chrome/browser/ui/browser_commands.h"
95 #include "chrome/browser/ui/browser_content_setting_bubble_model_delegate.h"
96 #include "chrome/browser/ui/browser_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/media_utils.h"
120 #include "chrome/browser/ui/omnibox/location_bar.h"
121 #include "chrome/browser/ui/search/search_delegate.h"
122 #include "chrome/browser/ui/search/search_model.h"
123 #include "chrome/browser/ui/search/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/dock_info.h"
132 #include "chrome/browser/ui/tabs/tab_menu_model.h"
133 #include "chrome/browser/ui/tabs/tab_strip_model.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/web_applications/web_app_ui.h"
138 #include "chrome/browser/ui/website_settings/permission_bubble_manager.h"
139 #include "chrome/browser/ui/webui/signin/login_ui_service.h"
140 #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h"
141 #include "chrome/browser/ui/window_sizer/window_sizer.h"
142 #include "chrome/browser/ui/zoom/zoom_controller.h"
143 #include "chrome/browser/upgrade_detector.h"
144 #include "chrome/browser/web_applications/web_app.h"
145 #include "chrome/common/chrome_constants.h"
146 #include "chrome/common/chrome_switches.h"
147 #include "chrome/common/custom_handlers/protocol_handler.h"
148 #include "chrome/common/net/url_fixer_upper.h"
149 #include "chrome/common/pref_names.h"
150 #include "chrome/common/profiling.h"
151 #include "chrome/common/search_types.h"
152 #include "chrome/common/url_constants.h"
153 #include "components/startup_metric_utils/startup_metric_utils.h"
154 #include "components/web_modal/web_contents_modal_dialog_manager.h"
155 #include "content/public/browser/devtools_manager.h"
156 #include "content/public/browser/download_item.h"
157 #include "content/public/browser/download_manager.h"
158 #include "content/public/browser/interstitial_page.h"
159 #include "content/public/browser/invalidate_type.h"
160 #include "content/public/browser/navigation_controller.h"
161 #include "content/public/browser/navigation_entry.h"
162 #include "content/public/browser/notification_details.h"
163 #include "content/public/browser/notification_service.h"
164 #include "content/public/browser/plugin_service.h"
165 #include "content/public/browser/render_process_host.h"
166 #include "content/public/browser/render_view_host.h"
167 #include "content/public/browser/render_widget_host_view.h"
168 #include "content/public/browser/site_instance.h"
169 #include "content/public/browser/user_metrics.h"
170 #include "content/public/browser/web_contents.h"
171 #include "content/public/browser/web_contents_view.h"
172 #include "content/public/common/content_switches.h"
173 #include "content/public/common/page_zoom.h"
174 #include "content/public/common/renderer_preferences.h"
175 #include "content/public/common/webplugininfo.h"
176 #include "extensions/browser/extension_prefs.h"
177 #include "extensions/browser/extension_system.h"
178 #include "extensions/common/constants.h"
179 #include "extensions/common/extension.h"
180 #include "extensions/common/manifest_handlers/background_info.h"
181 #include "grit/chromium_strings.h"
182 #include "grit/generated_resources.h"
183 #include "grit/locale_settings.h"
184 #include "grit/theme_resources.h"
185 #include "net/base/net_util.h"
186 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
187 #include "net/cookies/cookie_monster.h"
188 #include "net/url_request/url_request_context.h"
189 #include "third_party/WebKit/public/web/WebWindowFeatures.h"
190 #include "ui/base/l10n/l10n_util.h"
191 #include "ui/base/window_open_disposition.h"
192 #include "ui/gfx/point.h"
193 #include "ui/shell_dialogs/selected_file_info.h"
196 #include "base/win/metro.h"
197 #include "chrome/browser/ssl/ssl_error_info.h"
198 #include "chrome/browser/task_manager/task_manager.h"
199 #include "chrome/browser/ui/view_ids.h"
200 #include "components/autofill/core/browser/autofill_ie_toolbar_import_win.h"
201 #include "ui/base/win/shell.h"
204 #if defined(OS_CHROMEOS)
205 #include "chrome/browser/chromeos/drive/file_system_util.h"
209 #include "ash/ash_switches.h"
212 using base::TimeDelta
;
213 using base::UserMetricsAction
;
214 using content::NativeWebKeyboardEvent
;
215 using content::NavigationController
;
216 using content::NavigationEntry
;
217 using content::OpenURLParams
;
218 using content::PluginService
;
219 using content::Referrer
;
220 using content::RenderWidgetHostView
;
221 using content::SiteInstance
;
222 using content::WebContents
;
223 using extensions::Extension
;
224 using ui::WebDialogDelegate
;
225 using web_modal::WebContentsModalDialogManager
;
226 using blink::WebWindowFeatures
;
228 ///////////////////////////////////////////////////////////////////////////////
232 // How long we wait before updating the browser chrome while loading a page.
233 const int kUIUpdateCoalescingTimeMS
= 200;
235 BrowserWindow
* CreateBrowserWindow(Browser
* browser
) {
236 return BrowserWindow::CreateBrowserWindow(browser
);
239 // Is the fast tab unload experiment enabled?
240 bool IsFastTabUnloadEnabled() {
241 return CommandLine::ForCurrentProcess()->HasSwitch(
242 switches::kEnableFastUnload
);
247 ////////////////////////////////////////////////////////////////////////////////
248 // Browser, CreateParams:
250 Browser::CreateParams::CreateParams(Profile
* profile
,
251 chrome::HostDesktopType host_desktop_type
)
254 host_desktop_type(host_desktop_type
),
255 app_type(APP_TYPE_HOST
),
256 initial_show_state(ui::SHOW_STATE_DEFAULT
),
257 is_session_restore(false),
261 Browser::CreateParams::CreateParams(Type type
,
263 chrome::HostDesktopType host_desktop_type
)
266 host_desktop_type(host_desktop_type
),
267 app_type(APP_TYPE_HOST
),
268 initial_show_state(ui::SHOW_STATE_DEFAULT
),
269 is_session_restore(false),
274 Browser::CreateParams
Browser::CreateParams::CreateForApp(
276 const std::string
& app_name
,
277 const gfx::Rect
& window_bounds
,
279 chrome::HostDesktopType host_desktop_type
) {
280 DCHECK(type
!= TYPE_TABBED
);
281 DCHECK(!app_name
.empty());
283 CreateParams
params(type
, profile
, host_desktop_type
);
284 params
.app_name
= app_name
;
285 params
.app_type
= APP_TYPE_CHILD
;
286 params
.initial_bounds
= window_bounds
;
292 Browser::CreateParams
Browser::CreateParams::CreateForDevTools(
294 chrome::HostDesktopType host_desktop_type
) {
295 CreateParams
params(TYPE_POPUP
, profile
, host_desktop_type
);
296 params
.app_name
= DevToolsWindow::kDevToolsApp
;
300 ////////////////////////////////////////////////////////////////////////////////
301 // Browser, InterstitialObserver:
303 class Browser::InterstitialObserver
: public content::WebContentsObserver
{
305 InterstitialObserver(Browser
* browser
, content::WebContents
* web_contents
)
306 : WebContentsObserver(web_contents
),
310 using content::WebContentsObserver::web_contents
;
312 virtual void DidAttachInterstitialPage() OVERRIDE
{
313 browser_
->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE
);
316 virtual void DidDetachInterstitialPage() OVERRIDE
{
317 browser_
->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE
);
323 DISALLOW_COPY_AND_ASSIGN(InterstitialObserver
);
326 ///////////////////////////////////////////////////////////////////////////////
327 // Browser, Constructors, Creation, Showing:
329 Browser::Browser(const CreateParams
& params
)
330 : type_(params
.type
),
331 profile_(params
.profile
),
333 tab_strip_model_delegate_(new chrome::BrowserTabStripModelDelegate(this)),
334 tab_strip_model_(new TabStripModel(tab_strip_model_delegate_
.get(),
336 app_name_(params
.app_name
),
337 app_type_(params
.app_type
),
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_(BrowserWindow::AdjustHostDesktopType(
343 params
.host_desktop_type
)),
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 chrome_updater_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";
364 // TODO(jeremy): Move to initializer list once flag is removed.
365 if (IsFastTabUnloadEnabled())
366 fast_unload_controller_
.reset(new chrome::FastUnloadController(this));
368 unload_controller_
.reset(new chrome::UnloadController(this));
370 if (!app_name_
.empty())
371 chrome::RegisterAppPrefs(app_name_
, profile_
);
372 tab_strip_model_
->AddObserver(this);
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()));
378 registrar_
.Add(this, chrome::NOTIFICATION_EXTENSION_LOADED
,
379 content::Source
<Profile
>(profile_
->GetOriginalProfile()));
380 registrar_
.Add(this, chrome::NOTIFICATION_EXTENSION_UNLOADED
,
381 content::Source
<Profile
>(profile_
->GetOriginalProfile()));
382 registrar_
.Add(this, chrome::NOTIFICATION_EXTENSION_UNINSTALLED
,
383 content::Source
<Profile
>(profile_
->GetOriginalProfile()));
384 registrar_
.Add(this, chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED
,
385 content::NotificationService::AllSources());
386 #if defined(ENABLE_THEMES)
388 this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED
,
389 content::Source
<ThemeService
>(
390 ThemeServiceFactory::GetForProfile(profile_
)));
392 registrar_
.Add(this, chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED
,
393 content::NotificationService::AllSources());
395 profile_pref_registrar_
.Init(profile_
->GetPrefs());
396 profile_pref_registrar_
.Add(
397 prefs::kDevToolsDisabled
,
398 base::Bind(&Browser::OnDevToolsDisabledChanged
, base::Unretained(this)));
399 profile_pref_registrar_
.Add(
400 prefs::kShowBookmarkBar
,
401 base::Bind(&Browser::UpdateBookmarkBarState
, base::Unretained(this),
402 BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE
));
404 BrowserList::AddBrowser(this);
406 // NOTE: These prefs all need to be explicitly destroyed in the destructor
407 // or you'll get a nasty surprise when you run the incognito tests.
408 encoding_auto_detect_
.Init(prefs::kWebKitUsesUniversalDetector
,
409 profile_
->GetPrefs());
411 if (chrome::IsInstantExtendedAPIEnabled() && is_type_tabbed())
412 instant_controller_
.reset(new BrowserInstantController(this));
414 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_INIT
);
416 ProfileMetrics::LogProfileLaunch(profile_
);
418 window_
= params
.window
? params
.window
: CreateBrowserWindow(this);
420 // Create the extension window controller before sending notifications.
421 extension_window_controller_
.reset(
422 new BrowserExtensionWindowController(this));
424 SessionService
* session_service
=
425 SessionServiceFactory::GetForProfileForSessionRestore(profile_
);
427 session_service
->WindowOpened(this);
429 // TODO(beng): Move BrowserList::AddBrowser() to the end of this function and
430 // replace uses of this with BL's notifications.
431 content::NotificationService::current()->Notify(
432 chrome::NOTIFICATION_BROWSER_WINDOW_READY
,
433 content::Source
<Browser
>(this),
434 content::NotificationService::NoDetails());
436 // TODO(beng): move to ChromeBrowserMain:
437 if (first_run::ShouldDoPersonalDataManagerFirstRun()) {
439 // Notify PDM that this is a first run.
440 ImportAutofillDataWin(
441 autofill::PersonalDataManagerFactory::GetForProfile(profile_
));
442 #endif // defined(OS_WIN)
445 fullscreen_controller_
.reset(new FullscreenController(this));
448 Browser::~Browser() {
449 // The tab strip should not have any tabs at this point.
450 if (!browser_shutdown::ShuttingDownWithoutClosingBrowsers())
451 DCHECK(tab_strip_model_
->empty());
453 tab_strip_model_
->RemoveObserver(this);
455 // Destroy the BrowserCommandController before removing the browser, so that
456 // it doesn't act on any notifications that are sent as a result of removing
458 command_controller_
.reset();
459 BrowserList::RemoveBrowser(this);
461 SessionService
* session_service
=
462 SessionServiceFactory::GetForProfile(profile_
);
464 session_service
->WindowClosed(session_id_
);
466 TabRestoreService
* tab_restore_service
=
467 TabRestoreServiceFactory::GetForProfile(profile());
468 if (tab_restore_service
)
469 tab_restore_service
->BrowserClosed(tab_restore_service_delegate());
471 #if !defined(OS_MACOSX)
472 if (!chrome::GetTotalBrowserCountForProfile(profile_
)) {
473 // We're the last browser window with this profile. We need to nuke the
474 // TabRestoreService, which will start the shutdown of the
475 // NavigationControllers and allow for proper shutdown. If we don't do this
476 // chrome won't shutdown cleanly, and may end up crashing when some
477 // thread tries to use the IO thread (or another thread) that is no longer
479 // This isn't a valid assumption for Mac OS, as it stays running after
480 // the last browser has closed. The Mac equivalent is in its app
482 TabRestoreServiceFactory::ResetForProfile(profile_
);
486 profile_pref_registrar_
.RemoveAll();
488 encoding_auto_detect_
.Destroy();
490 // Destroy BrowserExtensionWindowController before the incognito profile
491 // is destroyed to make sure the chrome.windows.onRemoved event is sent.
492 extension_window_controller_
.reset();
494 // Destroy BrowserInstantController before the incongnito profile is destroyed
495 // because the InstantController destructor depends on this profile.
496 instant_controller_
.reset();
498 if (profile_
->IsOffTheRecord() &&
499 !BrowserList::IsOffTheRecordSessionActiveForProfile(profile_
)) {
500 // An incognito profile is no longer needed, this indirectly frees
501 // its cache and cookies once it gets destroyed at the appropriate time.
502 ProfileDestroyer::DestroyProfileWhenAppropriate(profile_
);
505 // There may be pending file dialogs, we need to tell them that we've gone
506 // away so they don't try and call back to us.
507 if (select_file_dialog_
.get())
508 select_file_dialog_
->ListenerDestroyed();
511 if (OkToCloseWithInProgressDownloads(&num_downloads
) ==
512 DOWNLOAD_CLOSE_BROWSER_SHUTDOWN
&&
513 !browser_defaults::kBrowserAliveWithNoWindows
) {
514 DownloadService::CancelAllDownloads();
518 ///////////////////////////////////////////////////////////////////////////////
521 FindBarController
* Browser::GetFindBarController() {
522 if (!find_bar_controller_
.get()) {
523 FindBar
* find_bar
= window_
->CreateFindBar();
524 find_bar_controller_
.reset(new FindBarController(find_bar
));
525 find_bar
->SetFindBarController(find_bar_controller_
.get());
526 find_bar_controller_
->ChangeWebContents(
527 tab_strip_model_
->GetActiveWebContents());
528 find_bar_controller_
->find_bar()->MoveWindowIfNecessary(gfx::Rect(), true);
530 return find_bar_controller_
.get();
533 bool Browser::HasFindBarController() const {
534 return find_bar_controller_
.get() != NULL
;
537 bool Browser::is_app() const {
538 return !app_name_
.empty();
541 bool Browser::is_devtools() const {
542 return app_name_
== DevToolsWindow::kDevToolsApp
;
545 ///////////////////////////////////////////////////////////////////////////////
546 // Browser, State Storage and Retrieval for UI:
548 gfx::Image
Browser::GetCurrentPageIcon() const {
549 WebContents
* web_contents
= tab_strip_model_
->GetActiveWebContents();
550 // |web_contents| can be NULL since GetCurrentPageIcon() is called by the
551 // window during the window's creation (before tabs have been added).
552 FaviconTabHelper
* favicon_tab_helper
=
553 web_contents
? FaviconTabHelper::FromWebContents(web_contents
) : NULL
;
554 return favicon_tab_helper
? favicon_tab_helper
->GetFavicon() : gfx::Image();
557 base::string16
Browser::GetWindowTitleForCurrentTab() const {
558 WebContents
* contents
= tab_strip_model_
->GetActiveWebContents();
559 base::string16 title
;
561 // |contents| can be NULL because GetWindowTitleForCurrentTab is called by the
562 // window during the window's creation (before tabs have been added).
564 title
= contents
->GetTitle();
565 FormatTitleForDisplay(&title
);
568 title
= CoreTabHelper::GetDefaultTitle();
570 #if defined(OS_MACOSX)
571 // On Mac, we don't want to suffix the page title with
572 // the application name.
574 #elif defined(USE_ASH)
575 // On Ash, we don't want to suffix the page title with the application name,
576 // but on Windows, where USE_ASH can also be true, we still want the prefix
578 if (host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH
)
581 // Don't append the app name to window titles on app frames and app popups
584 l10n_util::GetStringFUTF16(IDS_BROWSER_WINDOW_TITLE_FORMAT
, title
);
588 void Browser::FormatTitleForDisplay(base::string16
* title
) {
589 size_t current_index
= 0;
591 while ((match_index
= title
->find(L
'\n', current_index
)) !=
592 base::string16::npos
) {
593 title
->replace(match_index
, 1, base::string16());
594 current_index
= match_index
;
598 ///////////////////////////////////////////////////////////////////////////////
599 // Browser, OnBeforeUnload handling:
601 bool Browser::ShouldCloseWindow() {
602 if (!CanCloseWithInProgressDownloads())
605 if (IsFastTabUnloadEnabled())
606 return fast_unload_controller_
->ShouldCloseWindow();
607 return unload_controller_
->ShouldCloseWindow();
610 bool Browser::CallBeforeUnloadHandlers(
611 const base::Callback
<void(bool)>& on_close_confirmed
) {
612 cancel_download_confirmation_state_
= RESPONSE_RECEIVED
;
613 if (IsFastTabUnloadEnabled()) {
614 return fast_unload_controller_
->CallBeforeUnloadHandlers(
617 return unload_controller_
->CallBeforeUnloadHandlers(on_close_confirmed
);
620 void Browser::ResetBeforeUnloadHandlers() {
621 cancel_download_confirmation_state_
= NOT_PROMPTED
;
622 if (IsFastTabUnloadEnabled())
623 fast_unload_controller_
->ResetBeforeUnloadHandlers();
625 unload_controller_
->ResetBeforeUnloadHandlers();
628 bool Browser::HasCompletedUnloadProcessing() const {
629 DCHECK(IsFastTabUnloadEnabled());
630 return fast_unload_controller_
->HasCompletedUnloadProcessing();
633 bool Browser::IsAttemptingToCloseBrowser() const {
634 if (IsFastTabUnloadEnabled())
635 return fast_unload_controller_
->is_attempting_to_close_browser();
636 return unload_controller_
->is_attempting_to_close_browser();
639 void Browser::OnWindowClosing() {
640 if (!ShouldCloseWindow())
643 // Application should shutdown on last window close if the user is explicitly
644 // trying to quit, or if there is nothing keeping the browser alive (such as
645 // AppController on the Mac, or BackgroundContentsService for background
647 bool should_quit_if_last_browser
=
648 browser_shutdown::IsTryingToQuit() || !chrome::WillKeepAlive();
650 if (should_quit_if_last_browser
&& chrome::ShouldStartShutdown(this))
651 browser_shutdown::OnShutdownStarting(browser_shutdown::WINDOW_CLOSE
);
653 // Don't use GetForProfileIfExisting here, we want to force creation of the
654 // session service so that user can restore what was open.
655 SessionService
* session_service
=
656 SessionServiceFactory::GetForProfile(profile());
658 session_service
->WindowClosing(session_id());
660 TabRestoreService
* tab_restore_service
=
661 TabRestoreServiceFactory::GetForProfile(profile());
663 #if defined(USE_AURA)
664 if (tab_restore_service
&& is_app() && !is_devtools())
665 tab_restore_service
->BrowserClosing(tab_restore_service_delegate());
668 if (tab_restore_service
&& is_type_tabbed() && tab_strip_model_
->count())
669 tab_restore_service
->BrowserClosing(tab_restore_service_delegate());
671 // TODO(sky): convert session/tab restore to use notification.
672 content::NotificationService::current()->Notify(
673 chrome::NOTIFICATION_BROWSER_CLOSING
,
674 content::Source
<Browser
>(this),
675 content::NotificationService::NoDetails());
677 if (!IsFastTabUnloadEnabled())
678 tab_strip_model_
->CloseAllTabs();
681 ////////////////////////////////////////////////////////////////////////////////
682 // In-progress download termination handling:
684 void Browser::InProgressDownloadResponse(bool cancel_downloads
) {
685 if (cancel_downloads
) {
686 cancel_download_confirmation_state_
= RESPONSE_RECEIVED
;
687 chrome::CloseWindow(this);
691 // Sets the confirmation state to NOT_PROMPTED so that if the user tries to
692 // close again we'll show the warning again.
693 cancel_download_confirmation_state_
= NOT_PROMPTED
;
695 // Show the download page so the user can figure-out what downloads are still
697 chrome::ShowDownloads(this);
700 Browser::DownloadClosePreventionType
Browser::OkToCloseWithInProgressDownloads(
701 int* num_downloads_blocking
) const {
702 DCHECK(num_downloads_blocking
);
703 *num_downloads_blocking
= 0;
705 // If we're not running a full browser process with a profile manager
706 // (testing), it's ok to close the browser.
707 if (!g_browser_process
->profile_manager())
708 return DOWNLOAD_CLOSE_OK
;
710 int total_download_count
=
711 DownloadService::NonMaliciousDownloadCountAllProfiles();
712 if (total_download_count
== 0)
713 return DOWNLOAD_CLOSE_OK
; // No downloads; can definitely close.
715 // Figure out how many windows are open total, and associated with this
716 // profile, that are relevant for the ok-to-close decision.
717 int profile_window_count
= 0;
718 int total_window_count
= 0;
719 for (chrome::BrowserIterator it
; !it
.done(); it
.Next()) {
720 // Don't count this browser window or any other in the process of closing.
721 Browser
* const browser
= *it
;
722 // Window closing may be delayed, and windows that are in the process of
723 // closing don't count against our totals.
724 if (browser
== this || browser
->IsAttemptingToCloseBrowser())
727 if (it
->profile() == profile())
728 profile_window_count
++;
729 total_window_count
++;
732 // If there aren't any other windows, we're at browser shutdown,
733 // which would cancel all current downloads.
734 if (total_window_count
== 0) {
735 *num_downloads_blocking
= total_download_count
;
736 return DOWNLOAD_CLOSE_BROWSER_SHUTDOWN
;
739 // If there aren't any other windows on our profile, and we're an incognito
740 // profile, and there are downloads associated with that profile,
741 // those downloads would be cancelled by our window (-> profile) close.
742 DownloadService
* download_service
=
743 DownloadServiceFactory::GetForBrowserContext(profile());
744 if ((profile_window_count
== 0) &&
745 (download_service
->NonMaliciousDownloadCount() > 0) &&
746 profile()->IsOffTheRecord()) {
747 *num_downloads_blocking
= download_service
->NonMaliciousDownloadCount();
748 return DOWNLOAD_CLOSE_LAST_WINDOW_IN_INCOGNITO_PROFILE
;
751 // Those are the only conditions under which we will block shutdown.
752 return DOWNLOAD_CLOSE_OK
;
755 ////////////////////////////////////////////////////////////////////////////////
756 // Browser, Tab adding/showing functions:
758 void Browser::WindowFullscreenStateChanged() {
759 fullscreen_controller_
->WindowFullscreenStateChanged();
760 command_controller_
->FullscreenStateChanged();
761 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TOGGLE_FULLSCREEN
);
764 void Browser::VisibleSSLStateChanged(content::WebContents
* web_contents
) {
765 // When the current tab's SSL state changes, we need to update the URL
766 // bar to reflect the new state.
767 DCHECK(web_contents
);
768 if (tab_strip_model_
->GetActiveWebContents() == web_contents
)
769 UpdateToolbar(false);
772 void Browser::OnWebContentsInstantSupportDisabled(
773 const content::WebContents
* web_contents
) {
774 DCHECK(web_contents
);
775 if (tab_strip_model_
->GetActiveWebContents() == web_contents
)
776 UpdateToolbar(false);
779 ///////////////////////////////////////////////////////////////////////////////
780 // Browser, Assorted browser commands:
782 void Browser::ToggleFullscreenModeWithExtension(const GURL
& extension_url
) {
783 fullscreen_controller_
->ToggleFullscreenModeWithExtension(extension_url
);
786 bool Browser::SupportsWindowFeature(WindowFeature feature
) const {
787 return SupportsWindowFeatureImpl(feature
, true);
790 bool Browser::CanSupportWindowFeature(WindowFeature feature
) const {
791 return SupportsWindowFeatureImpl(feature
, false);
794 void Browser::ToggleEncodingAutoDetect() {
795 content::RecordAction(UserMetricsAction("AutoDetectChange"));
796 encoding_auto_detect_
.SetValue(!encoding_auto_detect_
.GetValue());
797 // If "auto detect" is turned on, then any current override encoding
798 // is cleared. This also implicitly performs a reload.
799 // OTOH, if "auto detect" is turned off, we don't change the currently
801 if (encoding_auto_detect_
.GetValue()) {
802 WebContents
* contents
= tab_strip_model_
->GetActiveWebContents();
804 contents
->ResetOverrideEncoding();
808 void Browser::OverrideEncoding(int encoding_id
) {
809 content::RecordAction(UserMetricsAction("OverrideEncoding"));
810 const std::string selected_encoding
=
811 CharacterEncoding::GetCanonicalEncodingNameByCommandId(encoding_id
);
812 WebContents
* contents
= tab_strip_model_
->GetActiveWebContents();
813 if (!selected_encoding
.empty() && contents
)
814 contents
->SetOverrideEncoding(selected_encoding
);
815 // Update the list of recently selected encodings.
816 std::string new_selected_encoding_list
;
817 if (CharacterEncoding::UpdateRecentlySelectedEncoding(
818 profile_
->GetPrefs()->GetString(prefs::kRecentlySelectedEncoding
),
820 &new_selected_encoding_list
)) {
821 profile_
->GetPrefs()->SetString(prefs::kRecentlySelectedEncoding
,
822 new_selected_encoding_list
);
826 void Browser::OpenFile() {
827 content::RecordAction(UserMetricsAction("OpenFile"));
828 select_file_dialog_
= ui::SelectFileDialog::Create(
829 this, new ChromeSelectFilePolicy(
830 tab_strip_model_
->GetActiveWebContents()));
832 const base::FilePath directory
= profile_
->last_selected_directory();
834 // TODO(beng): figure out how to juggle this.
835 gfx::NativeWindow parent_window
= window_
->GetNativeWindow();
836 ui::SelectFileDialog::FileTypeInfo file_types
;
837 file_types
.support_drive
= true;
838 select_file_dialog_
->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE
,
843 base::FilePath::StringType(),
848 void Browser::UpdateDownloadShelfVisibility(bool visible
) {
849 if (GetStatusBubble())
850 GetStatusBubble()->UpdateDownloadShelfVisibility(visible
);
853 ///////////////////////////////////////////////////////////////////////////////
855 void Browser::UpdateUIForNavigationInTab(WebContents
* contents
,
856 content::PageTransition transition
,
857 bool user_initiated
) {
858 tab_strip_model_
->TabNavigating(contents
, transition
);
860 bool contents_is_selected
=
861 contents
== tab_strip_model_
->GetActiveWebContents();
862 if (user_initiated
&& contents_is_selected
&& window()->GetLocationBar()) {
863 // Forcibly reset the location bar if the url is going to change in the
864 // current tab, since otherwise it won't discard any ongoing user edits,
865 // since it doesn't realize this is a user-initiated action.
866 window()->GetLocationBar()->Revert();
869 if (GetStatusBubble())
870 GetStatusBubble()->Hide();
872 // Update the location bar. This is synchronous. We specifically don't
873 // update the load state since the load hasn't started yet and updating it
874 // will put it out of sync with the actual state like whether we're
875 // displaying a favicon, which controls the throbber. If we updated it here,
876 // the throbber will show the default favicon for a split second when
877 // navigating away from the new tab page.
878 ScheduleUIUpdate(contents
, content::INVALIDATE_TYPE_URL
);
880 if (contents_is_selected
)
881 contents
->GetView()->SetInitialFocus();
884 ///////////////////////////////////////////////////////////////////////////////
885 // Browser, PageNavigator implementation:
887 WebContents
* Browser::OpenURL(const OpenURLParams
& params
) {
888 return OpenURLFromTab(NULL
, params
);
891 ///////////////////////////////////////////////////////////////////////////////
892 // Browser, TabStripModelObserver implementation:
894 void Browser::TabInsertedAt(WebContents
* contents
,
897 SetAsDelegate(contents
, this);
898 SessionTabHelper
* session_tab_helper
=
899 SessionTabHelper::FromWebContents(contents
);
900 session_tab_helper
->SetWindowID(session_id());
902 content::NotificationService::current()->Notify(
903 chrome::NOTIFICATION_TAB_PARENTED
,
904 content::Source
<content::WebContents
>(contents
),
905 content::NotificationService::NoDetails());
907 SyncHistoryWithTabs(index
);
909 // Make sure the loading state is updated correctly, otherwise the throbber
910 // won't start if the page is loading.
911 LoadingStateChanged(contents
);
913 interstitial_observers_
.push_back(new InterstitialObserver(this, contents
));
915 SessionService
* session_service
=
916 SessionServiceFactory::GetForProfile(profile_
);
917 if (session_service
) {
918 session_service
->TabInserted(contents
);
919 int new_active_index
= tab_strip_model_
->active_index();
920 if (index
< new_active_index
)
921 session_service
->SetSelectedTabInWindow(session_id(),
926 void Browser::TabClosingAt(TabStripModel
* tab_strip_model
,
927 WebContents
* contents
,
929 fullscreen_controller_
->OnTabClosing(contents
);
930 SessionService
* session_service
=
931 SessionServiceFactory::GetForProfile(profile_
);
933 session_service
->TabClosing(contents
);
934 content::NotificationService::current()->Notify(
935 chrome::NOTIFICATION_TAB_CLOSING
,
936 content::Source
<NavigationController
>(&contents
->GetController()),
937 content::NotificationService::NoDetails());
939 // Sever the WebContents' connection back to us.
940 SetAsDelegate(contents
, NULL
);
943 void Browser::TabDetachedAt(WebContents
* contents
, int index
) {
944 // TabDetachedAt is called before TabStripModel has updated the
946 int old_active_index
= tab_strip_model_
->active_index();
947 if (index
< old_active_index
&& !tab_strip_model_
->closing_all()) {
948 SessionService
* session_service
=
949 SessionServiceFactory::GetForProfileIfExisting(profile_
);
951 session_service
->SetSelectedTabInWindow(session_id(),
952 old_active_index
- 1);
954 TabDetachedAtImpl(contents
, index
, DETACH_TYPE_DETACH
);
957 void Browser::TabDeactivated(WebContents
* contents
) {
958 fullscreen_controller_
->OnTabDeactivated(contents
);
959 search_delegate_
->OnTabDeactivated(contents
);
960 SearchTabHelper::FromWebContents(contents
)->OnTabDeactivated();
962 // Save what the user's currently typing, so it can be restored when we
963 // switch back to this tab.
964 window_
->GetLocationBar()->SaveStateToContents(contents
);
966 if (instant_controller_
)
967 instant_controller_
->TabDeactivated(contents
);
970 void Browser::ActiveTabChanged(WebContents
* old_contents
,
971 WebContents
* new_contents
,
974 content::RecordAction(UserMetricsAction("ActiveTabChanged"));
976 // Update the bookmark state, since the BrowserWindow may query it during
977 // OnActiveTabChanged() below.
978 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH
);
980 // Let the BrowserWindow do its handling. On e.g. views this changes the
981 // focused object, which should happen before we update the toolbar below,
982 // since the omnibox expects the correct element to already be focused when it
984 window_
->OnActiveTabChanged(old_contents
, new_contents
, index
, reason
);
986 fullscreen_controller_
->OnTabDetachedFromView(old_contents
);
988 // Discarded tabs always get reloaded.
989 if (tab_strip_model_
->IsTabDiscarded(index
)) {
990 LOG(WARNING
) << "Reloading discarded tab at " << index
;
991 static int reload_count
= 0;
992 UMA_HISTOGRAM_CUSTOM_COUNTS(
993 "Tabs.Discard.ReloadCount", ++reload_count
, 1, 1000, 50);
994 chrome::Reload(this, CURRENT_TAB
);
997 // If we have any update pending, do it now.
998 if (chrome_updater_factory_
.HasWeakPtrs() && old_contents
)
999 ProcessPendingUIUpdates();
1001 // Propagate the profile to the location bar.
1002 UpdateToolbar((reason
& CHANGE_REASON_REPLACED
) == 0);
1004 if (chrome::IsInstantExtendedAPIEnabled())
1005 search_delegate_
->OnTabActivated(new_contents
);
1007 // Update reload/stop state.
1008 command_controller_
->LoadingStateChanged(new_contents
->IsLoading(), true);
1010 // Update commands to reflect current state.
1011 command_controller_
->TabStateChanged();
1013 // Reset the status bubble.
1014 StatusBubble
* status_bubble
= GetStatusBubble();
1015 if (status_bubble
) {
1016 status_bubble
->Hide();
1018 // Show the loading state (if any).
1019 status_bubble
->SetStatus(CoreTabHelper::FromWebContents(
1020 tab_strip_model_
->GetActiveWebContents())->GetStatusText());
1023 if (HasFindBarController()) {
1024 find_bar_controller_
->ChangeWebContents(new_contents
);
1025 find_bar_controller_
->find_bar()->MoveWindowIfNecessary(gfx::Rect(), true);
1028 // Update sessions. Don't force creation of sessions. If sessions doesn't
1029 // exist, the change will be picked up by sessions when created.
1030 SessionService
* session_service
=
1031 SessionServiceFactory::GetForProfileIfExisting(profile_
);
1032 if (session_service
&& !tab_strip_model_
->closing_all()) {
1033 session_service
->SetSelectedTabInWindow(session_id(),
1034 tab_strip_model_
->active_index());
1037 // This needs to be called after notifying SearchDelegate.
1038 if (instant_controller_
)
1039 instant_controller_
->ActiveTabChanged();
1041 autofill::TabAutofillManagerDelegate::FromWebContents(new_contents
)->
1043 SearchTabHelper::FromWebContents(new_contents
)->OnTabActivated();
1046 void Browser::TabMoved(WebContents
* contents
,
1049 DCHECK(from_index
>= 0 && to_index
>= 0);
1050 // Notify the history service.
1051 SyncHistoryWithTabs(std::min(from_index
, to_index
));
1054 void Browser::TabReplacedAt(TabStripModel
* tab_strip_model
,
1055 WebContents
* old_contents
,
1056 WebContents
* new_contents
,
1058 TabDetachedAtImpl(old_contents
, index
, DETACH_TYPE_REPLACE
);
1059 fullscreen_controller_
->OnTabClosing(old_contents
);
1060 SessionService
* session_service
=
1061 SessionServiceFactory::GetForProfile(profile_
);
1062 if (session_service
)
1063 session_service
->TabClosing(old_contents
);
1064 TabInsertedAt(new_contents
,
1066 (index
== tab_strip_model_
->active_index()));
1068 int entry_count
= new_contents
->GetController().GetEntryCount();
1069 if (entry_count
> 0) {
1070 // Send out notification so that observers are updated appropriately.
1071 new_contents
->GetController().NotifyEntryChanged(
1072 new_contents
->GetController().GetEntryAtIndex(entry_count
- 1),
1076 if (session_service
) {
1077 // The new_contents may end up with a different navigation stack. Force
1078 // the session service to update itself.
1079 session_service
->TabRestored(new_contents
,
1080 tab_strip_model_
->IsTabPinned(index
));
1084 void Browser::TabPinnedStateChanged(WebContents
* contents
, int index
) {
1085 SessionService
* session_service
=
1086 SessionServiceFactory::GetForProfileIfExisting(profile());
1087 if (session_service
) {
1088 SessionTabHelper
* session_tab_helper
=
1089 SessionTabHelper::FromWebContents(contents
);
1090 session_service
->SetPinnedState(session_id(),
1091 session_tab_helper
->session_id(),
1092 tab_strip_model_
->IsTabPinned(index
));
1096 void Browser::TabStripEmpty() {
1097 // Close the frame after we return to the message loop (not immediately,
1098 // otherwise it will destroy this object before the stack has a chance to
1100 // Note: This will be called several times if TabStripEmpty is called several
1101 // times. This is because it does not close the window if tabs are
1103 base::MessageLoop::current()->PostTask(
1104 FROM_HERE
, base::Bind(&Browser::CloseFrame
, weak_factory_
.GetWeakPtr()));
1106 // Instant may have visible WebContents that need to be detached before the
1107 // window system closes.
1108 instant_controller_
.reset();
1111 bool Browser::CanOverscrollContent() const {
1112 #if defined(USE_AURA)
1113 bool overscroll_enabled
= CommandLine::ForCurrentProcess()->
1114 GetSwitchValueASCII(switches::kOverscrollHistoryNavigation
) != "0";
1115 if (!overscroll_enabled
)
1117 if (is_app() || is_devtools() || !is_type_tabbed())
1120 // The detached bookmark bar has appearance of floating above the
1121 // web-contents. This does not play nicely with overscroll navigation
1122 // gestures. So disable overscroll navigation when the bookmark bar is in the
1124 if (bookmark_bar_state_
== BookmarkBar::DETACHED
)
1132 bool Browser::PreHandleKeyboardEvent(content::WebContents
* source
,
1133 const NativeWebKeyboardEvent
& event
,
1134 bool* is_keyboard_shortcut
) {
1135 // Escape exits tabbed fullscreen mode.
1136 // TODO(koz): Write a test for this http://crbug.com/100441.
1137 if (event
.windowsKeyCode
== 27 &&
1138 fullscreen_controller_
->HandleUserPressedEscape()) {
1141 return window()->PreHandleKeyboardEvent(event
, is_keyboard_shortcut
);
1144 void Browser::HandleKeyboardEvent(content::WebContents
* source
,
1145 const NativeWebKeyboardEvent
& event
) {
1146 window()->HandleKeyboardEvent(event
);
1149 bool Browser::TabsNeedBeforeUnloadFired() {
1150 if (IsFastTabUnloadEnabled())
1151 return fast_unload_controller_
->TabsNeedBeforeUnloadFired();
1152 return unload_controller_
->TabsNeedBeforeUnloadFired();
1155 void Browser::OverscrollUpdate(int delta_y
) {
1156 window_
->OverscrollUpdate(delta_y
);
1159 void Browser::ShowValidationMessage(content::WebContents
* web_contents
,
1160 const gfx::Rect
& anchor_in_root_view
,
1161 const base::string16
& main_text
,
1162 const base::string16
& sub_text
) {
1163 RenderWidgetHostView
* rwhv
= web_contents
->GetRenderWidgetHostView();
1165 validation_message_bubble_
=
1166 chrome::ValidationMessageBubble::CreateAndShow(
1167 rwhv
->GetRenderWidgetHost(),
1168 anchor_in_root_view
,
1174 void Browser::HideValidationMessage(content::WebContents
* web_contents
) {
1175 validation_message_bubble_
.reset();
1178 void Browser::MoveValidationMessage(content::WebContents
* web_contents
,
1179 const gfx::Rect
& anchor_in_root_view
) {
1180 if (!validation_message_bubble_
)
1182 RenderWidgetHostView
* rwhv
= web_contents
->GetRenderWidgetHostView();
1184 validation_message_bubble_
->SetPositionRelativeToAnchor(
1185 rwhv
->GetRenderWidgetHost(), anchor_in_root_view
);
1189 bool Browser::IsMouseLocked() const {
1190 return fullscreen_controller_
->IsMouseLocked();
1193 void Browser::OnWindowDidShow() {
1194 if (window_has_shown_
)
1196 window_has_shown_
= true;
1198 // CurrentProcessInfo::CreationTime() is missing on some platforms.
1199 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
1200 // Measure the latency from startup till the first browser window becomes
1202 static bool is_first_browser_window
= true;
1203 if (is_first_browser_window
&&
1204 !startup_metric_utils::WasNonBrowserUIDisplayed()) {
1205 is_first_browser_window
= false;
1206 const base::Time process_creation_time
=
1207 base::CurrentProcessInfo::CreationTime();
1209 if (!process_creation_time
.is_null()) {
1210 UMA_HISTOGRAM_LONG_TIMES(
1211 "Startup.BrowserWindowDisplay",
1212 base::Time::Now() - process_creation_time
);
1215 #endif // defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
1217 // Nothing to do for non-tabbed windows.
1218 if (!is_type_tabbed())
1221 // Show any pending global error bubble.
1222 GlobalErrorService
* service
=
1223 GlobalErrorServiceFactory::GetForProfile(profile());
1224 GlobalError
* error
= service
->GetFirstGlobalErrorWithBubbleView();
1226 error
->ShowBubbleView(this);
1229 void Browser::ShowFirstRunBubble() {
1230 window()->GetLocationBar()->ShowFirstRunBubble();
1233 void Browser::ShowDownload(content::DownloadItem
* download
) {
1237 // If the download occurs in a new tab, and it's not a save page
1238 // download (started before initial navigation completed) close it.
1239 WebContents
* source
= download
->GetWebContents();
1240 if (source
&& source
->GetController().IsInitialNavigation() &&
1241 tab_strip_model_
->count() > 1 && !download
->IsSavePackageDownload()) {
1242 CloseContents(source
);
1245 // Some (app downloads) are not supposed to appear on the shelf.
1246 if (!DownloadItemModel(download
).ShouldShowInShelf())
1249 // GetDownloadShelf creates the download shelf if it was not yet created.
1250 DownloadShelf
* shelf
= window()->GetDownloadShelf();
1251 shelf
->AddDownload(download
);
1254 ///////////////////////////////////////////////////////////////////////////////
1255 // Browser, content::WebContentsDelegate implementation:
1257 WebContents
* Browser::OpenURLFromTab(WebContents
* source
,
1258 const OpenURLParams
& params
) {
1259 chrome::NavigateParams
nav_params(this, params
.url
, params
.transition
);
1260 FillNavigateParamsFromOpenURLParams(&nav_params
, params
);
1261 nav_params
.source_contents
= source
;
1262 nav_params
.tabstrip_add_types
= TabStripModel::ADD_NONE
;
1263 nav_params
.window_action
= chrome::NavigateParams::SHOW_WINDOW
;
1264 nav_params
.user_gesture
= params
.user_gesture
;
1266 PopupBlockerTabHelper
* popup_blocker_helper
= NULL
;
1268 popup_blocker_helper
= PopupBlockerTabHelper::FromWebContents(source
);
1270 if (popup_blocker_helper
) {
1271 if ((params
.disposition
== NEW_POPUP
||
1272 params
.disposition
== NEW_FOREGROUND_TAB
||
1273 params
.disposition
== NEW_BACKGROUND_TAB
||
1274 params
.disposition
== NEW_WINDOW
) &&
1275 !params
.user_gesture
&& !CommandLine::ForCurrentProcess()->HasSwitch(
1276 switches::kDisablePopupBlocking
)) {
1277 if (popup_blocker_helper
->MaybeBlockPopup(nav_params
,
1278 WebWindowFeatures())) {
1284 chrome::Navigate(&nav_params
);
1286 return nav_params
.target_contents
;
1289 void Browser::NavigationStateChanged(const WebContents
* source
,
1290 unsigned changed_flags
) {
1291 // Only update the UI when something visible has changed.
1293 ScheduleUIUpdate(source
, changed_flags
);
1295 // We can synchronously update commands since they will only change once per
1296 // navigation, so we don't have to worry about flickering. We do, however,
1297 // need to update the command state early on load to always present usable
1298 // actions in the face of slow-to-commit pages.
1299 if (changed_flags
& (content::INVALIDATE_TYPE_URL
|
1300 content::INVALIDATE_TYPE_LOAD
))
1301 command_controller_
->TabStateChanged();
1304 void Browser::AddNewContents(WebContents
* source
,
1305 WebContents
* new_contents
,
1306 WindowOpenDisposition disposition
,
1307 const gfx::Rect
& initial_pos
,
1309 bool* was_blocked
) {
1310 chrome::AddWebContents(this, source
, new_contents
, disposition
, initial_pos
,
1311 user_gesture
, was_blocked
);
1314 void Browser::ActivateContents(WebContents
* contents
) {
1315 tab_strip_model_
->ActivateTabAt(
1316 tab_strip_model_
->GetIndexOfWebContents(contents
), false);
1317 window_
->Activate();
1320 void Browser::DeactivateContents(WebContents
* contents
) {
1321 window_
->Deactivate();
1324 void Browser::LoadingStateChanged(WebContents
* source
) {
1325 window_
->UpdateLoadingAnimations(tab_strip_model_
->TabsAreLoading());
1326 window_
->UpdateTitleBar();
1328 WebContents
* selected_contents
= tab_strip_model_
->GetActiveWebContents();
1329 if (source
== selected_contents
) {
1330 bool is_loading
= source
->IsLoading();
1331 command_controller_
->LoadingStateChanged(is_loading
, false);
1332 if (GetStatusBubble()) {
1333 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
1334 tab_strip_model_
->GetActiveWebContents())->GetStatusText());
1339 void Browser::CloseContents(WebContents
* source
) {
1340 bool can_close_contents
;
1341 if (IsFastTabUnloadEnabled())
1342 can_close_contents
= fast_unload_controller_
->CanCloseContents(source
);
1344 can_close_contents
= unload_controller_
->CanCloseContents(source
);
1346 if (can_close_contents
)
1347 chrome::CloseWebContents(this, source
, true);
1350 void Browser::MoveContents(WebContents
* source
, const gfx::Rect
& pos
) {
1351 if (!IsPopupOrPanel(source
)) {
1352 NOTREACHED() << "moving invalid browser type";
1355 window_
->SetBounds(pos
);
1358 bool Browser::IsPopupOrPanel(const WebContents
* source
) const {
1359 return is_type_popup();
1362 void Browser::UpdateTargetURL(WebContents
* source
, int32 page_id
,
1364 if (!GetStatusBubble())
1367 if (source
== tab_strip_model_
->GetActiveWebContents()) {
1368 PrefService
* prefs
= profile_
->GetPrefs();
1369 GetStatusBubble()->SetURL(url
, prefs
->GetString(prefs::kAcceptLanguages
));
1373 void Browser::ContentsMouseEvent(
1374 WebContents
* source
, const gfx::Point
& location
, bool motion
) {
1375 if (!GetStatusBubble())
1378 if (source
== tab_strip_model_
->GetActiveWebContents()) {
1379 GetStatusBubble()->MouseMoved(location
, !motion
);
1381 GetStatusBubble()->SetURL(GURL(), std::string());
1385 void Browser::ContentsZoomChange(bool zoom_in
) {
1386 chrome::ExecuteCommand(this, zoom_in
? IDC_ZOOM_PLUS
: IDC_ZOOM_MINUS
);
1389 void Browser::WebContentsFocused(WebContents
* contents
) {
1390 window_
->WebContentsFocused(contents
);
1393 bool Browser::TakeFocus(content::WebContents
* source
,
1395 content::NotificationService::current()->Notify(
1396 chrome::NOTIFICATION_FOCUS_RETURNED_TO_BROWSER
,
1397 content::Source
<Browser
>(this),
1398 content::NotificationService::NoDetails());
1402 gfx::Rect
Browser::GetRootWindowResizerRect() const {
1403 return window_
->GetRootWindowResizerRect();
1406 void Browser::BeforeUnloadFired(WebContents
* web_contents
,
1408 bool* proceed_to_fire_unload
) {
1409 if (is_devtools() && DevToolsWindow::HandleBeforeUnload(web_contents
,
1410 proceed
, proceed_to_fire_unload
))
1413 if (IsFastTabUnloadEnabled()) {
1414 *proceed_to_fire_unload
=
1415 fast_unload_controller_
->BeforeUnloadFired(web_contents
, proceed
);
1417 *proceed_to_fire_unload
=
1418 unload_controller_
->BeforeUnloadFired(web_contents
, proceed
);
1422 bool Browser::ShouldFocusLocationBarByDefault(WebContents
* source
) {
1423 const content::NavigationEntry
* entry
=
1424 source
->GetController().GetActiveEntry();
1426 GURL url
= entry
->GetURL();
1427 GURL virtual_url
= entry
->GetVirtualURL();
1428 if ((url
.SchemeIs(content::kChromeUIScheme
) &&
1429 url
.host() == chrome::kChromeUINewTabHost
) ||
1430 (virtual_url
.SchemeIs(content::kChromeUIScheme
) &&
1431 virtual_url
.host() == chrome::kChromeUINewTabHost
)) {
1436 return chrome::NavEntryIsInstantNTP(source
, entry
);
1439 void Browser::SetFocusToLocationBar(bool select_all
) {
1440 // Two differences between this and FocusLocationBar():
1441 // (1) This doesn't get recorded in user metrics, since it's called
1443 // (2) This checks whether the location bar can be focused, and if not, clears
1444 // the focus. FocusLocationBar() is only reached when the location bar is
1445 // focusable, but this may be reached at other times, e.g. while in
1446 // fullscreen mode, where we need to leave focus in a consistent state.
1447 window_
->SetFocusToLocationBar(select_all
);
1450 int Browser::GetExtraRenderViewHeight() const {
1451 return window_
->GetExtraRenderViewHeight();
1454 void Browser::ViewSourceForTab(WebContents
* source
, const GURL
& page_url
) {
1456 chrome::ViewSource(this, source
);
1459 void Browser::ViewSourceForFrame(WebContents
* source
,
1460 const GURL
& frame_url
,
1461 const content::PageState
& frame_page_state
) {
1463 chrome::ViewSource(this, source
, frame_url
, frame_page_state
);
1466 void Browser::ShowRepostFormWarningDialog(WebContents
* source
) {
1467 TabModalConfirmDialog::Create(new RepostFormWarningController(source
),
1471 bool Browser::ShouldCreateWebContents(
1472 WebContents
* web_contents
,
1474 WindowContainerType window_container_type
,
1475 const base::string16
& frame_name
,
1476 const GURL
& target_url
,
1477 const std::string
& partition_id
,
1478 content::SessionStorageNamespace
* session_storage_namespace
) {
1479 if (window_container_type
== WINDOW_CONTAINER_TYPE_BACKGROUND
) {
1480 // If a BackgroundContents is created, suppress the normal WebContents.
1481 return !MaybeCreateBackgroundContents(route_id
,
1486 session_storage_namespace
);
1492 void Browser::WebContentsCreated(WebContents
* source_contents
,
1493 int64 source_frame_id
,
1494 const base::string16
& frame_name
,
1495 const GURL
& target_url
,
1496 WebContents
* new_contents
) {
1497 // Adopt the WebContents now, so all observers are in place, as the network
1498 // requests for its initial navigation will start immediately. The WebContents
1499 // will later be inserted into this browser using Browser::Navigate via
1501 TabHelpers::AttachTabHelpers(new_contents
);
1504 RetargetingDetails details
;
1505 details
.source_web_contents
= source_contents
;
1506 details
.source_frame_id
= source_frame_id
;
1507 details
.target_url
= target_url
;
1508 details
.target_web_contents
= new_contents
;
1509 details
.not_yet_in_tabstrip
= true;
1510 content::NotificationService::current()->Notify(
1511 chrome::NOTIFICATION_RETARGETING
,
1512 content::Source
<Profile
>(profile_
),
1513 content::Details
<RetargetingDetails
>(&details
));
1516 void Browser::RendererUnresponsive(WebContents
* source
) {
1517 // Ignore hangs if a tab is blocked.
1518 int index
= tab_strip_model_
->GetIndexOfWebContents(source
);
1519 DCHECK_NE(TabStripModel::kNoTab
, index
);
1520 if (tab_strip_model_
->IsTabBlocked(index
))
1523 chrome::ShowHungRendererDialog(source
);
1526 void Browser::RendererResponsive(WebContents
* source
) {
1527 chrome::HideHungRendererDialog(source
);
1530 void Browser::WorkerCrashed(WebContents
* source
) {
1531 SimpleAlertInfoBarDelegate::Create(
1532 InfoBarService::FromWebContents(source
), InfoBarDelegate::kNoIconID
,
1533 l10n_util::GetStringUTF16(IDS_WEBWORKER_CRASHED_PROMPT
), true);
1536 void Browser::DidNavigateMainFramePostCommit(WebContents
* web_contents
) {
1537 if (web_contents
== tab_strip_model_
->GetActiveWebContents())
1538 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE
);
1541 void Browser::DidNavigateToPendingEntry(WebContents
* web_contents
) {
1542 if (web_contents
== tab_strip_model_
->GetActiveWebContents())
1543 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE
);
1546 content::JavaScriptDialogManager
* Browser::GetJavaScriptDialogManager() {
1547 return GetJavaScriptDialogManagerInstance();
1550 content::ColorChooser
* Browser::OpenColorChooser(
1551 WebContents
* web_contents
,
1552 SkColor initial_color
,
1553 const std::vector
<content::ColorSuggestion
>& suggestions
) {
1554 return chrome::ShowColorChooser(web_contents
, initial_color
);
1557 void Browser::RunFileChooser(WebContents
* web_contents
,
1558 const content::FileChooserParams
& params
) {
1559 FileSelectHelper::RunFileChooser(web_contents
, params
);
1562 void Browser::EnumerateDirectory(WebContents
* web_contents
,
1564 const base::FilePath
& path
) {
1565 FileSelectHelper::EnumerateDirectory(web_contents
, request_id
, path
);
1568 bool Browser::EmbedsFullscreenWidget() const {
1569 return CommandLine::ForCurrentProcess()->
1570 HasSwitch(switches::kEmbedFlashFullscreen
);
1573 void Browser::ToggleFullscreenModeForTab(WebContents
* web_contents
,
1574 bool enter_fullscreen
) {
1575 fullscreen_controller_
->ToggleFullscreenModeForTab(web_contents
,
1579 bool Browser::IsFullscreenForTabOrPending(
1580 const WebContents
* web_contents
) const {
1581 return fullscreen_controller_
->IsFullscreenForTabOrPending(web_contents
);
1584 void Browser::JSOutOfMemory(WebContents
* web_contents
) {
1585 InfoBarService
* infobar_service
=
1586 InfoBarService::FromWebContents(web_contents
);
1587 if (!infobar_service
)
1589 SimpleAlertInfoBarDelegate::Create(
1590 infobar_service
, InfoBarDelegate::kNoIconID
,
1591 l10n_util::GetStringUTF16(IDS_JS_OUT_OF_MEMORY_PROMPT
), true);
1594 void Browser::RegisterProtocolHandler(WebContents
* web_contents
,
1595 const std::string
& protocol
,
1597 const base::string16
& title
,
1598 bool user_gesture
) {
1600 Profile::FromBrowserContext(web_contents
->GetBrowserContext());
1601 if (profile
->IsOffTheRecord())
1604 ProtocolHandler handler
=
1605 ProtocolHandler::CreateProtocolHandler(protocol
, url
, title
);
1607 ProtocolHandlerRegistry
* registry
=
1608 ProtocolHandlerRegistryFactory::GetForProfile(profile
);
1609 if (registry
->SilentlyHandleRegisterHandlerRequest(handler
))
1612 TabSpecificContentSettings
* tab_content_settings
=
1613 TabSpecificContentSettings::FromWebContents(web_contents
);
1614 if (!user_gesture
&& window_
) {
1615 tab_content_settings
->set_pending_protocol_handler(handler
);
1616 tab_content_settings
->set_previous_protocol_handler(
1617 registry
->GetHandlerFor(handler
.protocol()));
1618 window_
->GetLocationBar()->UpdateContentSettingsIcons();
1622 // Make sure content-setting icon is turned off in case the page does
1623 // ungestured and gestured RPH calls.
1625 tab_content_settings
->ClearPendingProtocolHandler();
1626 window_
->GetLocationBar()->UpdateContentSettingsIcons();
1629 PermissionBubbleManager
* bubble_manager
=
1630 PermissionBubbleManager::FromWebContents(web_contents
);
1631 if (PermissionBubbleManager::Enabled() && bubble_manager
) {
1632 bubble_manager
->AddRequest(
1633 new RegisterProtocolHandlerPermissionRequest(registry
, handler
));
1635 RegisterProtocolHandlerInfoBarDelegate::Create(
1636 InfoBarService::FromWebContents(web_contents
), registry
, handler
);
1640 void Browser::UpdatePreferredSize(WebContents
* source
,
1641 const gfx::Size
& pref_size
) {
1642 window_
->UpdatePreferredSize(source
, pref_size
);
1645 void Browser::ResizeDueToAutoResize(WebContents
* source
,
1646 const gfx::Size
& new_size
) {
1647 window_
->ResizeDueToAutoResize(source
, new_size
);
1650 void Browser::FindReply(WebContents
* web_contents
,
1652 int number_of_matches
,
1653 const gfx::Rect
& selection_rect
,
1654 int active_match_ordinal
,
1655 bool final_update
) {
1656 FindTabHelper
* find_tab_helper
= FindTabHelper::FromWebContents(web_contents
);
1657 if (!find_tab_helper
)
1660 find_tab_helper
->HandleFindReply(request_id
,
1663 active_match_ordinal
,
1667 void Browser::RequestToLockMouse(WebContents
* web_contents
,
1669 bool last_unlocked_by_target
) {
1670 fullscreen_controller_
->RequestToLockMouse(web_contents
,
1672 last_unlocked_by_target
);
1675 void Browser::LostMouseLock() {
1676 fullscreen_controller_
->LostMouseLock();
1679 void Browser::RequestMediaAccessPermission(
1680 content::WebContents
* web_contents
,
1681 const content::MediaStreamRequest
& request
,
1682 const content::MediaResponseCallback
& callback
) {
1683 ::RequestMediaAccessPermission(web_contents
, profile_
, request
, callback
);
1686 bool Browser::RequestPpapiBrokerPermission(
1687 WebContents
* web_contents
,
1689 const base::FilePath
& plugin_path
,
1690 const base::Callback
<void(bool)>& callback
) {
1691 PepperBrokerInfoBarDelegate::Create(web_contents
, url
, plugin_path
, callback
);
1695 gfx::Size
Browser::GetSizeForNewRenderView(
1696 const WebContents
* web_contents
) const {
1697 // When navigating away from NTP with unpinned bookmark bar, the bookmark bar
1698 // would disappear on non-NTP pages, resulting in a bigger size for the new
1700 gfx::Size size
= web_contents
->GetView()->GetContainerSize();
1701 // Don't change render view size if bookmark bar is currently not detached,
1702 // or there's no pending entry, or navigating to a NTP page.
1703 if (size
.IsEmpty() || bookmark_bar_state_
!= BookmarkBar::DETACHED
)
1705 const NavigationEntry
* pending_entry
=
1706 web_contents
->GetController().GetPendingEntry();
1707 if (pending_entry
&&
1708 !chrome::IsNTPURL(pending_entry
->GetVirtualURL(), profile_
)) {
1710 0, window()->GetRenderViewHeightInsetWithDetachedBookmarkBar());
1715 ///////////////////////////////////////////////////////////////////////////////
1716 // Browser, CoreTabHelperDelegate implementation:
1718 void Browser::SwapTabContents(content::WebContents
* old_contents
,
1719 content::WebContents
* new_contents
,
1720 bool did_start_load
,
1721 bool did_finish_load
) {
1722 int index
= tab_strip_model_
->GetIndexOfWebContents(old_contents
);
1723 DCHECK_NE(TabStripModel::kNoTab
, index
);
1724 tab_strip_model_
->ReplaceWebContentsAt(index
, new_contents
);
1727 bool Browser::CanReloadContents(content::WebContents
* web_contents
) const {
1728 return chrome::CanReload(this);
1731 bool Browser::CanSaveContents(content::WebContents
* web_contents
) const {
1732 return chrome::CanSavePage(this);
1735 ///////////////////////////////////////////////////////////////////////////////
1736 // Browser, SearchEngineTabHelperDelegate implementation:
1738 void Browser::ConfirmAddSearchProvider(TemplateURL
* template_url
,
1740 window()->ConfirmAddSearchProvider(template_url
, profile
);
1743 ///////////////////////////////////////////////////////////////////////////////
1744 // Browser, web_modal::WebContentsModalDialogManagerDelegate implementation:
1746 void Browser::SetWebContentsBlocked(content::WebContents
* web_contents
,
1748 int index
= tab_strip_model_
->GetIndexOfWebContents(web_contents
);
1749 if (index
== TabStripModel::kNoTab
) {
1753 tab_strip_model_
->SetTabBlocked(index
, blocked
);
1754 if (!blocked
&& tab_strip_model_
->GetActiveWebContents() == web_contents
)
1755 web_contents
->GetView()->Focus();
1758 web_modal::WebContentsModalDialogHost
*
1759 Browser::GetWebContentsModalDialogHost() {
1760 return window_
->GetWebContentsModalDialogHost();
1763 ///////////////////////////////////////////////////////////////////////////////
1764 // Browser, BookmarkTabHelperDelegate implementation:
1766 void Browser::URLStarredChanged(content::WebContents
* web_contents
,
1768 if (web_contents
== tab_strip_model_
->GetActiveWebContents())
1769 window_
->SetStarredState(starred
);
1772 ///////////////////////////////////////////////////////////////////////////////
1773 // Browser, ZoomObserver implementation:
1775 void Browser::OnZoomChanged(content::WebContents
* source
,
1776 bool can_show_bubble
) {
1777 if (source
== tab_strip_model_
->GetActiveWebContents()) {
1778 // Only show the zoom bubble for zoom changes in the active window.
1779 window_
->ZoomChangedForActiveTab(can_show_bubble
&& window_
->IsActive() &&
1784 ///////////////////////////////////////////////////////////////////////////////
1785 // Browser, ui::SelectFileDialog::Listener implementation:
1787 void Browser::FileSelected(const base::FilePath
& path
, int index
,
1789 FileSelectedWithExtraInfo(ui::SelectedFileInfo(path
, path
), index
, params
);
1792 void Browser::FileSelectedWithExtraInfo(const ui::SelectedFileInfo
& file_info
,
1795 profile_
->set_last_selected_directory(file_info
.file_path
.DirName());
1797 GURL url
= net::FilePathToFileURL(file_info
.local_path
);
1799 #if defined(OS_CHROMEOS)
1800 drive::util::MaybeSetDriveURL(profile_
, file_info
.file_path
, &url
);
1806 OpenURL(OpenURLParams(
1807 url
, Referrer(), CURRENT_TAB
, content::PAGE_TRANSITION_TYPED
, false));
1810 ///////////////////////////////////////////////////////////////////////////////
1811 // Browser, content::NotificationObserver implementation:
1813 void Browser::Observe(int type
,
1814 const content::NotificationSource
& source
,
1815 const content::NotificationDetails
& details
) {
1817 case chrome::NOTIFICATION_EXTENSION_UNLOADED
: {
1818 if (window()->GetLocationBar())
1819 window()->GetLocationBar()->UpdatePageActions();
1821 const extensions::UnloadedExtensionInfo
* extension_info
=
1822 content::Details
<extensions::UnloadedExtensionInfo
>(details
).ptr();
1824 // Close any tabs from the unloaded extension, unless it's terminated,
1825 // in which case let the sad tabs remain.
1826 if (extension_info
->reason
!=
1827 extensions::UnloadedExtensionInfo::REASON_TERMINATE
) {
1828 const Extension
* extension
= extension_info
->extension
;
1829 // Iterate backwards as we may remove items while iterating.
1830 for (int i
= tab_strip_model_
->count() - 1; i
>= 0; --i
) {
1831 WebContents
* web_contents
= tab_strip_model_
->GetWebContentsAt(i
);
1832 // Two cases are handled here:
1833 // - The scheme check is for when an extension page is loaded in a
1834 // tab, e.g. chrome-extension://id/page.html.
1835 // - The extension_app check is for apps, which can have non-extension
1836 // schemes, e.g. https://mail.google.com if you have the Gmail app
1838 if ((web_contents
->GetURL().SchemeIs(extensions::kExtensionScheme
) &&
1839 web_contents
->GetURL().host() == extension
->id()) ||
1840 (extensions::TabHelper::FromWebContents(
1841 web_contents
)->extension_app() == extension
)) {
1842 tab_strip_model_
->CloseWebContentsAt(i
, TabStripModel::CLOSE_NONE
);
1849 case chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED
: {
1850 Profile
* profile
= content::Source
<Profile
>(source
).ptr();
1851 if (profile_
->IsSameProfile(profile
) && window()->GetLocationBar())
1852 window()->GetLocationBar()->InvalidatePageActions();
1856 case chrome::NOTIFICATION_EXTENSION_UNINSTALLED
:
1857 case chrome::NOTIFICATION_EXTENSION_LOADED
:
1858 // During window creation on Windows we may end up calling into
1859 // SHAppBarMessage, which internally spawns a nested message loop. This
1860 // makes it possible for us to end up here before window creation has
1861 // completed, at which point window_ is NULL. See 94752 for details.
1862 if (window() && window()->GetLocationBar())
1863 window()->GetLocationBar()->UpdatePageActions();
1866 #if defined(ENABLE_THEMES)
1867 case chrome::NOTIFICATION_BROWSER_THEME_CHANGED
:
1868 window()->UserChangedTheme();
1872 case chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED
: {
1873 WebContents
* web_contents
= content::Source
<WebContents
>(source
).ptr();
1874 if (web_contents
== tab_strip_model_
->GetActiveWebContents()) {
1875 LocationBar
* location_bar
= window()->GetLocationBar();
1877 location_bar
->UpdateContentSettingsIcons();
1883 NOTREACHED() << "Got a notification we didn't register for.";
1887 ///////////////////////////////////////////////////////////////////////////////
1888 // Browser, Command and state updating (private):
1890 void Browser::OnDevToolsDisabledChanged() {
1891 if (profile_
->GetPrefs()->GetBoolean(prefs::kDevToolsDisabled
))
1892 content::DevToolsManager::GetInstance()->CloseAllClientHosts();
1895 ///////////////////////////////////////////////////////////////////////////////
1896 // Browser, UI update coalescing and handling (private):
1898 void Browser::UpdateToolbar(bool should_restore_state
) {
1899 window_
->UpdateToolbar(should_restore_state
?
1900 tab_strip_model_
->GetActiveWebContents() : NULL
);
1903 void Browser::ScheduleUIUpdate(const WebContents
* source
,
1904 unsigned changed_flags
) {
1906 int index
= tab_strip_model_
->GetIndexOfWebContents(source
);
1907 DCHECK_NE(TabStripModel::kNoTab
, index
);
1909 // Do some synchronous updates.
1910 if (changed_flags
& content::INVALIDATE_TYPE_URL
&&
1911 source
== tab_strip_model_
->GetActiveWebContents()) {
1912 // Only update the URL for the current tab. Note that we do not update
1913 // the navigation commands since those would have already been updated
1914 // synchronously by NavigationStateChanged.
1915 UpdateToolbar(false);
1916 changed_flags
&= ~content::INVALIDATE_TYPE_URL
;
1918 if (changed_flags
& content::INVALIDATE_TYPE_LOAD
) {
1919 // Update the loading state synchronously. This is so the throbber will
1920 // immediately start/stop, which gives a more snappy feel. We want to do
1921 // this for any tab so they start & stop quickly.
1922 tab_strip_model_
->UpdateWebContentsStateAt(
1923 tab_strip_model_
->GetIndexOfWebContents(source
),
1924 TabStripModelObserver::LOADING_ONLY
);
1925 // The status bubble needs to be updated during INVALIDATE_TYPE_LOAD too,
1926 // but we do that asynchronously by not stripping INVALIDATE_TYPE_LOAD from
1930 if (changed_flags
& content::INVALIDATE_TYPE_TITLE
&& !source
->IsLoading()) {
1931 // To correctly calculate whether the title changed while not loading
1932 // we need to process the update synchronously. This state only matters for
1933 // the TabStripModel, so we notify the TabStripModel now and notify others
1935 tab_strip_model_
->UpdateWebContentsStateAt(
1936 tab_strip_model_
->GetIndexOfWebContents(source
),
1937 TabStripModelObserver::TITLE_NOT_LOADING
);
1940 // If the only updates were synchronously handled above, we're done.
1941 if (changed_flags
== 0)
1944 // Save the dirty bits.
1945 scheduled_updates_
[source
] |= changed_flags
;
1947 if (!chrome_updater_factory_
.HasWeakPtrs()) {
1948 // No task currently scheduled, start another.
1949 base::MessageLoop::current()->PostDelayedTask(
1951 base::Bind(&Browser::ProcessPendingUIUpdates
,
1952 chrome_updater_factory_
.GetWeakPtr()),
1953 base::TimeDelta::FromMilliseconds(kUIUpdateCoalescingTimeMS
));
1957 void Browser::ProcessPendingUIUpdates() {
1959 // Validate that all tabs we have pending updates for exist. This is scary
1960 // because the pending list must be kept in sync with any detached or
1962 for (UpdateMap::const_iterator i
= scheduled_updates_
.begin();
1963 i
!= scheduled_updates_
.end(); ++i
) {
1965 for (int tab
= 0; tab
< tab_strip_model_
->count(); tab
++) {
1966 if (tab_strip_model_
->GetWebContentsAt(tab
) == i
->first
) {
1975 chrome_updater_factory_
.InvalidateWeakPtrs();
1977 for (UpdateMap::const_iterator i
= scheduled_updates_
.begin();
1978 i
!= scheduled_updates_
.end(); ++i
) {
1979 // Do not dereference |contents|, it may be out-of-date!
1980 const WebContents
* contents
= i
->first
;
1981 unsigned flags
= i
->second
;
1983 if (contents
== tab_strip_model_
->GetActiveWebContents()) {
1984 // Updates that only matter when the tab is selected go here.
1986 if (flags
& content::INVALIDATE_TYPE_PAGE_ACTIONS
) {
1987 LocationBar
* location_bar
= window()->GetLocationBar();
1989 location_bar
->UpdatePageActions();
1991 // Updating the URL happens synchronously in ScheduleUIUpdate.
1992 if (flags
& content::INVALIDATE_TYPE_LOAD
&& GetStatusBubble()) {
1993 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
1994 tab_strip_model_
->GetActiveWebContents())->GetStatusText());
1997 if (flags
& (content::INVALIDATE_TYPE_TAB
|
1998 content::INVALIDATE_TYPE_TITLE
)) {
1999 window_
->UpdateTitleBar();
2003 // Updates that don't depend upon the selected state go here.
2005 (content::INVALIDATE_TYPE_TAB
| content::INVALIDATE_TYPE_TITLE
)) {
2006 tab_strip_model_
->UpdateWebContentsStateAt(
2007 tab_strip_model_
->GetIndexOfWebContents(contents
),
2008 TabStripModelObserver::ALL
);
2011 // Update the bookmark bar. It may happen that the tab is crashed, and if
2012 // so, the bookmark bar should be hidden.
2013 if (flags
& content::INVALIDATE_TYPE_TAB
)
2014 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE
);
2016 // We don't need to process INVALIDATE_STATE, since that's not visible.
2019 scheduled_updates_
.clear();
2022 void Browser::RemoveScheduledUpdatesFor(WebContents
* contents
) {
2026 UpdateMap::iterator i
= scheduled_updates_
.find(contents
);
2027 if (i
!= scheduled_updates_
.end())
2028 scheduled_updates_
.erase(i
);
2031 ///////////////////////////////////////////////////////////////////////////////
2032 // Browser, Getters for UI (private):
2034 StatusBubble
* Browser::GetStatusBubble() {
2035 // In kiosk and exclusive app mode, we want to always hide the status bubble.
2036 if (chrome::IsRunningInAppMode())
2039 return window_
? window_
->GetStatusBubble() : NULL
;
2042 ///////////////////////////////////////////////////////////////////////////////
2043 // Browser, Session restore functions (private):
2045 void Browser::SyncHistoryWithTabs(int index
) {
2046 SessionService
* session_service
=
2047 SessionServiceFactory::GetForProfileIfExisting(profile());
2048 if (session_service
) {
2049 for (int i
= index
; i
< tab_strip_model_
->count(); ++i
) {
2050 WebContents
* web_contents
= tab_strip_model_
->GetWebContentsAt(i
);
2052 SessionTabHelper
* session_tab_helper
=
2053 SessionTabHelper::FromWebContents(web_contents
);
2054 session_service
->SetTabIndexInWindow(
2055 session_id(), session_tab_helper
->session_id(), i
);
2056 session_service
->SetPinnedState(
2058 session_tab_helper
->session_id(),
2059 tab_strip_model_
->IsTabPinned(i
));
2065 ///////////////////////////////////////////////////////////////////////////////
2066 // Browser, In-progress download termination handling (private):
2068 bool Browser::CanCloseWithInProgressDownloads() {
2069 // If we've prompted, we need to hear from the user before we
2071 if (cancel_download_confirmation_state_
!= NOT_PROMPTED
)
2072 return cancel_download_confirmation_state_
!= WAITING_FOR_RESPONSE
;
2074 int num_downloads_blocking
;
2075 Browser::DownloadClosePreventionType dialog_type
=
2076 OkToCloseWithInProgressDownloads(&num_downloads_blocking
);
2077 if (dialog_type
== DOWNLOAD_CLOSE_OK
)
2080 // Closing this window will kill some downloads; prompt to make sure
2082 cancel_download_confirmation_state_
= WAITING_FOR_RESPONSE
;
2083 window_
->ConfirmBrowserCloseWithPendingDownloads(
2084 num_downloads_blocking
,
2087 base::Bind(&Browser::InProgressDownloadResponse
,
2088 weak_factory_
.GetWeakPtr()));
2090 // Return false so the browser does not close. We'll close if the user
2091 // confirms in the dialog.
2095 ///////////////////////////////////////////////////////////////////////////////
2096 // Browser, Assorted utility functions (private):
2098 void Browser::SetAsDelegate(WebContents
* web_contents
, Browser
* delegate
) {
2100 web_contents
->SetDelegate(delegate
);
2102 // ...and all the helpers.
2103 BookmarkTabHelper::FromWebContents(web_contents
)->set_delegate(delegate
);
2104 WebContentsModalDialogManager::FromWebContents(web_contents
)->
2105 SetDelegate(delegate
);
2106 CoreTabHelper::FromWebContents(web_contents
)->set_delegate(delegate
);
2107 SearchEngineTabHelper::FromWebContents(web_contents
)->set_delegate(delegate
);
2108 ZoomController::FromWebContents(web_contents
)->set_observer(delegate
);
2109 TranslateTabHelper
* translate_tab_helper
=
2110 TranslateTabHelper::FromWebContents(web_contents
);
2111 translate_tab_helper
->translate_driver().set_observer(
2112 delegate
? delegate
->translate_driver_observer_
.get() : NULL
);
2115 void Browser::CloseFrame() {
2119 void Browser::TabDetachedAtImpl(content::WebContents
* contents
,
2122 if (type
== DETACH_TYPE_DETACH
) {
2123 // Save the current location bar state, but only if the tab being detached
2124 // is the selected tab. Because saving state can conditionally revert the
2125 // location bar, saving the current tab's location bar state to a
2126 // non-selected tab can corrupt both tabs.
2127 if (contents
== tab_strip_model_
->GetActiveWebContents()) {
2128 LocationBar
* location_bar
= window()->GetLocationBar();
2130 location_bar
->SaveStateToContents(contents
);
2133 if (!tab_strip_model_
->closing_all())
2134 SyncHistoryWithTabs(0);
2137 SetAsDelegate(contents
, NULL
);
2138 RemoveScheduledUpdatesFor(contents
);
2140 if (find_bar_controller_
.get() && index
== tab_strip_model_
->active_index()) {
2141 find_bar_controller_
->ChangeWebContents(NULL
);
2144 // Stop observing search model changes for this tab.
2145 search_delegate_
->OnTabDetached(contents
);
2147 for (size_t i
= 0; i
< interstitial_observers_
.size(); i
++) {
2148 if (interstitial_observers_
[i
]->web_contents() != contents
)
2151 delete interstitial_observers_
[i
];
2152 interstitial_observers_
.erase(interstitial_observers_
.begin() + i
);
2157 bool Browser::SupportsWindowFeatureImpl(WindowFeature feature
,
2158 bool check_fullscreen
) const {
2159 bool hide_ui_for_fullscreen
= check_fullscreen
&& ShouldHideUIForFullscreen();
2161 unsigned int features
= FEATURE_INFOBAR
| FEATURE_DOWNLOADSHELF
;
2163 if (is_type_tabbed())
2164 features
|= FEATURE_BOOKMARKBAR
;
2166 if (!hide_ui_for_fullscreen
) {
2167 if (!is_type_tabbed())
2168 features
|= FEATURE_TITLEBAR
;
2170 if (is_type_tabbed())
2171 features
|= FEATURE_TABSTRIP
;
2173 if (is_type_tabbed())
2174 features
|= FEATURE_TOOLBAR
;
2176 ExtensionService
* service
=
2177 extensions::ExtensionSystem::Get(profile_
)->extension_service();
2178 const extensions::Extension
* extension
=
2179 service
? service
->GetInstalledExtension(
2180 web_app::GetExtensionIdFromApplicationName(app_name()))
2183 if (!is_app() || (app_type() == APP_TYPE_HOST
&&
2184 app_name() != DevToolsWindow::kDevToolsApp
&&
2185 (!extension
|| !extension
->is_legacy_packaged_app()) &&
2186 CommandLine::ForCurrentProcess()->HasSwitch(
2187 switches::kEnableStreamlinedHostedApps
))) {
2188 features
|= FEATURE_LOCATIONBAR
;
2191 return !!(features
& feature
);
2194 void Browser::UpdateBookmarkBarState(BookmarkBarStateChangeReason reason
) {
2195 BookmarkBar::State state
;
2196 // The bookmark bar is hidden in fullscreen mode, unless on the new tab page.
2197 if (browser_defaults::bookmarks_enabled
&&
2198 profile_
->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar
) &&
2199 !ShouldHideUIForFullscreen()) {
2200 state
= BookmarkBar::SHOW
;
2202 WebContents
* web_contents
= tab_strip_model_
->GetActiveWebContents();
2203 BookmarkTabHelper
* bookmark_tab_helper
=
2204 web_contents
? BookmarkTabHelper::FromWebContents(web_contents
) : NULL
;
2205 if (bookmark_tab_helper
&& bookmark_tab_helper
->ShouldShowBookmarkBar())
2206 state
= BookmarkBar::DETACHED
;
2208 state
= BookmarkBar::HIDDEN
;
2211 if (state
== bookmark_bar_state_
)
2214 bookmark_bar_state_
= state
;
2217 return; // This is called from the constructor when window_ is NULL.
2219 if (reason
== BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH
) {
2220 // Don't notify BrowserWindow on a tab switch as at the time this is invoked
2221 // BrowserWindow hasn't yet switched tabs. The BrowserWindow implementations
2222 // end up querying state once they process the tab switch.
2226 bool shouldAnimate
= reason
== BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE
;
2227 window_
->BookmarkBarStateChanged(shouldAnimate
?
2228 BookmarkBar::ANIMATE_STATE_CHANGE
:
2229 BookmarkBar::DONT_ANIMATE_STATE_CHANGE
);
2232 bool Browser::ShouldHideUIForFullscreen() const {
2233 // Windows and GTK remove the top controls in fullscreen, but Mac and Ash
2234 // keep the controls in a slide-down panel.
2235 return window_
&& window_
->ShouldHideUIForFullscreen();
2238 bool Browser::MaybeCreateBackgroundContents(
2240 WebContents
* opener_web_contents
,
2241 const base::string16
& frame_name
,
2242 const GURL
& target_url
,
2243 const std::string
& partition_id
,
2244 content::SessionStorageNamespace
* session_storage_namespace
) {
2245 GURL opener_url
= opener_web_contents
->GetURL();
2246 ExtensionService
* extensions_service
=
2247 extensions::ExtensionSystem::Get(profile_
)->extension_service();
2249 if (!opener_url
.is_valid() ||
2250 frame_name
.empty() ||
2251 !extensions_service
||
2252 !extensions_service
->is_ready())
2255 // Only hosted apps have web extents, so this ensures that only hosted apps
2256 // can create BackgroundContents. We don't have to check for background
2257 // permission as that is checked in RenderMessageFilter when the CreateWindow
2258 // message is processed.
2259 const Extension
* extension
=
2260 extensions_service
->extensions()->GetHostedAppByURL(opener_url
);
2264 // No BackgroundContents allowed if BackgroundContentsService doesn't exist.
2265 BackgroundContentsService
* service
=
2266 BackgroundContentsServiceFactory::GetForProfile(profile_
);
2270 // Ensure that we're trying to open this from the extension's process.
2271 SiteInstance
* opener_site_instance
= opener_web_contents
->GetSiteInstance();
2272 extensions::ProcessMap
* process_map
= extensions::ProcessMap::Get(profile_
);
2273 if (!opener_site_instance
->GetProcess() ||
2274 !process_map
->Contains(
2275 extension
->id(), opener_site_instance
->GetProcess()->GetID())) {
2279 // Only allow a single background contents per app.
2280 bool allow_js_access
= extensions::BackgroundInfo::AllowJSAccess(extension
);
2281 BackgroundContents
* existing
=
2282 service
->GetAppBackgroundContents(base::ASCIIToUTF16(extension
->id()));
2284 // For non-scriptable background contents, ignore the request altogether,
2285 // (returning true, so that a regular WebContents isn't created either).
2286 if (!allow_js_access
)
2288 // For scriptable background pages, if one already exists, close it (even
2289 // if it was specified in the manifest).
2293 // If script access is not allowed, create the the background contents in a
2294 // new SiteInstance, so that a separate process is used.
2295 scoped_refptr
<content::SiteInstance
> site_instance
=
2297 opener_site_instance
:
2298 content::SiteInstance::Create(opener_web_contents
->GetBrowserContext());
2300 // Passed all the checks, so this should be created as a BackgroundContents.
2301 BackgroundContents
* contents
=
2302 service
->CreateBackgroundContents(site_instance
.get(),
2306 base::ASCIIToUTF16(extension
->id()),
2308 session_storage_namespace
);
2310 // When a separate process is used, the original renderer cannot access the
2311 // new window later, thus we need to navigate the window now.
2312 if (contents
&& !allow_js_access
) {
2313 contents
->web_contents()->GetController().LoadURL(
2315 content::Referrer(),
2316 content::PAGE_TRANSITION_LINK
,
2317 std::string()); // No extra headers.
2320 return contents
!= NULL
;