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

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: Many cleanup, such device ID, woww. Created 6 years, 10 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 base::ScopedCFTypeRef<CFSetRef> devices(IOHIDManagerCopyDevices(hid_manager));
46 if (devices)
47 CFSetApplyFunction(devices, HidEnumerationBackInserter, device_list);
48 }
49
50 } // namespace
51
52 HidServiceMac::HidServiceMac() {
53 DCHECK(thread_checker_.CalledOnValidThread());
54 message_loop_ = base::MessageLoopProxy::current();
55 DCHECK(message_loop_);
56 hid_manager_.reset(IOHIDManagerCreate(NULL, 0));
57 if (!hid_manager_) {
38 LOG(ERROR) << "Failed to initialize HidManager"; 58 LOG(ERROR) << "Failed to initialize HidManager";
39 return; 59 return;
40 } 60 }
41 CFRetain(hid_manager_ref_); 61 DCHECK(CFGetTypeID(hid_manager_) == IOHIDManagerGetTypeID());
62 IOHIDManagerOpen(hid_manager_, kIOHIDOptionsTypeNone);
63 IOHIDManagerSetDeviceMatching(hid_manager_, NULL);
64
65 // Enumerate all the currently known devices.
66 Enumerate();
42 67
43 // Register for plug/unplug notifications. 68 // Register for plug/unplug notifications.
44 IOHIDManagerSetDeviceMatching(hid_manager_ref_.get(), NULL); 69 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 } 70 }
77 71
78 HidServiceMac::~HidServiceMac() { 72 HidServiceMac::~HidServiceMac() { StopWatchingDevices(); }
Mark Mentovai 2014/02/21 17:48:18 I mentioned this before at https://codereview.chro
Ken Rockot(use gerrit already) 2014/02/22 01:17:04 I have considered writing the code like this inste
Mark Mentovai 2014/02/24 20:23:36 Ken Rockot wrote:
79 enumeration_runloop_thread_->message_loop()->PostTask(
80 FROM_HERE,
81 base::Bind(&HidServiceMac::UnscheduleRunLoop, base::Unretained(this)));
82 73
83 enumeration_runloop_thread_->Stop(); 74 void HidServiceMac::StartWatchingDevices() {
75 DCHECK(thread_checker_.CalledOnValidThread());
76 IOHIDManagerRegisterDeviceMatchingCallback(
77 hid_manager_, &AddDeviceCallback, this);
78 IOHIDManagerRegisterDeviceRemovalCallback(
79 hid_manager_, &RemoveDeviceCallback, this);
80 IOHIDManagerScheduleWithRunLoop(
81 hid_manager_, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
84 } 82 }
85 83
86 void HidServiceMac::ScheduleRunLoop() { 84 void HidServiceMac::StopWatchingDevices() {
87 enumeration_runloop_ = CFRunLoopGetCurrent(); 85 DCHECK(thread_checker_.CalledOnValidThread());
88 86 if (!hid_manager_)
89 IOHIDManagerScheduleWithRunLoop( 87 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( 88 IOHIDManagerUnscheduleFromRunLoop(
101 hid_manager_ref_, 89 hid_manager_, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
102 enumeration_runloop_, 90 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 } 91 }
112 92
113 void HidServiceMac::AddDeviceCallback(void* context, 93 void HidServiceMac::AddDeviceCallback(void* context,
114 IOReturn result, 94 IOReturn result,
115 void* sender, 95 void* sender,
116 IOHIDDeviceRef ref) { 96 IOHIDDeviceRef hid_device) {
117 HidServiceMac* service = InstanceFromContext(context); 97 DCHECK(CFRunLoopGetMain() == CFRunLoopGetCurrent());
118 98 HidServiceMac* service = HidServiceFromContext(context);
119 // Takes ownership of ref. Will be released inside PlatformDeviceAdd. 99 service->message_loop_->PostTask(FROM_HERE,
120 CFRetain(ref); 100 base::Bind(&HidServiceMac::PlatformAddDevice,
121 service->message_loop_->PostTask( 101 base::Unretained(service),
122 FROM_HERE, 102 base::Unretained(hid_device)));
123 base::Bind(&HidServiceMac::PlatformAddDevice,
124 base::Unretained(service),
125 base::Unretained(ref)));
126 } 103 }
127 104
128 void HidServiceMac::RemoveDeviceCallback(void* context, 105 void HidServiceMac::RemoveDeviceCallback(void* context,
129 IOReturn result, 106 IOReturn result,
130 void* sender, 107 void* sender,
131 IOHIDDeviceRef ref) { 108 IOHIDDeviceRef hid_device) {
132 HidServiceMac* service = InstanceFromContext(context); 109 DCHECK(CFRunLoopGetMain() == CFRunLoopGetCurrent());
133 110 HidServiceMac* service = HidServiceFromContext(context);
134 // Takes ownership of ref. Will be released inside PlatformDeviceRemove.
135 CFRetain(ref);
136 service->message_loop_->PostTask( 111 service->message_loop_->PostTask(
137 FROM_HERE, 112 FROM_HERE,
138 base::Bind(&HidServiceMac::PlatformRemoveDevice, 113 base::Bind(&HidServiceMac::PlatformRemoveDevice,
139 base::Unretained(service), 114 base::Unretained(service),
140 base::Unretained(ref))); 115 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 } 116 }
162 117
163 void HidServiceMac::Enumerate() { 118 void HidServiceMac::Enumerate() {
164 base::ScopedCFTypeRef<CFSetRef> devices( 119 DCHECK(thread_checker_.CalledOnValidThread());
165 IOHIDManagerCopyDevices(hid_manager_ref_)); 120 HidDeviceList devices;
166 CFIndex count = CFSetGetCount(devices); 121 EnumerateHidDevices(hid_manager_, &devices);
167 scoped_ptr<IOHIDDeviceRef[]> device_refs(new IOHIDDeviceRef[count]); 122 for (HidDeviceList::const_iterator iter = devices.begin();
168 CFSetGetValues(devices, (const void **)(device_refs.get())); 123 iter != devices.end();
169 124 ++iter) {
170 for (CFIndex i = 0; i < count; i++) { 125 IOHIDDeviceRef hid_device = *iter;
171 // Takes ownership. Will be released inside PlatformDeviceAdd. 126 PlatformAddDevice(hid_device);
172 CFRetain(device_refs[i]);
173 PlatformAddDevice(device_refs[i]);
174 } 127 }
175 } 128 }
176 129
177 void HidServiceMac::PlatformAddDevice(IOHIDDeviceRef raw_ref) { 130 void HidServiceMac::PlatformAddDevice(IOHIDDeviceRef hid_device) {
178 HidDeviceInfo device; 131 // Unique identifier for HID device.
179 int32_t int_property = 0; 132 DCHECK(thread_checker_.CalledOnValidThread());
180 std::string str_property;
181 133
182 // Auto-release. 134 HidDeviceInfo device_info;
183 base::ScopedCFTypeRef<IOHIDDeviceRef> ref(raw_ref); 135 device_info.device_id = GenerateDeviceId();
136 device_info.vendor_id =
137 GetHidIntProperty(hid_device, CFSTR(kIOHIDVendorIDKey));
138 device_info.product_id =
139 GetHidIntProperty(hid_device, CFSTR(kIOHIDProductIDKey));
140 device_info.usage =
141 GetHidIntProperty(hid_device, CFSTR(kIOHIDPrimaryUsageKey));
142 device_info.usage_page =
143 GetHidIntProperty(hid_device, CFSTR(kIOHIDPrimaryUsagePageKey));
144 device_info.input_report_size =
145 GetHidIntProperty(hid_device, CFSTR(kIOHIDMaxInputReportSizeKey));
146 device_info.output_report_size =
147 GetHidIntProperty(hid_device, CFSTR(kIOHIDMaxOutputReportSizeKey));
148 device_info.feature_report_size =
149 GetHidIntProperty(hid_device, CFSTR(kIOHIDMaxFeatureReportSizeKey));
150 device_info.product_name =
151 GetHidStringProperty(hid_device, CFSTR(kIOHIDProductKey));
152 device_info.serial_number =
153 GetHidStringProperty(hid_device, CFSTR(kIOHIDSerialNumberKey));
184 154
185 // Unique identifier for HID device. 155 if (!platform_resource_map_.Add(device_info.device_id, hid_device))
186 if (GetHidIntProperty(ref, CFSTR(kIOHIDLocationIDKey), &int_property)) {
187 device.device_id = base::HexEncode(&int_property, sizeof(int_property));
188 } else {
189 // Not an available device.
190 return; 156 return;
191 } 157 CFRetain(hid_device);
192 158 AddDevice(device_info);
193 if (GetHidIntProperty(ref, CFSTR(kIOHIDVendorIDKey), &int_property)) {
194 device.vendor_id = int_property;
195 }
196 if (GetHidIntProperty(ref, CFSTR(kIOHIDProductIDKey), &int_property)) {
197 device.product_id = int_property;
198 }
199 if (GetHidIntProperty(ref, CFSTR(kIOHIDPrimaryUsageKey), &int_property)) {
200 device.usage = int_property;
201 }
202 if (GetHidIntProperty(ref, CFSTR(kIOHIDPrimaryUsagePageKey), &int_property)) {
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
229 // Auto-release. 164 HidDeviceId device_id;
230 base::ScopedCFTypeRef<IOHIDDeviceRef> ref(raw_ref); 165 if (!platform_resource_map_.GetIdByResource(hid_device, &device_id))
231 if (!GetHidIntProperty(ref, CFSTR(kIOHIDLocationIDKey), &int_property)) {
232 return; 166 return;
233 } 167 platform_resource_map_.RemoveById(device_id);
234 device_id = base::HexEncode(&int_property, sizeof(int_property)); 168 CFRelease(hid_device);
Mark Mentovai 2014/02/21 17:48:18 Since you retained the device before calling AddDe
Ken Rockot(use gerrit already) 2014/02/22 01:17:04 Done.
235 HidService::RemoveDevice(device_id); 169
170 RemoveDevice(device_id);
236 } 171 }
237 172
238 scoped_refptr<HidConnection> 173 scoped_refptr<HidConnection> HidServiceMac::Connect(HidDeviceId device_id) {
239 HidServiceMac::Connect(std::string device_id) { 174 DCHECK(thread_checker_.CalledOnValidThread());
240 if (!ContainsKey(devices_, device_id)) 175 HidDeviceInfo device_info;
176 if (!GetInfo(device_id, &device_info))
177 return NULL;
178 IOHIDDeviceRef hid_device;
179 if (!platform_resource_map_.GetResourceById(device_id, &hid_device))
180 return NULL;
181 if (hid_device == NULL)
241 return NULL; 182 return NULL;
242 183
243 IOHIDDeviceRef ref = FindDevice(device_id);
244 if (ref == NULL)
245 return NULL;
246 return scoped_refptr<HidConnection>( 184 return scoped_refptr<HidConnection>(
247 new HidConnectionMac(this, devices_[device_id], ref)); 185 new HidConnectionMac(this, device_info, hid_device));
248 } 186 }
249 187
250 } // namespace device 188 } // namespace device
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698