Re-subimission of https://codereview.chromium.org/1041213003/
[chromium-blink-merge.git] / content / browser / gamepad / gamepad_provider.cc
blobe16339cbc9690418ef9c96e9f2a4635923282ee3
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 <cmath>
6 #include <set>
7 #include <vector>
9 #include "base/bind.h"
10 #include "base/logging.h"
11 #include "base/message_loop/message_loop.h"
12 #include "base/message_loop/message_loop_proxy.h"
13 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
14 #include "base/threading/thread.h"
15 #include "base/threading/thread_restrictions.h"
16 #include "content/browser/gamepad/gamepad_data_fetcher.h"
17 #include "content/browser/gamepad/gamepad_platform_data_fetcher.h"
18 #include "content/browser/gamepad/gamepad_provider.h"
19 #include "content/browser/gamepad/gamepad_service.h"
20 #include "content/common/gamepad_hardware_buffer.h"
21 #include "content/common/gamepad_messages.h"
22 #include "content/common/gamepad_user_gesture.h"
23 #include "content/public/browser/browser_thread.h"
25 using blink::WebGamepad;
26 using blink::WebGamepads;
28 namespace content {
30 GamepadProvider::ClosureAndThread::ClosureAndThread(
31 const base::Closure& c,
32 const scoped_refptr<base::MessageLoopProxy>& m)
33 : closure(c),
34 message_loop(m) {
37 GamepadProvider::ClosureAndThread::~ClosureAndThread() {
40 GamepadProvider::GamepadProvider()
41 : is_paused_(true),
42 have_scheduled_do_poll_(false),
43 devices_changed_(true),
44 ever_had_user_gesture_(false) {
45 Initialize(scoped_ptr<GamepadDataFetcher>());
48 GamepadProvider::GamepadProvider(scoped_ptr<GamepadDataFetcher> fetcher)
49 : is_paused_(true),
50 have_scheduled_do_poll_(false),
51 devices_changed_(true),
52 ever_had_user_gesture_(false) {
53 Initialize(fetcher.Pass());
56 GamepadProvider::~GamepadProvider() {
57 base::SystemMonitor* monitor = base::SystemMonitor::Get();
58 if (monitor)
59 monitor->RemoveDevicesChangedObserver(this);
61 // Use Stop() to join the polling thread, as there may be pending callbacks
62 // which dereference |polling_thread_|.
63 polling_thread_->Stop();
64 data_fetcher_.reset();
67 base::SharedMemoryHandle GamepadProvider::GetSharedMemoryHandleForProcess(
68 base::ProcessHandle process) {
69 base::SharedMemoryHandle renderer_handle;
70 gamepad_shared_memory_.ShareToProcess(process, &renderer_handle);
71 return renderer_handle;
74 void GamepadProvider::GetCurrentGamepadData(WebGamepads* data) {
75 const WebGamepads& pads = SharedMemoryAsHardwareBuffer()->buffer;
76 base::AutoLock lock(shared_memory_lock_);
77 *data = pads;
80 void GamepadProvider::Pause() {
82 base::AutoLock lock(is_paused_lock_);
83 is_paused_ = true;
85 base::MessageLoop* polling_loop = polling_thread_->message_loop();
86 polling_loop->PostTask(
87 FROM_HERE,
88 base::Bind(&GamepadProvider::SendPauseHint, Unretained(this), true));
91 void GamepadProvider::Resume() {
93 base::AutoLock lock(is_paused_lock_);
94 if (!is_paused_)
95 return;
96 is_paused_ = false;
99 base::MessageLoop* polling_loop = polling_thread_->message_loop();
100 polling_loop->PostTask(
101 FROM_HERE,
102 base::Bind(&GamepadProvider::SendPauseHint, Unretained(this), false));
103 polling_loop->PostTask(
104 FROM_HERE,
105 base::Bind(&GamepadProvider::ScheduleDoPoll, Unretained(this)));
108 void GamepadProvider::RegisterForUserGesture(const base::Closure& closure) {
109 base::AutoLock lock(user_gesture_lock_);
110 user_gesture_observers_.push_back(ClosureAndThread(
111 closure, base::MessageLoop::current()->message_loop_proxy()));
114 void GamepadProvider::OnDevicesChanged(base::SystemMonitor::DeviceType type) {
115 base::AutoLock lock(devices_changed_lock_);
116 devices_changed_ = true;
119 void GamepadProvider::Initialize(scoped_ptr<GamepadDataFetcher> fetcher) {
120 size_t data_size = sizeof(GamepadHardwareBuffer);
121 base::SystemMonitor* monitor = base::SystemMonitor::Get();
122 if (monitor)
123 monitor->AddDevicesChangedObserver(this);
124 bool res = gamepad_shared_memory_.CreateAndMapAnonymous(data_size);
125 CHECK(res);
126 GamepadHardwareBuffer* hwbuf = SharedMemoryAsHardwareBuffer();
127 memset(hwbuf, 0, sizeof(GamepadHardwareBuffer));
128 pad_states_.reset(new PadState[WebGamepads::itemsLengthCap]);
130 polling_thread_.reset(new base::Thread("Gamepad polling thread"));
131 #if defined(OS_LINUX)
132 // On Linux, the data fetcher needs to watch file descriptors, so the message
133 // loop needs to be a libevent loop.
134 const base::MessageLoop::Type kMessageLoopType = base::MessageLoop::TYPE_IO;
135 #elif defined(OS_ANDROID)
136 // On Android, keeping a message loop of default type.
137 const base::MessageLoop::Type kMessageLoopType =
138 base::MessageLoop::TYPE_DEFAULT;
139 #else
140 // On Mac, the data fetcher uses IOKit which depends on CFRunLoop, so the
141 // message loop needs to be a UI-type loop. On Windows it must be a UI loop
142 // to properly pump the MessageWindow that captures device state.
143 const base::MessageLoop::Type kMessageLoopType = base::MessageLoop::TYPE_UI;
144 #endif
145 polling_thread_->StartWithOptions(base::Thread::Options(kMessageLoopType, 0));
147 polling_thread_->message_loop()->PostTask(
148 FROM_HERE,
149 base::Bind(&GamepadProvider::DoInitializePollingThread,
150 base::Unretained(this),
151 base::Passed(&fetcher)));
154 void GamepadProvider::DoInitializePollingThread(
155 scoped_ptr<GamepadDataFetcher> fetcher) {
156 DCHECK(base::MessageLoop::current() == polling_thread_->message_loop());
157 DCHECK(!data_fetcher_.get()); // Should only initialize once.
159 if (!fetcher)
160 fetcher.reset(new GamepadPlatformDataFetcher);
161 data_fetcher_ = fetcher.Pass();
164 void GamepadProvider::SendPauseHint(bool paused) {
165 DCHECK(base::MessageLoop::current() == polling_thread_->message_loop());
166 if (data_fetcher_)
167 data_fetcher_->PauseHint(paused);
170 bool GamepadProvider::PadState::Match(const WebGamepad& pad) const {
171 return connected_ == pad.connected &&
172 axes_length_ == pad.axesLength &&
173 buttons_length_ == pad.buttonsLength &&
174 memcmp(id_, pad.id, sizeof(id_)) == 0 &&
175 memcmp(mapping_, pad.mapping, sizeof(mapping_)) == 0;
178 void GamepadProvider::PadState::SetPad(const WebGamepad& pad) {
179 connected_ = pad.connected;
180 axes_length_ = pad.axesLength;
181 buttons_length_ = pad.buttonsLength;
182 memcpy(id_, pad.id, sizeof(id_));
183 memcpy(mapping_, pad.mapping, sizeof(mapping_));
186 void GamepadProvider::PadState::SetDisconnected() {
187 connected_ = false;
188 axes_length_ = 0;
189 buttons_length_ = 0;
190 memset(id_, 0, sizeof(id_));
191 memset(mapping_, 0, sizeof(mapping_));
194 void GamepadProvider::PadState::AsWebGamepad(WebGamepad* pad) {
195 pad->connected = connected_;
196 pad->axesLength = axes_length_;
197 pad->buttonsLength = buttons_length_;
198 memcpy(pad->id, id_, sizeof(id_));
199 memcpy(pad->mapping, mapping_, sizeof(mapping_));
200 memset(pad->axes, 0, sizeof(pad->axes));
201 memset(pad->buttons, 0, sizeof(pad->buttons));
204 void GamepadProvider::DoPoll() {
205 DCHECK(base::MessageLoop::current() == polling_thread_->message_loop());
206 DCHECK(have_scheduled_do_poll_);
207 have_scheduled_do_poll_ = false;
209 bool changed;
210 GamepadHardwareBuffer* hwbuf = SharedMemoryAsHardwareBuffer();
212 ANNOTATE_BENIGN_RACE_SIZED(
213 &hwbuf->buffer,
214 sizeof(WebGamepads),
215 "Racey reads are discarded");
218 base::AutoLock lock(devices_changed_lock_);
219 changed = devices_changed_;
220 devices_changed_ = false;
224 base::AutoLock lock(shared_memory_lock_);
226 // Acquire the SeqLock. There is only ever one writer to this data.
227 // See gamepad_hardware_buffer.h.
228 hwbuf->sequence.WriteBegin();
229 data_fetcher_->GetGamepadData(&hwbuf->buffer, changed);
230 hwbuf->sequence.WriteEnd();
233 if (ever_had_user_gesture_) {
234 for (unsigned i = 0; i < WebGamepads::itemsLengthCap; ++i) {
235 WebGamepad& pad = hwbuf->buffer.items[i];
236 PadState& state = pad_states_.get()[i];
237 if (pad.connected && !state.connected()) {
238 OnGamepadConnectionChange(true, i, pad);
239 } else if (!pad.connected && state.connected()) {
240 OnGamepadConnectionChange(false, i, pad);
241 } else if (pad.connected && state.connected() && !state.Match(pad)) {
242 WebGamepad old_pad;
243 state.AsWebGamepad(&old_pad);
244 OnGamepadConnectionChange(false, i, old_pad);
245 OnGamepadConnectionChange(true, i, pad);
250 CheckForUserGesture();
252 // Schedule our next interval of polling.
253 ScheduleDoPoll();
256 void GamepadProvider::ScheduleDoPoll() {
257 DCHECK(base::MessageLoop::current() == polling_thread_->message_loop());
258 if (have_scheduled_do_poll_)
259 return;
262 base::AutoLock lock(is_paused_lock_);
263 if (is_paused_)
264 return;
267 base::MessageLoop::current()->PostDelayedTask(
268 FROM_HERE,
269 base::Bind(&GamepadProvider::DoPoll, Unretained(this)),
270 base::TimeDelta::FromMilliseconds(kDesiredSamplingIntervalMs));
271 have_scheduled_do_poll_ = true;
274 void GamepadProvider::OnGamepadConnectionChange(
275 bool connected, int index, const WebGamepad& pad) {
276 PadState& state = pad_states_.get()[index];
277 if (connected)
278 state.SetPad(pad);
279 else
280 state.SetDisconnected();
282 BrowserThread::PostTask(
283 BrowserThread::IO,
284 FROM_HERE,
285 base::Bind(&GamepadProvider::DispatchGamepadConnectionChange,
286 base::Unretained(this),
287 connected,
288 index,
289 pad));
292 void GamepadProvider::DispatchGamepadConnectionChange(
293 bool connected, int index, const WebGamepad& pad) {
294 if (connected)
295 GamepadService::GetInstance()->OnGamepadConnected(index, pad);
296 else
297 GamepadService::GetInstance()->OnGamepadDisconnected(index, pad);
300 GamepadHardwareBuffer* GamepadProvider::SharedMemoryAsHardwareBuffer() {
301 void* mem = gamepad_shared_memory_.memory();
302 CHECK(mem);
303 return static_cast<GamepadHardwareBuffer*>(mem);
306 void GamepadProvider::CheckForUserGesture() {
307 base::AutoLock lock(user_gesture_lock_);
308 if (user_gesture_observers_.empty() && ever_had_user_gesture_)
309 return;
311 bool had_gesture_before = ever_had_user_gesture_;
312 const WebGamepads& pads = SharedMemoryAsHardwareBuffer()->buffer;
313 if (GamepadsHaveUserGesture(pads)) {
314 ever_had_user_gesture_ = true;
315 for (size_t i = 0; i < user_gesture_observers_.size(); i++) {
316 user_gesture_observers_[i].message_loop->PostTask(FROM_HERE,
317 user_gesture_observers_[i].closure);
319 user_gesture_observers_.clear();
321 if (!had_gesture_before && ever_had_user_gesture_) {
322 // Initialize pad_states_ for the first time.
323 for (size_t i = 0; i < WebGamepads::itemsLengthCap; ++i) {
324 pad_states_.get()[i].SetPad(pads.items[i]);
329 } // namespace content