Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / mojo / application / public / cpp / lib / app_lifetime_helper.cc
blob74c7ee86ecd61b85b72cff874ec16e51a7b9fddc
1 // Copyright 2015 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 "mojo/application/public/cpp/app_lifetime_helper.h"
7 #include "base/bind.h"
8 #include "base/message_loop/message_loop.h"
9 #include "mojo/application/public/cpp/application_impl.h"
11 namespace mojo {
13 AppRefCount::AppRefCount(
14 AppLifetimeHelper* app_lifetime_helper,
15 scoped_refptr<base::SingleThreadTaskRunner> app_task_runner)
16 : app_lifetime_helper_(app_lifetime_helper),
17 app_task_runner_(app_task_runner) {
20 AppRefCount::~AppRefCount() {
21 #ifndef NDEBUG
22 // Ensure that this object is used on only one thread at a time, or else there
23 // could be races where the object is being reset on one thread and cloned on
24 // another.
25 if (clone_task_runner_) {
26 DCHECK(clone_task_runner_->BelongsToCurrentThread());
28 #endif
30 if (app_task_runner_->BelongsToCurrentThread()) {
31 app_lifetime_helper_->Release();
32 return;
35 app_task_runner_->PostTask(
36 FROM_HERE,
37 base::Bind(&AppLifetimeHelper::Release,
38 base::Unretained(app_lifetime_helper_)));
41 scoped_ptr<AppRefCount> AppRefCount::Clone() {
42 if (app_task_runner_->BelongsToCurrentThread()) {
43 app_lifetime_helper_->AddRef();
44 } else {
45 app_task_runner_->PostTask(
46 FROM_HERE,
47 base::Bind(&AppLifetimeHelper::AddRef,
48 base::Unretained(app_lifetime_helper_)));
51 #ifndef NDEBUG
52 // Ensure that this object is used on only one thread at a time, or else there
53 // could be races where the object is being reset on one thread and cloned on
54 // another.
55 if (clone_task_runner_) {
56 DCHECK(clone_task_runner_->BelongsToCurrentThread());
57 } else {
58 clone_task_runner_ = base::MessageLoop::current()->task_runner();
60 #endif
62 return make_scoped_ptr(new AppRefCount(
63 app_lifetime_helper_, app_task_runner_));
66 AppLifetimeHelper::AppLifetimeHelper(ApplicationImpl* app)
67 : app_(app), ref_count_(0) {
70 AppLifetimeHelper::~AppLifetimeHelper() {
73 scoped_ptr<AppRefCount> AppLifetimeHelper::CreateAppRefCount() {
74 AddRef();
75 return make_scoped_ptr(new AppRefCount(
76 this, base::MessageLoop::current()->task_runner()));
79 void AppLifetimeHelper::AddRef() {
80 ref_count_++;
83 void AppLifetimeHelper::Release() {
84 if (!--ref_count_) {
85 if (app_)
86 app_->Quit();
90 void AppLifetimeHelper::OnQuit() {
91 app_ = nullptr;
94 } // namespace mojo