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

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 #include "chrome/browser/extensions/api/commands/command_service.h"
12 #include "content/public/browser/browser_thread.h"
13 #include "ui/base/accelerators/accelerator.h"
14 #include "ui/events/event.h"
15 #import "ui/events/keycodes/keyboard_code_conversion_mac.h"
16
17 using content::BrowserThread;
18 using extensions::GlobalShortcutListenerMac;
19
20 namespace {
21
22 // The media keys subtype. No official docs found, but widely known.
23 // http://lists.apple.com/archives/cocoa-dev/2007/Aug/msg00499.html
24 const int kSystemDefinedEventMediaKeys = 8;
25
26 OSStatus HotKeyHandler(
27 EventHandlerCallRef next_handler, EventRef event, void* user_data) {
28 DVLOG(0) << "HotKeyHandler fired with event: " << event;
Mark Mentovai 2013/12/09 19:31:54 Are these still useful? If development is wrapped
smus 2013/12/09 23:37:06 Done.
29 // Extract the hotkey from the event.
30 EventHotKeyID hot_key_id;
31 int result = GetEventParameter(event, kEventParamDirectObject,
32 typeEventHotKeyID, NULL, sizeof(hot_key_id), NULL, &hot_key_id);
33 if (result != noErr)
34 return result;
35
36 GlobalShortcutListenerMac* shortcut_listener =
37 static_cast<GlobalShortcutListenerMac*>(user_data);
38 shortcut_listener->OnKeyEvent(hot_key_id);
39 return noErr;
40 }
41
42 ui::KeyboardCode MediaKeyCodeToKeyboardCode(
43 int key_code) {
Mark Mentovai 2013/12/09 19:31:54 No need to wrap this line.
smus 2013/12/09 23:37:06 Done.
44 switch (key_code) {
45 case NX_KEYTYPE_PLAY:
46 return ui::VKEY_MEDIA_PLAY_PAUSE;
47 case NX_KEYTYPE_PREVIOUS:
48 case NX_KEYTYPE_REWIND:
49 return ui::VKEY_MEDIA_PREV_TRACK;
50 case NX_KEYTYPE_NEXT:
51 case NX_KEYTYPE_FAST:
52 return ui::VKEY_MEDIA_NEXT_TRACK;
53 }
54 return ui::VKEY_UNKNOWN;
55 }
56
57
Robert Sesek 2013/12/09 19:17:42 nit: extra blank line
smus 2013/12/09 23:37:06 Done.
58 static base::LazyInstance<extensions::GlobalShortcutListenerMac> g_instance =
Mark Mentovai 2013/12/09 19:31:54 You’re already in an unnamed namespace, “static” d
smus 2013/12/09 23:37:06 Done.
59 LAZY_INSTANCE_INITIALIZER;
60
61 } // namespace
62
63 namespace extensions {
64
65 // static
66 GlobalShortcutListener* GlobalShortcutListener::GetInstance() {
67 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
68 return g_instance.Pointer();
Mark Mentovai 2013/12/09 19:31:54 g_instance is only referenced here, so you can jus
smus 2013/12/09 23:37:06 Mark, this code is mostly based on other (Windows,
Finnur 2013/12/09 23:59:49 As I recall, we've gotten a similar comment on one
smus 2013/12/10 01:06:43 Mark, I removed the lazy instantiation. Is this wh
69 }
70
71 GlobalShortcutListenerMac::GlobalShortcutListenerMac() {
72 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
73 is_listening_ = false;
Robert Sesek 2013/12/09 19:17:42 Why not use an initializer list for this?
smus 2013/12/09 23:37:06 Done.
74 hot_key_id_ = 0;
75 event_tap_ = NULL;
76 event_tap_source_ = NULL;
77 }
78
79 GlobalShortcutListenerMac::~GlobalShortcutListenerMac() {
Mark Mentovai 2013/12/09 19:31:54 Is an object of this class ever created anywhere o
smus 2013/12/09 23:37:06 Don't believe so.
80 if (is_listening_)
81 StopListening();
Robert Sesek 2013/12/09 19:17:42 What's the point of calling this? It just sets a b
smus 2013/12/09 23:37:06 There is some sanity checking too, which seems use
82
83 // If media keys are still registered, make sure we stop the tap.
84 if (IsAnyMediaKeyRegistered())
85 StopWatchingMediaKeys();
86 }
87
88 void GlobalShortcutListenerMac::StartListening() {
89 DCHECK(!is_listening_); // Don't start twice.
90 DCHECK(!hot_key_ids_.empty()); // Don't start if no hot key registered.
91 DCHECK(!id_hot_keys_.empty());
92 is_listening_ = true;
93 }
94
95 void GlobalShortcutListenerMac::StopListening() {
96 DCHECK(is_listening_); // No point if we are not already listening.
97 DCHECK(hot_key_ids_.empty()); // Make sure the set is clean.
98 DCHECK(id_hot_keys_.empty());
99 is_listening_ = false;
100 }
101
102 bool GlobalShortcutListenerMac::OnKeyEvent(EventHotKeyID hot_key_id) {
103 // Look up the accelerator based on this hot key ID.
104 DVLOG(0) << "OnKeyEvent! hot_key_id: " << hot_key_id.id;
105 const ui::Accelerator& accelerator = id_hot_keys_[hot_key_id.id];
Robert Sesek 2013/12/09 19:17:42 What if it's not found?
smus 2013/12/09 23:37:06 Done.
106 DVLOG(0) << "Key code: " << accelerator.key_code()
107 << " modifiers: " << accelerator.modifiers();
Mark Mentovai 2013/12/09 19:31:54 Line up the first << operator on this new line wit
smus 2013/12/09 23:37:06 Done.
108 NotifyKeyPressed(accelerator);
109 return true;
Mark Mentovai 2013/12/09 19:31:54 Seems like there’s an interface here to signal tha
smus 2013/12/09 23:37:06 Media keys and hot keys are handled differently. M
110 }
111
112 bool GlobalShortcutListenerMac::OnMediaKeyEvent(int media_key_code) {
113 ui::KeyboardCode key_code = MediaKeyCodeToKeyboardCode(media_key_code);
114 DVLOG(0) << "OnMediaKeyEvent! keyCode: " << key_code;
115 // Create an accelerator corresponding to the keyCode.
116 ui::Accelerator accelerator(key_code, 0);
117 // Look for a match with a bound hot_key.
118 if (hot_key_ids_.find(accelerator) != hot_key_ids_.end()) {
119 // If matched, callback to the event handling system.
120 NotifyKeyPressed(accelerator);
121 return true;
122 }
123 return false;
124 }
125
126 void GlobalShortcutListenerMac::RegisterAccelerator(
127 const ui::Accelerator& accelerator,
128 GlobalShortcutListener::Observer* observer) {
129 DVLOG(0) << "Registered keyCode: " << accelerator.key_code()
130 << ", modifiers: " << accelerator.modifiers();
131
132 if (hot_key_ids_.find(accelerator) != hot_key_ids_.end()) {
133 // The shortcut has already been registered. Some shortcuts, such as
134 // MediaKeys can have multiple targets, all keyed off of the same
135 // accelerator.
136 return;
137 }
138
139 // If this is the first media key registered, start the event tap.
140 if (CommandService::IsMediaKey(accelerator) && !IsAnyMediaKeyRegistered()) {
141 DVLOG(0) << "Registered the first media key, so starting event tap.";
142 StartWatchingMediaKeys();
143 }
144
145 // Register hot_key if they are non-media keyboard shortcuts.
146 if (!CommandService::IsMediaKey(accelerator))
147 RegisterHotKey(accelerator, hot_key_id_);
148
149 // Store the hotkey-ID mappings we will need for lookup later.
150 id_hot_keys_[hot_key_id_] = accelerator;
151 hot_key_ids_[accelerator] = hot_key_id_;
152 ++hot_key_id_;
153 GlobalShortcutListener::RegisterAccelerator(accelerator, observer);
154 }
155
156 void GlobalShortcutListenerMac::UnregisterAccelerator(
157 const ui::Accelerator& accelerator,
158 GlobalShortcutListener::Observer* observer) {
159 // Unregister the hot_key if it's a keyboard shortcut.
160 if (!CommandService::IsMediaKey(accelerator))
161 UnregisterHotKey(accelerator);
162
163 // Remove hot_key from the mappings.
164 int id = hot_key_ids_[accelerator];
165 id_hot_keys_.erase(id);
166 hot_key_ids_.erase(accelerator);
167 GlobalShortcutListener::UnregisterAccelerator(accelerator, observer);
168
169 // If we unregistered a media key, and now if no media keys are registered,
170 // stop the media key tap.
171 if (CommandService::IsMediaKey(accelerator) && !IsAnyMediaKeyRegistered()) {
172 DVLOG(0) << "Unregistered the last media key, stopping event tap.";
173 StopWatchingMediaKeys();
174 }
175 }
176
177 void GlobalShortcutListenerMac::RegisterHotKey(
178 const ui::Accelerator& accelerator, int hot_key_id) {
179 DVLOG(0) << "Registering hot_key. Keycode: " << accelerator.key_code();
180 EventHotKeyRef hot_key_ref;
181 EventHotKeyID event_hot_key_id;
182 EventHandlerUPP hot_key_function = NewEventHandlerUPP(HotKeyHandler);
183
184 EventTypeSpec event_type;
185 event_type.eventClass = kEventClassKeyboard;
186 event_type.eventKind = kEventHotKeyPressed;
187 InstallApplicationEventHandler(hot_key_function, 1, &event_type, this, NULL);
188
189 // Signature uniquely identifies the application that owns this hot_key.
190 event_hot_key_id.signature = 'rimZ';
Mark Mentovai 2013/12/09 19:31:54 Don’t hard-code the creator code. You can use CFBu
smus 2013/12/09 23:37:06 This is apparently implemented in base/mac/foundat
191 event_hot_key_id.id = hot_key_id;
192
193 // Translate ui::Accelerator modifiers to cmdKey, altKey, etc.
194 int modifiers = 0;
195 modifiers |= (accelerator.IsShiftDown() ? shiftKey : 0);
196 modifiers |= (accelerator.IsCtrlDown() ? controlKey : 0);
197 modifiers |= (accelerator.IsAltDown() ? optionKey : 0);
198 modifiers |= (accelerator.IsCmdDown() ? cmdKey : 0);
199
200 unichar character;
201 unichar character_nomods;
202 int key_code = ui::MacKeyCodeForWindowsKeyCode(accelerator.key_code(), 0,
203 &character, &character_nomods);
204 DVLOG(0) << "RegisterHotKey. Code: " << key_code
205 << " modifier: " << modifiers;
206
207 // Register the event hot key.
208 RegisterEventHotKey(key_code, modifiers, event_hot_key_id,
209 GetApplicationEventTarget(), 0, &hot_key_ref);
210
211 id_hot_key_refs_[hot_key_id] = hot_key_ref;
212 }
213
214 void GlobalShortcutListenerMac::UnregisterHotKey(
215 const ui::Accelerator& accelerator) {
216 // Get the ref corresponding to this accelerator.
217 int id = hot_key_ids_[accelerator];
218 EventHotKeyRef ref = id_hot_key_refs_[id];
219 // Unregister the event hot key.
220 UnregisterEventHotKey(ref);
221
222 // Remove the event from the mapping.
223 id_hot_key_refs_.erase(id);
224 }
225
226 void GlobalShortcutListenerMac::StartWatchingMediaKeys() {
227 DVLOG(0) << "StartWatchingMediaKeys";
228 // Make sure there's no existing event tap.
229 DCHECK(event_tap_ == NULL);
230
231 // Add an event tap to intercept the system defined media key events.
232 event_tap_ = CGEventTapCreate(kCGSessionEventTap,
233 kCGHeadInsertEventTap,
234 kCGEventTapOptionDefault,
235 CGEventMaskBit(NX_SYSDEFINED),
236 EventTapCallback,
237 this);
238 if (event_tap_ == NULL) {
239 LOG(ERROR) << "Error: failed to create event tap.";
240 return;
241 }
242
243 event_tap_source_ = CFMachPortCreateRunLoopSource(kCFAllocatorSystemDefault,
244 event_tap_, 0);
245 if (event_tap_source_ == NULL) {
246 LOG(ERROR) << "Error: failed to create new run loop source.";
247 return;
248 }
249
250 CFRunLoopAddSource(CFRunLoopGetCurrent(), event_tap_source_,
251 kCFRunLoopCommonModes);
252 }
253
254 void GlobalShortcutListenerMac::StopWatchingMediaKeys() {
255 DVLOG(0) << "StopWatchingMediaKeys";
256 CFRunLoopRemoveSource(CFRunLoopGetCurrent(), event_tap_source_,
257 kCFRunLoopCommonModes);
258
259 // Invalidate the event tap.
260 DCHECK(event_tap_ != NULL);
261 CFMachPortInvalidate(event_tap_);
262 CFRelease(event_tap_);
263 event_tap_ = NULL;
264
265 // Release the event tap source.
266 DCHECK(event_tap_source_ != NULL);
267 CFRelease(event_tap_source_);
268 event_tap_source_ = NULL;
269 }
270
271 bool GlobalShortcutListenerMac::IsAnyMediaKeyRegistered() {
272 // Iterate through registered accelerators, looking for media keys.
273 HotKeyIdMap::iterator iter;
274 for (iter = hot_key_ids_.begin(); iter != hot_key_ids_.end(); ++iter) {
275 if (CommandService::IsMediaKey(iter->first))
276 return true;
277 }
278 return false;
279 }
280
281 // Processed events should propagate if they aren't handled by any listeners.
282 // For events that don't matter, this handler should return as quickly as
283 // possible.
284 // Returning event causes the event to propagate to other applications.
285 // Returning NULL prevents the event from propagating.
286 // static
287 CGEventRef GlobalShortcutListenerMac::EventTapCallback(
288 CGEventTapProxy proxy, CGEventType type, CGEventRef event, void* refcon) {
289 GlobalShortcutListenerMac* shortcut_listener =
290 static_cast<GlobalShortcutListenerMac*>(refcon);
291
292 // Handle the timeout case by re-enabling the tap.
293 if (type == kCGEventTapDisabledByTimeout) {
294 CGEventTapEnable(shortcut_listener->event_tap_, TRUE);
295 return event;
296 }
297
298 // Convert the CGEvent to an NSEvent for access to the data1 field.
299 NSEvent* ns_event = [NSEvent eventWithCGEvent:event];
300 if (ns_event == nil) {
301 return event;
302 }
303
304 // Ignore events that are not system defined media keys.
305 if (type != NX_SYSDEFINED ||
306 [ns_event type] != NSSystemDefined ||
307 [ns_event subtype] != kSystemDefinedEventMediaKeys) {
308 return event;
309 }
310
311 NSInteger data1 = [ns_event data1];
312 // Ignore media keys that aren't previous, next and play/pause.
313 // Magical constants are from http://weblog.rogueamoeba.com/2007/09/29/
314 int key_code = ((data1 & 0xFFFF0000) >> 16);
315 if (key_code != NX_KEYTYPE_PLAY && key_code != NX_KEYTYPE_NEXT &&
316 key_code != NX_KEYTYPE_PREVIOUS && key_code != NX_KEYTYPE_FAST &&
317 key_code != NX_KEYTYPE_REWIND) {
318 return event;
319 }
320
321 int key_flags = (data1 & 0x0000FFFF);
322 bool is_key_pressed = (((key_flags & 0xFF00) >> 8)) == 0xA;
323
324 // If the key wasn't pressed (eg. was released), ignore this event.
325 if (!is_key_pressed)
326 return event;
327
328 // Now we have a media key that we care about. Send it to the caller.
329 bool was_handled = shortcut_listener->OnMediaKeyEvent(key_code);
330
331 // Prevent event from proagating to other apps if handled by Chrome.
332 if (was_handled)
333 return NULL;
334
335 // By default, pass the event through.
336 return event;
337 }
338
339 } // namespace extensions
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698