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

Side by Side Diff: chrome/browser/extensions/global_shortcut_listener_mac.mm

Issue 60353008: Mac global keybindings (Closed) Base URL: https://src.chromium.org/chrome/trunk/src/
Patch Set: Created 7 years 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
OLDNEW
(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 *g_instance =
Mark Mentovai 2013/12/11 02:55:02 This is no longer global, you don’t need the g_ pr
smus 2013/12/11 17:52:07 Done.
49 new GlobalShortcutListenerMac();
50 return g_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.
67 if (event_handler_)
68 StopListening();
Mark Mentovai 2013/12/11 02:55:02 If event_handler_ is true, then hot_key_ids_ will
smus 2013/12/11 17:52:07 The comment above: // By this point, Unregister
69
70 // If media keys are still registered, make sure we stop the tap.
71 if (IsAnyMediaKeyRegistered())
72 StopWatchingMediaKeys();
73 }
74
75 void GlobalShortcutListenerMac::StartListening() {
76 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
77
78 DCHECK(!hot_key_ids_.empty()); // Don't start if no hot key registered.
Mark Mentovai 2013/12/11 02:55:02 It’s not really “don’t start,” it’s “this should n
smus 2013/12/11 17:52:07 I think “this should never happen and is fatal in
79 DCHECK(!id_hot_keys_.empty());
80 DCHECK(!is_listening_);
81
82 is_listening_ = true;
83 }
84
85 void GlobalShortcutListenerMac::StopListening() {
86 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
87
88 DCHECK(hot_key_ids_.empty()); // Make sure the set is clean.
89 DCHECK(id_hot_keys_.empty());
90 DCHECK(is_listening_);
91
92 is_listening_ = false;
93 }
94
95 void GlobalShortcutListenerMac::OnHotKeyEvent(EventHotKeyID hot_key_id) {
96 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
97
98 // This hot key should be registered.
99 DCHECK(id_hot_keys_.find(hot_key_id.id) != id_hot_keys_.end());
100 // Look up the accelerator based on this hot key ID.
101 const ui::Accelerator& accelerator = id_hot_keys_[hot_key_id.id];
102 NotifyKeyPressed(accelerator);
103 }
104
105 bool GlobalShortcutListenerMac::OnMediaKeyEvent(int media_key_code) {
106 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
107 ui::KeyboardCode key_code = MediaKeyCodeToKeyboardCode(media_key_code);
108 // Create an accelerator corresponding to the keyCode.
109 ui::Accelerator accelerator(key_code, 0);
110 // Look for a match with a bound hot_key.
111 if (hot_key_ids_.find(accelerator) != hot_key_ids_.end()) {
112 // If matched, callback to the event handling system.
113 NotifyKeyPressed(accelerator);
114 return true;
115 }
116 return false;
117 }
118
119 void GlobalShortcutListenerMac::RegisterAccelerator(
120 const ui::Accelerator& accelerator,
121 GlobalShortcutListener::Observer* observer) {
122 if (hot_key_ids_.find(accelerator) != hot_key_ids_.end()) {
123 // The shortcut has already been registered. Some shortcuts, such as
124 // MediaKeys can have multiple targets, all keyed off of the same
Mark Mentovai 2013/12/11 02:55:02 I hadn’t noticed this property before, but now tha
smus 2013/12/11 17:52:07 Looks like I copied this code directly from the ot
Finnur 2013/12/11 18:43:36 This should work the same way on all platforms: Me
Finnur 2013/12/11 19:21:41 And to clarify... If a second extension comes in
125 // accelerator.
126 return;
127 }
128
129 if (CommandService::IsMediaKey(accelerator)) {
130 if (!IsAnyMediaKeyRegistered()) {
131 // If this is the first media key registered, start the event tap.
132 StartWatchingMediaKeys();
133 }
134 } else {
135 // Register hot_key if they are non-media keyboard shortcuts.
136 RegisterHotKey(accelerator, hot_key_id_);
137 }
138
139 // Store the hotkey-ID mappings we will need for lookup later.
140 id_hot_keys_[hot_key_id_] = accelerator;
141 hot_key_ids_[accelerator] = hot_key_id_;
142 ++hot_key_id_;
143 GlobalShortcutListener::RegisterAccelerator(accelerator, observer);
144 }
145
146 void GlobalShortcutListenerMac::UnregisterAccelerator(
147 const ui::Accelerator& accelerator,
148 GlobalShortcutListener::Observer* observer) {
149 // Ensure this accelerator is registered.
150 DCHECK(hot_key_ids_.find(accelerator) != hot_key_ids_.end());
151
152 // Unregister the hot_key if it's a keyboard shortcut.
153 if (!CommandService::IsMediaKey(accelerator))
154 UnregisterHotKey(accelerator);
155
156 // Remove hot_key from the mappings.
157 HotKeyId id = hot_key_ids_[accelerator];
158 id_hot_keys_.erase(id);
159 hot_key_ids_.erase(accelerator);
160 GlobalShortcutListener::UnregisterAccelerator(accelerator, observer);
161
162 // If we unregistered a media key, and now if no media keys are registered,
163 // stop the media key tap.
164 if (CommandService::IsMediaKey(accelerator) && !IsAnyMediaKeyRegistered()) {
165 StopWatchingMediaKeys();
166 }
167 }
168
169 void GlobalShortcutListenerMac::RegisterHotKey(
170 const ui::Accelerator& accelerator, HotKeyId hot_key_id) {
171 DVLOG(0) << "RegisterHotKey";
172 EventHotKeyID event_hot_key_id;
173
174 // Signature uniquely identifies the application that owns this hot_key.
175 event_hot_key_id.signature = base::mac::CreatorCodeForApplication();
176 event_hot_key_id.id = hot_key_id;
177
178 // Translate ui::Accelerator modifiers to cmdKey, altKey, etc.
179 int modifiers = 0;
180 modifiers |= (accelerator.IsShiftDown() ? shiftKey : 0);
181 modifiers |= (accelerator.IsCtrlDown() ? controlKey : 0);
182 modifiers |= (accelerator.IsAltDown() ? optionKey : 0);
183 modifiers |= (accelerator.IsCmdDown() ? cmdKey : 0);
184
185 int key_code = ui::MacKeyCodeForWindowsKeyCode(accelerator.key_code(), 0,
186 NULL, NULL);
187
188 // Register the event hot key.
189 EventHotKeyRef hot_key_ref;
190 RegisterEventHotKey(key_code, modifiers, event_hot_key_id,
191 GetApplicationEventTarget(), 0, &hot_key_ref);
192
193 id_hot_key_refs_[hot_key_id] = hot_key_ref;
194
195 // If there is no event handler, install it.
196 if (!event_handler_) {
197 DVLOG(0) << "Installing event handler";
198 EventHandlerUPP hot_key_function = NewEventHandlerUPP(HotKeyHandler);
199 EventTypeSpec event_type;
200 event_type.eventClass = kEventClassKeyboard;
201 event_type.eventKind = kEventHotKeyPressed;
202 InstallApplicationEventHandler(
203 hot_key_function, 1, &event_type, this, &event_handler_);
204 }
205 }
206
207 void GlobalShortcutListenerMac::UnregisterHotKey(
208 const ui::Accelerator& accelerator) {
209 // Ensure this accelerator is already registered.
210 DCHECK(hot_key_ids_.find(accelerator) != hot_key_ids_.end());
211 // Get the ref corresponding to this accelerator.
212 HotKeyId id = hot_key_ids_[accelerator];
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 // If no more hot keys are registered, remove the event handler.
Mark Mentovai 2013/12/11 02:55:02 The comment says “if no more hot keys are register
smus 2013/12/11 17:52:07 Done.
221 if (event_handler_) {
222 DVLOG(0) << "Removing event handler";
223 RemoveEventHandler(event_handler_);
224 event_handler_ = NULL;
225 }
226 }
227
228 void GlobalShortcutListenerMac::StartWatchingMediaKeys() {
229 // Make sure there's no existing event tap.
230 DCHECK(event_tap_ == NULL);
231 DCHECK(event_tap_source_ == NULL);
232
233 // Add an event tap to intercept the system defined media key events.
234 event_tap_ = CGEventTapCreate(kCGSessionEventTap,
235 kCGHeadInsertEventTap,
236 kCGEventTapOptionDefault,
237 CGEventMaskBit(NX_SYSDEFINED),
238 EventTapCallback,
239 this);
240 if (event_tap_ == NULL) {
241 LOG(ERROR) << "Error: failed to create event tap.";
242 return;
243 }
244
245 event_tap_source_ = CFMachPortCreateRunLoopSource(kCFAllocatorSystemDefault,
246 event_tap_, 0);
247 if (event_tap_source_ == NULL) {
248 LOG(ERROR) << "Error: failed to create new run loop source.";
249 return;
250 }
251
252 CFRunLoopAddSource(CFRunLoopGetCurrent(), event_tap_source_,
253 kCFRunLoopCommonModes);
254 }
255
256 void GlobalShortcutListenerMac::StopWatchingMediaKeys() {
257 CFRunLoopRemoveSource(CFRunLoopGetCurrent(), event_tap_source_,
258 kCFRunLoopCommonModes);
259 // Ensure both event tap and source are initialized.
260 DCHECK(event_tap_ != NULL);
261 DCHECK(event_tap_source_ != NULL);
262
263 // Invalidate the event tap.
264 CFMachPortInvalidate(event_tap_);
265 CFRelease(event_tap_);
266 event_tap_ = NULL;
267
268 // Release the event tap source.
269 CFRelease(event_tap_source_);
270 event_tap_source_ = NULL;
271 }
272
273 bool GlobalShortcutListenerMac::IsAnyMediaKeyRegistered() {
274 // Iterate through registered accelerators, looking for media keys.
275 HotKeyIdMap::iterator iter;
276 for (iter = hot_key_ids_.begin(); iter != hot_key_ids_.end(); ++iter) {
277 if (CommandService::IsMediaKey(iter->first))
278 return true;
279 }
280 return false;
281 }
282
283 bool GlobalShortcutListenerMac::IsAnyHotKeyRegistered() {
Mark Mentovai 2013/12/11 02:55:02 Who calls this? It seems like you could use this t
smus 2013/12/11 17:52:07 Done.
284 HotKeyIdMap::iterator iter;
285 for (iter = hot_key_ids_.begin(); iter != hot_key_ids_.end(); ++iter) {
286 if (!CommandService::IsMediaKey(iter->first))
287 return true;
288 }
289 return false;
290 }
291
292 // Processed events should propagate if they aren't handled by any listeners.
293 // For events that don't matter, this handler should return as quickly as
294 // possible.
295 // Returning event causes the event to propagate to other applications.
296 // Returning NULL prevents the event from propagating.
297 // static
298 CGEventRef GlobalShortcutListenerMac::EventTapCallback(
299 CGEventTapProxy proxy, CGEventType type, CGEventRef event, void* refcon) {
300 GlobalShortcutListenerMac* shortcut_listener =
301 static_cast<GlobalShortcutListenerMac*>(refcon);
302
303 // Handle the timeout case by re-enabling the tap.
304 if (type == kCGEventTapDisabledByTimeout) {
305 CGEventTapEnable(shortcut_listener->event_tap_, TRUE);
306 return event;
307 }
308
309 // Convert the CGEvent to an NSEvent for access to the data1 field.
310 NSEvent* ns_event = [NSEvent eventWithCGEvent:event];
311 if (ns_event == nil) {
312 return event;
313 }
314
315 // Ignore events that are not system defined media keys.
316 if (type != NX_SYSDEFINED ||
317 [ns_event type] != NSSystemDefined ||
318 [ns_event subtype] != kSystemDefinedEventMediaKeysSubtype) {
319 return event;
320 }
321
322 NSInteger data1 = [ns_event data1];
323 // Ignore media keys that aren't previous, next and play/pause.
324 // Magical constants are from http://weblog.rogueamoeba.com/2007/09/29/
325 int key_code = (data1 & 0xFFFF0000) >> 16;
326 if (key_code != NX_KEYTYPE_PLAY && key_code != NX_KEYTYPE_NEXT &&
327 key_code != NX_KEYTYPE_PREVIOUS && key_code != NX_KEYTYPE_FAST &&
328 key_code != NX_KEYTYPE_REWIND) {
329 return event;
330 }
331
332 int key_flags = data1 & 0x0000FFFF;
333 bool is_key_pressed = ((key_flags & 0xFF00) >> 8) == 0xA;
334
335 // If the key wasn't pressed (eg. was released), ignore this event.
336 if (!is_key_pressed)
337 return event;
338
339 // Now we have a media key that we care about. Send it to the caller.
340 bool was_handled = shortcut_listener->OnMediaKeyEvent(key_code);
341
342 // Prevent event from proagating to other apps if handled by Chrome.
343 if (was_handled)
344 return NULL;
345
346 // By default, pass the event through.
347 return event;
348 }
349
350 // static
351 OSStatus GlobalShortcutListenerMac::HotKeyHandler(
352 EventHandlerCallRef next_handler, EventRef event, void* user_data) {
353 // Extract the hotkey from the event.
354 EventHotKeyID hot_key_id;
355 OSStatus result = GetEventParameter(event, kEventParamDirectObject,
356 typeEventHotKeyID, NULL, sizeof(hot_key_id), NULL, &hot_key_id);
357 if (result != noErr)
358 return result;
359
360 GlobalShortcutListenerMac* shortcut_listener =
361 static_cast<GlobalShortcutListenerMac*>(user_data);
362 shortcut_listener->OnHotKeyEvent(hot_key_id);
363 return noErr;
364 }
365
366
367 } // namespace extensions
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698