summaryrefslogtreecommitdiffstats
path: root/mojo/shell/public/cpp/lib/app_lifetime_helper.cc
blob: b2a95a79141ee53a3ffbab07ac38f8603894fe1f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// 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 "mojo/shell/public/cpp/app_lifetime_helper.h"

#include "base/bind.h"
#include "base/message_loop/message_loop.h"
#include "mojo/shell/public/cpp/shell_connection.h"

namespace mojo {

AppRefCount::AppRefCount(
    AppLifetimeHelper* app_lifetime_helper,
    scoped_refptr<base::SingleThreadTaskRunner> app_task_runner)
    : app_lifetime_helper_(app_lifetime_helper),
      app_task_runner_(app_task_runner) {
}

AppRefCount::~AppRefCount() {
#ifndef NDEBUG
  // Ensure that this object is used on only one thread at a time, or else there
  // could be races where the object is being reset on one thread and cloned on
  // another.
  if (clone_task_runner_) {
    DCHECK(clone_task_runner_->BelongsToCurrentThread());
  }
#endif

  if (app_task_runner_->BelongsToCurrentThread()) {
    app_lifetime_helper_->Release();
    return;
  }

  app_task_runner_->PostTask(
      FROM_HERE,
      base::Bind(&AppLifetimeHelper::Release,
                 base::Unretained(app_lifetime_helper_)));
}

scoped_ptr<AppRefCount> AppRefCount::Clone() {
  if (app_task_runner_->BelongsToCurrentThread()) {
    app_lifetime_helper_->AddRef();
  } else {
    app_task_runner_->PostTask(
        FROM_HERE,
        base::Bind(&AppLifetimeHelper::AddRef,
                   base::Unretained(app_lifetime_helper_)));
  }

#ifndef NDEBUG
  // Ensure that this object is used on only one thread at a time, or else there
  // could be races where the object is being reset on one thread and cloned on
  // another.
  if (clone_task_runner_) {
    DCHECK(clone_task_runner_->BelongsToCurrentThread());
  } else {
    clone_task_runner_ = base::MessageLoop::current()->task_runner();
  }
#endif

  return make_scoped_ptr(new AppRefCount(
      app_lifetime_helper_, app_task_runner_));
}

AppLifetimeHelper::AppLifetimeHelper(ShellConnection* app)
    : app_(app), ref_count_(0) {
}

AppLifetimeHelper::~AppLifetimeHelper() {
}

scoped_ptr<AppRefCount> AppLifetimeHelper::CreateAppRefCount() {
  AddRef();
  return make_scoped_ptr(new AppRefCount(
      this, base::MessageLoop::current()->task_runner()));
}

void AppLifetimeHelper::AddRef() {
  ref_count_++;
}

void AppLifetimeHelper::Release() {
  if (!--ref_count_) {
    if (app_)
      app_->Quit();
  }
}

void AppLifetimeHelper::OnQuit() {
  app_ = nullptr;
}

}  // namespace mojo