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.
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
;
30 GamepadProvider::ClosureAndThread::ClosureAndThread(
31 const base::Closure
& c
,
32 const scoped_refptr
<base::MessageLoopProxy
>& m
)
37 GamepadProvider::ClosureAndThread::~ClosureAndThread() {
40 GamepadProvider::GamepadProvider()
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
)
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();
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_
);
80 void GamepadProvider::Pause() {
82 base::AutoLock
lock(is_paused_lock_
);
85 base::MessageLoop
* polling_loop
= polling_thread_
->message_loop();
86 polling_loop
->PostTask(
88 base::Bind(&GamepadProvider::SendPauseHint
, Unretained(this), true));
91 void GamepadProvider::Resume() {
93 base::AutoLock
lock(is_paused_lock_
);
99 base::MessageLoop
* polling_loop
= polling_thread_
->message_loop();
100 polling_loop
->PostTask(
102 base::Bind(&GamepadProvider::SendPauseHint
, Unretained(this), false));
103 polling_loop
->PostTask(
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();
123 monitor
->AddDevicesChangedObserver(this);
124 bool res
= gamepad_shared_memory_
.CreateAndMapAnonymous(data_size
);
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
;
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
;
145 polling_thread_
->StartWithOptions(base::Thread::Options(kMessageLoopType
, 0));
147 polling_thread_
->message_loop()->PostTask(
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.
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());
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() {
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;
210 GamepadHardwareBuffer
* hwbuf
= SharedMemoryAsHardwareBuffer();
212 ANNOTATE_BENIGN_RACE_SIZED(
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
)) {
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.
256 void GamepadProvider::ScheduleDoPoll() {
257 DCHECK(base::MessageLoop::current() == polling_thread_
->message_loop());
258 if (have_scheduled_do_poll_
)
262 base::AutoLock
lock(is_paused_lock_
);
267 base::MessageLoop::current()->PostDelayedTask(
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
];
280 state
.SetDisconnected();
282 BrowserThread::PostTask(
285 base::Bind(&GamepadProvider::DispatchGamepadConnectionChange
,
286 base::Unretained(this),
292 void GamepadProvider::DispatchGamepadConnectionChange(
293 bool connected
, int index
, const WebGamepad
& pad
) {
295 GamepadService::GetInstance()->OnGamepadConnected(index
, pad
);
297 GamepadService::GetInstance()->OnGamepadDisconnected(index
, pad
);
300 GamepadHardwareBuffer
* GamepadProvider::SharedMemoryAsHardwareBuffer() {
301 void* mem
= gamepad_shared_memory_
.memory();
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_
)
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