Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(101)

Side by Side Diff: content/browser/gamepad/xbox_data_fetcher_mac.cc

Issue 2081583002: Migrating majority of gamepad from content/browser/ to device/ (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Final tweaks Created 4 years, 5 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright 2013 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.
4
5 #include "content/browser/gamepad/xbox_data_fetcher_mac.h"
6
7 #include <algorithm>
8 #include <cmath>
9 #include <limits>
10
11 #include <CoreFoundation/CoreFoundation.h>
12 #include <IOKit/IOCFPlugIn.h>
13 #include <IOKit/IOKitLib.h>
14 #include <IOKit/usb/IOUSBLib.h>
15 #include <IOKit/usb/USB.h>
16
17 #include "base/logging.h"
18 #include "base/mac/foundation_util.h"
19
20 namespace {
21 const int kVendorMicrosoft = 0x045e;
22 const int kProductXbox360Controller = 0x028e;
23 const int kProductXboxOneController = 0x02d1;
24
25 const int kXbox360ReadEndpoint = 1;
26 const int kXbox360ControlEndpoint = 2;
27
28 const int kXboxOneReadEndpoint = 2;
29 const int kXboxOneControlEndpoint = 1;
30
31 enum {
32 STATUS_MESSAGE_BUTTONS = 0,
33 STATUS_MESSAGE_LED = 1,
34
35 // Apparently this message tells you if the rumble pack is disabled in the
36 // controller. If the rumble pack is disabled, vibration control messages
37 // have no effect.
38 STATUS_MESSAGE_RUMBLE = 3,
39 };
40
41 enum {
42 XBOX_ONE_STATUS_MESSAGE_BUTTONS = 0x20,
43 };
44
45 enum {
46 CONTROL_MESSAGE_SET_RUMBLE = 0,
47 CONTROL_MESSAGE_SET_LED = 1,
48 };
49
50 #pragma pack(push, 1)
51 struct Xbox360ButtonData {
52 bool dpad_up : 1;
53 bool dpad_down : 1;
54 bool dpad_left : 1;
55 bool dpad_right : 1;
56
57 bool start : 1;
58 bool back : 1;
59 bool stick_left_click : 1;
60 bool stick_right_click : 1;
61
62 bool bumper_left : 1;
63 bool bumper_right : 1;
64 bool guide : 1;
65 bool dummy1 : 1; // Always 0.
66
67 bool a : 1;
68 bool b : 1;
69 bool x : 1;
70 bool y : 1;
71
72 uint8_t trigger_left;
73 uint8_t trigger_right;
74
75 int16_t stick_left_x;
76 int16_t stick_left_y;
77 int16_t stick_right_x;
78 int16_t stick_right_y;
79
80 // Always 0.
81 uint32_t dummy2;
82 uint16_t dummy3;
83 };
84
85 struct XboxOneButtonData {
86 bool sync : 1;
87 bool dummy1 : 1; // Always 0.
88 bool start : 1;
89 bool back : 1;
90
91 bool a : 1;
92 bool b : 1;
93 bool x : 1;
94 bool y : 1;
95
96 bool dpad_up : 1;
97 bool dpad_down : 1;
98 bool dpad_left : 1;
99 bool dpad_right : 1;
100
101 bool bumper_left : 1;
102 bool bumper_right : 1;
103 bool stick_left_click : 1;
104 bool stick_right_click : 1;
105
106 uint16_t trigger_left;
107 uint16_t trigger_right;
108
109 int16_t stick_left_x;
110 int16_t stick_left_y;
111 int16_t stick_right_x;
112 int16_t stick_right_y;
113 };
114 #pragma pack(pop)
115
116 static_assert(sizeof(Xbox360ButtonData) == 18, "xbox button data wrong size");
117 static_assert(sizeof(XboxOneButtonData) == 14, "xbox button data wrong size");
118
119 // From MSDN:
120 // http://msdn.microsoft.com/en-us/library/windows/desktop/ee417001(v=vs.85).asp x#dead_zone
121 const int16_t kLeftThumbDeadzone = 7849;
122 const int16_t kRightThumbDeadzone = 8689;
123 const uint8_t kXbox360TriggerDeadzone = 30;
124 const uint16_t kXboxOneTriggerMax = 1023;
125 const uint16_t kXboxOneTriggerDeadzone = 120;
126
127 void NormalizeAxis(int16_t x,
128 int16_t y,
129 int16_t deadzone,
130 float* x_out,
131 float* y_out) {
132 float x_val = x;
133 float y_val = y;
134
135 // Determine how far the stick is pushed.
136 float real_magnitude = std::sqrt(x_val * x_val + y_val * y_val);
137
138 // Check if the controller is outside a circular dead zone.
139 if (real_magnitude > deadzone) {
140 // Clip the magnitude at its expected maximum value.
141 float magnitude = std::min(32767.0f, real_magnitude);
142
143 // Adjust magnitude relative to the end of the dead zone.
144 magnitude -= deadzone;
145
146 // Normalize the magnitude with respect to its expected range giving a
147 // magnitude value of 0.0 to 1.0
148 float ratio = (magnitude / (32767 - deadzone)) / real_magnitude;
149
150 // Y is negated because xbox controllers have an opposite sign from
151 // the 'standard controller' recommendations.
152 *x_out = x_val * ratio;
153 *y_out = -y_val * ratio;
154 } else {
155 // If the controller is in the deadzone zero out the magnitude.
156 *x_out = *y_out = 0.0f;
157 }
158 }
159
160 float NormalizeTrigger(uint8_t value) {
161 return value < kXbox360TriggerDeadzone
162 ? 0
163 : static_cast<float>(value - kXbox360TriggerDeadzone) /
164 (std::numeric_limits<uint8_t>::max() -
165 kXbox360TriggerDeadzone);
166 }
167
168 float NormalizeXboxOneTrigger(uint16_t value) {
169 return value < kXboxOneTriggerDeadzone ? 0 :
170 static_cast<float>(value - kXboxOneTriggerDeadzone) /
171 (kXboxOneTriggerMax - kXboxOneTriggerDeadzone);
172 }
173
174 void NormalizeXbox360ButtonData(const Xbox360ButtonData& data,
175 XboxController::Data* normalized_data) {
176 normalized_data->buttons[0] = data.a;
177 normalized_data->buttons[1] = data.b;
178 normalized_data->buttons[2] = data.x;
179 normalized_data->buttons[3] = data.y;
180 normalized_data->buttons[4] = data.bumper_left;
181 normalized_data->buttons[5] = data.bumper_right;
182 normalized_data->buttons[6] = data.back;
183 normalized_data->buttons[7] = data.start;
184 normalized_data->buttons[8] = data.stick_left_click;
185 normalized_data->buttons[9] = data.stick_right_click;
186 normalized_data->buttons[10] = data.dpad_up;
187 normalized_data->buttons[11] = data.dpad_down;
188 normalized_data->buttons[12] = data.dpad_left;
189 normalized_data->buttons[13] = data.dpad_right;
190 normalized_data->buttons[14] = data.guide;
191 normalized_data->triggers[0] = NormalizeTrigger(data.trigger_left);
192 normalized_data->triggers[1] = NormalizeTrigger(data.trigger_right);
193 NormalizeAxis(data.stick_left_x,
194 data.stick_left_y,
195 kLeftThumbDeadzone,
196 &normalized_data->axes[0],
197 &normalized_data->axes[1]);
198 NormalizeAxis(data.stick_right_x,
199 data.stick_right_y,
200 kRightThumbDeadzone,
201 &normalized_data->axes[2],
202 &normalized_data->axes[3]);
203 }
204
205 void NormalizeXboxOneButtonData(const XboxOneButtonData& data,
206 XboxController::Data* normalized_data) {
207 normalized_data->buttons[0] = data.a;
208 normalized_data->buttons[1] = data.b;
209 normalized_data->buttons[2] = data.x;
210 normalized_data->buttons[3] = data.y;
211 normalized_data->buttons[4] = data.bumper_left;
212 normalized_data->buttons[5] = data.bumper_right;
213 normalized_data->buttons[6] = data.back;
214 normalized_data->buttons[7] = data.start;
215 normalized_data->buttons[8] = data.stick_left_click;
216 normalized_data->buttons[9] = data.stick_right_click;
217 normalized_data->buttons[10] = data.dpad_up;
218 normalized_data->buttons[11] = data.dpad_down;
219 normalized_data->buttons[12] = data.dpad_left;
220 normalized_data->buttons[13] = data.dpad_right;
221 normalized_data->buttons[14] = data.sync;
222 normalized_data->triggers[0] = NormalizeXboxOneTrigger(data.trigger_left);
223 normalized_data->triggers[1] = NormalizeXboxOneTrigger(data.trigger_right);
224 NormalizeAxis(data.stick_left_x,
225 data.stick_left_y,
226 kLeftThumbDeadzone,
227 &normalized_data->axes[0],
228 &normalized_data->axes[1]);
229 NormalizeAxis(data.stick_right_x,
230 data.stick_right_y,
231 kRightThumbDeadzone,
232 &normalized_data->axes[2],
233 &normalized_data->axes[3]);
234 }
235
236 } // namespace
237
238 XboxController::XboxController(Delegate* delegate)
239 : device_(NULL),
240 interface_(NULL),
241 device_is_open_(false),
242 interface_is_open_(false),
243 read_buffer_size_(0),
244 led_pattern_(LED_NUM_PATTERNS),
245 location_id_(0),
246 delegate_(delegate),
247 controller_type_(UNKNOWN_CONTROLLER),
248 read_endpoint_(0),
249 control_endpoint_(0) {
250 }
251
252 XboxController::~XboxController() {
253 if (source_)
254 CFRunLoopSourceInvalidate(source_);
255 if (interface_ && interface_is_open_)
256 (*interface_)->USBInterfaceClose(interface_);
257 if (device_ && device_is_open_)
258 (*device_)->USBDeviceClose(device_);
259 }
260
261 bool XboxController::OpenDevice(io_service_t service) {
262 IOCFPlugInInterface **plugin;
263 SInt32 score; // Unused, but required for IOCreatePlugInInterfaceForService.
264 kern_return_t kr =
265 IOCreatePlugInInterfaceForService(service,
266 kIOUSBDeviceUserClientTypeID,
267 kIOCFPlugInInterfaceID,
268 &plugin,
269 &score);
270 if (kr != KERN_SUCCESS)
271 return false;
272 base::mac::ScopedIOPluginInterface<IOCFPlugInInterface> plugin_ref(plugin);
273
274 HRESULT res =
275 (*plugin)->QueryInterface(plugin,
276 CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID320),
277 (LPVOID *)&device_);
278 if (!SUCCEEDED(res) || !device_)
279 return false;
280
281 UInt16 vendor_id;
282 kr = (*device_)->GetDeviceVendor(device_, &vendor_id);
283 if (kr != KERN_SUCCESS || vendor_id != kVendorMicrosoft)
284 return false;
285
286 UInt16 product_id;
287 kr = (*device_)->GetDeviceProduct(device_, &product_id);
288 if (kr != KERN_SUCCESS)
289 return false;
290
291 IOUSBFindInterfaceRequest request;
292 switch (product_id) {
293 case kProductXbox360Controller:
294 controller_type_ = XBOX_360_CONTROLLER;
295 read_endpoint_ = kXbox360ReadEndpoint;
296 control_endpoint_ = kXbox360ControlEndpoint;
297 request.bInterfaceClass = 255;
298 request.bInterfaceSubClass = 93;
299 request.bInterfaceProtocol = 1;
300 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
301 break;
302 case kProductXboxOneController:
303 controller_type_ = XBOX_ONE_CONTROLLER;
304 read_endpoint_ = kXboxOneReadEndpoint;
305 control_endpoint_ = kXboxOneControlEndpoint;
306 request.bInterfaceClass = 255;
307 request.bInterfaceSubClass = 71;
308 request.bInterfaceProtocol = 208;
309 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
310 break;
311 default:
312 return false;
313 }
314
315 // Open the device and configure it.
316 kr = (*device_)->USBDeviceOpen(device_);
317 if (kr != KERN_SUCCESS)
318 return false;
319 device_is_open_ = true;
320
321 // Xbox controllers have one configuration option which has configuration
322 // value 1. Try to set it and fail if it couldn't be configured.
323 IOUSBConfigurationDescriptorPtr config_desc;
324 kr = (*device_)->GetConfigurationDescriptorPtr(device_, 0, &config_desc);
325 if (kr != KERN_SUCCESS)
326 return false;
327 kr = (*device_)->SetConfiguration(device_, config_desc->bConfigurationValue);
328 if (kr != KERN_SUCCESS)
329 return false;
330
331 // The device has 4 interfaces. They are as follows:
332 // Protocol 1:
333 // - Endpoint 1 (in) : Controller events, including button presses.
334 // - Endpoint 2 (out): Rumble pack and LED control
335 // Protocol 2 has a single endpoint to read from a connected ChatPad device.
336 // Protocol 3 is used by a connected headset device.
337 // The device also has an interface on subclass 253, protocol 10 with no
338 // endpoints. It is unused.
339 //
340 // We don't currently support the ChatPad or headset, so protocol 1 is the
341 // only protocol we care about.
342 //
343 // For more detail, see
344 // https://github.com/Grumbel/xboxdrv/blob/master/PROTOCOL
345 io_iterator_t iter;
346 kr = (*device_)->CreateInterfaceIterator(device_, &request, &iter);
347 if (kr != KERN_SUCCESS)
348 return false;
349 base::mac::ScopedIOObject<io_iterator_t> iter_ref(iter);
350
351 // There should be exactly one USB interface which matches the requested
352 // settings.
353 io_service_t usb_interface = IOIteratorNext(iter);
354 if (!usb_interface)
355 return false;
356
357 // We need to make an InterfaceInterface to communicate with the device
358 // endpoint. This is the same process as earlier: first make a
359 // PluginInterface from the io_service then make the InterfaceInterface from
360 // that.
361 IOCFPlugInInterface **plugin_interface;
362 kr = IOCreatePlugInInterfaceForService(usb_interface,
363 kIOUSBInterfaceUserClientTypeID,
364 kIOCFPlugInInterfaceID,
365 &plugin_interface,
366 &score);
367 if (kr != KERN_SUCCESS || !plugin_interface)
368 return false;
369 base::mac::ScopedIOPluginInterface<IOCFPlugInInterface> interface_ref(
370 plugin_interface);
371
372 // Release the USB interface, and any subsequent interfaces returned by the
373 // iterator. (There shouldn't be any, but in case a future device does
374 // contain more interfaces, this will serve to avoid memory leaks.)
375 do {
376 IOObjectRelease(usb_interface);
377 } while ((usb_interface = IOIteratorNext(iter)));
378
379 // Actually create the interface.
380 res = (*plugin_interface)->QueryInterface(
381 plugin_interface,
382 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID300),
383 (LPVOID *)&interface_);
384
385 if (!SUCCEEDED(res) || !interface_)
386 return false;
387
388 // Actually open the interface.
389 kr = (*interface_)->USBInterfaceOpen(interface_);
390 if (kr != KERN_SUCCESS)
391 return false;
392 interface_is_open_ = true;
393
394 CFRunLoopSourceRef source_ref;
395 kr = (*interface_)->CreateInterfaceAsyncEventSource(interface_, &source_ref);
396 if (kr != KERN_SUCCESS || !source_ref)
397 return false;
398 source_.reset(source_ref);
399 CFRunLoopAddSource(CFRunLoopGetCurrent(), source_, kCFRunLoopDefaultMode);
400
401 // The interface should have two pipes. Pipe 1 with direction kUSBIn and pipe
402 // 2 with direction kUSBOut. Both pipes should have type kUSBInterrupt.
403 uint8_t num_endpoints;
404 kr = (*interface_)->GetNumEndpoints(interface_, &num_endpoints);
405 if (kr != KERN_SUCCESS || num_endpoints < 2)
406 return false;
407
408 for (int i = 1; i <= 2; i++) {
409 uint8_t direction;
410 uint8_t number;
411 uint8_t transfer_type;
412 uint16_t max_packet_size;
413 uint8_t interval;
414
415 kr = (*interface_)->GetPipeProperties(interface_,
416 i,
417 &direction,
418 &number,
419 &transfer_type,
420 &max_packet_size,
421 &interval);
422 if (kr != KERN_SUCCESS || transfer_type != kUSBInterrupt) {
423 return false;
424 }
425 if (i == read_endpoint_) {
426 if (direction != kUSBIn)
427 return false;
428 read_buffer_.reset(new uint8_t[max_packet_size]);
429 read_buffer_size_ = max_packet_size;
430 QueueRead();
431 } else if (i == control_endpoint_) {
432 if (direction != kUSBOut)
433 return false;
434 if (controller_type_ == XBOX_ONE_CONTROLLER)
435 WriteXboxOneInit();
436 }
437 }
438
439 // The location ID is unique per controller, and can be used to track
440 // controllers through reconnections (though if a controller is detached from
441 // one USB hub and attached to another, the location ID will change).
442 kr = (*device_)->GetLocationID(device_, &location_id_);
443 if (kr != KERN_SUCCESS)
444 return false;
445
446 return true;
447 }
448
449 void XboxController::SetLEDPattern(LEDPattern pattern) {
450 led_pattern_ = pattern;
451 const UInt8 length = 3;
452
453 // This buffer will be released in WriteComplete when WritePipeAsync
454 // finishes.
455 UInt8* buffer = new UInt8[length];
456 buffer[0] = static_cast<UInt8>(CONTROL_MESSAGE_SET_LED);
457 buffer[1] = length;
458 buffer[2] = static_cast<UInt8>(pattern);
459 kern_return_t kr = (*interface_)->WritePipeAsync(interface_,
460 control_endpoint_,
461 buffer,
462 (UInt32)length,
463 WriteComplete,
464 buffer);
465 if (kr != KERN_SUCCESS) {
466 delete[] buffer;
467 IOError();
468 return;
469 }
470 }
471
472 int XboxController::GetVendorId() const {
473 return kVendorMicrosoft;
474 }
475
476 int XboxController::GetProductId() const {
477 if (controller_type_ == XBOX_360_CONTROLLER)
478 return kProductXbox360Controller;
479 else
480 return kProductXboxOneController;
481 }
482
483 XboxController::ControllerType XboxController::GetControllerType() const {
484 return controller_type_;
485 }
486
487 void XboxController::WriteComplete(void* context, IOReturn result, void* arg0) {
488 UInt8* buffer = static_cast<UInt8*>(context);
489 delete[] buffer;
490
491 // Ignoring any errors sending data, because they will usually only occur
492 // when the device is disconnected, in which case it really doesn't matter if
493 // the data got to the controller or not.
494 if (result != kIOReturnSuccess)
495 return;
496 }
497
498 void XboxController::GotData(void* context, IOReturn result, void* arg0) {
499 size_t bytes_read = reinterpret_cast<size_t>(arg0);
500 XboxController* controller = static_cast<XboxController*>(context);
501
502 if (result != kIOReturnSuccess) {
503 // This will happen if the device was disconnected. The gamepad has
504 // probably been destroyed by a meteorite.
505 controller->IOError();
506 return;
507 }
508
509 if (controller->GetControllerType() == XBOX_360_CONTROLLER)
510 controller->ProcessXbox360Packet(bytes_read);
511 else
512 controller->ProcessXboxOnePacket(bytes_read);
513
514 // Queue up another read.
515 controller->QueueRead();
516 }
517
518 void XboxController::ProcessXbox360Packet(size_t length) {
519 if (length < 2)
520 return;
521 DCHECK(length <= read_buffer_size_);
522 if (length > read_buffer_size_) {
523 IOError();
524 return;
525 }
526 uint8_t* buffer = read_buffer_.get();
527
528 if (buffer[1] != length)
529 // Length in packet doesn't match length reported by USB.
530 return;
531
532 uint8_t type = buffer[0];
533 buffer += 2;
534 length -= 2;
535 switch (type) {
536 case STATUS_MESSAGE_BUTTONS: {
537 if (length != sizeof(Xbox360ButtonData))
538 return;
539 Xbox360ButtonData* data = reinterpret_cast<Xbox360ButtonData*>(buffer);
540 Data normalized_data;
541 NormalizeXbox360ButtonData(*data, &normalized_data);
542 delegate_->XboxControllerGotData(this, normalized_data);
543 break;
544 }
545 case STATUS_MESSAGE_LED:
546 if (length != 3)
547 return;
548 // The controller sends one of these messages every time the LED pattern
549 // is set, as well as once when it is plugged in.
550 if (led_pattern_ == LED_NUM_PATTERNS && buffer[0] < LED_NUM_PATTERNS)
551 led_pattern_ = static_cast<LEDPattern>(buffer[0]);
552 break;
553 default:
554 // Unknown packet: ignore!
555 break;
556 }
557 }
558
559 void XboxController::ProcessXboxOnePacket(size_t length) {
560 if (length < 2)
561 return;
562 DCHECK(length <= read_buffer_size_);
563 if (length > read_buffer_size_) {
564 IOError();
565 return;
566 }
567 uint8_t* buffer = read_buffer_.get();
568
569 uint8_t type = buffer[0];
570 buffer += 4;
571 length -= 4;
572 switch (type) {
573 case XBOX_ONE_STATUS_MESSAGE_BUTTONS: {
574 if (length != sizeof(XboxOneButtonData))
575 return;
576 XboxOneButtonData* data = reinterpret_cast<XboxOneButtonData*>(buffer);
577 Data normalized_data;
578 NormalizeXboxOneButtonData(*data, &normalized_data);
579 delegate_->XboxControllerGotData(this, normalized_data);
580 break;
581 }
582 default:
583 // Unknown packet: ignore!
584 break;
585 }
586 }
587
588 void XboxController::QueueRead() {
589 kern_return_t kr = (*interface_)->ReadPipeAsync(interface_,
590 read_endpoint_,
591 read_buffer_.get(),
592 read_buffer_size_,
593 GotData,
594 this);
595 if (kr != KERN_SUCCESS)
596 IOError();
597 }
598
599 void XboxController::IOError() {
600 delegate_->XboxControllerError(this);
601 }
602
603 void XboxController::WriteXboxOneInit() {
604 const UInt8 length = 2;
605
606 // This buffer will be released in WriteComplete when WritePipeAsync
607 // finishes.
608 UInt8* buffer = new UInt8[length];
609 buffer[0] = 0x05;
610 buffer[1] = 0x20;
611 kern_return_t kr = (*interface_)->WritePipeAsync(interface_,
612 control_endpoint_,
613 buffer,
614 (UInt32)length,
615 WriteComplete,
616 buffer);
617 if (kr != KERN_SUCCESS) {
618 delete[] buffer;
619 IOError();
620 return;
621 }
622 }
623
624 //-----------------------------------------------------------------------------
625
626 XboxDataFetcher::XboxDataFetcher(Delegate* delegate)
627 : delegate_(delegate),
628 listening_(false),
629 source_(NULL),
630 port_(NULL) {
631 }
632
633 XboxDataFetcher::~XboxDataFetcher() {
634 while (!controllers_.empty()) {
635 RemoveController(*controllers_.begin());
636 }
637 UnregisterFromNotifications();
638 }
639
640 void XboxDataFetcher::DeviceAdded(void* context, io_iterator_t iterator) {
641 DCHECK(context);
642 XboxDataFetcher* fetcher = static_cast<XboxDataFetcher*>(context);
643 io_service_t ref;
644 while ((ref = IOIteratorNext(iterator))) {
645 base::mac::ScopedIOObject<io_service_t> scoped_ref(ref);
646 XboxController* controller = new XboxController(fetcher);
647 if (controller->OpenDevice(ref)) {
648 fetcher->AddController(controller);
649 } else {
650 delete controller;
651 }
652 }
653 }
654
655 void XboxDataFetcher::DeviceRemoved(void* context, io_iterator_t iterator) {
656 DCHECK(context);
657 XboxDataFetcher* fetcher = static_cast<XboxDataFetcher*>(context);
658 io_service_t ref;
659 while ((ref = IOIteratorNext(iterator))) {
660 base::mac::ScopedIOObject<io_service_t> scoped_ref(ref);
661 base::ScopedCFTypeRef<CFNumberRef> number(
662 base::mac::CFCastStrict<CFNumberRef>(
663 IORegistryEntryCreateCFProperty(ref,
664 CFSTR(kUSBDevicePropertyLocationID),
665 kCFAllocatorDefault,
666 kNilOptions)));
667 UInt32 location_id = 0;
668 CFNumberGetValue(number, kCFNumberSInt32Type, &location_id);
669 fetcher->RemoveControllerByLocationID(location_id);
670 }
671 }
672
673 bool XboxDataFetcher::RegisterForNotifications() {
674 if (listening_)
675 return true;
676 port_ = IONotificationPortCreate(kIOMasterPortDefault);
677 if (!port_)
678 return false;
679 source_ = IONotificationPortGetRunLoopSource(port_);
680 if (!source_)
681 return false;
682 CFRunLoopAddSource(CFRunLoopGetCurrent(), source_, kCFRunLoopDefaultMode);
683
684 listening_ = true;
685
686 if (!RegisterForDeviceNotifications(
687 kVendorMicrosoft, kProductXboxOneController,
688 &xbox_one_device_added_iter_,
689 &xbox_one_device_removed_iter_))
690 return false;
691
692 if (!RegisterForDeviceNotifications(
693 kVendorMicrosoft, kProductXbox360Controller,
694 &xbox_360_device_added_iter_,
695 &xbox_360_device_removed_iter_))
696 return false;
697
698 return true;
699 }
700
701 bool XboxDataFetcher::RegisterForDeviceNotifications(
702 int vendor_id,
703 int product_id,
704 base::mac::ScopedIOObject<io_iterator_t>* added_iter,
705 base::mac::ScopedIOObject<io_iterator_t>* removed_iter) {
706 base::ScopedCFTypeRef<CFNumberRef> vendor_cf(CFNumberCreate(
707 kCFAllocatorDefault, kCFNumberSInt32Type, &vendor_id));
708 base::ScopedCFTypeRef<CFNumberRef> product_cf(CFNumberCreate(
709 kCFAllocatorDefault, kCFNumberSInt32Type, &product_id));
710 base::ScopedCFTypeRef<CFMutableDictionaryRef> matching_dict(
711 IOServiceMatching(kIOUSBDeviceClassName));
712 if (!matching_dict)
713 return false;
714 CFDictionarySetValue(matching_dict, CFSTR(kUSBVendorID), vendor_cf);
715 CFDictionarySetValue(matching_dict, CFSTR(kUSBProductID), product_cf);
716
717 // IOServiceAddMatchingNotification() releases the dictionary when it's done.
718 // Retain it before each call to IOServiceAddMatchingNotification to keep
719 // things balanced.
720 CFRetain(matching_dict);
721 io_iterator_t device_added_iter;
722 IOReturn ret;
723 ret = IOServiceAddMatchingNotification(port_,
724 kIOFirstMatchNotification,
725 matching_dict,
726 DeviceAdded,
727 this,
728 &device_added_iter);
729 added_iter->reset(device_added_iter);
730 if (ret != kIOReturnSuccess) {
731 LOG(ERROR) << "Error listening for Xbox controller add events: " << ret;
732 return false;
733 }
734 DeviceAdded(this, added_iter->get());
735
736 CFRetain(matching_dict);
737 io_iterator_t device_removed_iter;
738 ret = IOServiceAddMatchingNotification(port_,
739 kIOTerminatedNotification,
740 matching_dict,
741 DeviceRemoved,
742 this,
743 &device_removed_iter);
744 removed_iter->reset(device_removed_iter);
745 if (ret != kIOReturnSuccess) {
746 LOG(ERROR) << "Error listening for Xbox controller remove events: " << ret;
747 return false;
748 }
749 DeviceRemoved(this, removed_iter->get());
750 return true;
751 }
752
753 void XboxDataFetcher::UnregisterFromNotifications() {
754 if (!listening_)
755 return;
756 listening_ = false;
757 if (source_)
758 CFRunLoopSourceInvalidate(source_);
759 if (port_)
760 IONotificationPortDestroy(port_);
761 port_ = NULL;
762 }
763
764 XboxController* XboxDataFetcher::ControllerForLocation(UInt32 location_id) {
765 for (std::set<XboxController*>::iterator i = controllers_.begin();
766 i != controllers_.end();
767 ++i) {
768 if ((*i)->location_id() == location_id)
769 return *i;
770 }
771 return NULL;
772 }
773
774 void XboxDataFetcher::AddController(XboxController* controller) {
775 DCHECK(!ControllerForLocation(controller->location_id()))
776 << "Controller with location ID " << controller->location_id()
777 << " already exists in the set of controllers.";
778 controllers_.insert(controller);
779 delegate_->XboxDeviceAdd(controller);
780 }
781
782 void XboxDataFetcher::RemoveController(XboxController* controller) {
783 delegate_->XboxDeviceRemove(controller);
784 controllers_.erase(controller);
785 delete controller;
786 }
787
788 void XboxDataFetcher::RemoveControllerByLocationID(uint32_t location_id) {
789 XboxController* controller = NULL;
790 for (std::set<XboxController*>::iterator i = controllers_.begin();
791 i != controllers_.end();
792 ++i) {
793 if ((*i)->location_id() == location_id) {
794 controller = *i;
795 break;
796 }
797 }
798 if (controller)
799 RemoveController(controller);
800 }
801
802 void XboxDataFetcher::XboxControllerGotData(XboxController* controller,
803 const XboxController::Data& data) {
804 delegate_->XboxValueChanged(controller, data);
805 }
806
807 void XboxDataFetcher::XboxControllerError(XboxController* controller) {
808 RemoveController(controller);
809 }
OLDNEW
« no previous file with comments | « content/browser/gamepad/xbox_data_fetcher_mac.h ('k') | content/browser/renderer_host/gamepad_browser_message_filter.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698