OLD | NEW |
---|---|
(Empty) | |
1 // Copyright (c) 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 "chrome/browser/extensions/global_shortcut_listener_mac.h" | |
6 | |
7 #include <ApplicationServices/ApplicationServices.h> | |
8 #import <Cocoa/Cocoa.h> | |
9 #include <IOKit/hidsystem/ev_keymap.h> | |
10 | |
11 #import "base/mac/foundation_util.h" | |
12 #include "chrome/browser/extensions/api/commands/command_service.h" | |
13 #include "content/public/browser/browser_thread.h" | |
14 #include "ui/base/accelerators/accelerator.h" | |
15 #include "ui/events/event.h" | |
16 #import "ui/events/keycodes/keyboard_code_conversion_mac.h" | |
17 | |
18 using content::BrowserThread; | |
19 using extensions::GlobalShortcutListenerMac; | |
20 | |
21 namespace { | |
22 | |
23 // The media keys subtype. No official docs found, but widely known. | |
24 // http://lists.apple.com/archives/cocoa-dev/2007/Aug/msg00499.html | |
25 const int kSystemDefinedEventMediaKeysSubtype = 8; | |
26 | |
27 ui::KeyboardCode MediaKeyCodeToKeyboardCode(int key_code) { | |
28 switch (key_code) { | |
29 case NX_KEYTYPE_PLAY: | |
30 return ui::VKEY_MEDIA_PLAY_PAUSE; | |
31 case NX_KEYTYPE_PREVIOUS: | |
32 case NX_KEYTYPE_REWIND: | |
33 return ui::VKEY_MEDIA_PREV_TRACK; | |
34 case NX_KEYTYPE_NEXT: | |
35 case NX_KEYTYPE_FAST: | |
36 return ui::VKEY_MEDIA_NEXT_TRACK; | |
37 } | |
38 return ui::VKEY_UNKNOWN; | |
39 } | |
40 | |
41 } // namespace | |
42 | |
43 namespace extensions { | |
44 | |
45 // static | |
46 GlobalShortcutListener* GlobalShortcutListener::GetInstance() { | |
47 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); | |
48 static GlobalShortcutListenerMac *instance = | |
49 new GlobalShortcutListenerMac(); | |
50 return instance; | |
51 } | |
52 | |
53 GlobalShortcutListenerMac::GlobalShortcutListenerMac() | |
54 : is_listening_(false), | |
55 hot_key_id_(0), | |
56 event_tap_(NULL), | |
57 event_tap_source_(NULL), | |
58 event_handler_(NULL) { | |
59 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); | |
60 } | |
61 | |
62 GlobalShortcutListenerMac::~GlobalShortcutListenerMac() { | |
63 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); | |
64 | |
65 // By this point, UnregisterAccelerator should have been called for all | |
66 // keyboard shortcuts. Still we should clean up. | |
67 if (is_listening_) | |
68 StopListening(); | |
69 | |
70 // If media keys are still registered, make sure we stop the tap. Again, | |
71 // This should never happen. | |
Mark Mentovai
2013/12/12 19:51:20
(nit) lowercase T, since you’re continuing the sen
smus
2013/12/12 21:13:52
Done.
| |
72 if (IsAnyMediaKeyRegistered()) | |
Mark Mentovai
2013/12/12 19:51:20
If you’re going to go to the trouble of stopping l
smus
2013/12/12 21:13:52
Done.
| |
73 StopWatchingMediaKeys(); | |
74 } | |
75 | |
76 void GlobalShortcutListenerMac::StartListening() { | |
77 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); | |
78 | |
79 DCHECK(!accelerator_ids_.empty()); | |
80 DCHECK(!id_accelerators_.empty()); | |
81 DCHECK(!is_listening_); | |
82 | |
83 is_listening_ = true; | |
84 } | |
85 | |
86 void GlobalShortcutListenerMac::StopListening() { | |
87 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); | |
88 | |
89 DCHECK(accelerator_ids_.empty()); // Make sure the set is clean. | |
90 DCHECK(id_accelerators_.empty()); | |
91 DCHECK(is_listening_); | |
92 | |
93 is_listening_ = false; | |
94 } | |
95 | |
96 void GlobalShortcutListenerMac::OnHotKeyEvent(EventHotKeyID hot_key_id) { | |
97 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); | |
98 | |
99 // This hot key should be registered. | |
100 DCHECK(id_accelerators_.find(hot_key_id.id) != id_accelerators_.end()); | |
101 // Look up the accelerator based on this hot key ID. | |
102 const ui::Accelerator& accelerator = id_accelerators_[hot_key_id.id]; | |
103 NotifyKeyPressed(accelerator); | |
104 } | |
105 | |
106 bool GlobalShortcutListenerMac::OnMediaKeyEvent(int media_key_code) { | |
107 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); | |
108 ui::KeyboardCode key_code = MediaKeyCodeToKeyboardCode(media_key_code); | |
109 // Create an accelerator corresponding to the keyCode. | |
110 ui::Accelerator accelerator(key_code, 0); | |
111 // Look for a match with a bound hot_key. | |
112 if (accelerator_ids_.find(accelerator) != accelerator_ids_.end()) { | |
113 // If matched, callback to the event handling system. | |
114 NotifyKeyPressed(accelerator); | |
115 return true; | |
116 } | |
117 return false; | |
118 } | |
119 | |
120 void GlobalShortcutListenerMac::RegisterAccelerator( | |
Mark Mentovai
2013/12/12 20:04:50
Can you add
CHECK(BrowserThread::CurrentlyOn(Brow
smus
2013/12/12 21:13:52
Done.
| |
121 const ui::Accelerator& accelerator, | |
122 GlobalShortcutListener::Observer* observer) { | |
123 if (accelerator_ids_.find(accelerator) != accelerator_ids_.end()) { | |
124 // The shortcut has already been registered. Some shortcuts, such as | |
125 // MediaKeys can have multiple targets, all keyed off of the same | |
126 // accelerator. | |
127 return; | |
128 } | |
129 | |
130 if (CommandService::IsMediaKey(accelerator)) { | |
131 if (!IsAnyMediaKeyRegistered()) { | |
132 // If this is the first media key registered, start the event tap. | |
133 StartWatchingMediaKeys(); | |
134 } | |
135 } else { | |
136 // Register hot_key if they are non-media keyboard shortcuts. | |
137 RegisterHotKey(accelerator, hot_key_id_); | |
138 if (!IsAnyHotKeyRegistered()) { | |
139 StartWatchingHotKeys(); | |
140 } | |
141 } | |
142 | |
143 // Store the hotkey-ID mappings we will need for lookup later. | |
144 id_accelerators_[hot_key_id_] = accelerator; | |
145 accelerator_ids_[accelerator] = hot_key_id_; | |
146 ++hot_key_id_; | |
147 GlobalShortcutListener::RegisterAccelerator(accelerator, observer); | |
148 } | |
149 | |
150 void GlobalShortcutListenerMac::UnregisterAccelerator( | |
151 const ui::Accelerator& accelerator, | |
152 GlobalShortcutListener::Observer* observer) { | |
153 // Ensure this accelerator is registered. | |
Mark Mentovai
2013/12/11 22:59:57
The Windows implementation has an entirely differe
smus
2013/12/12 21:13:52
Done.
| |
154 DCHECK(accelerator_ids_.find(accelerator) != accelerator_ids_.end()); | |
Mark Mentovai
2013/12/12 19:51:20
If the goal of this CL is to achieve parity with e
smus
2013/12/12 21:13:52
Ok, switched to use the same approach as on other
| |
155 | |
156 // Unregister the hot_key if it's a keyboard shortcut. | |
157 if (!CommandService::IsMediaKey(accelerator)) | |
158 UnregisterHotKey(accelerator); | |
159 | |
160 // Remove hot_key from the mappings. | |
161 KeyId id = accelerator_ids_[accelerator]; | |
Mark Mentovai
2013/12/12 19:51:20
Avoid naming a variable id in an Objective-C file
smus
2013/12/12 21:13:52
Done.
| |
162 id_accelerators_.erase(id); | |
163 accelerator_ids_.erase(accelerator); | |
164 GlobalShortcutListener::UnregisterAccelerator(accelerator, observer); | |
165 | |
166 if (CommandService::IsMediaKey(accelerator)) { | |
167 // If we unregistered a media key, and now no media keys are registered, | |
168 // stop the media key tap. | |
169 if (!IsAnyMediaKeyRegistered()) | |
170 StopWatchingMediaKeys(); | |
171 } else { | |
172 // If we unregistered a hot key, and no more hot keys are registered, remove | |
173 // the hot key handler. | |
174 if (!IsAnyHotKeyRegistered() && event_handler_) { | |
Robert Sesek
2013/12/12 20:33:10
Why the |&& event_handler_| check here?
smus
2013/12/12 21:13:52
Fair point, this should never happen (which is cap
| |
175 StopWatchingHotKeys(); | |
176 } | |
177 } | |
178 | |
Mark Mentovai
2013/12/12 20:04:50
(nit) Extra blank line.
smus
2013/12/12 21:13:52
Done.
| |
179 } | |
180 | |
181 void GlobalShortcutListenerMac::RegisterHotKey( | |
182 const ui::Accelerator& accelerator, KeyId hot_key_id) { | |
183 EventHotKeyID event_hot_key_id; | |
184 | |
185 // Signature uniquely identifies the application that owns this hot_key. | |
186 event_hot_key_id.signature = base::mac::CreatorCodeForApplication(); | |
187 event_hot_key_id.id = hot_key_id; | |
188 | |
189 // Translate ui::Accelerator modifiers to cmdKey, altKey, etc. | |
190 int modifiers = 0; | |
191 modifiers |= (accelerator.IsShiftDown() ? shiftKey : 0); | |
192 modifiers |= (accelerator.IsCtrlDown() ? controlKey : 0); | |
193 modifiers |= (accelerator.IsAltDown() ? optionKey : 0); | |
194 modifiers |= (accelerator.IsCmdDown() ? cmdKey : 0); | |
195 | |
196 int key_code = ui::MacKeyCodeForWindowsKeyCode(accelerator.key_code(), 0, | |
197 NULL, NULL); | |
198 | |
199 // Register the event hot key. | |
200 EventHotKeyRef hot_key_ref; | |
201 RegisterEventHotKey(key_code, modifiers, event_hot_key_id, | |
202 GetApplicationEventTarget(), 0, &hot_key_ref); | |
203 | |
204 id_hot_key_refs_[hot_key_id] = hot_key_ref; | |
205 } | |
206 | |
207 void GlobalShortcutListenerMac::UnregisterHotKey( | |
208 const ui::Accelerator& accelerator) { | |
209 // Ensure this accelerator is already registered. | |
210 DCHECK(accelerator_ids_.find(accelerator) != accelerator_ids_.end()); | |
211 // Get the ref corresponding to this accelerator. | |
212 KeyId id = accelerator_ids_[accelerator]; | |
Mark Mentovai
2013/12/12 19:51:20
Same thing here.
smus
2013/12/12 21:13:52
Done.
| |
213 EventHotKeyRef ref = id_hot_key_refs_[id]; | |
214 // Unregister the event hot key. | |
215 UnregisterEventHotKey(ref); | |
216 | |
217 // Remove the event from the mapping. | |
218 id_hot_key_refs_.erase(id); | |
219 } | |
220 | |
221 void GlobalShortcutListenerMac::StartWatchingMediaKeys() { | |
222 // Make sure there's no existing event tap. | |
223 DCHECK(event_tap_ == NULL); | |
224 DCHECK(event_tap_source_ == NULL); | |
225 | |
226 // Add an event tap to intercept the system defined media key events. | |
227 event_tap_ = CGEventTapCreate(kCGSessionEventTap, | |
228 kCGHeadInsertEventTap, | |
229 kCGEventTapOptionDefault, | |
230 CGEventMaskBit(NX_SYSDEFINED), | |
231 EventTapCallback, | |
232 this); | |
233 if (event_tap_ == NULL) { | |
234 LOG(ERROR) << "Error: failed to create event tap."; | |
235 return; | |
236 } | |
237 | |
238 event_tap_source_ = CFMachPortCreateRunLoopSource(kCFAllocatorSystemDefault, | |
239 event_tap_, 0); | |
240 if (event_tap_source_ == NULL) { | |
241 LOG(ERROR) << "Error: failed to create new run loop source."; | |
242 return; | |
243 } | |
244 | |
245 CFRunLoopAddSource(CFRunLoopGetCurrent(), event_tap_source_, | |
246 kCFRunLoopCommonModes); | |
247 } | |
248 | |
249 void GlobalShortcutListenerMac::StopWatchingMediaKeys() { | |
250 CFRunLoopRemoveSource(CFRunLoopGetCurrent(), event_tap_source_, | |
251 kCFRunLoopCommonModes); | |
252 // Ensure both event tap and source are initialized. | |
253 DCHECK(event_tap_ != NULL); | |
254 DCHECK(event_tap_source_ != NULL); | |
255 | |
256 // Invalidate the event tap. | |
257 CFMachPortInvalidate(event_tap_); | |
258 CFRelease(event_tap_); | |
259 event_tap_ = NULL; | |
260 | |
261 // Release the event tap source. | |
262 CFRelease(event_tap_source_); | |
263 event_tap_source_ = NULL; | |
264 } | |
265 | |
266 void GlobalShortcutListenerMac::StartWatchingHotKeys() { | |
267 DCHECK(!event_handler_); | |
268 EventHandlerUPP hot_key_function = NewEventHandlerUPP(HotKeyHandler); | |
269 EventTypeSpec event_type; | |
270 event_type.eventClass = kEventClassKeyboard; | |
271 event_type.eventKind = kEventHotKeyPressed; | |
272 InstallApplicationEventHandler( | |
273 hot_key_function, 1, &event_type, this, &event_handler_); | |
274 } | |
275 | |
276 void GlobalShortcutListenerMac::StopWatchingHotKeys() { | |
277 DCHECK(event_handler_); | |
278 RemoveEventHandler(event_handler_); | |
279 event_handler_ = NULL; | |
280 } | |
281 | |
282 bool GlobalShortcutListenerMac::IsAnyMediaKeyRegistered() { | |
283 // Iterate through registered accelerators, looking for media keys. | |
284 AcceleratorIdMap::iterator it; | |
285 for (it = accelerator_ids_.begin(); it != accelerator_ids_.end(); ++it) { | |
286 if (CommandService::IsMediaKey(it->first)) | |
287 return true; | |
288 } | |
289 return false; | |
290 } | |
291 | |
292 bool GlobalShortcutListenerMac::IsAnyHotKeyRegistered() { | |
293 AcceleratorIdMap::iterator it; | |
294 for (it = accelerator_ids_.begin(); it != accelerator_ids_.end(); ++it) { | |
295 if (!CommandService::IsMediaKey(it->first)) | |
296 return true; | |
297 } | |
298 return false; | |
299 } | |
300 | |
301 // Processed events should propagate if they aren't handled by any listeners. | |
302 // For events that don't matter, this handler should return as quickly as | |
303 // possible. | |
304 // Returning event causes the event to propagate to other applications. | |
305 // Returning NULL prevents the event from propagating. | |
306 // static | |
307 CGEventRef GlobalShortcutListenerMac::EventTapCallback( | |
308 CGEventTapProxy proxy, CGEventType type, CGEventRef event, void* refcon) { | |
309 GlobalShortcutListenerMac* shortcut_listener = | |
310 static_cast<GlobalShortcutListenerMac*>(refcon); | |
311 | |
312 // Handle the timeout case by re-enabling the tap. | |
313 if (type == kCGEventTapDisabledByTimeout) { | |
314 CGEventTapEnable(shortcut_listener->event_tap_, TRUE); | |
315 return event; | |
316 } | |
317 | |
318 // Convert the CGEvent to an NSEvent for access to the data1 field. | |
319 NSEvent* ns_event = [NSEvent eventWithCGEvent:event]; | |
320 if (ns_event == nil) { | |
321 return event; | |
322 } | |
323 | |
324 // Ignore events that are not system defined media keys. | |
325 if (type != NX_SYSDEFINED || | |
326 [ns_event type] != NSSystemDefined || | |
327 [ns_event subtype] != kSystemDefinedEventMediaKeysSubtype) { | |
328 return event; | |
329 } | |
330 | |
331 NSInteger data1 = [ns_event data1]; | |
332 // Ignore media keys that aren't previous, next and play/pause. | |
333 // Magical constants are from http://weblog.rogueamoeba.com/2007/09/29/ | |
334 int key_code = (data1 & 0xFFFF0000) >> 16; | |
335 if (key_code != NX_KEYTYPE_PLAY && key_code != NX_KEYTYPE_NEXT && | |
336 key_code != NX_KEYTYPE_PREVIOUS && key_code != NX_KEYTYPE_FAST && | |
337 key_code != NX_KEYTYPE_REWIND) { | |
338 return event; | |
339 } | |
340 | |
341 int key_flags = data1 & 0x0000FFFF; | |
342 bool is_key_pressed = ((key_flags & 0xFF00) >> 8) == 0xA; | |
343 | |
344 // If the key wasn't pressed (eg. was released), ignore this event. | |
345 if (!is_key_pressed) | |
346 return event; | |
347 | |
348 // Now we have a media key that we care about. Send it to the caller. | |
349 bool was_handled = shortcut_listener->OnMediaKeyEvent(key_code); | |
350 | |
351 // Prevent event from proagating to other apps if handled by Chrome. | |
352 if (was_handled) | |
353 return NULL; | |
354 | |
355 // By default, pass the event through. | |
356 return event; | |
357 } | |
358 | |
359 // static | |
360 OSStatus GlobalShortcutListenerMac::HotKeyHandler( | |
361 EventHandlerCallRef next_handler, EventRef event, void* user_data) { | |
362 // Extract the hotkey from the event. | |
363 EventHotKeyID hot_key_id; | |
364 OSStatus result = GetEventParameter(event, kEventParamDirectObject, | |
365 typeEventHotKeyID, NULL, sizeof(hot_key_id), NULL, &hot_key_id); | |
366 if (result != noErr) | |
367 return result; | |
368 | |
369 GlobalShortcutListenerMac* shortcut_listener = | |
370 static_cast<GlobalShortcutListenerMac*>(user_data); | |
371 shortcut_listener->OnHotKeyEvent(hot_key_id); | |
372 return noErr; | |
373 } | |
374 | |
Mark Mentovai
2013/12/12 19:51:20
(nit) Extra blank line.
smus
2013/12/12 21:13:52
Done.
| |
375 | |
376 } // namespace extensions | |
OLD | NEW |