1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this
5  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 // mostly derived from the Allegro source code at:
8 // http://alleg.svn.sourceforge.net/viewvc/alleg/allegro/branches/4.9/src/macosx/hidjoy.m?revision=13760&view=markup
9 
10 #include "mozilla/dom/GamepadHandle.h"
11 #include "mozilla/dom/GamepadPlatformService.h"
12 #include "mozilla/dom/GamepadRemapping.h"
13 #include "mozilla/ipc/BackgroundParent.h"
14 #include "mozilla/ArrayUtils.h"
15 #include "mozilla/Tainting.h"
16 #include "nsComponentManagerUtils.h"
17 #include "nsITimer.h"
18 #include "nsThreadUtils.h"
19 #include <CoreFoundation/CoreFoundation.h>
20 #include <IOKit/hid/IOHIDBase.h>
21 #include <IOKit/hid/IOHIDKeys.h>
22 #include <IOKit/hid/IOHIDManager.h>
23 
24 #include <stdio.h>
25 #include <vector>
26 
27 namespace {
28 
29 using namespace mozilla;
30 using namespace mozilla::dom;
31 using std::vector;
32 class DarwinGamepadService;
33 
34 DarwinGamepadService* gService = nullptr;
35 
36 struct Button {
37   int id;
38   bool analog;
39   IOHIDElementRef element;
40   CFIndex min;
41   CFIndex max;
42   bool pressed;
43 
Button__anon0dd67fe50111::Button44   Button(int aId, IOHIDElementRef aElement, CFIndex aMin, CFIndex aMax)
45       : id(aId),
46         analog((aMax - aMin) > 1),
47         element(aElement),
48         min(aMin),
49         max(aMax),
50         pressed(false) {}
51 };
52 
53 struct Axis {
54   int id;
55   IOHIDElementRef element;
56   uint32_t usagePage;
57   uint32_t usage;
58   CFIndex min;
59   CFIndex max;
60   double value;
61 };
62 
63 // These values can be found in the USB HID Usage Tables:
64 // http://www.usb.org/developers/hidpage
65 const unsigned kDesktopUsagePage = 0x01;
66 const unsigned kSimUsagePage = 0x02;
67 const unsigned kAcceleratorUsage = 0xC4;
68 const unsigned kBrakeUsage = 0xC5;
69 const unsigned kJoystickUsage = 0x04;
70 const unsigned kGamepadUsage = 0x05;
71 const unsigned kAxisUsageMin = 0x30;
72 const unsigned kAxisUsageMax = 0x35;
73 const unsigned kDpadUsage = 0x39;
74 const unsigned kButtonUsagePage = 0x09;
75 const unsigned kConsumerPage = 0x0C;
76 const unsigned kHomeUsage = 0x223;
77 const unsigned kBackUsage = 0x224;
78 
79 // We poll it periodically,
80 // 50ms is arbitrarily chosen.
81 const uint32_t kDarwinGamepadPollInterval = 50;
82 
83 class Gamepad {
84  private:
85   IOHIDDeviceRef mDevice;
86   nsTArray<Button> buttons;
87   nsTArray<Axis> axes;
88 
89  public:
Gamepad()90   Gamepad() : mDevice(nullptr) {}
91 
operator ==(IOHIDDeviceRef device) const92   bool operator==(IOHIDDeviceRef device) const { return mDevice == device; }
empty() const93   bool empty() const { return mDevice == nullptr; }
clear()94   void clear() {
95     mDevice = nullptr;
96     buttons.Clear();
97     axes.Clear();
98     mHandle = GamepadHandle{};
99   }
100   void init(IOHIDDeviceRef device, bool defaultRemapper);
101   void ReportChanged(uint8_t* report, CFIndex report_length);
102   size_t WriteOutputReport(const std::vector<uint8_t>& aReport) const;
103 
numButtons()104   size_t numButtons() { return buttons.Length(); }
numAxes()105   size_t numAxes() { return axes.Length(); }
106 
lookupButton(IOHIDElementRef element)107   Button* lookupButton(IOHIDElementRef element) {
108     for (unsigned i = 0; i < buttons.Length(); i++) {
109       if (buttons[i].element == element) return &buttons[i];
110     }
111     return nullptr;
112   }
113 
lookupAxis(IOHIDElementRef element)114   Axis* lookupAxis(IOHIDElementRef element) {
115     for (unsigned i = 0; i < axes.Length(); i++) {
116       if (axes[i].element == element) return &axes[i];
117     }
118     return nullptr;
119   }
120 
121   GamepadHandle mHandle;
122   RefPtr<GamepadRemapper> mRemapper;
123   std::vector<uint8_t> mInputReport;
124 };
125 
init(IOHIDDeviceRef aDevice,bool aDefaultRemapper)126 void Gamepad::init(IOHIDDeviceRef aDevice, bool aDefaultRemapper) {
127   clear();
128   mDevice = aDevice;
129 
130   CFArrayRef elements =
131       IOHIDDeviceCopyMatchingElements(aDevice, nullptr, kIOHIDOptionsTypeNone);
132   CFIndex n = CFArrayGetCount(elements);
133   for (CFIndex i = 0; i < n; i++) {
134     IOHIDElementRef element =
135         (IOHIDElementRef)CFArrayGetValueAtIndex(elements, i);
136     uint32_t usagePage = IOHIDElementGetUsagePage(element);
137     uint32_t usage = IOHIDElementGetUsage(element);
138 
139     if (usagePage == kDesktopUsagePage && usage >= kAxisUsageMin &&
140         usage <= kAxisUsageMax) {
141       Axis axis = {aDefaultRemapper ? int(axes.Length())
142                                     : static_cast<int>(usage - kAxisUsageMin),
143                    element,
144                    usagePage,
145                    usage,
146                    IOHIDElementGetLogicalMin(element),
147                    IOHIDElementGetLogicalMax(element)};
148       axes.AppendElement(axis);
149     } else if (usagePage == kDesktopUsagePage && usage == kDpadUsage &&
150                // Don't know how to handle d-pads that return weird values.
151                IOHIDElementGetLogicalMax(element) -
152                        IOHIDElementGetLogicalMin(element) ==
153                    7) {
154       Axis axis = {aDefaultRemapper ? int(axes.Length())
155                                     : static_cast<int>(usage - kAxisUsageMin),
156                    element,
157                    usagePage,
158                    usage,
159                    IOHIDElementGetLogicalMin(element),
160                    IOHIDElementGetLogicalMax(element)};
161       axes.AppendElement(axis);
162     } else if ((usagePage == kSimUsagePage &&
163                 (usage == kAcceleratorUsage || usage == kBrakeUsage)) ||
164                (usagePage == kButtonUsagePage) ||
165                (usagePage == kConsumerPage &&
166                 (usage == kHomeUsage || usage == kBackUsage))) {
167       Button button(int(buttons.Length()), element,
168                     IOHIDElementGetLogicalMin(element),
169                     IOHIDElementGetLogicalMax(element));
170       buttons.AppendElement(button);
171     } else {
172       // TODO: handle other usage pages
173     }
174   }
175 }
176 
177 // This service is created and destroyed in Background thread while
178 // operates in a seperate thread(We call it Monitor thread here).
179 class DarwinGamepadService {
180  private:
181   IOHIDManagerRef mManager;
182   vector<Gamepad> mGamepads;
183 
184   nsCOMPtr<nsIThread> mMonitorThread;
185   nsCOMPtr<nsIThread> mBackgroundThread;
186   nsCOMPtr<nsITimer> mPollingTimer;
187   bool mIsRunning;
188 
189   static void DeviceAddedCallback(void* data, IOReturn result, void* sender,
190                                   IOHIDDeviceRef device);
191   static void DeviceRemovedCallback(void* data, IOReturn result, void* sender,
192                                     IOHIDDeviceRef device);
193   static void InputValueChangedCallback(void* data, IOReturn result,
194                                         void* sender, IOHIDValueRef newValue);
195   static void EventLoopOnceCallback(nsITimer* aTimer, void* aClosure);
196 
197   void DeviceAdded(IOHIDDeviceRef device);
198   void DeviceRemoved(IOHIDDeviceRef device);
199   void InputValueChanged(IOHIDValueRef value);
200   void StartupInternal();
201   void RunEventLoopOnce();
202 
203  public:
204   DarwinGamepadService();
205   ~DarwinGamepadService();
206 
207   static void ReportChangedCallback(void* context, IOReturn result,
208                                     void* sender, IOHIDReportType report_type,
209                                     uint32_t report_id, uint8_t* report,
210                                     CFIndex report_length);
211 
212   void Startup();
213   void Shutdown();
214   void SetLightIndicatorColor(const Tainted<GamepadHandle>& aGamepadHandle,
215                               const Tainted<uint32_t>& aLightColorIndex,
216                               const uint8_t& aRed, const uint8_t& aGreen,
217                               const uint8_t& aBlue);
218   friend class DarwinGamepadServiceStartupRunnable;
219   friend class DarwinGamepadServiceShutdownRunnable;
220 };
221 
222 class DarwinGamepadServiceStartupRunnable final : public Runnable {
223  private:
~DarwinGamepadServiceStartupRunnable()224   ~DarwinGamepadServiceStartupRunnable() {}
225   // This Runnable schedules startup of DarwinGamepadService
226   // in a new thread, pointer to DarwinGamepadService is only
227   // used by this Runnable within its thread.
228   DarwinGamepadService MOZ_NON_OWNING_REF* mService;
229 
230  public:
DarwinGamepadServiceStartupRunnable(DarwinGamepadService * service)231   explicit DarwinGamepadServiceStartupRunnable(DarwinGamepadService* service)
232       : Runnable("DarwinGamepadServiceStartupRunnable"), mService(service) {}
Run()233   NS_IMETHOD Run() override {
234     MOZ_ASSERT(mService);
235     mService->StartupInternal();
236     return NS_OK;
237   }
238 };
239 
240 class DarwinGamepadServiceShutdownRunnable final : public Runnable {
241  private:
~DarwinGamepadServiceShutdownRunnable()242   ~DarwinGamepadServiceShutdownRunnable() {}
243 
244  public:
245   // This Runnable schedules shutdown of DarwinGamepadService
246   // in background thread.
DarwinGamepadServiceShutdownRunnable()247   explicit DarwinGamepadServiceShutdownRunnable()
248       : Runnable("DarwinGamepadServiceStartupRunnable") {}
Run()249   NS_IMETHOD Run() override {
250     MOZ_ASSERT(gService);
251     MOZ_ASSERT(NS_GetCurrentThread() == gService->mBackgroundThread);
252 
253     IOHIDManagerRef manager = (IOHIDManagerRef)gService->mManager;
254 
255     if (manager) {
256       IOHIDManagerClose(manager, 0);
257       CFRelease(manager);
258       gService->mManager = nullptr;
259     }
260     gService->mMonitorThread->Shutdown();
261     delete gService;
262     gService = nullptr;
263     return NS_OK;
264   }
265 };
266 
DeviceAdded(IOHIDDeviceRef device)267 void DarwinGamepadService::DeviceAdded(IOHIDDeviceRef device) {
268   RefPtr<GamepadPlatformService> service =
269       GamepadPlatformService::GetParentService();
270   if (!service) {
271     return;
272   }
273 
274   size_t slot = size_t(-1);
275   for (size_t i = 0; i < mGamepads.size(); i++) {
276     if (mGamepads[i] == device) return;
277     if (slot == size_t(-1) && mGamepads[i].empty()) slot = i;
278   }
279 
280   if (slot == size_t(-1)) {
281     slot = mGamepads.size();
282     mGamepads.push_back(Gamepad());
283   }
284 
285   // Gather some identifying information
286   CFNumberRef vendorIdRef =
287       (CFNumberRef)IOHIDDeviceGetProperty(device, CFSTR(kIOHIDVendorIDKey));
288   CFNumberRef productIdRef =
289       (CFNumberRef)IOHIDDeviceGetProperty(device, CFSTR(kIOHIDProductIDKey));
290   CFStringRef productRef =
291       (CFStringRef)IOHIDDeviceGetProperty(device, CFSTR(kIOHIDProductKey));
292   int vendorId, productId;
293   CFNumberGetValue(vendorIdRef, kCFNumberIntType, &vendorId);
294   CFNumberGetValue(productIdRef, kCFNumberIntType, &productId);
295   char product_name[128];
296   CFStringGetCString(productRef, product_name, sizeof(product_name),
297                      kCFStringEncodingASCII);
298   char buffer[256];
299   sprintf(buffer, "%x-%x-%s", vendorId, productId, product_name);
300 
301   bool defaultRemapper = false;
302   RefPtr<GamepadRemapper> remapper =
303       GetGamepadRemapper(vendorId, productId, defaultRemapper);
304   MOZ_ASSERT(remapper);
305   mGamepads[slot].init(device, defaultRemapper);
306 
307   remapper->SetAxisCount(mGamepads[slot].numAxes());
308   remapper->SetButtonCount(mGamepads[slot].numButtons());
309 
310   GamepadHandle handle = service->AddGamepad(
311       buffer, remapper->GetMappingType(), mozilla::dom::GamepadHand::_empty,
312       remapper->GetButtonCount(), remapper->GetAxisCount(),
313       0,  // TODO: Bug 680289, implement gamepad haptics for cocoa.
314       remapper->GetLightIndicatorCount(), remapper->GetTouchEventCount());
315 
316   nsTArray<GamepadLightIndicatorType> lightTypes;
317   remapper->GetLightIndicators(lightTypes);
318   for (uint32_t i = 0; i < lightTypes.Length(); ++i) {
319     if (lightTypes[i] != GamepadLightIndicator::DefaultType()) {
320       service->NewLightIndicatorTypeEvent(handle, i, lightTypes[i]);
321     }
322   }
323 
324   mGamepads[slot].mHandle = handle;
325   mGamepads[slot].mInputReport.resize(remapper->GetMaxInputReportLength());
326   mGamepads[slot].mRemapper = remapper.forget();
327 
328   IOHIDDeviceRegisterInputReportCallback(
329       device, mGamepads[slot].mInputReport.data(),
330       mGamepads[slot].mInputReport.size(), ReportChangedCallback,
331       &mGamepads[slot]);
332 }
333 
DeviceRemoved(IOHIDDeviceRef device)334 void DarwinGamepadService::DeviceRemoved(IOHIDDeviceRef device) {
335   RefPtr<GamepadPlatformService> service =
336       GamepadPlatformService::GetParentService();
337   if (!service) {
338     return;
339   }
340   for (size_t i = 0; i < mGamepads.size(); i++) {
341     if (mGamepads[i] == device) {
342       IOHIDDeviceRegisterInputReportCallback(
343           device, mGamepads[i].mInputReport.data(), 0, NULL, &mGamepads[i]);
344 
345       service->RemoveGamepad(mGamepads[i].mHandle);
346       mGamepads[i].clear();
347       return;
348     }
349   }
350 }
351 
352 // Replace context to be Gamepad.
ReportChangedCallback(void * context,IOReturn result,void * sender,IOHIDReportType report_type,uint32_t report_id,uint8_t * report,CFIndex report_length)353 void DarwinGamepadService::ReportChangedCallback(
354     void* context, IOReturn result, void* sender, IOHIDReportType report_type,
355     uint32_t report_id, uint8_t* report, CFIndex report_length) {
356   if (context && report_type == kIOHIDReportTypeInput && report_length) {
357     reinterpret_cast<Gamepad*>(context)->ReportChanged(report, report_length);
358   }
359 }
360 
ReportChanged(uint8_t * report,CFIndex report_len)361 void Gamepad::ReportChanged(uint8_t* report, CFIndex report_len) {
362   MOZ_RELEASE_ASSERT(report_len <= mRemapper->GetMaxInputReportLength());
363   mRemapper->ProcessTouchData(mHandle, report);
364 }
365 
WriteOutputReport(const std::vector<uint8_t> & aReport) const366 size_t Gamepad::WriteOutputReport(const std::vector<uint8_t>& aReport) const {
367   IOReturn success =
368       IOHIDDeviceSetReport(mDevice, kIOHIDReportTypeOutput, aReport[0],
369                            aReport.data(), aReport.size());
370 
371   MOZ_ASSERT(success == kIOReturnSuccess);
372   return (success == kIOReturnSuccess) ? aReport.size() : 0;
373 }
374 
InputValueChanged(IOHIDValueRef value)375 void DarwinGamepadService::InputValueChanged(IOHIDValueRef value) {
376   RefPtr<GamepadPlatformService> service =
377       GamepadPlatformService::GetParentService();
378   if (!service) {
379     return;
380   }
381 
382   uint32_t value_length = IOHIDValueGetLength(value);
383   if (value_length > 4) {
384     // Workaround for bizarre issue with PS3 controllers that try to return
385     // massive (30+ byte) values and crash IOHIDValueGetIntegerValue
386     return;
387   }
388   IOHIDElementRef element = IOHIDValueGetElement(value);
389   IOHIDDeviceRef device = IOHIDElementGetDevice(element);
390 
391   for (unsigned i = 0; i < mGamepads.size(); i++) {
392     Gamepad& gamepad = mGamepads[i];
393     if (gamepad == device) {
394       // Axis elements represent axes and d-pads.
395       if (Axis* axis = gamepad.lookupAxis(element)) {
396         const double d = IOHIDValueGetIntegerValue(value);
397         const double v =
398             2.0f * (d - axis->min) / (double)(axis->max - axis->min) - 1.0f;
399         if (axis->value != v) {
400           gamepad.mRemapper->RemapAxisMoveEvent(gamepad.mHandle, axis->id, v);
401           axis->value = v;
402         }
403       } else if (Button* button = gamepad.lookupButton(element)) {
404         const int iv = IOHIDValueGetIntegerValue(value);
405         const bool pressed = iv != 0;
406         if (button->pressed != pressed) {
407           gamepad.mRemapper->RemapButtonEvent(gamepad.mHandle, button->id,
408                                               pressed);
409           button->pressed = pressed;
410         }
411       }
412       return;
413     }
414   }
415 }
416 
DeviceAddedCallback(void * data,IOReturn result,void * sender,IOHIDDeviceRef device)417 void DarwinGamepadService::DeviceAddedCallback(void* data, IOReturn result,
418                                                void* sender,
419                                                IOHIDDeviceRef device) {
420   DarwinGamepadService* service = (DarwinGamepadService*)data;
421   service->DeviceAdded(device);
422 }
423 
DeviceRemovedCallback(void * data,IOReturn result,void * sender,IOHIDDeviceRef device)424 void DarwinGamepadService::DeviceRemovedCallback(void* data, IOReturn result,
425                                                  void* sender,
426                                                  IOHIDDeviceRef device) {
427   DarwinGamepadService* service = (DarwinGamepadService*)data;
428   service->DeviceRemoved(device);
429 }
430 
InputValueChangedCallback(void * data,IOReturn result,void * sender,IOHIDValueRef newValue)431 void DarwinGamepadService::InputValueChangedCallback(void* data,
432                                                      IOReturn result,
433                                                      void* sender,
434                                                      IOHIDValueRef newValue) {
435   DarwinGamepadService* service = (DarwinGamepadService*)data;
436   service->InputValueChanged(newValue);
437 }
438 
EventLoopOnceCallback(nsITimer * aTimer,void * aClosure)439 void DarwinGamepadService::EventLoopOnceCallback(nsITimer* aTimer,
440                                                  void* aClosure) {
441   DarwinGamepadService* service = static_cast<DarwinGamepadService*>(aClosure);
442   service->RunEventLoopOnce();
443 }
444 
MatchingDictionary(UInt32 inUsagePage,UInt32 inUsage)445 static CFMutableDictionaryRef MatchingDictionary(UInt32 inUsagePage,
446                                                  UInt32 inUsage) {
447   CFMutableDictionaryRef dict = CFDictionaryCreateMutable(
448       kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks,
449       &kCFTypeDictionaryValueCallBacks);
450   if (!dict) return nullptr;
451   CFNumberRef number =
452       CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &inUsagePage);
453   if (!number) {
454     CFRelease(dict);
455     return nullptr;
456   }
457   CFDictionarySetValue(dict, CFSTR(kIOHIDDeviceUsagePageKey), number);
458   CFRelease(number);
459 
460   number = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &inUsage);
461   if (!number) {
462     CFRelease(dict);
463     return nullptr;
464   }
465   CFDictionarySetValue(dict, CFSTR(kIOHIDDeviceUsageKey), number);
466   CFRelease(number);
467 
468   return dict;
469 }
470 
DarwinGamepadService()471 DarwinGamepadService::DarwinGamepadService()
472     : mManager(nullptr), mIsRunning(false) {}
473 
~DarwinGamepadService()474 DarwinGamepadService::~DarwinGamepadService() {
475   if (mManager != nullptr) CFRelease(mManager);
476   mMonitorThread = nullptr;
477   mBackgroundThread = nullptr;
478   if (mPollingTimer) {
479     mPollingTimer->Cancel();
480     mPollingTimer = nullptr;
481   }
482 }
483 
RunEventLoopOnce()484 void DarwinGamepadService::RunEventLoopOnce() {
485   MOZ_ASSERT(NS_GetCurrentThread() == mMonitorThread);
486   CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.0, true);
487 
488   // This timer must be created in monitor thread
489   if (!mPollingTimer) {
490     mPollingTimer = do_CreateInstance("@mozilla.org/timer;1");
491   }
492   mPollingTimer->Cancel();
493   if (mIsRunning) {
494     mPollingTimer->InitWithNamedFuncCallback(
495         EventLoopOnceCallback, this, kDarwinGamepadPollInterval,
496         nsITimer::TYPE_ONE_SHOT, "EventLoopOnceCallback");
497   } else {
498     // We schedule a task shutdown and cleaning up resources to Background
499     // thread here to make sure no runloop is running to prevent potential race
500     // condition.
501     RefPtr<Runnable> shutdownTask = new DarwinGamepadServiceShutdownRunnable();
502     mBackgroundThread->Dispatch(shutdownTask.forget(), NS_DISPATCH_NORMAL);
503   }
504 }
505 
StartupInternal()506 void DarwinGamepadService::StartupInternal() {
507   if (mManager != nullptr) return;
508 
509   IOHIDManagerRef manager =
510       IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
511 
512   CFMutableDictionaryRef criteria_arr[2];
513   criteria_arr[0] = MatchingDictionary(kDesktopUsagePage, kJoystickUsage);
514   if (!criteria_arr[0]) {
515     CFRelease(manager);
516     return;
517   }
518 
519   criteria_arr[1] = MatchingDictionary(kDesktopUsagePage, kGamepadUsage);
520   if (!criteria_arr[1]) {
521     CFRelease(criteria_arr[0]);
522     CFRelease(manager);
523     return;
524   }
525 
526   CFArrayRef criteria = CFArrayCreate(kCFAllocatorDefault,
527                                       (const void**)criteria_arr, 2, nullptr);
528   if (!criteria) {
529     CFRelease(criteria_arr[1]);
530     CFRelease(criteria_arr[0]);
531     CFRelease(manager);
532     return;
533   }
534 
535   IOHIDManagerSetDeviceMatchingMultiple(manager, criteria);
536   CFRelease(criteria);
537   CFRelease(criteria_arr[1]);
538   CFRelease(criteria_arr[0]);
539 
540   IOHIDManagerRegisterDeviceMatchingCallback(manager, DeviceAddedCallback,
541                                              this);
542   IOHIDManagerRegisterDeviceRemovalCallback(manager, DeviceRemovedCallback,
543                                             this);
544   IOHIDManagerRegisterInputValueCallback(manager, InputValueChangedCallback,
545                                          this);
546   IOHIDManagerScheduleWithRunLoop(manager, CFRunLoopGetCurrent(),
547                                   kCFRunLoopDefaultMode);
548   IOReturn rv = IOHIDManagerOpen(manager, kIOHIDOptionsTypeNone);
549   if (rv != kIOReturnSuccess) {
550     CFRelease(manager);
551     return;
552   }
553 
554   mManager = manager;
555 
556   mIsRunning = true;
557   RunEventLoopOnce();
558 }
559 
Startup()560 void DarwinGamepadService::Startup() {
561   mBackgroundThread = NS_GetCurrentThread();
562   Unused << NS_NewNamedThread("Gamepad", getter_AddRefs(mMonitorThread),
563                               new DarwinGamepadServiceStartupRunnable(this));
564 }
565 
Shutdown()566 void DarwinGamepadService::Shutdown() {
567   // Flipping this flag will stop the eventloop in Monitor thread
568   // and dispatch a task destroying and cleaning up resources in
569   // Background thread
570   mIsRunning = false;
571 }
572 
SetLightIndicatorColor(const Tainted<GamepadHandle> & aGamepadHandle,const Tainted<uint32_t> & aLightColorIndex,const uint8_t & aRed,const uint8_t & aGreen,const uint8_t & aBlue)573 void DarwinGamepadService::SetLightIndicatorColor(
574     const Tainted<GamepadHandle>& aGamepadHandle,
575     const Tainted<uint32_t>& aLightColorIndex, const uint8_t& aRed,
576     const uint8_t& aGreen, const uint8_t& aBlue) {
577   // We get aControllerIdx from GamepadPlatformService::AddGamepad(),
578   // It begins from 1 and is stored at Gamepad.id.
579   const Gamepad* gamepad = MOZ_FIND_AND_VALIDATE(
580       aGamepadHandle, list_item.mHandle == aGamepadHandle, mGamepads);
581   if (!gamepad) {
582     MOZ_ASSERT(false);
583     return;
584   }
585 
586   RefPtr<GamepadRemapper> remapper = gamepad->mRemapper;
587   if (!remapper ||
588       MOZ_IS_VALID(aLightColorIndex,
589                    remapper->GetLightIndicatorCount() <= aLightColorIndex)) {
590     MOZ_ASSERT(false);
591     return;
592   }
593 
594   std::vector<uint8_t> report;
595   remapper->GetLightColorReport(aRed, aGreen, aBlue, report);
596   gamepad->WriteOutputReport(report);
597 }
598 
599 }  // namespace
600 
601 namespace mozilla {
602 namespace dom {
603 
StartGamepadMonitoring()604 void StartGamepadMonitoring() {
605   ::mozilla::ipc::AssertIsOnBackgroundThread();
606   if (gService) {
607     return;
608   }
609 
610   gService = new DarwinGamepadService();
611   gService->Startup();
612 }
613 
StopGamepadMonitoring()614 void StopGamepadMonitoring() {
615   ::mozilla::ipc::AssertIsOnBackgroundThread();
616   if (!gService) {
617     return;
618   }
619 
620   // Calling Shutdown() will delete gService as well
621   gService->Shutdown();
622 }
623 
SetGamepadLightIndicatorColor(const Tainted<GamepadHandle> & aGamepadHandle,const Tainted<uint32_t> & aLightColorIndex,const uint8_t & aRed,const uint8_t & aGreen,const uint8_t & aBlue)624 void SetGamepadLightIndicatorColor(const Tainted<GamepadHandle>& aGamepadHandle,
625                                    const Tainted<uint32_t>& aLightColorIndex,
626                                    const uint8_t& aRed, const uint8_t& aGreen,
627                                    const uint8_t& aBlue) {
628   MOZ_ASSERT(gService);
629   if (!gService) {
630     return;
631   }
632   gService->SetLightIndicatorColor(aGamepadHandle, aLightColorIndex, aRed,
633                                    aGreen, aBlue);
634 }
635 
636 }  // namespace dom
637 }  // namespace mozilla
638