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

Side by Side Diff: device/hid/hid_service_mac.cc

Issue 161823002: Clean up HID backend and API. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: addressed comments Created 6 years, 9 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 | Annotate | Revision Log
OLDNEW
1 // Copyright (c) 2014 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "device/hid/hid_service_mac.h" 5 #include "device/hid/hid_service_mac.h"
6 6
7 #include <map> 7 #include <CoreFoundation/CoreFoundation.h>
8 #include <set> 8 #include <IOKit/hid/IOHIDManager.h>
9
9 #include <string> 10 #include <string>
11 #include <vector>
10 12
11 #include "base/bind.h" 13 #include "base/bind.h"
12 #include "base/callback.h"
13 #include "base/lazy_instance.h"
14 #include "base/logging.h" 14 #include "base/logging.h"
15 #include "base/mac/foundation_util.h" 15 #include "base/message_loop/message_loop_proxy.h"
16 #include "base/memory/scoped_vector.h" 16 #include "base/stl_util.h"
17 #include "base/strings/string_number_conversions.h" 17 #include "base/strings/string_number_conversions.h"
18 #include "base/threading/thread_restrictions.h" 18 #include "base/threading/thread_restrictions.h"
19 #include "device/hid/hid_connection.h"
20 #include "device/hid/hid_connection_mac.h" 19 #include "device/hid/hid_connection_mac.h"
21 #include "device/hid/hid_utils_mac.h" 20 #include "device/hid/hid_utils_mac.h"
22 #include "net/base/io_buffer.h"
23
24 #include <CoreFoundation/CoreFoundation.h>
25 #include <IOKit/hid/IOHIDManager.h>
26 21
27 namespace device { 22 namespace device {
28 23
29 class HidServiceMac; 24 class HidServiceMac;
30 25
31 HidServiceMac::HidServiceMac() : enumeration_runloop_init_(true, false) { 26 namespace {
32 base::ThreadRestrictions::AssertIOAllowed();
33 27
34 hid_manager_ref_.reset(IOHIDManagerCreate(kCFAllocatorDefault, 28 typedef std::vector<IOHIDDeviceRef> HidDeviceList;
35 kIOHIDOptionsTypeNone)); 29
36 if (!hid_manager_ref_ || 30 HidServiceMac* HidServiceFromContext(void* context) {
37 CFGetTypeID(hid_manager_ref_) != IOHIDManagerGetTypeID()) { 31 return static_cast<HidServiceMac*>(context);
32 }
33
34 // Callback for CFSetApplyFunction as used by EnumerateHidDevices.
35 void HidEnumerationBackInserter(const void* value, void* context) {
36 HidDeviceList* devices = static_cast<HidDeviceList*>(context);
37 const IOHIDDeviceRef device =
38 static_cast<IOHIDDeviceRef>(const_cast<void*>(value));
39 devices->push_back(device);
40 }
41
42 void EnumerateHidDevices(IOHIDManagerRef hid_manager,
43 HidDeviceList* device_list) {
44 DCHECK(device_list->size() == 0);
45 // Note that our ownership of each copied device is implied.
46 base::ScopedCFTypeRef<CFSetRef> devices(IOHIDManagerCopyDevices(hid_manager));
47 if (devices)
48 CFSetApplyFunction(devices, HidEnumerationBackInserter, device_list);
49 }
50
51 } // namespace
52
53 HidServiceMac::HidServiceMac() {
54 DCHECK(thread_checker_.CalledOnValidThread());
55 message_loop_ = base::MessageLoopProxy::current();
56 DCHECK(message_loop_);
57 hid_manager_.reset(IOHIDManagerCreate(NULL, 0));
58 if (!hid_manager_) {
38 LOG(ERROR) << "Failed to initialize HidManager"; 59 LOG(ERROR) << "Failed to initialize HidManager";
39 return; 60 return;
40 } 61 }
41 CFRetain(hid_manager_ref_); 62 DCHECK(CFGetTypeID(hid_manager_) == IOHIDManagerGetTypeID());
63 IOHIDManagerOpen(hid_manager_, kIOHIDOptionsTypeNone);
64 IOHIDManagerSetDeviceMatching(hid_manager_, NULL);
65
66 // Enumerate all the currently known devices.
67 Enumerate();
42 68
43 // Register for plug/unplug notifications. 69 // Register for plug/unplug notifications.
44 IOHIDManagerSetDeviceMatching(hid_manager_ref_.get(), NULL); 70 StartWatchingDevices();
45 IOHIDManagerRegisterDeviceMatchingCallback(
46 hid_manager_ref_.get(),
47 &HidServiceMac::AddDeviceCallback,
48 this);
49 IOHIDManagerRegisterDeviceRemovalCallback(
50 hid_manager_ref_.get(),
51 &HidServiceMac::RemoveDeviceCallback,
52 this);
53
54 // Blocking operation to enumerate all the pre-existing devices.
55 Enumerate();
56
57 // Save the owner message loop.
58 message_loop_ = base::MessageLoopProxy::current();
59
60 // Start a thread to monitor HID device changes.
61 // The reason to create a new thread is that by default the only thread in the
62 // browser process having a CFRunLoop is the UI thread. We do not want to
63 // run potentially blocking routines on it.
64 enumeration_runloop_thread_.reset(
65 new base::Thread("HidService Device Enumeration Thread"));
66
67 base::Thread::Options options;
68 options.message_loop_type = base::MessageLoop::TYPE_UI;
69 enumeration_runloop_thread_->StartWithOptions(options);
70 enumeration_runloop_thread_->message_loop()->PostTask(
71 FROM_HERE,
72 base::Bind(&HidServiceMac::ScheduleRunLoop, base::Unretained(this)));
73
74 enumeration_runloop_init_.Wait();
75 initialized_ = true;
76 } 71 }
77 72
78 HidServiceMac::~HidServiceMac() { 73 HidServiceMac::~HidServiceMac() { StopWatchingDevices(); }
79 enumeration_runloop_thread_->message_loop()->PostTask(
80 FROM_HERE,
81 base::Bind(&HidServiceMac::UnscheduleRunLoop, base::Unretained(this)));
82 74
83 enumeration_runloop_thread_->Stop(); 75 void HidServiceMac::StartWatchingDevices() {
76 DCHECK(thread_checker_.CalledOnValidThread());
77 IOHIDManagerRegisterDeviceMatchingCallback(
78 hid_manager_, &AddDeviceCallback, this);
79 IOHIDManagerRegisterDeviceRemovalCallback(
80 hid_manager_, &RemoveDeviceCallback, this);
81 IOHIDManagerScheduleWithRunLoop(
82 hid_manager_, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
84 } 83 }
85 84
86 void HidServiceMac::ScheduleRunLoop() { 85 void HidServiceMac::StopWatchingDevices() {
87 enumeration_runloop_ = CFRunLoopGetCurrent(); 86 DCHECK(thread_checker_.CalledOnValidThread());
88 87 if (!hid_manager_)
89 IOHIDManagerScheduleWithRunLoop( 88 return;
90 hid_manager_ref_,
91 enumeration_runloop_,
92 kCFRunLoopDefaultMode);
93
94 IOHIDManagerOpen(hid_manager_ref_, kIOHIDOptionsTypeNone);
95
96 enumeration_runloop_init_.Signal();
97 }
98
99 void HidServiceMac::UnscheduleRunLoop() {
100 IOHIDManagerUnscheduleFromRunLoop( 89 IOHIDManagerUnscheduleFromRunLoop(
101 hid_manager_ref_, 90 hid_manager_, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
102 enumeration_runloop_, 91 IOHIDManagerClose(hid_manager_, kIOHIDOptionsTypeNone);
103 kCFRunLoopDefaultMode);
104
105 IOHIDManagerClose(hid_manager_ref_, kIOHIDOptionsTypeNone);
106
107 }
108
109 HidServiceMac* HidServiceMac::InstanceFromContext(void* context) {
110 return reinterpret_cast<HidServiceMac*>(context);
111 } 92 }
112 93
113 void HidServiceMac::AddDeviceCallback(void* context, 94 void HidServiceMac::AddDeviceCallback(void* context,
114 IOReturn result, 95 IOReturn result,
115 void* sender, 96 void* sender,
116 IOHIDDeviceRef ref) { 97 IOHIDDeviceRef hid_device) {
117 HidServiceMac* service = InstanceFromContext(context); 98 DCHECK(CFRunLoopGetMain() == CFRunLoopGetCurrent());
118 99 // Claim ownership of the device.
119 // Takes ownership of ref. Will be released inside PlatformDeviceAdd. 100 CFRetain(hid_device);
120 CFRetain(ref); 101 HidServiceMac* service = HidServiceFromContext(context);
121 service->message_loop_->PostTask( 102 service->message_loop_->PostTask(FROM_HERE,
122 FROM_HERE, 103 base::Bind(&HidServiceMac::PlatformAddDevice,
123 base::Bind(&HidServiceMac::PlatformAddDevice, 104 base::Unretained(service),
124 base::Unretained(service), 105 base::Unretained(hid_device)));
125 base::Unretained(ref)));
126 } 106 }
127 107
128 void HidServiceMac::RemoveDeviceCallback(void* context, 108 void HidServiceMac::RemoveDeviceCallback(void* context,
129 IOReturn result, 109 IOReturn result,
130 void* sender, 110 void* sender,
131 IOHIDDeviceRef ref) { 111 IOHIDDeviceRef hid_device) {
132 HidServiceMac* service = InstanceFromContext(context); 112 DCHECK(CFRunLoopGetMain() == CFRunLoopGetCurrent());
133 113 HidServiceMac* service = HidServiceFromContext(context);
134 // Takes ownership of ref. Will be released inside PlatformDeviceRemove.
135 CFRetain(ref);
136 service->message_loop_->PostTask( 114 service->message_loop_->PostTask(
137 FROM_HERE, 115 FROM_HERE,
138 base::Bind(&HidServiceMac::PlatformRemoveDevice, 116 base::Bind(&HidServiceMac::PlatformRemoveDevice,
139 base::Unretained(service), 117 base::Unretained(service),
140 base::Unretained(ref))); 118 base::Unretained(hid_device)));
141 }
142
143 IOHIDDeviceRef HidServiceMac::FindDevice(std::string id) {
144 base::ScopedCFTypeRef<CFSetRef> devices(
145 IOHIDManagerCopyDevices(hid_manager_ref_));
146 CFIndex count = CFSetGetCount(devices);
147 scoped_ptr<IOHIDDeviceRef[]> device_refs(new IOHIDDeviceRef[count]);
148 CFSetGetValues(devices, (const void **)(device_refs.get()));
149
150 for (CFIndex i = 0; i < count; i++) {
151 int32_t int_property = 0;
152 if (GetHidIntProperty(device_refs[i], CFSTR(kIOHIDLocationIDKey),
153 &int_property)) {
154 if (id == base::HexEncode(&int_property, sizeof(int_property))) {
155 return device_refs[i];
156 }
157 }
158 }
159
160 return NULL;
161 } 119 }
162 120
163 void HidServiceMac::Enumerate() { 121 void HidServiceMac::Enumerate() {
164 base::ScopedCFTypeRef<CFSetRef> devices( 122 DCHECK(thread_checker_.CalledOnValidThread());
165 IOHIDManagerCopyDevices(hid_manager_ref_)); 123 HidDeviceList devices;
166 CFIndex count = CFSetGetCount(devices); 124 EnumerateHidDevices(hid_manager_, &devices);
167 scoped_ptr<IOHIDDeviceRef[]> device_refs(new IOHIDDeviceRef[count]); 125 for (HidDeviceList::const_iterator iter = devices.begin();
168 CFSetGetValues(devices, (const void **)(device_refs.get())); 126 iter != devices.end();
169 127 ++iter) {
170 for (CFIndex i = 0; i < count; i++) { 128 IOHIDDeviceRef hid_device = *iter;
171 // Takes ownership. Will be released inside PlatformDeviceAdd. 129 PlatformAddDevice(hid_device);
172 CFRetain(device_refs[i]);
173 PlatformAddDevice(device_refs[i]);
174 } 130 }
175 } 131 }
176 132
177 void HidServiceMac::PlatformAddDevice(IOHIDDeviceRef raw_ref) { 133 void HidServiceMac::PlatformAddDevice(IOHIDDeviceRef hid_device) {
178 HidDeviceInfo device; 134 // Note that our ownership of hid_device is implied if calling this method.
179 int32_t int_property = 0; 135 // It is balanced in PlatformRemoveDevice.
180 std::string str_property; 136 DCHECK(thread_checker_.CalledOnValidThread());
181 137
182 // Auto-release. 138 HidDeviceInfo device_info;
183 base::ScopedCFTypeRef<IOHIDDeviceRef> ref(raw_ref); 139 device_info.device_id = hid_device;
184 140 device_info.vendor_id =
185 // Unique identifier for HID device. 141 GetHidIntProperty(hid_device, CFSTR(kIOHIDVendorIDKey));
186 if (GetHidIntProperty(ref, CFSTR(kIOHIDLocationIDKey), &int_property)) { 142 device_info.product_id =
187 device.device_id = base::HexEncode(&int_property, sizeof(int_property)); 143 GetHidIntProperty(hid_device, CFSTR(kIOHIDProductIDKey));
188 } else { 144 device_info.usage =
189 // Not an available device. 145 GetHidIntProperty(hid_device, CFSTR(kIOHIDPrimaryUsageKey));
190 return; 146 device_info.usage_page =
191 } 147 GetHidIntProperty(hid_device, CFSTR(kIOHIDPrimaryUsagePageKey));
192 148 device_info.input_report_size =
193 if (GetHidIntProperty(ref, CFSTR(kIOHIDVendorIDKey), &int_property)) { 149 GetHidIntProperty(hid_device, CFSTR(kIOHIDMaxInputReportSizeKey));
194 device.vendor_id = int_property; 150 device_info.output_report_size =
195 } 151 GetHidIntProperty(hid_device, CFSTR(kIOHIDMaxOutputReportSizeKey));
196 if (GetHidIntProperty(ref, CFSTR(kIOHIDProductIDKey), &int_property)) { 152 device_info.feature_report_size =
197 device.product_id = int_property; 153 GetHidIntProperty(hid_device, CFSTR(kIOHIDMaxFeatureReportSizeKey));
198 } 154 device_info.product_name =
199 if (GetHidIntProperty(ref, CFSTR(kIOHIDPrimaryUsageKey), &int_property)) { 155 GetHidStringProperty(hid_device, CFSTR(kIOHIDProductKey));
200 device.usage = int_property; 156 device_info.serial_number =
201 } 157 GetHidStringProperty(hid_device, CFSTR(kIOHIDSerialNumberKey));
202 if (GetHidIntProperty(ref, CFSTR(kIOHIDPrimaryUsagePageKey), &int_property)) { 158 AddDevice(device_info);
203 device.usage_page = int_property;
204 }
205 if (GetHidIntProperty(ref, CFSTR(kIOHIDMaxInputReportSizeKey),
206 &int_property)) {
207 device.input_report_size = int_property;
208 }
209 if (GetHidIntProperty(ref, CFSTR(kIOHIDMaxOutputReportSizeKey),
210 &int_property)) {
211 device.output_report_size = int_property;
212 }
213 if (GetHidIntProperty(ref, CFSTR(kIOHIDMaxFeatureReportSizeKey),
214 &int_property)) {
215 device.feature_report_size = int_property;
216 }
217 if (GetHidStringProperty(ref, CFSTR(kIOHIDProductKey), &str_property)) {
218 device.product_name = str_property;
219 }
220 if (GetHidStringProperty(ref, CFSTR(kIOHIDSerialNumberKey), &str_property)) {
221 device.serial_number = str_property;
222 }
223 HidService::AddDevice(device);
224 } 159 }
225 160
226 void HidServiceMac::PlatformRemoveDevice(IOHIDDeviceRef raw_ref) { 161 void HidServiceMac::PlatformRemoveDevice(IOHIDDeviceRef hid_device) {
227 std::string device_id; 162 DCHECK(thread_checker_.CalledOnValidThread());
228 int32_t int_property = 0; 163 RemoveDevice(hid_device);
229 // Auto-release. 164 CFRelease(hid_device);
230 base::ScopedCFTypeRef<IOHIDDeviceRef> ref(raw_ref);
231 if (!GetHidIntProperty(ref, CFSTR(kIOHIDLocationIDKey), &int_property)) {
232 return;
233 }
234 device_id = base::HexEncode(&int_property, sizeof(int_property));
235 HidService::RemoveDevice(device_id);
236 } 165 }
237 166
238 scoped_refptr<HidConnection> 167 scoped_refptr<HidConnection> HidServiceMac::Connect(
239 HidServiceMac::Connect(std::string device_id) { 168 const HidDeviceId& device_id) {
240 if (!ContainsKey(devices_, device_id)) 169 DCHECK(thread_checker_.CalledOnValidThread());
170 HidDeviceInfo device_info;
171 if (!GetDeviceInfo(device_id, &device_info))
241 return NULL; 172 return NULL;
242 173 return scoped_refptr<HidConnection>(new HidConnectionMac(device_info));
243 IOHIDDeviceRef ref = FindDevice(device_id);
244 if (ref == NULL)
245 return NULL;
246 return scoped_refptr<HidConnection>(
247 new HidConnectionMac(this, devices_[device_id], ref));
248 } 174 }
249 175
250 } // namespace device 176 } // namespace device
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698