1 // Copyright 2014 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 "device/hid/hid_service_mac.h"
7 #include <CoreFoundation/CoreFoundation.h>
8 #include <IOKit/hid/IOHIDDevice.h>
14 #include "base/bind.h"
15 #include "base/location.h"
16 #include "base/logging.h"
17 #include "base/mac/foundation_util.h"
18 #include "base/single_thread_task_runner.h"
19 #include "base/stl_util.h"
20 #include "base/strings/stringprintf.h"
21 #include "base/strings/sys_string_conversions.h"
22 #include "base/thread_task_runner_handle.h"
23 #include "base/threading/thread_restrictions.h"
24 #include "components/device_event_log/device_event_log.h"
25 #include "device/hid/hid_connection_mac.h"
31 std::string
HexErrorCode(IOReturn error_code
) {
32 return base::StringPrintf("0x%04x", error_code
);
35 bool TryGetHidIntProperty(IOHIDDeviceRef device
,
39 base::mac::CFCast
<CFNumberRef
>(IOHIDDeviceGetProperty(device
, key
));
40 return ref
&& CFNumberGetValue(ref
, kCFNumberSInt32Type
, result
);
43 int32_t GetHidIntProperty(IOHIDDeviceRef device
, CFStringRef key
) {
45 if (TryGetHidIntProperty(device
, key
, &value
))
50 bool TryGetHidStringProperty(IOHIDDeviceRef device
,
52 std::string
* result
) {
54 base::mac::CFCast
<CFStringRef
>(IOHIDDeviceGetProperty(device
, key
));
58 *result
= base::SysCFStringRefToUTF8(ref
);
62 std::string
GetHidStringProperty(IOHIDDeviceRef device
, CFStringRef key
) {
64 TryGetHidStringProperty(device
, key
, &value
);
68 bool TryGetHidDataProperty(IOHIDDeviceRef device
,
70 std::vector
<uint8
>* result
) {
72 base::mac::CFCast
<CFDataRef
>(IOHIDDeviceGetProperty(device
, key
));
76 STLClearObject(result
);
77 const uint8
* bytes
= CFDataGetBytePtr(ref
);
78 result
->insert(result
->begin(), bytes
, bytes
+ CFDataGetLength(ref
));
84 HidServiceMac::HidServiceMac(
85 scoped_refptr
<base::SingleThreadTaskRunner
> file_task_runner
)
86 : file_task_runner_(file_task_runner
) {
87 task_runner_
= base::ThreadTaskRunnerHandle::Get();
88 DCHECK(task_runner_
.get());
90 notify_port_
= IONotificationPortCreate(kIOMasterPortDefault
);
91 CFRunLoopAddSource(CFRunLoopGetMain(),
92 IONotificationPortGetRunLoopSource(notify_port_
),
93 kCFRunLoopDefaultMode
);
95 io_iterator_t iterator
;
97 IOServiceAddMatchingNotification(notify_port_
,
98 kIOFirstMatchNotification
,
99 IOServiceMatching(kIOHIDDeviceKey
),
103 if (result
!= kIOReturnSuccess
) {
104 HID_LOG(ERROR
) << "Failed to listen for device arrival: "
105 << HexErrorCode(result
);
109 // Drain the iterator to arm the notification.
110 devices_added_iterator_
.reset(iterator
);
112 iterator
= IO_OBJECT_NULL
;
114 result
= IOServiceAddMatchingNotification(notify_port_
,
115 kIOTerminatedNotification
,
116 IOServiceMatching(kIOHIDDeviceKey
),
120 if (result
!= kIOReturnSuccess
) {
121 HID_LOG(ERROR
) << "Failed to listen for device removal: "
122 << HexErrorCode(result
);
126 // Drain devices_added_iterator_ to arm the notification.
127 devices_removed_iterator_
.reset(iterator
);
129 FirstEnumerationComplete();
132 void HidServiceMac::Connect(const HidDeviceId
& device_id
,
133 const ConnectCallback
& callback
) {
134 DCHECK(thread_checker_
.CalledOnValidThread());
136 const auto& map_entry
= devices().find(device_id
);
137 if (map_entry
== devices().end()) {
138 task_runner_
->PostTask(FROM_HERE
, base::Bind(callback
, nullptr));
141 scoped_refptr
<HidDeviceInfo
> device_info
= map_entry
->second
;
143 base::ScopedCFTypeRef
<CFDictionaryRef
> matching_dict(
144 IORegistryEntryIDMatching(device_id
));
146 base::mac::ScopedIOObject
<io_service_t
> service(
147 IOServiceGetMatchingService(kIOMasterPortDefault
, matching_dict
.get()));
148 if (!service
.get()) {
149 HID_LOG(EVENT
) << "IOService not found for ID: " << device_id
;
150 task_runner_
->PostTask(FROM_HERE
, base::Bind(callback
, nullptr));
154 base::ScopedCFTypeRef
<IOHIDDeviceRef
> hid_device(
155 IOHIDDeviceCreate(kCFAllocatorDefault
, service
));
157 HID_LOG(EVENT
) << "Unable to create IOHIDDevice object.";
158 task_runner_
->PostTask(FROM_HERE
, base::Bind(callback
, nullptr));
162 IOReturn result
= IOHIDDeviceOpen(hid_device
, kIOHIDOptionsTypeNone
);
163 if (result
!= kIOReturnSuccess
) {
164 HID_LOG(EVENT
) << "Failed to open device: " << HexErrorCode(result
);
165 task_runner_
->PostTask(FROM_HERE
, base::Bind(callback
, nullptr));
169 task_runner_
->PostTask(
170 FROM_HERE
, base::Bind(callback
, make_scoped_refptr(new HidConnectionMac(
171 hid_device
.release(), device_info
,
172 file_task_runner_
))));
175 HidServiceMac::~HidServiceMac() {
179 void HidServiceMac::FirstMatchCallback(void* context
, io_iterator_t iterator
) {
180 DCHECK_EQ(CFRunLoopGetMain(), CFRunLoopGetCurrent());
181 HidServiceMac
* service
= static_cast<HidServiceMac
*>(context
);
182 DCHECK_EQ(service
->devices_added_iterator_
, iterator
);
183 service
->AddDevices();
187 void HidServiceMac::TerminatedCallback(void* context
, io_iterator_t iterator
) {
188 DCHECK_EQ(CFRunLoopGetMain(), CFRunLoopGetCurrent());
189 HidServiceMac
* service
= static_cast<HidServiceMac
*>(context
);
190 DCHECK_EQ(service
->devices_removed_iterator_
, iterator
);
191 service
->RemoveDevices();
194 void HidServiceMac::AddDevices() {
195 DCHECK(thread_checker_
.CalledOnValidThread());
198 while ((device
= IOIteratorNext(devices_added_iterator_
)) != IO_OBJECT_NULL
) {
199 scoped_refptr
<HidDeviceInfo
> device_info
= CreateDeviceInfo(device
);
201 AddDevice(device_info
);
202 // The reference retained by IOIteratorNext is released below in
203 // RemoveDevices when the device is removed.
205 IOObjectRelease(device
);
210 void HidServiceMac::RemoveDevices() {
211 DCHECK(thread_checker_
.CalledOnValidThread());
214 while ((device
= IOIteratorNext(devices_removed_iterator_
)) !=
217 IOReturn result
= IORegistryEntryGetRegistryEntryID(device
, &entry_id
);
218 if (result
== kIOReturnSuccess
) {
219 RemoveDevice(entry_id
);
222 // Release reference retained by AddDevices above.
223 IOObjectRelease(device
);
224 // Release the reference retained by IOIteratorNext.
225 IOObjectRelease(device
);
230 scoped_refptr
<HidDeviceInfo
> HidServiceMac::CreateDeviceInfo(
231 io_service_t service
) {
233 IOReturn result
= IORegistryEntryGetRegistryEntryID(service
, &entry_id
);
234 if (result
!= kIOReturnSuccess
) {
235 HID_LOG(EVENT
) << "Failed to get IORegistryEntry ID: "
236 << HexErrorCode(result
);
240 base::ScopedCFTypeRef
<IOHIDDeviceRef
> hid_device(
241 IOHIDDeviceCreate(kCFAllocatorDefault
, service
));
243 HID_LOG(EVENT
) << "Unable to create IOHIDDevice object for new device.";
247 std::vector
<uint8
> report_descriptor
;
248 if (!TryGetHidDataProperty(hid_device
, CFSTR(kIOHIDReportDescriptorKey
),
249 &report_descriptor
)) {
250 HID_LOG(EVENT
) << "Unable to get report descriptor for new device.";
254 return new HidDeviceInfo(
255 entry_id
, GetHidIntProperty(hid_device
, CFSTR(kIOHIDVendorIDKey
)),
256 GetHidIntProperty(hid_device
, CFSTR(kIOHIDProductIDKey
)),
257 GetHidStringProperty(hid_device
, CFSTR(kIOHIDProductKey
)),
258 GetHidStringProperty(hid_device
, CFSTR(kIOHIDSerialNumberKey
)),
259 kHIDBusTypeUSB
, // TODO(reillyg): Detect Bluetooth. crbug.com/443335
263 } // namespace device