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(); | |
zhchbin
2013/12/14 00:52:58
Hm... Who will delete this object?
| |
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 keys are still registered, make sure we stop the tap. Again, this | |
71 // should never happen. | |
72 if (IsAnyMediaKeyRegistered()) | |
73 StopWatchingMediaKeys(); | |
74 | |
75 if (IsAnyHotKeyRegistered()) | |
76 StopWatchingHotKeys(); | |
77 } | |
78 | |
79 void GlobalShortcutListenerMac::StartListening() { | |
80 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); | |
81 | |
82 DCHECK(!accelerator_ids_.empty()); | |
83 DCHECK(!id_accelerators_.empty()); | |
84 DCHECK(!is_listening_); | |
85 | |
86 is_listening_ = true; | |
87 } | |
88 | |
89 void GlobalShortcutListenerMac::StopListening() { | |
90 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); | |
91 | |
92 DCHECK(accelerator_ids_.empty()); // Make sure the set is clean. | |
93 DCHECK(id_accelerators_.empty()); | |
94 DCHECK(is_listening_); | |
95 | |
96 is_listening_ = false; | |
97 } | |
98 | |
99 void GlobalShortcutListenerMac::OnHotKeyEvent(EventHotKeyID hot_key_id) { | |
100 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); | |
101 | |
102 // This hot key should be registered. | |
103 DCHECK(id_accelerators_.find(hot_key_id.id) != id_accelerators_.end()); | |
104 // Look up the accelerator based on this hot key ID. | |
105 const ui::Accelerator& accelerator = id_accelerators_[hot_key_id.id]; | |
106 NotifyKeyPressed(accelerator); | |
107 } | |
108 | |
109 bool GlobalShortcutListenerMac::OnMediaKeyEvent(int media_key_code) { | |
110 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); | |
111 ui::KeyboardCode key_code = MediaKeyCodeToKeyboardCode(media_key_code); | |
112 // Create an accelerator corresponding to the keyCode. | |
113 ui::Accelerator accelerator(key_code, 0); | |
114 // Look for a match with a bound hot_key. | |
115 if (accelerator_ids_.find(accelerator) != accelerator_ids_.end()) { | |
116 // If matched, callback to the event handling system. | |
117 NotifyKeyPressed(accelerator); | |
118 return true; | |
119 } | |
120 return false; | |
121 } | |
122 | |
123 void GlobalShortcutListenerMac::RegisterAccelerator( | |
124 const ui::Accelerator& accelerator, | |
125 GlobalShortcutListener::Observer* observer) { | |
126 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); | |
127 if (accelerator_ids_.find(accelerator) != accelerator_ids_.end()) { | |
128 // The shortcut has already been registered. Some shortcuts, such as | |
129 // MediaKeys can have multiple targets, all keyed off of the same | |
130 // accelerator. | |
131 return; | |
132 } | |
133 | |
134 if (CommandService::IsMediaKey(accelerator)) { | |
135 if (!IsAnyMediaKeyRegistered()) { | |
136 // If this is the first media key registered, start the event tap. | |
137 StartWatchingMediaKeys(); | |
138 } | |
139 } else { | |
140 // Register hot_key if they are non-media keyboard shortcuts. | |
141 RegisterHotKey(accelerator, hot_key_id_); | |
142 if (!IsAnyHotKeyRegistered()) { | |
143 StartWatchingHotKeys(); | |
144 } | |
145 } | |
146 | |
147 // Store the hotkey-ID mappings we will need for lookup later. | |
148 id_accelerators_[hot_key_id_] = accelerator; | |
149 accelerator_ids_[accelerator] = hot_key_id_; | |
150 ++hot_key_id_; | |
151 GlobalShortcutListener::RegisterAccelerator(accelerator, observer); | |
152 } | |
153 | |
154 void GlobalShortcutListenerMac::UnregisterAccelerator( | |
155 const ui::Accelerator& accelerator, | |
156 GlobalShortcutListener::Observer* observer) { | |
157 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); | |
158 | |
159 // We may get asked to unregister something that we couldn't register (for | |
160 // example if the shortcut was already taken by another app), so we | |
161 // need to handle that gracefully. | |
162 AcceleratorIdMap::iterator it = accelerator_ids_.find(accelerator); | |
163 if (it == accelerator_ids_.end()) | |
164 return; | |
165 | |
166 // Unregister the hot_key if it's a keyboard shortcut. | |
167 if (!CommandService::IsMediaKey(accelerator)) | |
168 UnregisterHotKey(accelerator); | |
169 | |
170 // Remove hot_key from the mappings. | |
171 KeyId key_id = accelerator_ids_[accelerator]; | |
172 id_accelerators_.erase(key_id); | |
173 accelerator_ids_.erase(accelerator); | |
174 GlobalShortcutListener::UnregisterAccelerator(accelerator, observer); | |
175 | |
176 if (CommandService::IsMediaKey(accelerator)) { | |
177 // If we unregistered a media key, and now no media keys are registered, | |
178 // stop the media key tap. | |
179 if (!IsAnyMediaKeyRegistered()) | |
180 StopWatchingMediaKeys(); | |
181 } else { | |
182 // If we unregistered a hot key, and no more hot keys are registered, remove | |
183 // the hot key handler. | |
184 if (!IsAnyHotKeyRegistered()) { | |
185 StopWatchingHotKeys(); | |
186 } | |
187 } | |
188 } | |
189 | |
190 void GlobalShortcutListenerMac::RegisterHotKey( | |
191 const ui::Accelerator& accelerator, KeyId hot_key_id) { | |
192 EventHotKeyID event_hot_key_id; | |
193 | |
194 // Signature uniquely identifies the application that owns this hot_key. | |
195 event_hot_key_id.signature = base::mac::CreatorCodeForApplication(); | |
196 event_hot_key_id.id = hot_key_id; | |
197 | |
198 // Translate ui::Accelerator modifiers to cmdKey, altKey, etc. | |
199 int modifiers = 0; | |
200 modifiers |= (accelerator.IsShiftDown() ? shiftKey : 0); | |
201 modifiers |= (accelerator.IsCtrlDown() ? controlKey : 0); | |
202 modifiers |= (accelerator.IsAltDown() ? optionKey : 0); | |
203 modifiers |= (accelerator.IsCmdDown() ? cmdKey : 0); | |
204 | |
205 int key_code = ui::MacKeyCodeForWindowsKeyCode(accelerator.key_code(), 0, | |
206 NULL, NULL); | |
207 | |
208 // Register the event hot key. | |
209 EventHotKeyRef hot_key_ref; | |
210 RegisterEventHotKey(key_code, modifiers, event_hot_key_id, | |
211 GetApplicationEventTarget(), 0, &hot_key_ref); | |
212 | |
213 id_hot_key_refs_[hot_key_id] = hot_key_ref; | |
214 } | |
215 | |
216 void GlobalShortcutListenerMac::UnregisterHotKey( | |
217 const ui::Accelerator& accelerator) { | |
218 // Ensure this accelerator is already registered. | |
219 DCHECK(accelerator_ids_.find(accelerator) != accelerator_ids_.end()); | |
220 // Get the ref corresponding to this accelerator. | |
221 KeyId key_id = accelerator_ids_[accelerator]; | |
222 EventHotKeyRef ref = id_hot_key_refs_[key_id]; | |
223 // Unregister the event hot key. | |
224 UnregisterEventHotKey(ref); | |
225 | |
226 // Remove the event from the mapping. | |
227 id_hot_key_refs_.erase(key_id); | |
228 } | |
229 | |
230 void GlobalShortcutListenerMac::StartWatchingMediaKeys() { | |
231 // Make sure there's no existing event tap. | |
232 DCHECK(event_tap_ == NULL); | |
233 DCHECK(event_tap_source_ == NULL); | |
234 | |
235 // Add an event tap to intercept the system defined media key events. | |
236 event_tap_ = CGEventTapCreate(kCGSessionEventTap, | |
237 kCGHeadInsertEventTap, | |
238 kCGEventTapOptionDefault, | |
239 CGEventMaskBit(NX_SYSDEFINED), | |
240 EventTapCallback, | |
241 this); | |
242 if (event_tap_ == NULL) { | |
243 LOG(ERROR) << "Error: failed to create event tap."; | |
244 return; | |
245 } | |
246 | |
247 event_tap_source_ = CFMachPortCreateRunLoopSource(kCFAllocatorSystemDefault, | |
248 event_tap_, 0); | |
249 if (event_tap_source_ == NULL) { | |
250 LOG(ERROR) << "Error: failed to create new run loop source."; | |
251 return; | |
252 } | |
253 | |
254 CFRunLoopAddSource(CFRunLoopGetCurrent(), event_tap_source_, | |
255 kCFRunLoopCommonModes); | |
256 } | |
257 | |
258 void GlobalShortcutListenerMac::StopWatchingMediaKeys() { | |
259 CFRunLoopRemoveSource(CFRunLoopGetCurrent(), event_tap_source_, | |
260 kCFRunLoopCommonModes); | |
261 // Ensure both event tap and source are initialized. | |
262 DCHECK(event_tap_ != NULL); | |
263 DCHECK(event_tap_source_ != NULL); | |
264 | |
265 // Invalidate the event tap. | |
266 CFMachPortInvalidate(event_tap_); | |
267 CFRelease(event_tap_); | |
268 event_tap_ = NULL; | |
269 | |
270 // Release the event tap source. | |
271 CFRelease(event_tap_source_); | |
272 event_tap_source_ = NULL; | |
273 } | |
274 | |
275 void GlobalShortcutListenerMac::StartWatchingHotKeys() { | |
276 DCHECK(!event_handler_); | |
277 EventHandlerUPP hot_key_function = NewEventHandlerUPP(HotKeyHandler); | |
278 EventTypeSpec event_type; | |
279 event_type.eventClass = kEventClassKeyboard; | |
280 event_type.eventKind = kEventHotKeyPressed; | |
281 InstallApplicationEventHandler( | |
282 hot_key_function, 1, &event_type, this, &event_handler_); | |
283 } | |
284 | |
285 void GlobalShortcutListenerMac::StopWatchingHotKeys() { | |
286 DCHECK(event_handler_); | |
287 RemoveEventHandler(event_handler_); | |
288 event_handler_ = NULL; | |
289 } | |
290 | |
291 bool GlobalShortcutListenerMac::IsAnyMediaKeyRegistered() { | |
292 // Iterate through registered accelerators, looking for media keys. | |
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 bool GlobalShortcutListenerMac::IsAnyHotKeyRegistered() { | |
302 AcceleratorIdMap::iterator it; | |
303 for (it = accelerator_ids_.begin(); it != accelerator_ids_.end(); ++it) { | |
304 if (!CommandService::IsMediaKey(it->first)) | |
305 return true; | |
306 } | |
307 return false; | |
308 } | |
309 | |
310 // Processed events should propagate if they aren't handled by any listeners. | |
311 // For events that don't matter, this handler should return as quickly as | |
312 // possible. | |
313 // Returning event causes the event to propagate to other applications. | |
314 // Returning NULL prevents the event from propagating. | |
315 // static | |
316 CGEventRef GlobalShortcutListenerMac::EventTapCallback( | |
317 CGEventTapProxy proxy, CGEventType type, CGEventRef event, void* refcon) { | |
318 GlobalShortcutListenerMac* shortcut_listener = | |
319 static_cast<GlobalShortcutListenerMac*>(refcon); | |
320 | |
321 // Handle the timeout case by re-enabling the tap. | |
322 if (type == kCGEventTapDisabledByTimeout) { | |
323 CGEventTapEnable(shortcut_listener->event_tap_, TRUE); | |
324 return event; | |
325 } | |
326 | |
327 // Convert the CGEvent to an NSEvent for access to the data1 field. | |
328 NSEvent* ns_event = [NSEvent eventWithCGEvent:event]; | |
329 if (ns_event == nil) { | |
330 return event; | |
331 } | |
332 | |
333 // Ignore events that are not system defined media keys. | |
334 if (type != NX_SYSDEFINED || | |
335 [ns_event type] != NSSystemDefined || | |
336 [ns_event subtype] != kSystemDefinedEventMediaKeysSubtype) { | |
337 return event; | |
338 } | |
339 | |
340 NSInteger data1 = [ns_event data1]; | |
341 // Ignore media keys that aren't previous, next and play/pause. | |
342 // Magical constants are from http://weblog.rogueamoeba.com/2007/09/29/ | |
343 int key_code = (data1 & 0xFFFF0000) >> 16; | |
344 if (key_code != NX_KEYTYPE_PLAY && key_code != NX_KEYTYPE_NEXT && | |
345 key_code != NX_KEYTYPE_PREVIOUS && key_code != NX_KEYTYPE_FAST && | |
346 key_code != NX_KEYTYPE_REWIND) { | |
347 return event; | |
348 } | |
349 | |
350 int key_flags = data1 & 0x0000FFFF; | |
351 bool is_key_pressed = ((key_flags & 0xFF00) >> 8) == 0xA; | |
352 | |
353 // If the key wasn't pressed (eg. was released), ignore this event. | |
354 if (!is_key_pressed) | |
355 return event; | |
356 | |
357 // Now we have a media key that we care about. Send it to the caller. | |
358 bool was_handled = shortcut_listener->OnMediaKeyEvent(key_code); | |
359 | |
360 // Prevent event from proagating to other apps if handled by Chrome. | |
361 if (was_handled) | |
362 return NULL; | |
363 | |
364 // By default, pass the event through. | |
365 return event; | |
366 } | |
367 | |
368 // static | |
369 OSStatus GlobalShortcutListenerMac::HotKeyHandler( | |
370 EventHandlerCallRef next_handler, EventRef event, void* user_data) { | |
371 // Extract the hotkey from the event. | |
372 EventHotKeyID hot_key_id; | |
373 OSStatus result = GetEventParameter(event, kEventParamDirectObject, | |
374 typeEventHotKeyID, NULL, sizeof(hot_key_id), NULL, &hot_key_id); | |
375 if (result != noErr) | |
376 return result; | |
377 | |
378 GlobalShortcutListenerMac* shortcut_listener = | |
379 static_cast<GlobalShortcutListenerMac*>(user_data); | |
380 shortcut_listener->OnHotKeyEvent(hot_key_id); | |
381 return noErr; | |
382 } | |
383 | |
384 } // namespace extensions | |
OLD | NEW |