summaryrefslogtreecommitdiffstats
path: root/extensions/browser/api/idle/idle_manager.cc
blob: 5e8fc1ad0052ecd524c34660a9cf940db0611d85 (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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
// Copyright (c) 2012 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 "extensions/browser/api/idle/idle_manager.h"

#include <utility>

#include "base/stl_util.h"
#include "content/public/browser/browser_context.h"
#include "extensions/browser/api/idle/idle_api_constants.h"
#include "extensions/browser/event_router.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/common/api/idle.h"
#include "extensions/common/extension.h"

namespace keys = extensions::idle_api_constants;
namespace idle = extensions::core_api::idle;

namespace extensions {

namespace {

const int kDefaultIdleThreshold = 60;
const int kPollInterval = 1;

class DefaultEventDelegate : public IdleManager::EventDelegate {
 public:
  explicit DefaultEventDelegate(content::BrowserContext* context);
  ~DefaultEventDelegate() override;

  void OnStateChanged(const std::string& extension_id,
                      ui::IdleState new_state) override;
  void RegisterObserver(EventRouter::Observer* observer) override;
  void UnregisterObserver(EventRouter::Observer* observer) override;

 private:
  content::BrowserContext* const context_;
};

DefaultEventDelegate::DefaultEventDelegate(content::BrowserContext* context)
    : context_(context) {
}

DefaultEventDelegate::~DefaultEventDelegate() {
}

void DefaultEventDelegate::OnStateChanged(const std::string& extension_id,
                                          ui::IdleState new_state) {
  scoped_ptr<base::ListValue> args(new base::ListValue());
  args->Append(IdleManager::CreateIdleValue(new_state));
  scoped_ptr<Event> event(
      new Event(idle::OnStateChanged::kEventName, args.Pass()));
  event->restrict_to_browser_context = context_;
  EventRouter::Get(context_)
      ->DispatchEventToExtension(extension_id, event.Pass());
}

void DefaultEventDelegate::RegisterObserver(EventRouter::Observer* observer) {
  EventRouter::Get(context_)
      ->RegisterObserver(observer, idle::OnStateChanged::kEventName);
}

void DefaultEventDelegate::UnregisterObserver(EventRouter::Observer* observer) {
  EventRouter::Get(context_)->UnregisterObserver(observer);
}

class DefaultIdleProvider : public IdleManager::IdleTimeProvider {
 public:
  DefaultIdleProvider();
  ~DefaultIdleProvider() override;

  void CalculateIdleState(int idle_threshold, ui::IdleCallback notify) override;
  void CalculateIdleTime(ui::IdleTimeCallback notify) override;
  bool CheckIdleStateIsLocked() override;
};

DefaultIdleProvider::DefaultIdleProvider() {
}

DefaultIdleProvider::~DefaultIdleProvider() {
}

void DefaultIdleProvider::CalculateIdleState(int idle_threshold,
                                             ui::IdleCallback notify) {
  ui::CalculateIdleState(idle_threshold, notify);
}

void DefaultIdleProvider::CalculateIdleTime(ui::IdleTimeCallback notify) {
  ui::CalculateIdleTime(notify);
}

bool DefaultIdleProvider::CheckIdleStateIsLocked() {
  return ui::CheckIdleStateIsLocked();
}

ui::IdleState IdleTimeToIdleState(bool locked,
                                  int idle_time,
                                  int idle_threshold) {
  ui::IdleState state;

  if (locked) {
    state = ui::IDLE_STATE_LOCKED;
  } else if (idle_time >= idle_threshold) {
    state = ui::IDLE_STATE_IDLE;
  } else {
    state = ui::IDLE_STATE_ACTIVE;
  }
  return state;
}

}  // namespace

IdleMonitor::IdleMonitor(ui::IdleState initial_state)
    : last_state(initial_state),
      listeners(0),
      threshold(kDefaultIdleThreshold) {
}

IdleManager::IdleManager(content::BrowserContext* context)
    : context_(context),
      last_state_(ui::IDLE_STATE_ACTIVE),
      idle_time_provider_(new DefaultIdleProvider()),
      event_delegate_(new DefaultEventDelegate(context)),
      extension_registry_observer_(this),
      weak_factory_(this) {
}

IdleManager::~IdleManager() {
}

void IdleManager::Init() {
  extension_registry_observer_.Add(ExtensionRegistry::Get(context_));
  event_delegate_->RegisterObserver(this);
}

void IdleManager::Shutdown() {
  DCHECK(thread_checker_.CalledOnValidThread());
  event_delegate_->UnregisterObserver(this);
}

void IdleManager::OnExtensionUnloaded(content::BrowserContext* browser_context,
                                      const Extension* extension,
                                      UnloadedExtensionInfo::Reason reason) {
  DCHECK(thread_checker_.CalledOnValidThread());
  monitors_.erase(extension->id());
}

void IdleManager::OnListenerAdded(const EventListenerInfo& details) {
  DCHECK(thread_checker_.CalledOnValidThread());

  ++GetMonitor(details.extension_id)->listeners;
  StartPolling();
}

void IdleManager::OnListenerRemoved(const EventListenerInfo& details) {
  DCHECK(thread_checker_.CalledOnValidThread());

  // During unload the monitor could already have been deleted. No need to do
  // anything in that case.
  MonitorMap::iterator it = monitors_.find(details.extension_id);
  if (it != monitors_.end()) {
    DCHECK_GT(it->second.listeners, 0);
    // Note: Deliberately leave the listener count as 0 rather than erase()ing
    // this record so that the threshold doesn't get reset when all listeners
    // are removed.
    --it->second.listeners;
  }
}

void IdleManager::QueryState(int threshold, QueryStateCallback notify) {
  DCHECK(thread_checker_.CalledOnValidThread());
  idle_time_provider_->CalculateIdleState(threshold, notify);
}

void IdleManager::SetThreshold(const std::string& extension_id, int threshold) {
  DCHECK(thread_checker_.CalledOnValidThread());
  GetMonitor(extension_id)->threshold = threshold;
}

// static
base::StringValue* IdleManager::CreateIdleValue(ui::IdleState idle_state) {
  const char* description;

  if (idle_state == ui::IDLE_STATE_ACTIVE) {
    description = keys::kStateActive;
  } else if (idle_state == ui::IDLE_STATE_IDLE) {
    description = keys::kStateIdle;
  } else {
    description = keys::kStateLocked;
  }

  return new base::StringValue(description);
}

void IdleManager::SetEventDelegateForTest(
    scoped_ptr<EventDelegate> event_delegate) {
  DCHECK(thread_checker_.CalledOnValidThread());
  event_delegate_ = event_delegate.Pass();
}

void IdleManager::SetIdleTimeProviderForTest(
    scoped_ptr<IdleTimeProvider> idle_time_provider) {
  DCHECK(thread_checker_.CalledOnValidThread());
  idle_time_provider_ = idle_time_provider.Pass();
}

IdleMonitor* IdleManager::GetMonitor(const std::string& extension_id) {
  DCHECK(thread_checker_.CalledOnValidThread());
  MonitorMap::iterator it = monitors_.find(extension_id);

  if (it == monitors_.end()) {
    it = monitors_.insert(std::make_pair(extension_id,
                                         IdleMonitor(last_state_))).first;
  }
  return &it->second;
}

void IdleManager::StartPolling() {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (!poll_timer_.IsRunning()) {
    poll_timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(kPollInterval),
                      this, &IdleManager::UpdateIdleState);
  }
}

void IdleManager::StopPolling() {
  DCHECK(thread_checker_.CalledOnValidThread());
  poll_timer_.Stop();
}

void IdleManager::UpdateIdleState() {
  DCHECK(thread_checker_.CalledOnValidThread());
  idle_time_provider_->CalculateIdleTime(base::Bind(
      &IdleManager::UpdateIdleStateCallback, weak_factory_.GetWeakPtr()));
}

void IdleManager::UpdateIdleStateCallback(int idle_time) {
  DCHECK(thread_checker_.CalledOnValidThread());
  bool locked = idle_time_provider_->CheckIdleStateIsLocked();
  int listener_count = 0;

  // Remember this state for initializing new event listeners.
  last_state_ = IdleTimeToIdleState(locked, idle_time, kDefaultIdleThreshold);

  for (MonitorMap::iterator it = monitors_.begin(); it != monitors_.end();
       ++it) {
    IdleMonitor& monitor = it->second;
    ui::IdleState new_state =
        IdleTimeToIdleState(locked, idle_time, monitor.threshold);
    // TODO(kalman): Use EventRouter::HasListeners for these sorts of checks.
    if (monitor.listeners > 0 && monitor.last_state != new_state)
      event_delegate_->OnStateChanged(it->first, new_state);
    monitor.last_state = new_state;
    listener_count += monitor.listeners;
  }

  if (listener_count == 0)
    StopPolling();
}

}  // namespace extensions