Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / chrome / browser / lifetime / application_lifetime.cc
blob0fcddbcaa5cc9e09f9cd34452e1709a94401da04
1 // Copyright (c) 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/lifetime/application_lifetime.h"
7 #include "base/bind.h"
8 #include "base/command_line.h"
9 #include "base/logging.h"
10 #include "base/memory/scoped_ptr.h"
11 #include "base/message_loop/message_loop.h"
12 #include "base/prefs/pref_service.h"
13 #include "base/process/process.h"
14 #include "base/process/process_handle.h"
15 #include "base/trace_event/trace_event.h"
16 #include "build/build_config.h"
17 #include "chrome/browser/browser_process.h"
18 #include "chrome/browser/browser_process_platform_part.h"
19 #include "chrome/browser/browser_shutdown.h"
20 #include "chrome/browser/chrome_notification_types.h"
21 #include "chrome/browser/download/download_service.h"
22 #include "chrome/browser/lifetime/browser_close_manager.h"
23 #include "chrome/browser/metrics/thread_watcher.h"
24 #include "chrome/browser/profiles/profile.h"
25 #include "chrome/browser/profiles/profile_manager.h"
26 #include "chrome/browser/ui/browser.h"
27 #include "chrome/browser/ui/browser_finder.h"
28 #include "chrome/browser/ui/browser_iterator.h"
29 #include "chrome/browser/ui/browser_tabstrip.h"
30 #include "chrome/browser/ui/browser_window.h"
31 #include "chrome/browser/ui/tabs/tab_strip_model.h"
32 #include "chrome/browser/ui/user_manager.h"
33 #include "chrome/common/chrome_constants.h"
34 #include "chrome/common/chrome_switches.h"
35 #include "chrome/common/pref_names.h"
36 #include "content/public/browser/browser_thread.h"
37 #include "content/public/browser/navigation_details.h"
38 #include "content/public/browser/notification_service.h"
40 #if defined(OS_CHROMEOS)
41 #include "base/sys_info.h"
42 #include "chrome/browser/chromeos/boot_times_recorder.h"
43 #include "chromeos/dbus/dbus_thread_manager.h"
44 #include "chromeos/dbus/session_manager_client.h"
45 #include "chromeos/dbus/update_engine_client.h"
46 #endif
48 #if defined(OS_WIN)
49 #include "base/win/win_util.h"
50 #include "components/browser_watcher/exit_funnel_win.h"
51 #endif
53 #if defined(USE_ASH)
54 #include "ash/shell.h"
55 #endif
57 namespace chrome {
58 namespace {
60 #if !defined(OS_ANDROID)
61 // Returns true if all browsers can be closed without user interaction.
62 // This currently checks if there is pending download, or if it needs to
63 // handle unload handler.
64 bool AreAllBrowsersCloseable() {
65 chrome::BrowserIterator browser_it;
66 if (browser_it.done())
67 return true;
69 // If there are any downloads active, all browsers are not closeable.
70 // However, this does not block for malicious downloads.
71 if (DownloadService::NonMaliciousDownloadCountAllProfiles() > 0)
72 return false;
74 // Check TabsNeedBeforeUnloadFired().
75 for (; !browser_it.done(); browser_it.Next()) {
76 if (browser_it->TabsNeedBeforeUnloadFired())
77 return false;
79 return true;
81 #endif // !defined(OS_ANDROID)
83 int g_keep_alive_count = 0;
84 bool g_disable_shutdown_for_testing = false;
86 #if defined(OS_CHROMEOS)
87 // Whether chrome should send stop request to a session manager.
88 bool g_send_stop_request_to_session_manager = false;
89 #endif
91 } // namespace
93 void MarkAsCleanShutdown() {
94 // TODO(beng): Can this use ProfileManager::GetLoadedProfiles() instead?
95 for (chrome::BrowserIterator it; !it.done(); it.Next())
96 it->profile()->SetExitType(Profile::EXIT_NORMAL);
99 void AttemptExitInternal(bool try_to_quit_application) {
100 // On Mac, the platform-specific part handles setting this.
101 #if !defined(OS_MACOSX)
102 if (try_to_quit_application)
103 browser_shutdown::SetTryingToQuit(true);
104 #endif
106 content::NotificationService::current()->Notify(
107 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
108 content::NotificationService::AllSources(),
109 content::NotificationService::NoDetails());
111 g_browser_process->platform_part()->AttemptExit();
114 void CloseAllBrowsersAndQuit() {
115 browser_shutdown::SetTryingToQuit(true);
116 CloseAllBrowsers();
119 void CloseAllBrowsers() {
120 // If there are no browsers and closing the last browser would quit the
121 // application, send the APP_TERMINATING action here. Otherwise, it will be
122 // sent by RemoveBrowser() when the last browser has closed.
123 if (chrome::GetTotalBrowserCount() == 0 &&
124 (browser_shutdown::IsTryingToQuit() || !chrome::WillKeepAlive())) {
125 // Tell everyone that we are shutting down.
126 browser_shutdown::SetTryingToQuit(true);
128 #if defined(ENABLE_SESSION_SERVICE)
129 // If ShuttingDownWithoutClosingBrowsers() returns true, the session
130 // services may not get a chance to shut down normally, so explicitly shut
131 // them down here to ensure they have a chance to persist their data.
132 ProfileManager::ShutdownSessionServices();
133 #endif
135 chrome::NotifyAndTerminate(true);
136 chrome::OnAppExiting();
137 return;
140 #if defined(OS_CHROMEOS)
141 chromeos::BootTimesRecorder::Get()->AddLogoutTimeMarker(
142 "StartedClosingWindows", false);
143 #endif
144 scoped_refptr<BrowserCloseManager> browser_close_manager =
145 new BrowserCloseManager;
146 browser_close_manager->StartClosingBrowsers();
149 void AttemptUserExit() {
150 #if defined(OS_CHROMEOS)
151 StartShutdownTracing();
152 chromeos::BootTimesRecorder::Get()->AddLogoutTimeMarker("LogoutStarted",
153 false);
155 PrefService* state = g_browser_process->local_state();
156 if (state) {
157 chromeos::BootTimesRecorder::Get()->OnLogoutStarted(state);
159 // Login screen should show up in owner's locale.
160 std::string owner_locale = state->GetString(prefs::kOwnerLocale);
161 if (!owner_locale.empty() &&
162 state->GetString(prefs::kApplicationLocale) != owner_locale &&
163 !state->IsManagedPreference(prefs::kApplicationLocale)) {
164 state->SetString(prefs::kApplicationLocale, owner_locale);
165 TRACE_EVENT0("shutdown", "CommitPendingWrite");
166 state->CommitPendingWrite();
169 g_send_stop_request_to_session_manager = true;
170 // On ChromeOS, always terminate the browser, regardless of the result of
171 // AreAllBrowsersCloseable(). See crbug.com/123107.
172 chrome::NotifyAndTerminate(true);
173 #else
174 // Reset the restart bit that might have been set in cancelled restart
175 // request.
176 UserManager::Hide();
177 PrefService* pref_service = g_browser_process->local_state();
178 pref_service->SetBoolean(prefs::kRestartLastSessionOnShutdown, false);
179 AttemptExitInternal(false);
180 #endif
183 void StartShutdownTracing() {
184 const base::CommandLine& command_line =
185 *base::CommandLine::ForCurrentProcess();
186 if (command_line.HasSwitch(switches::kTraceShutdown)) {
187 base::trace_event::TraceConfig trace_config(
188 command_line.GetSwitchValueASCII(switches::kTraceShutdown), "");
189 base::trace_event::TraceLog::GetInstance()->SetEnabled(
190 trace_config,
191 base::trace_event::TraceLog::RECORDING_MODE);
193 TRACE_EVENT0("shutdown", "StartShutdownTracing");
196 // The Android implementation is in application_lifetime_android.cc
197 #if !defined(OS_ANDROID)
198 void AttemptRestart() {
199 // TODO(beng): Can this use ProfileManager::GetLoadedProfiles instead?
200 for (chrome::BrowserIterator it; !it.done(); it.Next())
201 content::BrowserContext::SaveSessionState(it->profile());
203 PrefService* pref_service = g_browser_process->local_state();
204 pref_service->SetBoolean(prefs::kWasRestarted, true);
206 #if defined(OS_CHROMEOS)
207 chromeos::BootTimesRecorder::Get()->set_restart_requested();
209 DCHECK(!g_send_stop_request_to_session_manager);
210 // Make sure we don't send stop request to the session manager.
211 g_send_stop_request_to_session_manager = false;
212 // Run exit process in clean stack.
213 content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE,
214 base::Bind(&ExitCleanly));
215 #else
216 // Set the flag to restore state after the restart.
217 pref_service->SetBoolean(prefs::kRestartLastSessionOnShutdown, true);
218 AttemptExit();
219 #endif
221 #endif
223 void AttemptExit() {
224 #if defined(OS_CHROMEOS)
225 // On ChromeOS, user exit and system exits are the same.
226 AttemptUserExit();
227 #else
228 // If we know that all browsers can be closed without blocking,
229 // don't notify users of crashes beyond this point.
230 // Note that MarkAsCleanShutdown() does not set UMA's exit cleanly bit
231 // so crashes during shutdown are still reported in UMA.
232 #if !defined(OS_ANDROID)
233 // Android doesn't use Browser.
234 if (AreAllBrowsersCloseable())
235 MarkAsCleanShutdown();
236 #endif
237 AttemptExitInternal(true);
238 #endif
241 #if defined(OS_CHROMEOS)
242 // A function called when SIGTERM is received.
243 void ExitCleanly() {
244 // We always mark exit cleanly.
245 MarkAsCleanShutdown();
247 // Don't block when SIGTERM is received. AreaAllBrowsersCloseable()
248 // can be false in following cases. a) power-off b) signout from
249 // screen locker.
250 if (!AreAllBrowsersCloseable())
251 browser_shutdown::OnShutdownStarting(browser_shutdown::END_SESSION);
252 else
253 browser_shutdown::OnShutdownStarting(browser_shutdown::BROWSER_EXIT);
254 AttemptExitInternal(true);
256 #endif
258 void SessionEnding() {
259 #if defined(OS_WIN)
260 browser_watcher::ExitFunnel funnel;
262 funnel.Init(kBrowserExitCodesRegistryPath, base::GetCurrentProcessHandle());
263 funnel.RecordEvent(L"SessionEnding");
264 #endif
265 // This is a time-limited shutdown where we need to write as much to
266 // disk as we can as soon as we can, and where we must kill the
267 // process within a hang timeout to avoid user prompts.
269 // Start watching for hang during shutdown, and crash it if takes too long.
270 // We disarm when |shutdown_watcher| object is destroyed, which is when we
271 // exit this function.
272 ShutdownWatcherHelper shutdown_watcher;
273 shutdown_watcher.Arm(base::TimeDelta::FromSeconds(90));
275 // EndSession is invoked once per frame. Only do something the first time.
276 static bool already_ended = false;
277 // We may get called in the middle of shutdown, e.g. http://crbug.com/70852
278 // In this case, do nothing.
279 if (already_ended || !content::NotificationService::current())
280 return;
281 already_ended = true;
283 browser_shutdown::OnShutdownStarting(browser_shutdown::END_SESSION);
285 content::NotificationService::current()->Notify(
286 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
287 content::NotificationService::AllSources(),
288 content::NotificationService::NoDetails());
290 #if defined(OS_WIN)
291 funnel.RecordEvent(L"EndSession");
292 #endif
293 // Write important data first.
294 g_browser_process->EndSession();
296 #if defined(OS_WIN)
297 base::win::SetShouldCrashOnProcessDetach(false);
298 #endif
300 #if defined(OS_WIN)
301 // KillProcess ought to terminate the process without further ado, so if
302 // execution gets to this point, presumably this is normal exit.
303 funnel.RecordEvent(L"KillProcess");
304 #endif
306 // On Windows 7 and later, the system will consider the process ripe for
307 // termination as soon as it hides or destroys its windows. Since any
308 // execution past that point will be non-deterministically cut short, we
309 // might as well put ourselves out of that misery deterministically.
310 base::Process::Current().Terminate(0, false);
313 void IncrementKeepAliveCount() {
314 // Increment the browser process refcount as long as we're keeping the
315 // application alive.
316 if (!WillKeepAlive())
317 g_browser_process->AddRefModule();
318 ++g_keep_alive_count;
321 void CloseAllBrowsersIfNeeded() {
322 // If there are no browsers open and we aren't already shutting down,
323 // initiate a shutdown. Also skips shutdown if this is a unit test.
324 // (MessageLoop::current() == null or explicitly disabled).
325 if (chrome::GetTotalBrowserCount() == 0 &&
326 !browser_shutdown::IsTryingToQuit() && base::MessageLoop::current() &&
327 !g_disable_shutdown_for_testing) {
328 CloseAllBrowsers();
332 void DecrementKeepAliveCount() {
333 DCHECK_GT(g_keep_alive_count, 0);
334 --g_keep_alive_count;
335 // Although we should have a browser process, if there is none,
336 // there is nothing to do.
337 if (!g_browser_process) return;
339 // Allow the app to shutdown again.
340 if (!WillKeepAlive()) {
341 g_browser_process->ReleaseModule();
342 CloseAllBrowsersIfNeeded();
346 bool WillKeepAlive() {
347 return g_keep_alive_count > 0;
350 void NotifyAppTerminating() {
351 static bool notified = false;
352 if (notified)
353 return;
354 notified = true;
355 content::NotificationService::current()->Notify(
356 chrome::NOTIFICATION_APP_TERMINATING,
357 content::NotificationService::AllSources(),
358 content::NotificationService::NoDetails());
361 void NotifyAndTerminate(bool fast_path) {
362 #if defined(OS_CHROMEOS)
363 static bool notified = false;
364 // Return if a shutdown request has already been sent.
365 if (notified)
366 return;
367 notified = true;
368 #endif
370 if (fast_path)
371 NotifyAppTerminating();
373 #if defined(OS_CHROMEOS)
374 if (base::SysInfo::IsRunningOnChromeOS()) {
375 // If we're on a ChromeOS device, reboot if an update has been applied,
376 // or else signal the session manager to log out.
377 chromeos::UpdateEngineClient* update_engine_client
378 = chromeos::DBusThreadManager::Get()->GetUpdateEngineClient();
379 if (update_engine_client->GetLastStatus().status ==
380 chromeos::UpdateEngineClient::UPDATE_STATUS_UPDATED_NEED_REBOOT) {
381 update_engine_client->RebootAfterUpdate();
382 } else if (g_send_stop_request_to_session_manager) {
383 // Don't ask SessionManager to stop session if the shutdown request comes
384 // from session manager.
385 chromeos::DBusThreadManager::Get()->GetSessionManagerClient()
386 ->StopSession();
388 } else {
389 if (g_send_stop_request_to_session_manager) {
390 // If running the Chrome OS build, but we're not on the device, act
391 // as if we received signal from SessionManager.
392 content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE,
393 base::Bind(&ExitCleanly));
396 #endif
399 void OnAppExiting() {
400 static bool notified = false;
401 if (notified)
402 return;
403 notified = true;
404 HandleAppExitingForPlatform();
407 bool ShouldStartShutdown(Browser* browser) {
408 if (BrowserList::GetInstance(browser->host_desktop_type())->size() > 1)
409 return false;
410 #if defined(OS_WIN)
411 // On Windows 8 the desktop and ASH environments could be active
412 // at the same time.
413 // We should not start the shutdown process in the following cases:-
414 // 1. If the desktop type of the browser going away is ASH and there
415 // are browser windows open in the desktop.
416 // 2. If the desktop type of the browser going away is desktop and the ASH
417 // environment is still active.
418 if (browser->host_desktop_type() == chrome::HOST_DESKTOP_TYPE_NATIVE)
419 return !ash::Shell::HasInstance();
420 else if (browser->host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH)
421 return BrowserList::GetInstance(chrome::HOST_DESKTOP_TYPE_NATIVE)->empty();
422 #endif
423 return true;
426 void DisableShutdownForTesting(bool disable_shutdown_for_testing) {
427 g_disable_shutdown_for_testing = disable_shutdown_for_testing;
428 if (!g_disable_shutdown_for_testing && !WillKeepAlive())
429 CloseAllBrowsersIfNeeded();
432 } // namespace chrome