Index: chrome/browser/lifetime/browser_keep_alive.cc |
diff --git a/chrome/browser/lifetime/browser_keep_alive.cc b/chrome/browser/lifetime/browser_keep_alive.cc |
new file mode 100644 |
index 0000000000000000000000000000000000000000..c78e25ad805fef3b279b32de382d1da6f9d94d81 |
--- /dev/null |
+++ b/chrome/browser/lifetime/browser_keep_alive.cc |
@@ -0,0 +1,78 @@ |
+// Copyright 2015 The Chromium Authors. All rights reserved. |
+// Use of this source code is governed by a BSD-style license that can be |
+// found in the LICENSE file. |
+ |
+#include "chrome/browser/lifetime/browser_keep_alive.h" |
+ |
+#include "base/message_loop/message_loop.h" |
+#include "chrome/browser/browser_process.h" |
+#include "chrome/browser/browser_shutdown.h" |
+#include "chrome/browser/lifetime/application_lifetime.h" |
+#include "chrome/browser/ui/browser_finder.h" |
+ |
+namespace browser_lifetime { |
+ |
+namespace { |
+ |
+int g_keep_alive_count = 0; |
sky
2015/10/07 17:27:24
These aren't global, they are file local. My under
|
+bool g_disable_shutdown_for_testing = false; |
+ |
+void CloseAllBrowsersIfNeeded() { |
+ // If there are no browsers open and we aren't already shutting down, |
+ // initiate a shutdown. Also skips shutdown if this is a unit test. |
+ // (MessageLoop::current() == null or explicitly disabled). |
+ if (chrome::GetTotalBrowserCount() == 0 && |
+ !browser_shutdown::IsTryingToQuit() && |
+ base::MessageLoop::current() && |
+ !g_disable_shutdown_for_testing) { |
+ chrome::CloseAllBrowsers(); |
+ } |
+} |
+ |
+} // namespace |
+ |
+ScopedKeepAlive::ScopedKeepAlive() { |
+ // Allow ScopedKeepAlive to be used in unit tests. |
+ if (g_browser_process) |
+ browser_lifetime::IncrementKeepAliveCount(); |
+} |
+ |
+ScopedKeepAlive::~ScopedKeepAlive() { |
+ if (g_browser_process) |
+ browser_lifetime::DecrementKeepAliveCount(); |
+} |
+ |
+void IncrementKeepAliveCount() { |
+ // Increment the browser process refcount as long as we're keeping the |
+ // application alive. |
+ if (!WillKeepAlive()) |
+ g_browser_process->AddRefModule(); |
+ ++g_keep_alive_count; |
+} |
+ |
+void DecrementKeepAliveCount() { |
+ DCHECK_GT(g_keep_alive_count, 0); |
+ --g_keep_alive_count; |
+ // Although we should have a browser process, if there is none, |
+ // there is nothing to do. |
+ if (!g_browser_process) |
+ return; |
+ |
+ // Allow the app to shutdown again. |
+ if (!WillKeepAlive()) { |
+ g_browser_process->ReleaseModule(); |
+ CloseAllBrowsersIfNeeded(); |
+ } |
+} |
+ |
+bool WillKeepAlive() { |
+ return g_keep_alive_count > 0; |
+} |
+ |
+void DisableShutdownForTesting(bool disable_shutdown_for_testing) { |
+ g_disable_shutdown_for_testing = disable_shutdown_for_testing; |
+ if (!g_disable_shutdown_for_testing && !WillKeepAlive()) |
+ CloseAllBrowsersIfNeeded(); |
+} |
+ |
+} // namespace browser_lifetime |