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/location.h"
19 #include "base/logging.h"
20 #include "base/metrics/histogram.h"
21 #include "base/prefs/pref_service.h"
22 #include "base/process/process_info.h"
23 #include "base/profiler/scoped_tracker.h"
24 #include "base/single_thread_task_runner.h"
25 #include "base/strings/string_number_conversions.h"
26 #include "base/strings/string_util.h"
27 #include "base/strings/stringprintf.h"
28 #include "base/strings/utf_string_conversions.h"
29 #include "base/thread_task_runner_handle.h"
30 #include "base/threading/thread.h"
31 #include "base/threading/thread_restrictions.h"
32 #include "base/time/time.h"
33 #include "chrome/app/chrome_command_ids.h"
34 #include "chrome/browser/app_mode/app_mode_utils.h"
35 #include "chrome/browser/autofill/personal_data_manager_factory.h"
36 #include "chrome/browser/background/background_contents.h"
37 #include "chrome/browser/background/background_contents_service.h"
38 #include "chrome/browser/background/background_contents_service_factory.h"
39 #include "chrome/browser/browser_process.h"
40 #include "chrome/browser/browser_shutdown.h"
41 #include "chrome/browser/character_encoding.h"
42 #include "chrome/browser/chrome_notification_types.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_service.h"
52 #include "chrome/browser/download/download_service_factory.h"
53 #include "chrome/browser/extensions/api/tabs/tabs_event_router.h"
54 #include "chrome/browser/extensions/api/tabs/tabs_windows_api.h"
55 #include "chrome/browser/extensions/browser_extension_window_controller.h"
56 #include "chrome/browser/extensions/extension_service.h"
57 #include "chrome/browser/extensions/extension_ui_util.h"
58 #include "chrome/browser/extensions/extension_util.h"
59 #include "chrome/browser/extensions/tab_helper.h"
60 #include "chrome/browser/file_select_helper.h"
61 #include "chrome/browser/first_run/first_run.h"
62 #include "chrome/browser/history/top_sites_factory.h"
63 #include "chrome/browser/infobars/infobar_service.h"
64 #include "chrome/browser/lifetime/application_lifetime.h"
65 #include "chrome/browser/notifications/notification_ui_manager.h"
66 #include "chrome/browser/pepper_broker_infobar_delegate.h"
67 #include "chrome/browser/prefs/incognito_mode_prefs.h"
68 #include "chrome/browser/profiles/profile.h"
69 #include "chrome/browser/profiles/profile_destroyer.h"
70 #include "chrome/browser/profiles/profile_metrics.h"
71 #include "chrome/browser/profiles/profiles_state.h"
72 #include "chrome/browser/repost_form_warning_controller.h"
73 #include "chrome/browser/search/search.h"
74 #include "chrome/browser/sessions/session_restore.h"
75 #include "chrome/browser/sessions/session_service.h"
76 #include "chrome/browser/sessions/session_service_factory.h"
77 #include "chrome/browser/sessions/session_tab_helper.h"
78 #include "chrome/browser/sessions/tab_restore_service.h"
79 #include "chrome/browser/sessions/tab_restore_service_factory.h"
80 #include "chrome/browser/ssl/security_state_model.h"
81 #include "chrome/browser/sync/profile_sync_service.h"
82 #include "chrome/browser/sync/profile_sync_service_factory.h"
83 #include "chrome/browser/sync/sync_ui_util.h"
84 #include "chrome/browser/tab_contents/retargeting_details.h"
85 #include "chrome/browser/tab_contents/tab_util.h"
86 #include "chrome/browser/task_management/web_contents_tags.h"
87 #include "chrome/browser/themes/theme_service.h"
88 #include "chrome/browser/themes/theme_service_factory.h"
89 #include "chrome/browser/translate/chrome_translate_client.h"
90 #include "chrome/browser/ui/autofill/chrome_autofill_client.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/bookmarks/bookmark_utils.h"
94 #include "chrome/browser/ui/browser_command_controller.h"
95 #include "chrome/browser/ui/browser_commands.h"
96 #include "chrome/browser/ui/browser_content_setting_bubble_model_delegate.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/exclusive_access/fullscreen_controller.h"
112 #include "chrome/browser/ui/exclusive_access/mouse_lock_controller.h"
113 #include "chrome/browser/ui/extensions/hosted_app_browser_controller.h"
114 #include "chrome/browser/ui/fast_unload_controller.h"
115 #include "chrome/browser/ui/find_bar/find_bar.h"
116 #include "chrome/browser/ui/find_bar/find_bar_controller.h"
117 #include "chrome/browser/ui/find_bar/find_tab_helper.h"
118 #include "chrome/browser/ui/global_error/global_error.h"
119 #include "chrome/browser/ui/global_error/global_error_service.h"
120 #include "chrome/browser/ui/global_error/global_error_service_factory.h"
121 #include "chrome/browser/ui/location_bar/location_bar.h"
122 #include "chrome/browser/ui/media_utils.h"
123 #include "chrome/browser/ui/search/search_delegate.h"
124 #include "chrome/browser/ui/search/search_model.h"
125 #include "chrome/browser/ui/search/search_tab_helper.h"
126 #include "chrome/browser/ui/search_engines/search_engine_tab_helper.h"
127 #include "chrome/browser/ui/settings_window_manager.h"
128 #include "chrome/browser/ui/singleton_tabs.h"
129 #include "chrome/browser/ui/status_bubble.h"
130 #include "chrome/browser/ui/sync/browser_synced_window_delegate.h"
131 #include "chrome/browser/ui/tab_contents/core_tab_helper.h"
132 #include "chrome/browser/ui/tab_dialogs.h"
133 #include "chrome/browser/ui/tab_helpers.h"
134 #include "chrome/browser/ui/tab_modal_confirm_dialog.h"
135 #include "chrome/browser/ui/tabs/tab_menu_model.h"
136 #include "chrome/browser/ui/tabs/tab_strip_model.h"
137 #include "chrome/browser/ui/tabs/tab_strip_model_utils.h"
138 #include "chrome/browser/ui/tabs/tab_utils.h"
139 #include "chrome/browser/ui/toolbar/toolbar_model_impl.h"
140 #include "chrome/browser/ui/unload_controller.h"
141 #include "chrome/browser/ui/validation_message_bubble.h"
142 #include "chrome/browser/ui/website_settings/permission_bubble_manager.h"
143 #include "chrome/browser/ui/webui/signin/login_ui_service.h"
144 #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h"
145 #include "chrome/browser/ui/window_sizer/window_sizer.h"
146 #include "chrome/browser/upgrade_detector.h"
147 #include "chrome/common/chrome_constants.h"
148 #include "chrome/common/chrome_switches.h"
149 #include "chrome/common/custom_handlers/protocol_handler.h"
150 #include "chrome/common/pref_names.h"
151 #include "chrome/common/profiling.h"
152 #include "chrome/common/search_types.h"
153 #include "chrome/common/url_constants.h"
154 #include "chrome/grit/chromium_strings.h"
155 #include "chrome/grit/generated_resources.h"
156 #include "chrome/grit/locale_settings.h"
157 #include "components/app_modal/javascript_dialog_manager.h"
158 #include "components/bookmarks/browser/bookmark_model.h"
159 #include "components/bookmarks/browser/bookmark_utils.h"
160 #include "components/content_settings/core/browser/host_content_settings_map.h"
161 #include "components/favicon/content/content_favicon_driver.h"
162 #include "components/history/core/browser/top_sites.h"
163 #include "components/search/search.h"
164 #include "components/sessions/session_types.h"
165 #include "components/startup_metric_utils/startup_metric_utils.h"
166 #include "components/translate/core/browser/language_state.h"
167 #include "components/ui/zoom/zoom_controller.h"
168 #include "components/web_modal/web_contents_modal_dialog_manager.h"
169 #include "content/public/browser/devtools_agent_host.h"
170 #include "content/public/browser/interstitial_page.h"
171 #include "content/public/browser/invalidate_type.h"
172 #include "content/public/browser/navigation_controller.h"
173 #include "content/public/browser/navigation_entry.h"
174 #include "content/public/browser/notification_details.h"
175 #include "content/public/browser/notification_service.h"
176 #include "content/public/browser/plugin_service.h"
177 #include "content/public/browser/render_process_host.h"
178 #include "content/public/browser/render_view_host.h"
179 #include "content/public/browser/render_widget_host_view.h"
180 #include "content/public/browser/security_style_explanation.h"
181 #include "content/public/browser/security_style_explanations.h"
182 #include "content/public/browser/site_instance.h"
183 #include "content/public/browser/user_metrics.h"
184 #include "content/public/browser/web_contents.h"
185 #include "content/public/common/content_switches.h"
186 #include "content/public/common/page_zoom.h"
187 #include "content/public/common/renderer_preferences.h"
188 #include "content/public/common/ssl_status.h"
189 #include "content/public/common/webplugininfo.h"
190 #include "extensions/browser/extension_prefs.h"
191 #include "extensions/browser/extension_registry.h"
192 #include "extensions/browser/extension_system.h"
193 #include "extensions/common/constants.h"
194 #include "extensions/common/extension.h"
195 #include "extensions/common/manifest_handlers/background_info.h"
196 #include "net/base/filename_util.h"
197 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
198 #include "net/cookies/cookie_monster.h"
199 #include "net/url_request/url_request_context.h"
200 #include "third_party/WebKit/public/web/WebWindowFeatures.h"
201 #include "ui/base/l10n/l10n_util.h"
202 #include "ui/base/window_open_disposition.h"
203 #include "ui/gfx/geometry/point.h"
204 #include "ui/shell_dialogs/selected_file_info.h"
207 #include "base/win/metro.h"
208 #include "chrome/browser/ssl/ssl_error_info.h"
209 #include "chrome/browser/task_manager/task_manager.h"
210 #include "chrome/browser/ui/view_ids.h"
211 #include "components/autofill/core/browser/autofill_ie_toolbar_import_win.h"
212 #include "components/browser_watcher/exit_funnel_win.h"
213 #include "ui/base/touch/touch_device.h"
214 #include "ui/base/win/shell.h"
217 #if defined(OS_CHROMEOS)
218 #include "chrome/browser/chromeos/fileapi/external_file_url_util.h"
222 #include "ash/ash_switches.h"
225 using base::TimeDelta
;
226 using base::UserMetricsAction
;
227 using content::NativeWebKeyboardEvent
;
228 using content::NavigationController
;
229 using content::NavigationEntry
;
230 using content::OpenURLParams
;
231 using content::PluginService
;
232 using content::Referrer
;
233 using content::RenderWidgetHostView
;
234 using content::SiteInstance
;
235 using content::WebContents
;
236 using extensions::Extension
;
237 using ui::WebDialogDelegate
;
238 using web_modal::WebContentsModalDialogManager
;
239 using blink::WebWindowFeatures
;
241 ///////////////////////////////////////////////////////////////////////////////
245 // How long we wait before updating the browser chrome while loading a page.
246 const int kUIUpdateCoalescingTimeMS
= 200;
248 BrowserWindow
* CreateBrowserWindow(Browser
* browser
) {
249 return BrowserWindow::CreateBrowserWindow(browser
);
252 // Is the fast tab unload experiment enabled?
253 bool IsFastTabUnloadEnabled() {
254 return base::CommandLine::ForCurrentProcess()->HasSwitch(
255 switches::kEnableFastUnload
);
258 // Note: This is a lossy operation. Not all of the policies that can be
259 // expressed by a SecurityLevel (a //chrome concept) can be expressed by
260 // a content::SecurityStyle.
261 content::SecurityStyle
SecurityLevelToSecurityStyle(
262 SecurityStateModel::SecurityLevel security_level
) {
263 switch (security_level
) {
264 case SecurityStateModel::NONE
:
265 return content::SECURITY_STYLE_UNAUTHENTICATED
;
266 case SecurityStateModel::SECURITY_WARNING
:
267 case SecurityStateModel::SECURITY_POLICY_WARNING
:
268 return content::SECURITY_STYLE_WARNING
;
269 case SecurityStateModel::EV_SECURE
:
270 case SecurityStateModel::SECURE
:
271 return content::SECURITY_STYLE_AUTHENTICATED
;
272 case SecurityStateModel::SECURITY_ERROR
:
273 return content::SECURITY_STYLE_AUTHENTICATION_BROKEN
;
277 return content::SECURITY_STYLE_UNKNOWN
;
282 ////////////////////////////////////////////////////////////////////////////////
283 // Browser, CreateParams:
285 Browser::CreateParams::CreateParams(Profile
* profile
,
286 chrome::HostDesktopType host_desktop_type
)
289 host_desktop_type(host_desktop_type
),
290 trusted_source(false),
291 initial_show_state(ui::SHOW_STATE_DEFAULT
),
292 is_session_restore(false),
296 Browser::CreateParams::CreateParams(Type type
,
298 chrome::HostDesktopType host_desktop_type
)
301 host_desktop_type(host_desktop_type
),
302 trusted_source(false),
303 initial_show_state(ui::SHOW_STATE_DEFAULT
),
304 is_session_restore(false),
309 Browser::CreateParams
Browser::CreateParams::CreateForApp(
310 const std::string
& app_name
,
312 const gfx::Rect
& window_bounds
,
314 chrome::HostDesktopType host_desktop_type
) {
315 DCHECK(!app_name
.empty());
317 CreateParams
params(TYPE_POPUP
, profile
, host_desktop_type
);
318 params
.app_name
= app_name
;
319 params
.trusted_source
= trusted_source
;
320 params
.initial_bounds
= window_bounds
;
326 Browser::CreateParams
Browser::CreateParams::CreateForDevTools(
328 chrome::HostDesktopType host_desktop_type
) {
329 CreateParams
params(TYPE_POPUP
, profile
, host_desktop_type
);
330 params
.app_name
= DevToolsWindow::kDevToolsApp
;
331 params
.trusted_source
= true;
335 ////////////////////////////////////////////////////////////////////////////////
336 // Browser, InterstitialObserver:
338 class Browser::InterstitialObserver
: public content::WebContentsObserver
{
340 InterstitialObserver(Browser
* browser
, content::WebContents
* web_contents
)
341 : WebContentsObserver(web_contents
),
345 void DidAttachInterstitialPage() override
{
346 browser_
->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE
);
349 void DidDetachInterstitialPage() override
{
350 browser_
->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE
);
356 DISALLOW_COPY_AND_ASSIGN(InterstitialObserver
);
359 ///////////////////////////////////////////////////////////////////////////////
360 // Browser, Constructors, Creation, Showing:
362 Browser::Browser(const CreateParams
& params
)
363 : extension_registry_observer_(this),
365 profile_(params
.profile
),
367 tab_strip_model_delegate_(new chrome::BrowserTabStripModelDelegate(this)),
369 new TabStripModel(tab_strip_model_delegate_
.get(), params
.profile
)),
370 app_name_(params
.app_name
),
371 is_trusted_source_(params
.trusted_source
),
372 cancel_download_confirmation_state_(NOT_PROMPTED
),
373 override_bounds_(params
.initial_bounds
),
374 initial_show_state_(params
.initial_show_state
),
375 is_session_restore_(params
.is_session_restore
),
377 BrowserWindow::AdjustHostDesktopType(params
.host_desktop_type
)),
378 content_setting_bubble_model_delegate_(
379 new BrowserContentSettingBubbleModelDelegate(this)),
380 toolbar_model_delegate_(new BrowserToolbarModelDelegate(this)),
381 tab_restore_service_delegate_(new BrowserTabRestoreServiceDelegate(this)),
382 synced_window_delegate_(new BrowserSyncedWindowDelegate(this)),
383 bookmark_bar_state_(BookmarkBar::HIDDEN
),
384 command_controller_(new chrome::BrowserCommandController(this)),
385 window_has_shown_(false),
386 chrome_updater_factory_(this),
387 weak_factory_(this) {
388 // If this causes a crash then a window is being opened using a profile type
389 // that is disallowed by policy. The crash prevents the disabled window type
390 // from opening at all, but the path that triggered it should be fixed.
391 CHECK(IncognitoModePrefs::CanOpenBrowser(profile_
));
392 CHECK(!profile_
->IsGuestSession() || profile_
->IsOffTheRecord())
393 << "Only off the record browser may be opened in guest mode";
394 DCHECK(!profile_
->IsSystemProfile())
395 << "The system profile should never have a real browser.";
396 // TODO(mlerman): After this hits stable channel, see if there are counts
397 // for this metric. If not, change the DCHECK above to a CHECK.
398 if (profile_
->IsSystemProfile())
399 content::RecordAction(base::UserMetricsAction("BrowserForSystemProfile"));
401 // TODO(jeremy): Move to initializer list once flag is removed.
402 if (IsFastTabUnloadEnabled())
403 fast_unload_controller_
.reset(new chrome::FastUnloadController(this));
405 unload_controller_
.reset(new chrome::UnloadController(this));
407 tab_strip_model_
->AddObserver(this);
409 toolbar_model_
.reset(new ToolbarModelImpl(toolbar_model_delegate_
.get()));
410 search_model_
.reset(new SearchModel());
411 search_delegate_
.reset(new SearchDelegate(search_model_
.get()));
413 extension_registry_observer_
.Add(
414 extensions::ExtensionRegistry::Get(profile_
));
416 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED
,
417 content::NotificationService::AllSources());
418 #if defined(ENABLE_THEMES)
420 this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED
,
421 content::Source
<ThemeService
>(
422 ThemeServiceFactory::GetForProfile(profile_
)));
424 registrar_
.Add(this, chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED
,
425 content::NotificationService::AllSources());
427 profile_pref_registrar_
.Init(profile_
->GetPrefs());
428 profile_pref_registrar_
.Add(
429 prefs::kDevToolsDisabled
,
430 base::Bind(&Browser::OnDevToolsDisabledChanged
, base::Unretained(this)));
431 profile_pref_registrar_
.Add(
432 bookmarks::prefs::kShowBookmarkBar
,
433 base::Bind(&Browser::UpdateBookmarkBarState
, base::Unretained(this),
434 BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE
));
436 // NOTE: These prefs all need to be explicitly destroyed in the destructor
437 // or you'll get a nasty surprise when you run the incognito tests.
438 encoding_auto_detect_
.Init(prefs::kWebKitUsesUniversalDetector
,
439 profile_
->GetPrefs());
441 if (search::IsInstantExtendedAPIEnabled() && is_type_tabbed())
442 instant_controller_
.reset(new BrowserInstantController(this));
444 if (extensions::HostedAppBrowserController::IsForHostedApp(this)) {
445 hosted_app_controller_
.reset(
446 new extensions::HostedAppBrowserController(this));
449 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_INIT
);
451 ProfileMetrics::LogProfileLaunch(profile_
);
453 window_
= params
.window
? params
.window
: CreateBrowserWindow(this);
455 if (hosted_app_controller_
)
456 hosted_app_controller_
->UpdateLocationBarVisibility(false);
458 // Create the extension window controller before sending notifications.
459 extension_window_controller_
.reset(
460 new BrowserExtensionWindowController(this));
462 SessionService
* session_service
=
463 SessionServiceFactory::GetForProfileForSessionRestore(profile_
);
465 session_service
->WindowOpened(this);
467 // TODO(beng): move to ChromeBrowserMain:
468 if (first_run::ShouldDoPersonalDataManagerFirstRun()) {
470 // Notify PDM that this is a first run.
471 ImportAutofillDataWin(
472 autofill::PersonalDataManagerFactory::GetForProfile(profile_
));
473 #endif // defined(OS_WIN)
476 exclusive_access_manager_
.reset(
477 new ExclusiveAccessManager(window_
->GetExclusiveAccessContext()));
479 // TODO(beng): Move BrowserList::AddBrowser() to the end of this function and
480 // replace uses of this with BL's notifications.
481 BrowserList::AddBrowser(this);
482 content::NotificationService::current()->Notify(
483 chrome::NOTIFICATION_BROWSER_WINDOW_READY
, content::Source
<Browser
>(this),
484 content::NotificationService::NoDetails());
487 Browser::~Browser() {
488 // Stop observing notifications before continuing with destruction. Profile
489 // destruction will unload extensions and reentrant calls to Browser:: should
490 // be avoided while it is being torn down.
491 registrar_
.RemoveAll();
492 extension_registry_observer_
.RemoveAll();
494 // The tab strip should not have any tabs at this point.
495 DCHECK(tab_strip_model_
->empty());
496 tab_strip_model_
->RemoveObserver(this);
497 bubble_manager_
.reset();
499 // Destroy the BrowserCommandController before removing the browser, so that
500 // it doesn't act on any notifications that are sent as a result of removing
502 command_controller_
.reset();
503 BrowserList::RemoveBrowser(this);
505 SessionService
* session_service
=
506 SessionServiceFactory::GetForProfile(profile_
);
508 session_service
->WindowClosed(session_id_
);
510 TabRestoreService
* tab_restore_service
=
511 TabRestoreServiceFactory::GetForProfile(profile());
512 if (tab_restore_service
)
513 tab_restore_service
->BrowserClosed(tab_restore_service_delegate());
515 #if !defined(OS_MACOSX)
516 if (!chrome::GetTotalBrowserCountForProfile(profile_
)) {
517 // We're the last browser window with this profile. We need to nuke the
518 // TabRestoreService, which will start the shutdown of the
519 // NavigationControllers and allow for proper shutdown. If we don't do this
520 // chrome won't shutdown cleanly, and may end up crashing when some
521 // thread tries to use the IO thread (or another thread) that is no longer
523 // This isn't a valid assumption for Mac OS, as it stays running after
524 // the last browser has closed. The Mac equivalent is in its app
526 TabRestoreServiceFactory::ResetForProfile(profile_
);
530 profile_pref_registrar_
.RemoveAll();
532 encoding_auto_detect_
.Destroy();
534 // Destroy BrowserExtensionWindowController before the incognito profile
535 // is destroyed to make sure the chrome.windows.onRemoved event is sent.
536 extension_window_controller_
.reset();
538 // Destroy BrowserInstantController before the incongnito profile is destroyed
539 // because the InstantController destructor depends on this profile.
540 instant_controller_
.reset();
542 if (profile_
->IsOffTheRecord() &&
543 !BrowserList::IsOffTheRecordSessionActiveForProfile(profile_
)) {
544 if (profile_
->IsGuestSession()) {
545 // ChromeOS handles guest data independently.
546 #if !defined(OS_CHROMEOS)
547 // Clear all browsing data once a Guest Session completes. The Guest
548 // profile has BrowserContextKeyedServices that the Incognito profile
549 // doesn't, so the ProfileDestroyer can't delete it properly.
550 // TODO(mlerman): Delete the guest using an improved ProfileDestroyer.
551 profiles::RemoveBrowsingDataForProfile(profile_
->GetPath());
554 // An incognito profile is no longer needed, this indirectly frees
555 // its cache and cookies once it gets destroyed at the appropriate time.
556 ProfileDestroyer::DestroyProfileWhenAppropriate(profile_
);
560 // There may be pending file dialogs, we need to tell them that we've gone
561 // away so they don't try and call back to us.
562 if (select_file_dialog_
.get())
563 select_file_dialog_
->ListenerDestroyed();
566 if (OkToCloseWithInProgressDownloads(&num_downloads
) ==
567 DOWNLOAD_CLOSE_BROWSER_SHUTDOWN
&&
568 !browser_defaults::kBrowserAliveWithNoWindows
) {
569 DownloadService::CancelAllDownloads();
573 ///////////////////////////////////////////////////////////////////////////////
576 ChromeBubbleManager
* Browser::GetBubbleManager() {
577 if (!bubble_manager_
)
578 bubble_manager_
.reset(new ChromeBubbleManager(tab_strip_model_
.get()));
579 return bubble_manager_
.get();
582 FindBarController
* Browser::GetFindBarController() {
583 if (!find_bar_controller_
.get()) {
584 FindBar
* find_bar
= window_
->CreateFindBar();
585 find_bar_controller_
.reset(new FindBarController(find_bar
));
586 find_bar
->SetFindBarController(find_bar_controller_
.get());
587 find_bar_controller_
->ChangeWebContents(
588 tab_strip_model_
->GetActiveWebContents());
589 find_bar_controller_
->find_bar()->MoveWindowIfNecessary(gfx::Rect());
591 return find_bar_controller_
.get();
594 bool Browser::HasFindBarController() const {
595 return find_bar_controller_
.get() != NULL
;
598 bool Browser::is_app() const {
599 return !app_name_
.empty();
602 bool Browser::is_devtools() const {
603 return app_name_
== DevToolsWindow::kDevToolsApp
;
606 ///////////////////////////////////////////////////////////////////////////////
607 // Browser, State Storage and Retrieval for UI:
609 gfx::Image
Browser::GetCurrentPageIcon() const {
610 WebContents
* web_contents
= tab_strip_model_
->GetActiveWebContents();
611 // |web_contents| can be NULL since GetCurrentPageIcon() is called by the
612 // window during the window's creation (before tabs have been added).
613 favicon::FaviconDriver
* favicon_driver
=
615 ? favicon::ContentFaviconDriver::FromWebContents(web_contents
)
617 return favicon_driver
? favicon_driver
->GetFavicon() : gfx::Image();
620 base::string16
Browser::GetWindowTitleForCurrentTab() const {
621 WebContents
* contents
= tab_strip_model_
->GetActiveWebContents();
622 base::string16 title
;
624 // |contents| can be NULL because GetWindowTitleForCurrentTab is called by the
625 // window during the window's creation (before tabs have been added).
627 // The web app frame uses the host instead of the title.
628 if (ShouldUseWebAppFrame())
629 return base::UTF8ToUTF16(contents
->GetURL().host());
631 title
= contents
->GetTitle();
632 FormatTitleForDisplay(&title
);
635 title
= CoreTabHelper::GetDefaultTitle();
637 #if defined(OS_MACOSX)
638 // On Mac, we don't want to suffix the page title with
639 // the application name.
641 #elif defined(USE_ASH)
642 // On Ash, we don't want to suffix the page title with the application name,
643 // but on Windows, where USE_ASH can also be true, we still want the prefix
645 if (host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH
)
648 // Don't append the app name to window titles on app frames and app popups
651 l10n_util::GetStringFUTF16(IDS_BROWSER_WINDOW_TITLE_FORMAT
, title
);
655 void Browser::FormatTitleForDisplay(base::string16
* title
) {
656 size_t current_index
= 0;
658 while ((match_index
= title
->find(L
'\n', current_index
)) !=
659 base::string16::npos
) {
660 title
->replace(match_index
, 1, base::string16());
661 current_index
= match_index
;
665 ///////////////////////////////////////////////////////////////////////////////
666 // Browser, OnBeforeUnload handling:
668 bool Browser::ShouldCloseWindow() {
669 if (!CanCloseWithInProgressDownloads())
672 if (IsFastTabUnloadEnabled())
673 return fast_unload_controller_
->ShouldCloseWindow();
674 return unload_controller_
->ShouldCloseWindow();
677 bool Browser::CallBeforeUnloadHandlers(
678 const base::Callback
<void(bool)>& on_close_confirmed
) {
679 cancel_download_confirmation_state_
= RESPONSE_RECEIVED
;
680 if (IsFastTabUnloadEnabled()) {
681 return fast_unload_controller_
->CallBeforeUnloadHandlers(
684 return unload_controller_
->CallBeforeUnloadHandlers(on_close_confirmed
);
687 void Browser::ResetBeforeUnloadHandlers() {
688 cancel_download_confirmation_state_
= NOT_PROMPTED
;
689 if (IsFastTabUnloadEnabled())
690 fast_unload_controller_
->ResetBeforeUnloadHandlers();
692 unload_controller_
->ResetBeforeUnloadHandlers();
695 bool Browser::HasCompletedUnloadProcessing() const {
696 DCHECK(IsFastTabUnloadEnabled());
697 return fast_unload_controller_
->HasCompletedUnloadProcessing();
700 bool Browser::IsAttemptingToCloseBrowser() const {
701 if (IsFastTabUnloadEnabled())
702 return fast_unload_controller_
->is_attempting_to_close_browser();
703 return unload_controller_
->is_attempting_to_close_browser();
706 void Browser::OnWindowClosing() {
707 if (!ShouldCloseWindow())
710 // Application should shutdown on last window close if the user is explicitly
711 // trying to quit, or if there is nothing keeping the browser alive (such as
712 // AppController on the Mac, or BackgroundContentsService for background
714 bool should_quit_if_last_browser
=
715 browser_shutdown::IsTryingToQuit() || !chrome::WillKeepAlive();
717 if (should_quit_if_last_browser
&& chrome::ShouldStartShutdown(this)) {
719 browser_watcher::ExitFunnel::RecordSingleEvent(
720 chrome::kBrowserExitCodesRegistryPath
, L
"LastWindowClose");
722 browser_shutdown::OnShutdownStarting(browser_shutdown::WINDOW_CLOSE
);
725 // Don't use GetForProfileIfExisting here, we want to force creation of the
726 // session service so that user can restore what was open.
727 SessionService
* session_service
=
728 SessionServiceFactory::GetForProfile(profile());
730 session_service
->WindowClosing(session_id());
732 TabRestoreService
* tab_restore_service
=
733 TabRestoreServiceFactory::GetForProfile(profile());
735 #if defined(USE_AURA)
736 if (tab_restore_service
&& is_app() && !is_devtools())
737 tab_restore_service
->BrowserClosing(tab_restore_service_delegate());
740 if (tab_restore_service
&& is_type_tabbed() && tab_strip_model_
->count())
741 tab_restore_service
->BrowserClosing(tab_restore_service_delegate());
743 // TODO(sky): convert session/tab restore to use notification.
744 content::NotificationService::current()->Notify(
745 chrome::NOTIFICATION_BROWSER_CLOSING
,
746 content::Source
<Browser
>(this),
747 content::NotificationService::NoDetails());
749 if (!IsFastTabUnloadEnabled())
750 tab_strip_model_
->CloseAllTabs();
753 ////////////////////////////////////////////////////////////////////////////////
754 // In-progress download termination handling:
756 void Browser::InProgressDownloadResponse(bool cancel_downloads
) {
757 if (cancel_downloads
) {
758 cancel_download_confirmation_state_
= RESPONSE_RECEIVED
;
759 chrome::CloseWindow(this);
763 // Sets the confirmation state to NOT_PROMPTED so that if the user tries to
764 // close again we'll show the warning again.
765 cancel_download_confirmation_state_
= NOT_PROMPTED
;
767 // Show the download page so the user can figure-out what downloads are still
769 chrome::ShowDownloads(this);
771 // Reset UnloadController::is_attempting_to_close_browser_ so that we don't
772 // prompt every time any tab is closed. http://crbug.com/305516
773 if (IsFastTabUnloadEnabled())
774 fast_unload_controller_
->CancelWindowClose();
776 unload_controller_
->CancelWindowClose();
779 Browser::DownloadClosePreventionType
Browser::OkToCloseWithInProgressDownloads(
780 int* num_downloads_blocking
) const {
781 DCHECK(num_downloads_blocking
);
782 *num_downloads_blocking
= 0;
784 // If we're not running a full browser process with a profile manager
785 // (testing), it's ok to close the browser.
786 if (!g_browser_process
->profile_manager())
787 return DOWNLOAD_CLOSE_OK
;
789 int total_download_count
=
790 DownloadService::NonMaliciousDownloadCountAllProfiles();
791 if (total_download_count
== 0)
792 return DOWNLOAD_CLOSE_OK
; // No downloads; can definitely close.
794 // Figure out how many windows are open total, and associated with this
795 // profile, that are relevant for the ok-to-close decision.
796 int profile_window_count
= 0;
797 int total_window_count
= 0;
798 for (chrome::BrowserIterator it
; !it
.done(); it
.Next()) {
799 // Don't count this browser window or any other in the process of closing.
800 Browser
* const browser
= *it
;
801 // Window closing may be delayed, and windows that are in the process of
802 // closing don't count against our totals.
803 if (browser
== this || browser
->IsAttemptingToCloseBrowser())
806 if (it
->profile() == profile())
807 profile_window_count
++;
808 total_window_count
++;
811 // If there aren't any other windows, we're at browser shutdown,
812 // which would cancel all current downloads.
813 if (total_window_count
== 0) {
814 *num_downloads_blocking
= total_download_count
;
815 return DOWNLOAD_CLOSE_BROWSER_SHUTDOWN
;
818 // If there aren't any other windows on our profile, and we're an incognito
819 // profile, and there are downloads associated with that profile,
820 // those downloads would be cancelled by our window (-> profile) close.
821 DownloadService
* download_service
=
822 DownloadServiceFactory::GetForBrowserContext(profile());
823 if ((profile_window_count
== 0) &&
824 (download_service
->NonMaliciousDownloadCount() > 0) &&
825 profile()->IsOffTheRecord()) {
826 *num_downloads_blocking
= download_service
->NonMaliciousDownloadCount();
827 return DOWNLOAD_CLOSE_LAST_WINDOW_IN_INCOGNITO_PROFILE
;
830 // Those are the only conditions under which we will block shutdown.
831 return DOWNLOAD_CLOSE_OK
;
834 ////////////////////////////////////////////////////////////////////////////////
835 // Browser, Tab adding/showing functions:
837 void Browser::WindowFullscreenStateChanged() {
838 exclusive_access_manager_
->fullscreen_controller()
839 ->WindowFullscreenStateChanged();
840 command_controller_
->FullscreenStateChanged();
841 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TOGGLE_FULLSCREEN
);
844 ///////////////////////////////////////////////////////////////////////////////
845 // Browser, Assorted browser commands:
847 void Browser::ToggleFullscreenModeWithExtension(const GURL
& extension_url
) {
848 exclusive_access_manager_
->fullscreen_controller()
849 ->ToggleBrowserFullscreenModeWithExtension(extension_url
);
852 bool Browser::SupportsWindowFeature(WindowFeature feature
) const {
853 return SupportsWindowFeatureImpl(feature
, true);
856 bool Browser::CanSupportWindowFeature(WindowFeature feature
) const {
857 return SupportsWindowFeatureImpl(feature
, false);
860 void Browser::ToggleEncodingAutoDetect() {
861 content::RecordAction(UserMetricsAction("AutoDetectChange"));
862 encoding_auto_detect_
.SetValue(!encoding_auto_detect_
.GetValue());
863 // If "auto detect" is turned on, then any current override encoding
864 // is cleared. This also implicitly performs a reload.
865 // OTOH, if "auto detect" is turned off, we don't change the currently
867 if (encoding_auto_detect_
.GetValue()) {
868 WebContents
* contents
= tab_strip_model_
->GetActiveWebContents();
870 contents
->ResetOverrideEncoding();
874 void Browser::OverrideEncoding(int encoding_id
) {
875 content::RecordAction(UserMetricsAction("OverrideEncoding"));
876 const std::string selected_encoding
=
877 CharacterEncoding::GetCanonicalEncodingNameByCommandId(encoding_id
);
878 WebContents
* contents
= tab_strip_model_
->GetActiveWebContents();
879 if (!selected_encoding
.empty() && contents
)
880 contents
->SetOverrideEncoding(selected_encoding
);
881 // Update the list of recently selected encodings.
882 std::string new_selected_encoding_list
;
883 if (CharacterEncoding::UpdateRecentlySelectedEncoding(
884 profile_
->GetPrefs()->GetString(prefs::kRecentlySelectedEncoding
),
886 &new_selected_encoding_list
)) {
887 profile_
->GetPrefs()->SetString(prefs::kRecentlySelectedEncoding
,
888 new_selected_encoding_list
);
892 void Browser::OpenFile() {
893 content::RecordAction(UserMetricsAction("OpenFile"));
894 select_file_dialog_
= ui::SelectFileDialog::Create(
895 this, new ChromeSelectFilePolicy(
896 tab_strip_model_
->GetActiveWebContents()));
898 const base::FilePath directory
= profile_
->last_selected_directory();
900 // TODO(beng): figure out how to juggle this.
901 gfx::NativeWindow parent_window
= window_
->GetNativeWindow();
902 ui::SelectFileDialog::FileTypeInfo file_types
;
903 file_types
.support_drive
= true;
904 select_file_dialog_
->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE
,
909 base::FilePath::StringType(),
914 void Browser::UpdateDownloadShelfVisibility(bool visible
) {
915 if (GetStatusBubble())
916 GetStatusBubble()->UpdateDownloadShelfVisibility(visible
);
919 ///////////////////////////////////////////////////////////////////////////////
921 void Browser::UpdateUIForNavigationInTab(WebContents
* contents
,
922 ui::PageTransition transition
,
923 bool user_initiated
) {
924 tab_strip_model_
->TabNavigating(contents
, transition
);
926 bool contents_is_selected
=
927 contents
== tab_strip_model_
->GetActiveWebContents();
928 if (user_initiated
&& contents_is_selected
&& window()->GetLocationBar()) {
929 // Forcibly reset the location bar if the url is going to change in the
930 // current tab, since otherwise it won't discard any ongoing user edits,
931 // since it doesn't realize this is a user-initiated action.
932 window()->GetLocationBar()->Revert();
935 if (GetStatusBubble())
936 GetStatusBubble()->Hide();
938 // Update the location bar. This is synchronous. We specifically don't
939 // update the load state since the load hasn't started yet and updating it
940 // will put it out of sync with the actual state like whether we're
941 // displaying a favicon, which controls the throbber. If we updated it here,
942 // the throbber will show the default favicon for a split second when
943 // navigating away from the new tab page.
944 ScheduleUIUpdate(contents
, content::INVALIDATE_TYPE_URL
);
946 if (contents_is_selected
)
947 contents
->SetInitialFocus();
950 ///////////////////////////////////////////////////////////////////////////////
951 // Browser, PageNavigator implementation:
953 WebContents
* Browser::OpenURL(const OpenURLParams
& params
) {
954 return OpenURLFromTab(NULL
, params
);
957 ///////////////////////////////////////////////////////////////////////////////
958 // Browser, TabStripModelObserver implementation:
960 void Browser::TabInsertedAt(WebContents
* contents
,
963 SetAsDelegate(contents
, true);
965 SessionTabHelper
* session_tab_helper
=
966 SessionTabHelper::FromWebContents(contents
);
967 session_tab_helper
->SetWindowID(session_id());
969 content::NotificationService::current()->Notify(
970 chrome::NOTIFICATION_TAB_PARENTED
,
971 content::Source
<content::WebContents
>(contents
),
972 content::NotificationService::NoDetails());
974 SyncHistoryWithTabs(index
);
976 // Make sure the loading state is updated correctly, otherwise the throbber
977 // won't start if the page is loading.
978 LoadingStateChanged(contents
, true);
980 interstitial_observers_
.push_back(new InterstitialObserver(this, contents
));
982 SessionService
* session_service
=
983 SessionServiceFactory::GetForProfile(profile_
);
984 if (session_service
) {
985 session_service
->TabInserted(contents
);
986 int new_active_index
= tab_strip_model_
->active_index();
987 if (index
< new_active_index
)
988 session_service
->SetSelectedTabInWindow(session_id(),
993 void Browser::TabClosingAt(TabStripModel
* tab_strip_model
,
994 WebContents
* contents
,
996 exclusive_access_manager_
->OnTabClosing(contents
);
997 SessionService
* session_service
=
998 SessionServiceFactory::GetForProfile(profile_
);
1000 session_service
->TabClosing(contents
);
1001 content::NotificationService::current()->Notify(
1002 chrome::NOTIFICATION_TAB_CLOSING
,
1003 content::Source
<NavigationController
>(&contents
->GetController()),
1004 content::NotificationService::NoDetails());
1006 // Sever the WebContents' connection back to us.
1007 SetAsDelegate(contents
, false);
1010 void Browser::TabDetachedAt(WebContents
* contents
, int index
) {
1011 // TabDetachedAt is called before TabStripModel has updated the
1013 int old_active_index
= tab_strip_model_
->active_index();
1014 if (index
< old_active_index
&& !tab_strip_model_
->closing_all()) {
1015 SessionService
* session_service
=
1016 SessionServiceFactory::GetForProfileIfExisting(profile_
);
1017 if (session_service
)
1018 session_service
->SetSelectedTabInWindow(session_id(),
1019 old_active_index
- 1);
1022 TabDetachedAtImpl(contents
, index
, DETACH_TYPE_DETACH
);
1025 void Browser::TabDeactivated(WebContents
* contents
) {
1026 exclusive_access_manager_
->OnTabDeactivated(contents
);
1027 search_delegate_
->OnTabDeactivated(contents
);
1028 SearchTabHelper::FromWebContents(contents
)->OnTabDeactivated();
1030 // Save what the user's currently typing, so it can be restored when we
1031 // switch back to this tab.
1032 window_
->GetLocationBar()->SaveStateToContents(contents
);
1034 if (instant_controller_
)
1035 instant_controller_
->TabDeactivated(contents
);
1038 void Browser::ActiveTabChanged(WebContents
* old_contents
,
1039 WebContents
* new_contents
,
1042 content::RecordAction(UserMetricsAction("ActiveTabChanged"));
1044 // Update the bookmark state, since the BrowserWindow may query it during
1045 // OnActiveTabChanged() below.
1046 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH
);
1048 // Let the BrowserWindow do its handling. On e.g. views this changes the
1049 // focused object, which should happen before we update the toolbar below,
1050 // since the omnibox expects the correct element to already be focused when it
1052 window_
->OnActiveTabChanged(old_contents
, new_contents
, index
, reason
);
1054 exclusive_access_manager_
->OnTabDetachedFromView(old_contents
);
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
);
1065 // If we have any update pending, do it now.
1066 if (chrome_updater_factory_
.HasWeakPtrs() && old_contents
)
1067 ProcessPendingUIUpdates();
1069 // Propagate the profile to the location bar.
1070 UpdateToolbar((reason
& CHANGE_REASON_REPLACED
) == 0);
1072 if (search::IsInstantExtendedAPIEnabled())
1073 search_delegate_
->OnTabActivated(new_contents
);
1075 // Update reload/stop state.
1076 command_controller_
->LoadingStateChanged(new_contents
->IsLoading(), true);
1078 // Update commands to reflect current state.
1079 command_controller_
->TabStateChanged();
1081 // Reset the status bubble.
1082 StatusBubble
* status_bubble
= GetStatusBubble();
1083 if (status_bubble
) {
1084 status_bubble
->Hide();
1086 // Show the loading state (if any).
1087 status_bubble
->SetStatus(CoreTabHelper::FromWebContents(
1088 tab_strip_model_
->GetActiveWebContents())->GetStatusText());
1091 if (HasFindBarController()) {
1092 find_bar_controller_
->ChangeWebContents(new_contents
);
1093 find_bar_controller_
->find_bar()->MoveWindowIfNecessary(gfx::Rect());
1096 // Update sessions (selected tab index and last active time). Don't force
1097 // creation of sessions. If sessions doesn't exist, the change will be picked
1098 // up by sessions when created.
1099 SessionService
* session_service
=
1100 SessionServiceFactory::GetForProfileIfExisting(profile_
);
1101 if (session_service
&& !tab_strip_model_
->closing_all()) {
1102 session_service
->SetSelectedTabInWindow(session_id(),
1103 tab_strip_model_
->active_index());
1104 if (SessionRestore::GetSmartRestoreMode() ==
1105 SessionRestore::SMART_RESTORE_MODE_MRU
) {
1106 SessionTabHelper
* session_tab_helper
=
1107 SessionTabHelper::FromWebContents(new_contents
);
1108 session_service
->SetLastActiveTime(session_id(),
1109 session_tab_helper
->session_id(),
1110 base::TimeTicks::Now());
1114 // This needs to be called after notifying SearchDelegate.
1115 if (instant_controller_
)
1116 instant_controller_
->ActiveTabChanged();
1118 autofill::ChromeAutofillClient::FromWebContents(new_contents
)->TabActivated();
1119 SearchTabHelper::FromWebContents(new_contents
)->OnTabActivated();
1122 void Browser::TabMoved(WebContents
* contents
,
1125 DCHECK(from_index
>= 0 && to_index
>= 0);
1126 // Notify the history service.
1127 SyncHistoryWithTabs(std::min(from_index
, to_index
));
1130 void Browser::TabReplacedAt(TabStripModel
* tab_strip_model
,
1131 WebContents
* old_contents
,
1132 WebContents
* new_contents
,
1134 TabDetachedAtImpl(old_contents
, index
, DETACH_TYPE_REPLACE
);
1135 exclusive_access_manager_
->OnTabClosing(old_contents
);
1136 SessionService
* session_service
=
1137 SessionServiceFactory::GetForProfile(profile_
);
1138 if (session_service
)
1139 session_service
->TabClosing(old_contents
);
1140 TabInsertedAt(new_contents
,
1142 (index
== tab_strip_model_
->active_index()));
1144 int entry_count
= new_contents
->GetController().GetEntryCount();
1145 if (entry_count
> 0) {
1146 // Send out notification so that observers are updated appropriately.
1147 new_contents
->GetController().NotifyEntryChanged(
1148 new_contents
->GetController().GetEntryAtIndex(entry_count
- 1));
1151 if (session_service
) {
1152 // The new_contents may end up with a different navigation stack. Force
1153 // the session service to update itself.
1154 session_service
->TabRestored(new_contents
,
1155 tab_strip_model_
->IsTabPinned(index
));
1159 void Browser::TabPinnedStateChanged(WebContents
* contents
, int index
) {
1160 SessionService
* session_service
=
1161 SessionServiceFactory::GetForProfileIfExisting(profile());
1162 if (session_service
) {
1163 SessionTabHelper
* session_tab_helper
=
1164 SessionTabHelper::FromWebContents(contents
);
1165 session_service
->SetPinnedState(session_id(),
1166 session_tab_helper
->session_id(),
1167 tab_strip_model_
->IsTabPinned(index
));
1171 void Browser::TabStripEmpty() {
1172 // Close the frame after we return to the message loop (not immediately,
1173 // otherwise it will destroy this object before the stack has a chance to
1175 // Note: This will be called several times if TabStripEmpty is called several
1176 // times. This is because it does not close the window if tabs are
1178 base::ThreadTaskRunnerHandle::Get()->PostTask(
1179 FROM_HERE
, base::Bind(&Browser::CloseFrame
, weak_factory_
.GetWeakPtr()));
1181 // Instant may have visible WebContents that need to be detached before the
1182 // window system closes.
1183 instant_controller_
.reset();
1186 bool Browser::CanOverscrollContent() const {
1188 // Don't enable overscroll on Windows machines unless they have a touch
1189 // screen as these machines typically don't have a touchpad capable of
1190 // horizontal scrolling. We are purposefully biased towards "no" here,
1191 // so that we don't waste resources capturing screenshots for horizontal
1192 // overscroll navigation unnecessarily.
1193 bool allow_overscroll
= ui::IsTouchDevicePresent();
1194 #elif defined(USE_AURA)
1195 bool allow_overscroll
= true;
1197 bool allow_overscroll
= false;
1200 if (!allow_overscroll
)
1203 const std::string value
=
1204 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
1205 switches::kOverscrollHistoryNavigation
);
1206 bool overscroll_enabled
= value
!= "0";
1207 if (!overscroll_enabled
)
1209 if (is_app() || is_devtools() || !is_type_tabbed())
1212 // The detached bookmark bar has appearance of floating above the
1213 // web-contents. This does not play nicely with overscroll navigation
1214 // gestures. So disable overscroll navigation when the bookmark bar is in the
1215 // detached state and the overscroll effect moves the layers.
1216 if (value
== "1" && bookmark_bar_state_
== BookmarkBar::DETACHED
)
1221 bool Browser::ShouldPreserveAbortedURLs(WebContents
* source
) {
1222 // Allow failed URLs to stick around in the omnibox on the NTP, but not when
1223 // other pages have committed.
1224 Profile
* profile
= Profile::FromBrowserContext(source
->GetBrowserContext());
1225 if (!profile
|| !source
->GetController().GetLastCommittedEntry())
1227 GURL
committed_url(source
->GetController().GetLastCommittedEntry()->GetURL());
1228 return search::IsNTPURL(committed_url
, profile
);
1231 void Browser::SetFocusToLocationBar(bool select_all
) {
1232 // Two differences between this and FocusLocationBar():
1233 // (1) This doesn't get recorded in user metrics, since it's called
1235 // (2) This checks whether the location bar can be focused, and if not, clears
1236 // the focus. FocusLocationBar() is only reached when the location bar is
1237 // focusable, but this may be reached at other times, e.g. while in
1238 // fullscreen mode, where we need to leave focus in a consistent state.
1239 window_
->SetFocusToLocationBar(select_all
);
1242 bool Browser::PreHandleKeyboardEvent(content::WebContents
* source
,
1243 const NativeWebKeyboardEvent
& event
,
1244 bool* is_keyboard_shortcut
) {
1245 // Escape exits tabbed fullscreen mode and mouse lock, and possibly others.
1246 // TODO(koz): Write a test for this http://crbug.com/100441.
1247 if (event
.windowsKeyCode
== 27 &&
1248 exclusive_access_manager_
->HandleUserPressedEscape()) {
1251 return window()->PreHandleKeyboardEvent(event
, is_keyboard_shortcut
);
1254 void Browser::HandleKeyboardEvent(content::WebContents
* source
,
1255 const NativeWebKeyboardEvent
& event
) {
1256 DevToolsWindow
* devtools_window
=
1257 DevToolsWindow::GetInstanceForInspectedWebContents(source
);
1258 bool handled
= false;
1259 if (devtools_window
)
1260 handled
= devtools_window
->ForwardKeyboardEvent(event
);
1263 window()->HandleKeyboardEvent(event
);
1266 bool Browser::TabsNeedBeforeUnloadFired() {
1267 if (IsFastTabUnloadEnabled())
1268 return fast_unload_controller_
->TabsNeedBeforeUnloadFired();
1269 return unload_controller_
->TabsNeedBeforeUnloadFired();
1272 void Browser::ShowValidationMessage(content::WebContents
* web_contents
,
1273 const gfx::Rect
& anchor_in_root_view
,
1274 const base::string16
& main_text
,
1275 const base::string16
& sub_text
) {
1276 validation_message_bubble_
=
1277 TabDialogs::FromWebContents(web_contents
)
1278 ->ShowValidationMessage(anchor_in_root_view
, main_text
, sub_text
);
1281 void Browser::HideValidationMessage(content::WebContents
* web_contents
) {
1282 validation_message_bubble_
.reset();
1285 void Browser::MoveValidationMessage(content::WebContents
* web_contents
,
1286 const gfx::Rect
& anchor_in_root_view
) {
1287 if (!validation_message_bubble_
)
1289 RenderWidgetHostView
* rwhv
= web_contents
->GetRenderWidgetHostView();
1291 validation_message_bubble_
->SetPositionRelativeToAnchor(
1292 rwhv
->GetRenderWidgetHost(), anchor_in_root_view
);
1296 bool Browser::PreHandleGestureEvent(content::WebContents
* source
,
1297 const blink::WebGestureEvent
& event
) {
1298 // Disable pinch zooming in undocked dev tools window due to poor UX.
1299 if (app_name() == DevToolsWindow::kDevToolsApp
)
1300 return event
.type
== blink::WebGestureEvent::GesturePinchBegin
||
1301 event
.type
== blink::WebGestureEvent::GesturePinchUpdate
||
1302 event
.type
== blink::WebGestureEvent::GesturePinchEnd
;
1307 bool Browser::CanDragEnter(content::WebContents
* source
,
1308 const content::DropData
& data
,
1309 blink::WebDragOperationsMask operations_allowed
) {
1310 // Disallow drag-and-drop navigation for Settings windows which do not support
1311 // external navigation.
1312 if ((operations_allowed
& blink::WebDragOperationLink
) &&
1313 chrome::SettingsWindowManager::GetInstance()->IsSettingsBrowser(this)) {
1319 content::SecurityStyle
Browser::GetSecurityStyle(
1320 WebContents
* web_contents
,
1321 content::SecurityStyleExplanations
* security_style_explanations
) {
1322 SecurityStateModel
* model
= SecurityStateModel::FromWebContents(web_contents
);
1324 const SecurityStateModel::SecurityInfo
& security_info
=
1325 model
->security_info();
1327 const content::SecurityStyle security_style
=
1328 SecurityLevelToSecurityStyle(security_info
.security_level
);
1330 security_style_explanations
->ran_insecure_content_style
=
1331 SecurityStateModel::kRanInsecureContentStyle
;
1332 security_style_explanations
->displayed_insecure_content_style
=
1333 SecurityStateModel::kDisplayedInsecureContentStyle
;
1335 // Check if the page is HTTP; if so, no explanations are needed. Note
1336 // that SECURITY_STYLE_UNAUTHENTICATED does not necessarily mean that
1337 // the page is loaded over HTTP, because the security style merely
1338 // represents how the embedder wishes to display the security state of
1339 // the page, and the embedder can choose to display HTTPS page as HTTP
1340 // if it wants to (for example, displaying deprecated crypto
1341 // algorithms with the same UI treatment as HTTP pages).
1342 security_style_explanations
->scheme_is_cryptographic
=
1343 security_info
.scheme_is_cryptographic
;
1344 if (!security_info
.scheme_is_cryptographic
) {
1345 return security_style
;
1348 if (security_info
.sha1_deprecation_status
==
1349 SecurityStateModel::DEPRECATED_SHA1_BROKEN
) {
1350 security_style_explanations
->broken_explanations
.push_back(
1351 content::SecurityStyleExplanation(
1352 l10n_util::GetStringUTF8(IDS_BROKEN_SHA1
),
1353 l10n_util::GetStringUTF8(IDS_BROKEN_SHA1_DESCRIPTION
),
1354 security_info
.cert_id
));
1355 } else if (security_info
.sha1_deprecation_status
==
1356 SecurityStateModel::DEPRECATED_SHA1_WARNING
) {
1357 security_style_explanations
->warning_explanations
.push_back(
1358 content::SecurityStyleExplanation(
1359 l10n_util::GetStringUTF8(IDS_WARNING_SHA1
),
1360 l10n_util::GetStringUTF8(IDS_WARNING_SHA1_DESCRIPTION
),
1361 security_info
.cert_id
));
1364 security_style_explanations
->ran_insecure_content
=
1365 security_info
.mixed_content_status
==
1366 SecurityStateModel::RAN_MIXED_CONTENT
||
1367 security_info
.mixed_content_status
==
1368 SecurityStateModel::RAN_AND_DISPLAYED_MIXED_CONTENT
;
1369 security_style_explanations
->displayed_insecure_content
=
1370 security_info
.mixed_content_status
==
1371 SecurityStateModel::DISPLAYED_MIXED_CONTENT
||
1372 security_info
.mixed_content_status
==
1373 SecurityStateModel::RAN_AND_DISPLAYED_MIXED_CONTENT
;
1375 if (net::IsCertStatusError(security_info
.cert_status
)) {
1376 base::string16 error_string
= base::UTF8ToUTF16(net::ErrorToString(
1377 net::MapCertStatusToNetError(security_info
.cert_status
)));
1379 content::SecurityStyleExplanation
explanation(
1380 l10n_util::GetStringUTF8(IDS_CERTIFICATE_CHAIN_ERROR
),
1381 l10n_util::GetStringFUTF8(
1382 IDS_CERTIFICATE_CHAIN_ERROR_DESCRIPTION_FORMAT
, error_string
),
1383 security_info
.cert_id
);
1385 if (net::IsCertStatusMinorError(security_info
.cert_status
))
1386 security_style_explanations
->warning_explanations
.push_back(explanation
);
1388 security_style_explanations
->broken_explanations
.push_back(explanation
);
1390 // If the certificate does not have errors and is not using
1391 // deprecated SHA1, then add an explanation that the certificate is
1393 if (security_info
.sha1_deprecation_status
==
1394 SecurityStateModel::NO_DEPRECATED_SHA1
) {
1395 security_style_explanations
->secure_explanations
.push_back(
1396 content::SecurityStyleExplanation(
1397 l10n_util::GetStringUTF8(IDS_VALID_SERVER_CERTIFICATE
),
1398 l10n_util::GetStringUTF8(
1399 IDS_VALID_SERVER_CERTIFICATE_DESCRIPTION
),
1400 security_info
.cert_id
));
1404 return security_style
;
1407 void Browser::ShowCertificateViewerInDevTools(
1408 content::WebContents
* web_contents
, int cert_id
) {
1409 DevToolsWindow
* devtools_window
=
1410 DevToolsWindow::GetInstanceForInspectedWebContents(web_contents
);
1411 if (devtools_window
)
1412 devtools_window
->ShowCertificateViewer(cert_id
);
1415 bool Browser::IsMouseLocked() const {
1416 return exclusive_access_manager_
->mouse_lock_controller()->IsMouseLocked();
1419 void Browser::OnWindowDidShow() {
1420 if (window_has_shown_
)
1422 window_has_shown_
= true;
1424 startup_metric_utils::RecordBrowserWindowDisplay(base::Time::Now());
1426 // Nothing to do for non-tabbed windows.
1427 if (!is_type_tabbed())
1430 // Show any pending global error bubble.
1431 GlobalErrorService
* service
=
1432 GlobalErrorServiceFactory::GetForProfile(profile());
1433 GlobalError
* error
= service
->GetFirstGlobalErrorWithBubbleView();
1435 error
->ShowBubbleView(this);
1438 void Browser::ShowFirstRunBubble() {
1439 window()->GetLocationBar()->ShowFirstRunBubble();
1442 ///////////////////////////////////////////////////////////////////////////////
1443 // Browser, content::WebContentsDelegate implementation:
1445 WebContents
* Browser::OpenURLFromTab(WebContents
* source
,
1446 const OpenURLParams
& params
) {
1447 if (is_devtools()) {
1448 DevToolsWindow
* window
= DevToolsWindow::AsDevToolsWindow(source
);
1450 return window
->OpenURLFromTab(source
, params
);
1453 chrome::NavigateParams
nav_params(this, params
.url
, params
.transition
);
1454 FillNavigateParamsFromOpenURLParams(&nav_params
, params
);
1455 nav_params
.source_contents
= source
;
1456 nav_params
.tabstrip_add_types
= TabStripModel::ADD_NONE
;
1457 if (params
.user_gesture
)
1458 nav_params
.window_action
= chrome::NavigateParams::SHOW_WINDOW
;
1459 nav_params
.user_gesture
= params
.user_gesture
;
1461 PopupBlockerTabHelper
* popup_blocker_helper
= NULL
;
1463 popup_blocker_helper
= PopupBlockerTabHelper::FromWebContents(source
);
1465 if (popup_blocker_helper
) {
1466 if ((params
.disposition
== NEW_POPUP
||
1467 params
.disposition
== NEW_FOREGROUND_TAB
||
1468 params
.disposition
== NEW_BACKGROUND_TAB
||
1469 params
.disposition
== NEW_WINDOW
) &&
1470 !params
.user_gesture
&&
1471 !base::CommandLine::ForCurrentProcess()->HasSwitch(
1472 switches::kDisablePopupBlocking
)) {
1473 if (popup_blocker_helper
->MaybeBlockPopup(nav_params
,
1474 WebWindowFeatures())) {
1480 chrome::Navigate(&nav_params
);
1482 return nav_params
.target_contents
;
1485 void Browser::NavigationStateChanged(WebContents
* source
,
1486 content::InvalidateTypes changed_flags
) {
1487 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
1489 tracked_objects::ScopedTracker
tracking_profile1(
1490 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1491 "466285 Browser::NavigationStateChanged::ScheduleUIUpdate"));
1492 // Only update the UI when something visible has changed.
1494 ScheduleUIUpdate(source
, changed_flags
);
1496 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
1498 tracked_objects::ScopedTracker
tracking_profile2(
1499 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1500 "466285 Browser::NavigationStateChanged::TabStateChanged"));
1501 // We can synchronously update commands since they will only change once per
1502 // navigation, so we don't have to worry about flickering. We do, however,
1503 // need to update the command state early on load to always present usable
1504 // actions in the face of slow-to-commit pages.
1505 if (changed_flags
& (content::INVALIDATE_TYPE_URL
|
1506 content::INVALIDATE_TYPE_LOAD
))
1507 command_controller_
->TabStateChanged();
1509 if (hosted_app_controller_
)
1510 hosted_app_controller_
->UpdateLocationBarVisibility(true);
1513 void Browser::VisibleSSLStateChanged(WebContents
* source
) {
1514 // When the current tab's SSL state changes, we need to update the URL
1515 // bar to reflect the new state.
1518 // Notify the model that the security state has changed, so that the
1519 // URL bar updates with up-to-date data computed by the model.
1520 SecurityStateModel
* model
= SecurityStateModel::FromWebContents(source
);
1522 model
->SecurityStateChanged();
1524 if (tab_strip_model_
->GetActiveWebContents() == source
)
1525 UpdateToolbar(false);
1528 void Browser::AddNewContents(WebContents
* source
,
1529 WebContents
* new_contents
,
1530 WindowOpenDisposition disposition
,
1531 const gfx::Rect
& initial_rect
,
1533 bool* was_blocked
) {
1534 chrome::AddWebContents(this, source
, new_contents
, disposition
, initial_rect
,
1535 user_gesture
, was_blocked
);
1538 void Browser::ActivateContents(WebContents
* contents
) {
1539 tab_strip_model_
->ActivateTabAt(
1540 tab_strip_model_
->GetIndexOfWebContents(contents
), false);
1541 window_
->Activate();
1544 void Browser::DeactivateContents(WebContents
* contents
) {
1545 window_
->Deactivate();
1548 void Browser::LoadingStateChanged(WebContents
* source
,
1549 bool to_different_document
) {
1550 window_
->UpdateLoadingAnimations(tab_strip_model_
->TabsAreLoading());
1551 window_
->UpdateTitleBar();
1553 WebContents
* selected_contents
= tab_strip_model_
->GetActiveWebContents();
1554 if (source
== selected_contents
) {
1555 bool is_loading
= source
->IsLoading() && to_different_document
;
1556 command_controller_
->LoadingStateChanged(is_loading
, false);
1557 if (GetStatusBubble()) {
1558 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
1559 tab_strip_model_
->GetActiveWebContents())->GetStatusText());
1564 void Browser::CloseContents(WebContents
* source
) {
1565 bool can_close_contents
;
1566 if (IsFastTabUnloadEnabled())
1567 can_close_contents
= fast_unload_controller_
->CanCloseContents(source
);
1569 can_close_contents
= unload_controller_
->CanCloseContents(source
);
1571 if (can_close_contents
)
1572 chrome::CloseWebContents(this, source
, true);
1575 void Browser::MoveContents(WebContents
* source
, const gfx::Rect
& pos
) {
1576 if (!IsPopupOrPanel(source
)) {
1577 NOTREACHED() << "moving invalid browser type";
1580 window_
->SetBounds(pos
);
1583 bool Browser::IsPopupOrPanel(const WebContents
* source
) const {
1584 return is_type_popup();
1587 void Browser::UpdateTargetURL(WebContents
* source
, const GURL
& url
) {
1588 if (!GetStatusBubble())
1591 if (source
== tab_strip_model_
->GetActiveWebContents()) {
1592 PrefService
* prefs
= profile_
->GetPrefs();
1593 GetStatusBubble()->SetURL(url
, prefs
->GetString(prefs::kAcceptLanguages
));
1597 void Browser::ContentsMouseEvent(
1598 WebContents
* source
, const gfx::Point
& location
, bool motion
) {
1599 if (!GetStatusBubble())
1602 if (source
== tab_strip_model_
->GetActiveWebContents()) {
1603 GetStatusBubble()->MouseMoved(location
, !motion
);
1605 GetStatusBubble()->SetURL(GURL(), std::string());
1609 void Browser::ContentsZoomChange(bool zoom_in
) {
1610 chrome::ExecuteCommand(this, zoom_in
? IDC_ZOOM_PLUS
: IDC_ZOOM_MINUS
);
1613 bool Browser::TakeFocus(content::WebContents
* source
,
1615 content::NotificationService::current()->Notify(
1616 chrome::NOTIFICATION_FOCUS_RETURNED_TO_BROWSER
,
1617 content::Source
<Browser
>(this),
1618 content::NotificationService::NoDetails());
1622 gfx::Rect
Browser::GetRootWindowResizerRect() const {
1623 return window_
->GetRootWindowResizerRect();
1626 void Browser::BeforeUnloadFired(WebContents
* web_contents
,
1628 bool* proceed_to_fire_unload
) {
1629 if (is_devtools() && DevToolsWindow::HandleBeforeUnload(web_contents
,
1630 proceed
, proceed_to_fire_unload
))
1633 if (IsFastTabUnloadEnabled()) {
1634 *proceed_to_fire_unload
=
1635 fast_unload_controller_
->BeforeUnloadFired(web_contents
, proceed
);
1637 *proceed_to_fire_unload
=
1638 unload_controller_
->BeforeUnloadFired(web_contents
, proceed
);
1642 bool Browser::ShouldFocusLocationBarByDefault(WebContents
* source
) {
1643 const content::NavigationEntry
* entry
=
1644 source
->GetController().GetActiveEntry();
1646 GURL url
= entry
->GetURL();
1647 GURL virtual_url
= entry
->GetVirtualURL();
1648 if ((url
.SchemeIs(content::kChromeUIScheme
) &&
1649 url
.host() == chrome::kChromeUINewTabHost
) ||
1650 (virtual_url
.SchemeIs(content::kChromeUIScheme
) &&
1651 virtual_url
.host() == chrome::kChromeUINewTabHost
)) {
1656 return search::NavEntryIsInstantNTP(source
, entry
);
1659 void Browser::ViewSourceForTab(WebContents
* source
, const GURL
& page_url
) {
1661 chrome::ViewSource(this, source
);
1664 void Browser::ViewSourceForFrame(WebContents
* source
,
1665 const GURL
& frame_url
,
1666 const content::PageState
& frame_page_state
) {
1668 chrome::ViewSource(this, source
, frame_url
, frame_page_state
);
1671 void Browser::ShowRepostFormWarningDialog(WebContents
* source
) {
1672 TabModalConfirmDialog::Create(new RepostFormWarningController(source
),
1676 bool Browser::ShouldCreateWebContents(
1677 WebContents
* web_contents
,
1679 int main_frame_route_id
,
1680 WindowContainerType window_container_type
,
1681 const std::string
& frame_name
,
1682 const GURL
& target_url
,
1683 const std::string
& partition_id
,
1684 content::SessionStorageNamespace
* session_storage_namespace
) {
1685 if (window_container_type
== WINDOW_CONTAINER_TYPE_BACKGROUND
) {
1686 // If a BackgroundContents is created, suppress the normal WebContents.
1687 return !MaybeCreateBackgroundContents(route_id
,
1688 main_frame_route_id
,
1693 session_storage_namespace
);
1699 void Browser::WebContentsCreated(WebContents
* source_contents
,
1700 int opener_render_frame_id
,
1701 const std::string
& frame_name
,
1702 const GURL
& target_url
,
1703 WebContents
* new_contents
) {
1704 // Adopt the WebContents now, so all observers are in place, as the network
1705 // requests for its initial navigation will start immediately. The WebContents
1706 // will later be inserted into this browser using Browser::Navigate via
1708 TabHelpers::AttachTabHelpers(new_contents
);
1710 // Make the tab show up in the task manager.
1711 task_management::WebContentsTags::CreateForTabContents(new_contents
);
1714 RetargetingDetails details
;
1715 details
.source_web_contents
= source_contents
;
1716 details
.source_render_frame_id
= opener_render_frame_id
;
1717 details
.target_url
= target_url
;
1718 details
.target_web_contents
= new_contents
;
1719 details
.not_yet_in_tabstrip
= true;
1720 content::NotificationService::current()->Notify(
1721 chrome::NOTIFICATION_RETARGETING
,
1722 content::Source
<Profile
>(profile_
),
1723 content::Details
<RetargetingDetails
>(&details
));
1726 void Browser::RendererUnresponsive(WebContents
* source
) {
1727 // Ignore hangs if a tab is blocked.
1728 int index
= tab_strip_model_
->GetIndexOfWebContents(source
);
1729 DCHECK_NE(TabStripModel::kNoTab
, index
);
1730 if (tab_strip_model_
->IsTabBlocked(index
))
1733 TabDialogs::FromWebContents(source
)->ShowHungRendererDialog();
1736 void Browser::RendererResponsive(WebContents
* source
) {
1737 TabDialogs::FromWebContents(source
)->HideHungRendererDialog();
1740 void Browser::DidNavigateMainFramePostCommit(WebContents
* web_contents
) {
1741 if (web_contents
== tab_strip_model_
->GetActiveWebContents())
1742 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE
);
1745 content::JavaScriptDialogManager
* Browser::GetJavaScriptDialogManager(
1746 WebContents
* source
) {
1747 return app_modal::JavaScriptDialogManager::GetInstance();
1750 content::ColorChooser
* Browser::OpenColorChooser(
1751 WebContents
* web_contents
,
1752 SkColor initial_color
,
1753 const std::vector
<content::ColorSuggestion
>& suggestions
) {
1754 return chrome::ShowColorChooser(web_contents
, initial_color
);
1757 void Browser::RunFileChooser(WebContents
* web_contents
,
1758 const content::FileChooserParams
& params
) {
1759 FileSelectHelper::RunFileChooser(web_contents
, params
);
1762 void Browser::EnumerateDirectory(WebContents
* web_contents
,
1764 const base::FilePath
& path
) {
1765 FileSelectHelper::EnumerateDirectory(web_contents
, request_id
, path
);
1768 bool Browser::EmbedsFullscreenWidget() const {
1772 void Browser::EnterFullscreenModeForTab(WebContents
* web_contents
,
1773 const GURL
& origin
) {
1774 exclusive_access_manager_
->fullscreen_controller()->EnterFullscreenModeForTab(
1775 web_contents
, origin
);
1778 void Browser::ExitFullscreenModeForTab(WebContents
* web_contents
) {
1779 exclusive_access_manager_
->fullscreen_controller()->ExitFullscreenModeForTab(
1783 bool Browser::IsFullscreenForTabOrPending(
1784 const WebContents
* web_contents
) const {
1785 return exclusive_access_manager_
->fullscreen_controller()
1786 ->IsFullscreenForTabOrPending(web_contents
);
1789 blink::WebDisplayMode
Browser::GetDisplayMode(
1790 const WebContents
* web_contents
) const {
1791 if (window_
->IsFullscreen())
1792 return blink::WebDisplayModeFullscreen
;
1794 if (is_type_popup())
1795 return blink::WebDisplayModeStandalone
;
1797 return blink::WebDisplayModeBrowser
;
1800 void Browser::RegisterProtocolHandler(WebContents
* web_contents
,
1801 const std::string
& protocol
,
1803 bool user_gesture
) {
1804 content::BrowserContext
* context
= web_contents
->GetBrowserContext();
1805 if (context
->IsOffTheRecord())
1808 ProtocolHandler handler
=
1809 ProtocolHandler::CreateProtocolHandler(protocol
, url
);
1811 ProtocolHandlerRegistry
* registry
=
1812 ProtocolHandlerRegistryFactory::GetForBrowserContext(context
);
1813 if (registry
->SilentlyHandleRegisterHandlerRequest(handler
))
1816 TabSpecificContentSettings
* tab_content_settings
=
1817 TabSpecificContentSettings::FromWebContents(web_contents
);
1818 if (!user_gesture
&& window_
) {
1819 tab_content_settings
->set_pending_protocol_handler(handler
);
1820 tab_content_settings
->set_previous_protocol_handler(
1821 registry
->GetHandlerFor(handler
.protocol()));
1822 window_
->GetLocationBar()->UpdateContentSettingsIcons();
1826 // Make sure content-setting icon is turned off in case the page does
1827 // ungestured and gestured RPH calls.
1829 tab_content_settings
->ClearPendingProtocolHandler();
1830 window_
->GetLocationBar()->UpdateContentSettingsIcons();
1833 PermissionBubbleManager
* bubble_manager
=
1834 PermissionBubbleManager::FromWebContents(web_contents
);
1835 if (PermissionBubbleManager::Enabled() && bubble_manager
) {
1836 bubble_manager
->AddRequest(
1837 new RegisterProtocolHandlerPermissionRequest(registry
, handler
,
1838 url
, user_gesture
));
1840 RegisterProtocolHandlerInfoBarDelegate::Create(
1841 InfoBarService::FromWebContents(web_contents
), registry
, handler
);
1845 void Browser::UnregisterProtocolHandler(WebContents
* web_contents
,
1846 const std::string
& protocol
,
1848 bool user_gesture
) {
1849 // user_gesture will be used in case we decide to have confirmation bubble
1850 // for user while un-registering the handler.
1851 content::BrowserContext
* context
= web_contents
->GetBrowserContext();
1852 if (context
->IsOffTheRecord())
1855 ProtocolHandler handler
=
1856 ProtocolHandler::CreateProtocolHandler(protocol
, url
);
1858 ProtocolHandlerRegistry
* registry
=
1859 ProtocolHandlerRegistryFactory::GetForBrowserContext(context
);
1860 registry
->RemoveHandler(handler
);
1863 void Browser::UpdatePreferredSize(WebContents
* source
,
1864 const gfx::Size
& pref_size
) {
1865 window_
->UpdatePreferredSize(source
, pref_size
);
1868 void Browser::ResizeDueToAutoResize(WebContents
* source
,
1869 const gfx::Size
& new_size
) {
1870 window_
->ResizeDueToAutoResize(source
, new_size
);
1873 void Browser::FindReply(WebContents
* web_contents
,
1875 int number_of_matches
,
1876 const gfx::Rect
& selection_rect
,
1877 int active_match_ordinal
,
1878 bool final_update
) {
1879 FindTabHelper
* find_tab_helper
= FindTabHelper::FromWebContents(web_contents
);
1880 if (!find_tab_helper
)
1883 find_tab_helper
->HandleFindReply(request_id
,
1886 active_match_ordinal
,
1890 void Browser::RequestToLockMouse(WebContents
* web_contents
,
1892 bool last_unlocked_by_target
) {
1893 exclusive_access_manager_
->mouse_lock_controller()->RequestToLockMouse(
1894 web_contents
, user_gesture
, last_unlocked_by_target
);
1897 void Browser::LostMouseLock() {
1898 exclusive_access_manager_
->mouse_lock_controller()->LostMouseLock();
1901 void Browser::RequestMediaAccessPermission(
1902 content::WebContents
* web_contents
,
1903 const content::MediaStreamRequest
& request
,
1904 const content::MediaResponseCallback
& callback
) {
1905 ::RequestMediaAccessPermission(web_contents
, profile_
, request
, callback
);
1908 bool Browser::CheckMediaAccessPermission(content::WebContents
* web_contents
,
1909 const GURL
& security_origin
,
1910 content::MediaStreamType type
) {
1911 return ::CheckMediaAccessPermission(web_contents
, security_origin
, type
);
1914 bool Browser::RequestPpapiBrokerPermission(
1915 WebContents
* web_contents
,
1917 const base::FilePath
& plugin_path
,
1918 const base::Callback
<void(bool)>& callback
) {
1919 PepperBrokerInfoBarDelegate::Create(web_contents
, url
, plugin_path
, callback
);
1923 gfx::Size
Browser::GetSizeForNewRenderView(WebContents
* web_contents
) const {
1924 // When navigating away from NTP with unpinned bookmark bar, the bookmark bar
1925 // would disappear on non-NTP pages, resulting in a bigger size for the new
1927 gfx::Size size
= web_contents
->GetContainerBounds().size();
1928 // Don't change render view size if bookmark bar is currently not detached,
1929 // or there's no pending entry, or navigating to a NTP page.
1930 if (size
.IsEmpty() || bookmark_bar_state_
!= BookmarkBar::DETACHED
)
1932 const NavigationEntry
* pending_entry
=
1933 web_contents
->GetController().GetPendingEntry();
1934 if (pending_entry
&&
1935 !search::IsNTPURL(pending_entry
->GetVirtualURL(), profile_
)) {
1937 0, window()->GetRenderViewHeightInsetWithDetachedBookmarkBar());
1942 ///////////////////////////////////////////////////////////////////////////////
1943 // Browser, CoreTabHelperDelegate implementation:
1945 void Browser::SwapTabContents(content::WebContents
* old_contents
,
1946 content::WebContents
* new_contents
,
1947 bool did_start_load
,
1948 bool did_finish_load
) {
1949 int index
= tab_strip_model_
->GetIndexOfWebContents(old_contents
);
1950 DCHECK_NE(TabStripModel::kNoTab
, index
);
1951 tab_strip_model_
->ReplaceWebContentsAt(index
, new_contents
);
1954 bool Browser::CanReloadContents(content::WebContents
* web_contents
) const {
1955 return chrome::CanReload(this);
1958 bool Browser::CanSaveContents(content::WebContents
* web_contents
) const {
1959 return chrome::CanSavePage(this);
1962 ///////////////////////////////////////////////////////////////////////////////
1963 // Browser, SearchEngineTabHelperDelegate implementation:
1965 void Browser::ConfirmAddSearchProvider(TemplateURL
* template_url
,
1967 window()->ConfirmAddSearchProvider(template_url
, profile
);
1970 ///////////////////////////////////////////////////////////////////////////////
1971 // Browser, SearchTabHelperDelegate implementation:
1973 void Browser::NavigateOnThumbnailClick(const GURL
& url
,
1974 WindowOpenDisposition disposition
,
1975 content::WebContents
* source_contents
) {
1976 DCHECK(source_contents
);
1977 // We're guaranteed that AUTO_BOOKMARK is the right transition since this only
1978 // gets called to handle clicks in the new tab page (to navigate to most
1979 // visited item URLs) and in the search results page (to navigate to
1980 // privileged destinations (e.g. chrome://URLs)).
1982 // TODO(kmadhusu): Page transitions to privileged destinations should be
1983 // marked as "LINK" instead of "AUTO_BOOKMARK"?
1984 chrome::NavigateParams
params(this, url
,
1985 ui::PAGE_TRANSITION_AUTO_BOOKMARK
);
1986 params
.referrer
= content::Referrer();
1987 params
.source_contents
= source_contents
;
1988 params
.disposition
= disposition
;
1989 params
.is_renderer_initiated
= false;
1990 params
.initiating_profile
= profile_
;
1991 chrome::Navigate(¶ms
);
1994 void Browser::OnWebContentsInstantSupportDisabled(
1995 const content::WebContents
* web_contents
) {
1996 DCHECK(web_contents
);
1997 if (tab_strip_model_
->GetActiveWebContents() == web_contents
)
1998 UpdateToolbar(false);
2001 OmniboxView
* Browser::GetOmniboxView() {
2002 return window_
->GetLocationBar()->GetOmniboxView();
2005 std::set
<std::string
> Browser::GetOpenUrls() {
2006 scoped_refptr
<history::TopSites
> top_sites
=
2007 TopSitesFactory::GetForProfile(profile_
);
2008 if (!top_sites
) // NULL for Incognito profiles.
2009 return std::set
<std::string
>();
2011 std::set
<std::string
> open_urls
;
2012 chrome::GetOpenUrls(*tab_strip_model_
, *top_sites
, &open_urls
);
2016 ///////////////////////////////////////////////////////////////////////////////
2017 // Browser, web_modal::WebContentsModalDialogManagerDelegate implementation:
2019 void Browser::SetWebContentsBlocked(content::WebContents
* web_contents
,
2021 int index
= tab_strip_model_
->GetIndexOfWebContents(web_contents
);
2022 if (index
== TabStripModel::kNoTab
) {
2026 tab_strip_model_
->SetTabBlocked(index
, blocked
);
2027 if (!blocked
&& tab_strip_model_
->GetActiveWebContents() == web_contents
)
2028 web_contents
->Focus();
2031 web_modal::WebContentsModalDialogHost
*
2032 Browser::GetWebContentsModalDialogHost() {
2033 return window_
->GetWebContentsModalDialogHost();
2036 ///////////////////////////////////////////////////////////////////////////////
2037 // Browser, BookmarkTabHelperDelegate implementation:
2039 void Browser::URLStarredChanged(content::WebContents
* web_contents
,
2041 if (web_contents
== tab_strip_model_
->GetActiveWebContents())
2042 window_
->SetStarredState(starred
);
2045 ///////////////////////////////////////////////////////////////////////////////
2046 // Browser, ZoomObserver implementation:
2048 void Browser::OnZoomChanged(
2049 const ui_zoom::ZoomController::ZoomChangedEventData
& data
) {
2050 if (data
.web_contents
== tab_strip_model_
->GetActiveWebContents()) {
2051 window_
->ZoomChangedForActiveTab(data
.can_show_bubble
);
2052 // Change the zoom commands state based on the zoom state
2053 command_controller_
->ZoomStateChanged();
2057 ///////////////////////////////////////////////////////////////////////////////
2058 // Browser, ui::SelectFileDialog::Listener implementation:
2060 void Browser::FileSelected(const base::FilePath
& path
, int index
,
2062 FileSelectedWithExtraInfo(ui::SelectedFileInfo(path
, path
), index
, params
);
2065 void Browser::FileSelectedWithExtraInfo(const ui::SelectedFileInfo
& file_info
,
2068 profile_
->set_last_selected_directory(file_info
.file_path
.DirName());
2070 GURL url
= net::FilePathToFileURL(file_info
.local_path
);
2072 #if defined(OS_CHROMEOS)
2073 const GURL external_url
=
2074 chromeos::CreateExternalFileURLFromPath(profile_
, file_info
.file_path
);
2075 if (!external_url
.is_empty())
2082 OpenURL(OpenURLParams(
2083 url
, Referrer(), CURRENT_TAB
, ui::PAGE_TRANSITION_TYPED
, false));
2086 ///////////////////////////////////////////////////////////////////////////////
2087 // Browser, content::NotificationObserver implementation:
2089 void Browser::Observe(int type
,
2090 const content::NotificationSource
& source
,
2091 const content::NotificationDetails
& details
) {
2093 case extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED
: {
2094 Profile
* profile
= content::Source
<Profile
>(source
).ptr();
2095 if (profile_
->IsSameProfile(profile
) && window()->GetLocationBar())
2096 window()->GetLocationBar()->UpdatePageActions();
2100 #if defined(ENABLE_THEMES)
2101 case chrome::NOTIFICATION_BROWSER_THEME_CHANGED
:
2102 window()->UserChangedTheme();
2106 case chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED
: {
2107 WebContents
* web_contents
= content::Source
<WebContents
>(source
).ptr();
2108 if (web_contents
== tab_strip_model_
->GetActiveWebContents()) {
2109 LocationBar
* location_bar
= window()->GetLocationBar();
2111 location_bar
->UpdateContentSettingsIcons();
2117 NOTREACHED() << "Got a notification we didn't register for.";
2121 #if defined(ENABLE_EXTENSIONS)
2122 ///////////////////////////////////////////////////////////////////////////////
2123 // Browser, extensions::ExtensionRegistryObserver implementation:
2125 void Browser::OnExtensionUninstalled(content::BrowserContext
* browser_context
,
2126 const extensions::Extension
* extension
,
2127 extensions::UninstallReason reason
) {
2128 // During window creation on Windows we may end up calling into
2129 // SHAppBarMessage, which internally spawns a nested message loop.This
2130 // makes it possible for us to end up here before window creation has
2131 // completed, at which point window_ is NULL. See 94752 for details.
2133 if (window() && window()->GetLocationBar())
2134 window()->GetLocationBar()->UpdatePageActions();
2137 void Browser::OnExtensionLoaded(content::BrowserContext
* browser_context
,
2138 const extensions::Extension
* extension
) {
2139 command_controller_
->ExtensionStateChanged();
2142 void Browser::OnExtensionUnloaded(
2143 content::BrowserContext
* browser_context
,
2144 const extensions::Extension
* extension
,
2145 extensions::UnloadedExtensionInfo::Reason reason
) {
2146 command_controller_
->ExtensionStateChanged();
2147 if (window()->GetLocationBar())
2148 window()->GetLocationBar()->UpdatePageActions();
2150 // Close any tabs from the unloaded extension, unless it's terminated,
2151 // in which case let the sad tabs remain.
2152 // Also, if tab is muted and the cause is the unloaded extension, unmute it.
2153 if (reason
!= extensions::UnloadedExtensionInfo::REASON_TERMINATE
) {
2154 // Iterate backwards as we may remove items while iterating.
2155 for (int i
= tab_strip_model_
->count() - 1; i
>= 0; --i
) {
2156 WebContents
* web_contents
= tab_strip_model_
->GetWebContentsAt(i
);
2157 // Two cases are handled here:
2159 // - The scheme check is for when an extension page is loaded in a
2160 // tab, e.g. chrome-extension://id/page.html.
2161 // - The extension_app check is for apps, which can have non-extension
2162 // schemes, e.g. https://mail.google.com if you have the Gmail app
2164 if ((web_contents
->GetURL().SchemeIs(extensions::kExtensionScheme
) &&
2165 web_contents
->GetURL().host() == extension
->id()) ||
2166 (extensions::TabHelper::FromWebContents(web_contents
)
2167 ->extension_app() == extension
)) {
2168 tab_strip_model_
->CloseWebContentsAt(i
, TabStripModel::CLOSE_NONE
);
2170 chrome::UnmuteIfMutedByExtension(web_contents
, extension
->id());
2175 #endif // defined(ENABLE_EXTENSIONS)
2177 ///////////////////////////////////////////////////////////////////////////////
2178 // Browser, translate::ContentTranslateDriver::Observer implementation:
2180 void Browser::OnIsPageTranslatedChanged(content::WebContents
* source
) {
2182 if (tab_strip_model_
->GetActiveWebContents() == source
) {
2183 window_
->SetTranslateIconToggled(
2184 ChromeTranslateClient::FromWebContents(
2185 source
)->GetLanguageState().IsPageTranslated());
2189 void Browser::OnTranslateEnabledChanged(content::WebContents
* source
) {
2191 if (tab_strip_model_
->GetActiveWebContents() == source
)
2192 UpdateToolbar(false);
2195 ///////////////////////////////////////////////////////////////////////////////
2196 // Browser, Command and state updating (private):
2198 void Browser::OnDevToolsDisabledChanged() {
2199 if (profile_
->GetPrefs()->GetBoolean(prefs::kDevToolsDisabled
))
2200 content::DevToolsAgentHost::DetachAllClients();
2203 ///////////////////////////////////////////////////////////////////////////////
2204 // Browser, UI update coalescing and handling (private):
2206 void Browser::UpdateToolbar(bool should_restore_state
) {
2207 window_
->UpdateToolbar(should_restore_state
?
2208 tab_strip_model_
->GetActiveWebContents() : NULL
);
2211 void Browser::ScheduleUIUpdate(WebContents
* source
,
2212 unsigned changed_flags
) {
2214 int index
= tab_strip_model_
->GetIndexOfWebContents(source
);
2215 DCHECK_NE(TabStripModel::kNoTab
, index
);
2217 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
2219 tracked_objects::ScopedTracker
tracking_profile1(
2220 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2221 "466285 Browser::ScheduleUIUpdate::Toolbar"));
2222 // Do some synchronous updates.
2223 if (changed_flags
& content::INVALIDATE_TYPE_URL
) {
2224 if (source
== tab_strip_model_
->GetActiveWebContents()) {
2225 // Only update the URL for the current tab. Note that we do not update
2226 // the navigation commands since those would have already been updated
2227 // synchronously by NavigationStateChanged.
2228 UpdateToolbar(false);
2230 // Clear the saved tab state for the tab that navigated, so that we don't
2231 // restore any user text after the old URL has been invalidated (e.g.,
2232 // after a new navigation commits in that tab while unfocused).
2233 window_
->ResetToolbarTabState(source
);
2235 changed_flags
&= ~content::INVALIDATE_TYPE_URL
;
2238 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
2240 tracked_objects::ScopedTracker
tracking_profile2(
2241 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2242 "466285 Browser::ScheduleUIUpdate::TabStripModel"));
2243 if (changed_flags
& content::INVALIDATE_TYPE_LOAD
) {
2244 // Update the loading state synchronously. This is so the throbber will
2245 // immediately start/stop, which gives a more snappy feel. We want to do
2246 // this for any tab so they start & stop quickly.
2247 tab_strip_model_
->UpdateWebContentsStateAt(
2248 tab_strip_model_
->GetIndexOfWebContents(source
),
2249 TabStripModelObserver::LOADING_ONLY
);
2250 // The status bubble needs to be updated during INVALIDATE_TYPE_LOAD too,
2251 // but we do that asynchronously by not stripping INVALIDATE_TYPE_LOAD from
2255 if (changed_flags
& content::INVALIDATE_TYPE_TITLE
&& !source
->IsLoading()) {
2256 // To correctly calculate whether the title changed while not loading
2257 // we need to process the update synchronously. This state only matters for
2258 // the TabStripModel, so we notify the TabStripModel now and notify others
2260 tab_strip_model_
->UpdateWebContentsStateAt(
2261 tab_strip_model_
->GetIndexOfWebContents(source
),
2262 TabStripModelObserver::TITLE_NOT_LOADING
);
2265 // If the only updates were synchronously handled above, we're done.
2266 if (changed_flags
== 0)
2269 // Save the dirty bits.
2270 scheduled_updates_
[source
] |= changed_flags
;
2272 if (!chrome_updater_factory_
.HasWeakPtrs()) {
2273 // No task currently scheduled, start another.
2274 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
2275 FROM_HERE
, base::Bind(&Browser::ProcessPendingUIUpdates
,
2276 chrome_updater_factory_
.GetWeakPtr()),
2277 base::TimeDelta::FromMilliseconds(kUIUpdateCoalescingTimeMS
));
2281 void Browser::ProcessPendingUIUpdates() {
2283 // Validate that all tabs we have pending updates for exist. This is scary
2284 // because the pending list must be kept in sync with any detached or
2286 for (UpdateMap::const_iterator i
= scheduled_updates_
.begin();
2287 i
!= scheduled_updates_
.end(); ++i
) {
2289 for (int tab
= 0; tab
< tab_strip_model_
->count(); tab
++) {
2290 if (tab_strip_model_
->GetWebContentsAt(tab
) == i
->first
) {
2299 chrome_updater_factory_
.InvalidateWeakPtrs();
2301 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2303 tracked_objects::ScopedTracker
tracking_profile1(
2304 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2305 "467185 Browser::ProcessPendingUIUpdates1"));
2307 for (UpdateMap::const_iterator i
= scheduled_updates_
.begin();
2308 i
!= scheduled_updates_
.end(); ++i
) {
2309 // Do not dereference |contents|, it may be out-of-date!
2310 const WebContents
* contents
= i
->first
;
2311 unsigned flags
= i
->second
;
2313 if (contents
== tab_strip_model_
->GetActiveWebContents()) {
2314 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2316 tracked_objects::ScopedTracker
tracking_profile2(
2317 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2318 "467185 Browser::ProcessPendingUIUpdates2"));
2320 // Updates that only matter when the tab is selected go here.
2322 // Updating the URL happens synchronously in ScheduleUIUpdate.
2323 if (flags
& content::INVALIDATE_TYPE_LOAD
&& GetStatusBubble()) {
2324 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents(
2325 tab_strip_model_
->GetActiveWebContents())->GetStatusText());
2328 if (flags
& (content::INVALIDATE_TYPE_TAB
|
2329 content::INVALIDATE_TYPE_TITLE
)) {
2330 window_
->UpdateTitleBar();
2334 // Updates that don't depend upon the selected state go here.
2336 (content::INVALIDATE_TYPE_TAB
| content::INVALIDATE_TYPE_TITLE
)) {
2337 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2339 tracked_objects::ScopedTracker
tracking_profile3(
2340 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2341 "467185 Browser::ProcessPendingUIUpdates3"));
2342 tab_strip_model_
->UpdateWebContentsStateAt(
2343 tab_strip_model_
->GetIndexOfWebContents(contents
),
2344 TabStripModelObserver::ALL
);
2347 // Update the bookmark bar. It may happen that the tab is crashed, and if
2348 // so, the bookmark bar should be hidden.
2349 if (flags
& content::INVALIDATE_TYPE_TAB
) {
2350 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2352 tracked_objects::ScopedTracker
tracking_profile4(
2353 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2354 "467185 Browser::ProcessPendingUIUpdates4"));
2355 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE
);
2358 // We don't need to process INVALIDATE_STATE, since that's not visible.
2361 scheduled_updates_
.clear();
2364 void Browser::RemoveScheduledUpdatesFor(WebContents
* contents
) {
2368 UpdateMap::iterator i
= scheduled_updates_
.find(contents
);
2369 if (i
!= scheduled_updates_
.end())
2370 scheduled_updates_
.erase(i
);
2373 ///////////////////////////////////////////////////////////////////////////////
2374 // Browser, Getters for UI (private):
2376 StatusBubble
* Browser::GetStatusBubble() {
2377 // In kiosk and exclusive app mode, we want to always hide the status bubble.
2378 if (chrome::IsRunningInAppMode())
2381 return window_
? window_
->GetStatusBubble() : NULL
;
2384 ///////////////////////////////////////////////////////////////////////////////
2385 // Browser, Session restore functions (private):
2387 void Browser::SyncHistoryWithTabs(int index
) {
2388 SessionService
* session_service
=
2389 SessionServiceFactory::GetForProfileIfExisting(profile());
2390 if (session_service
) {
2391 for (int i
= index
; i
< tab_strip_model_
->count(); ++i
) {
2392 WebContents
* web_contents
= tab_strip_model_
->GetWebContentsAt(i
);
2394 SessionTabHelper
* session_tab_helper
=
2395 SessionTabHelper::FromWebContents(web_contents
);
2396 session_service
->SetTabIndexInWindow(
2397 session_id(), session_tab_helper
->session_id(), i
);
2398 session_service
->SetPinnedState(
2400 session_tab_helper
->session_id(),
2401 tab_strip_model_
->IsTabPinned(i
));
2407 ///////////////////////////////////////////////////////////////////////////////
2408 // Browser, In-progress download termination handling (private):
2410 bool Browser::CanCloseWithInProgressDownloads() {
2411 // If we've prompted, we need to hear from the user before we
2413 if (cancel_download_confirmation_state_
!= NOT_PROMPTED
)
2414 return cancel_download_confirmation_state_
!= WAITING_FOR_RESPONSE
;
2416 int num_downloads_blocking
;
2417 Browser::DownloadClosePreventionType dialog_type
=
2418 OkToCloseWithInProgressDownloads(&num_downloads_blocking
);
2419 if (dialog_type
== DOWNLOAD_CLOSE_OK
)
2422 // Closing this window will kill some downloads; prompt to make sure
2424 cancel_download_confirmation_state_
= WAITING_FOR_RESPONSE
;
2425 window_
->ConfirmBrowserCloseWithPendingDownloads(
2426 num_downloads_blocking
,
2429 base::Bind(&Browser::InProgressDownloadResponse
,
2430 weak_factory_
.GetWeakPtr()));
2432 // Return false so the browser does not close. We'll close if the user
2433 // confirms in the dialog.
2437 ///////////////////////////////////////////////////////////////////////////////
2438 // Browser, Assorted utility functions (private):
2440 void Browser::SetAsDelegate(WebContents
* web_contents
, bool set_delegate
) {
2441 Browser
* delegate
= set_delegate
? this : NULL
;
2443 web_contents
->SetDelegate(delegate
);
2445 // ...and all the helpers.
2446 BookmarkTabHelper::FromWebContents(web_contents
)->set_delegate(delegate
);
2447 WebContentsModalDialogManager::FromWebContents(web_contents
)->
2448 SetDelegate(delegate
);
2449 CoreTabHelper::FromWebContents(web_contents
)->set_delegate(delegate
);
2450 SearchEngineTabHelper::FromWebContents(web_contents
)->set_delegate(delegate
);
2451 SearchTabHelper::FromWebContents(web_contents
)->set_delegate(delegate
);
2452 translate::ContentTranslateDriver
& content_translate_driver
=
2453 ChromeTranslateClient::FromWebContents(web_contents
)->translate_driver();
2455 ui_zoom::ZoomController::FromWebContents(web_contents
)->AddObserver(this);
2456 content_translate_driver
.AddObserver(this);
2458 ui_zoom::ZoomController::FromWebContents(web_contents
)->RemoveObserver(
2460 content_translate_driver
.RemoveObserver(this);
2464 void Browser::CloseFrame() {
2468 void Browser::TabDetachedAtImpl(content::WebContents
* contents
,
2471 if (type
== DETACH_TYPE_DETACH
) {
2472 // Save the current location bar state, but only if the tab being detached
2473 // is the selected tab. Because saving state can conditionally revert the
2474 // location bar, saving the current tab's location bar state to a
2475 // non-selected tab can corrupt both tabs.
2476 if (contents
== tab_strip_model_
->GetActiveWebContents()) {
2477 LocationBar
* location_bar
= window()->GetLocationBar();
2479 location_bar
->SaveStateToContents(contents
);
2482 if (!tab_strip_model_
->closing_all())
2483 SyncHistoryWithTabs(0);
2486 SetAsDelegate(contents
, false);
2487 RemoveScheduledUpdatesFor(contents
);
2489 if (find_bar_controller_
.get() && index
== tab_strip_model_
->active_index()) {
2490 find_bar_controller_
->ChangeWebContents(NULL
);
2493 // Stop observing search model changes for this tab.
2494 search_delegate_
->OnTabDetached(contents
);
2496 for (size_t i
= 0; i
< interstitial_observers_
.size(); i
++) {
2497 if (interstitial_observers_
[i
]->web_contents() != contents
)
2500 delete interstitial_observers_
[i
];
2501 interstitial_observers_
.erase(interstitial_observers_
.begin() + i
);
2506 bool Browser::SupportsLocationBar() const {
2507 // Tabbed browser always show a location bar.
2508 if (is_type_tabbed())
2511 // Non-app windows that aren't tabbed or system windows should always show a
2512 // location bar, unless they are from a trusted source.
2514 return !is_trusted_source();
2516 if (hosted_app_controller_
)
2517 return hosted_app_controller_
->SupportsLocationBar();
2522 bool Browser::ShouldUseWebAppFrame() const {
2523 // Only use the web app frame for apps in ash, and only if the web app frame
2528 if (hosted_app_controller_
)
2529 return hosted_app_controller_
->should_use_web_app_frame();
2534 bool Browser::SupportsWindowFeatureImpl(WindowFeature feature
,
2535 bool check_fullscreen
) const {
2536 bool hide_ui_for_fullscreen
= check_fullscreen
&& ShouldHideUIForFullscreen();
2538 unsigned int features
= FEATURE_INFOBAR
| FEATURE_DOWNLOADSHELF
;
2540 if (is_type_tabbed())
2541 features
|= FEATURE_BOOKMARKBAR
;
2543 if (!hide_ui_for_fullscreen
) {
2544 if (!is_type_tabbed())
2545 features
|= FEATURE_TITLEBAR
;
2547 if (is_type_tabbed())
2548 features
|= FEATURE_TABSTRIP
;
2550 if (is_type_tabbed())
2551 features
|= FEATURE_TOOLBAR
;
2553 if (SupportsLocationBar())
2554 features
|= FEATURE_LOCATIONBAR
;
2556 if (ShouldUseWebAppFrame())
2557 features
|= FEATURE_WEBAPPFRAME
;
2559 return !!(features
& feature
);
2562 void Browser::UpdateBookmarkBarState(BookmarkBarStateChangeReason reason
) {
2563 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185 is
2565 tracked_objects::ScopedTracker
tracking_profile1(
2566 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2567 "467185 Browser::UpdateBookmarkBarState1"));
2568 BookmarkBar::State state
;
2569 // The bookmark bar is always hidden for Guest Sessions and in fullscreen
2570 // mode, unless on the new tab page.
2571 if (profile_
->IsGuestSession()) {
2572 state
= BookmarkBar::HIDDEN
;
2573 } else if (browser_defaults::bookmarks_enabled
&&
2574 profile_
->GetPrefs()->GetBoolean(bookmarks::prefs::kShowBookmarkBar
) &&
2575 !ShouldHideUIForFullscreen()) {
2576 state
= BookmarkBar::SHOW
;
2578 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
2580 tracked_objects::ScopedTracker
tracking_profile2(
2581 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2582 "467185 Browser::UpdateBookmarkBarState2"));
2583 WebContents
* web_contents
= tab_strip_model_
->GetActiveWebContents();
2584 BookmarkTabHelper
* bookmark_tab_helper
=
2585 web_contents
? BookmarkTabHelper::FromWebContents(web_contents
) : NULL
;
2586 if (bookmark_tab_helper
&& bookmark_tab_helper
->ShouldShowBookmarkBar())
2587 state
= BookmarkBar::DETACHED
;
2589 state
= BookmarkBar::HIDDEN
;
2592 if (state
== bookmark_bar_state_
)
2595 bookmark_bar_state_
= state
;
2598 return; // This is called from the constructor when window_ is NULL.
2600 if (reason
== BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH
) {
2601 // Don't notify BrowserWindow on a tab switch as at the time this is invoked
2602 // BrowserWindow hasn't yet switched tabs. The BrowserWindow implementations
2603 // end up querying state once they process the tab switch.
2607 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185 is
2609 tracked_objects::ScopedTracker
tracking_profile3(
2610 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2611 "467185 Browser::UpdateBookmarkBarState3"));
2613 bool should_animate
= reason
== BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE
;
2614 window_
->BookmarkBarStateChanged(should_animate
?
2615 BookmarkBar::ANIMATE_STATE_CHANGE
:
2616 BookmarkBar::DONT_ANIMATE_STATE_CHANGE
);
2619 bool Browser::ShouldHideUIForFullscreen() const {
2620 // Windows and GTK remove the top controls in fullscreen, but Mac and Ash
2621 // keep the controls in a slide-down panel.
2622 return window_
&& window_
->ShouldHideUIForFullscreen();
2625 bool Browser::MaybeCreateBackgroundContents(
2627 int main_frame_route_id
,
2628 WebContents
* opener_web_contents
,
2629 const std::string
& frame_name
,
2630 const GURL
& target_url
,
2631 const std::string
& partition_id
,
2632 content::SessionStorageNamespace
* session_storage_namespace
) {
2633 GURL opener_url
= opener_web_contents
->GetURL();
2634 ExtensionService
* extensions_service
=
2635 extensions::ExtensionSystem::Get(profile_
)->extension_service();
2637 if (!opener_url
.is_valid() ||
2638 frame_name
.empty() ||
2639 !extensions_service
||
2640 !extensions_service
->is_ready())
2643 // Only hosted apps have web extents, so this ensures that only hosted apps
2644 // can create BackgroundContents. We don't have to check for background
2645 // permission as that is checked in RenderMessageFilter when the CreateWindow
2646 // message is processed.
2647 const Extension
* extension
= extensions::ExtensionRegistry::Get(profile_
)
2648 ->enabled_extensions()
2649 .GetHostedAppByURL(opener_url
);
2653 // No BackgroundContents allowed if BackgroundContentsService doesn't exist.
2654 BackgroundContentsService
* service
=
2655 BackgroundContentsServiceFactory::GetForProfile(profile_
);
2659 // Ensure that we're trying to open this from the extension's process.
2660 SiteInstance
* opener_site_instance
= opener_web_contents
->GetSiteInstance();
2661 extensions::ProcessMap
* process_map
= extensions::ProcessMap::Get(profile_
);
2662 if (!opener_site_instance
->GetProcess() ||
2663 !process_map
->Contains(
2664 extension
->id(), opener_site_instance
->GetProcess()->GetID())) {
2668 // Only allow a single background contents per app.
2669 bool allow_js_access
= extensions::BackgroundInfo::AllowJSAccess(extension
);
2670 BackgroundContents
* existing
=
2671 service
->GetAppBackgroundContents(base::ASCIIToUTF16(extension
->id()));
2673 // For non-scriptable background contents, ignore the request altogether,
2674 // (returning true, so that a regular WebContents isn't created either).
2675 if (!allow_js_access
)
2677 // For scriptable background pages, if one already exists, close it (even
2678 // if it was specified in the manifest).
2682 // If script access is not allowed, create the the background contents in a
2683 // new SiteInstance, so that a separate process is used.
2684 scoped_refptr
<content::SiteInstance
> site_instance
=
2686 opener_site_instance
:
2687 content::SiteInstance::Create(opener_web_contents
->GetBrowserContext());
2689 // Passed all the checks, so this should be created as a BackgroundContents.
2690 BackgroundContents
* contents
=
2691 service
->CreateBackgroundContents(site_instance
.get(),
2693 main_frame_route_id
,
2696 base::ASCIIToUTF16(extension
->id()),
2698 session_storage_namespace
);
2700 // When a separate process is used, the original renderer cannot access the
2701 // new window later, thus we need to navigate the window now.
2702 if (contents
&& !allow_js_access
) {
2703 contents
->web_contents()->GetController().LoadURL(
2705 content::Referrer(),
2706 ui::PAGE_TRANSITION_LINK
,
2707 std::string()); // No extra headers.
2710 return contents
!= NULL
;