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

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, 1 month 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 "content/public/browser/browser_thread.h"
12 #include "ui/base/accelerators/accelerator.h"
13 #include "ui/events/event.h"
14 #import "ui/events/keycodes/keyboard_code_conversion_mac.h"
15
16 using content::BrowserThread;
17 using extensions::GlobalShortcutListenerMac;
18
19 namespace {
20
21 // The media keys subtype.
22 const int kSystemDefinedEventMediaKeys = 8;
23
24 OSStatus HotKeyHandler(
25 EventHandlerCallRef next_handler, EventRef event, void* user_data) {
26 VLOG(0) << "HotKeyHandler fired with event: " << event;
Robert Sesek 2013/11/22 16:49:59 Are the VLOGs necessary? They seem to just add clu
smus 2013/11/22 20:48:09 Changed to DVLOGs.
Robert Sesek 2013/12/09 19:17:42 They still make the code considerably harder to re
27 // Extract the hotkey from the event.
28 EventHotKeyID hotkey_id;
29 int result = GetEventParameter(event, kEventParamDirectObject,
30 typeEventHotKeyID, NULL, sizeof(hotkey_id), NULL, &hotkey_id);
31 if (result != noErr)
32 return result;
33
34 GlobalShortcutListenerMac* shortcut_listener =
35 static_cast<GlobalShortcutListenerMac*>(user_data);
36 shortcut_listener->OnKeyEvent(hotkey_id);
37 return noErr;
38 }
39
40 static base::LazyInstance<extensions::GlobalShortcutListenerMac> g_instance =
41 LAZY_INSTANCE_INITIALIZER;
42
43 } // namespace
Robert Sesek 2013/11/22 16:49:59 nit: two spaces before //
smus 2013/11/22 20:48:09 Done.
44
45 namespace extensions {
46
47 // static
48 GlobalShortcutListener* GlobalShortcutListener::GetInstance() {
49 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
50 return g_instance.Pointer();
51 }
52
53 GlobalShortcutListenerMac::GlobalShortcutListenerMac()
54 : is_listening_(false) {
55 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
56 }
57
58 GlobalShortcutListenerMac::~GlobalShortcutListenerMac() {
59 if (is_listening_)
60 StopListening();
61
62 // If media keys are still registered, make sure we stop the tap.
63 if (AreMediaKeysRegistered())
64 StopWatchingMediaKeys();
65 }
66
67 void GlobalShortcutListenerMac::StartListening() {
68 DCHECK(!is_listening_); // Don't start twice.
69 DCHECK(!hotkey_ids_.empty()); // Don't start if no hotkey registered.
70 DCHECK(!id_hotkeys_.empty());
71 is_listening_ = true;
72 }
73
74 void GlobalShortcutListenerMac::StopListening() {
75 DCHECK(is_listening_); // No point if we are not already listening.
76 DCHECK(hotkey_ids_.empty()); // Make sure the set is clean.
77 DCHECK(id_hotkeys_.empty());
78 is_listening_ = false;
79 }
80
81 bool GlobalShortcutListenerMac::OnKeyEvent(EventHotKeyID hotkey_id) {
82 // Look up the accelerator based on this hot key ID.
83 VLOG(0) << "OnKeyEvent! hotkey_id: " << hotkey_id.id;
84 ui::Accelerator accelerator = id_hotkeys_[hotkey_id.id];
Robert Sesek 2013/11/22 16:49:59 Can this be a const& type?
smus 2013/11/22 20:48:09 Done.
85 VLOG(0) << "Key code: " << accelerator.key_code()
86 << " modifiers: " << accelerator.modifiers();
87 NotifyKeyPressed(accelerator);
88 return true;
89 }
90
91 bool GlobalShortcutListenerMac::OnMediaKeyEvent(int media_key_code) {
92 ui::KeyboardCode key_code = MediaKeyCodeToKeyboardCode(media_key_code);
93 VLOG(0) << "OnMediaKeyEvent! keyCode: " << key_code;
94 // Create an accelerator corresponding to the keyCode.
95 ui::Accelerator accelerator(key_code, 0);
96 // Look for a match with a bound hotkey.
97 if (hotkey_ids_.find(accelerator) != hotkey_ids_.end()) {
98 // If matched, callback to the event handling system.
99 NotifyKeyPressed(accelerator);
100 return true;
101 }
102 return false;
103 }
104
105 void GlobalShortcutListenerMac::RegisterAccelerator(
106 const ui::Accelerator& accelerator,
107 GlobalShortcutListener::Observer* observer) {
108 VLOG(0) << "Registered keyCode: " << accelerator.key_code()
109 << ", modifiers: " << accelerator.modifiers();
110
111 // If this is the first media key registered, start the event tap.
112 if (IsMediaKey(accelerator) && !AreMediaKeysRegistered()) {
113 VLOG(0) << "Registered the first media key, so starting event tap.";
114 StartWatchingMediaKeys();
115 }
116
117 // Register hotkey if they are non-media keyboard shortcuts.
118 if (!IsMediaKey(accelerator))
119 RegisterHotKey(accelerator);
120
121 // Store the hotkey-ID mappings we will need for lookup later.
122 id_hotkeys_[hotkey_id_] = accelerator;
123 hotkey_ids_[accelerator] = hotkey_id_;
124 ++hotkey_id_;
125 GlobalShortcutListener::RegisterAccelerator(accelerator, observer);
126 }
127
128 void GlobalShortcutListenerMac::UnregisterAccelerator(
129 const ui::Accelerator& accelerator,
130 GlobalShortcutListener::Observer* observer) {
131 // Unregister the hotkey if it's a keyboard shortcut.
132 if (!IsMediaKey(accelerator))
133 UnregisterHotKey(accelerator);
134
135 // Remove hotkey from the mappings.
136 int id = hotkey_ids_[accelerator];
137 id_hotkeys_.erase(id);
138 hotkey_ids_.erase(accelerator);
139 GlobalShortcutListener::UnregisterAccelerator(accelerator, observer);
140
141 // If we unregistered a media key, and now if no media keys are registered,
142 // stop the media key tap.
143 if (IsMediaKey(accelerator) && !AreMediaKeysRegistered()) {
144 VLOG(0) << "Unregistered the last media key, stopping event tap.";
145 StopWatchingMediaKeys();
146 }
147 }
148
149 void GlobalShortcutListenerMac::RegisterHotKey(
150 const ui::Accelerator& accelerator) {
151 VLOG(0) << "Registering hotkey. Windows keycode: " << accelerator.key_code();
152 EventHotKeyRef hotkey_ref;
153 EventHotKeyID event_hotkey_id;
154 EventHandlerUPP hotkey_function = NewEventHandlerUPP(HotKeyHandler);
155
156 EventTypeSpec event_type;
157 event_type.eventClass = kEventClassKeyboard;
158 event_type.eventKind = kEventHotKeyPressed;
159 InstallApplicationEventHandler(hotkey_function, 1, &event_type, this, NULL);
160
161 // Signature uniquely identifies the application that owns this hotkey.
162 event_hotkey_id.signature = 'rimZ';
163 event_hotkey_id.id = hotkey_id_;
164
165 // Translate ui::Accelerator modifiers to cmdKey, altKey, etc.
166 int modifiers = 0;
167 modifiers += (accelerator.IsShiftDown() ? shiftKey : 0);
168 modifiers += (accelerator.IsCtrlDown() ? controlKey : 0);
169 modifiers += (accelerator.IsAltDown() ? optionKey : 0);
170 modifiers += (accelerator.IsCmdDown() ? cmdKey : 0);
171
172 unichar character;
173 unichar character_nomods;
174 int key_code = ui::MacKeyCodeForWindowsKeyCode(accelerator.key_code(), 0,
175 &character, &character_nomods);
176 VLOG(0) << "RegisterHotKey. Code: " << key_code << " modifier: " << modifiers;
177
178 // Register the event hot key.
179 RegisterEventHotKey(key_code, modifiers, event_hotkey_id,
180 GetApplicationEventTarget(), 0, &hotkey_ref);
181
182 // Note: hotkey_id_ will be incremented in the caller (RegisterAccelerator).
183 id_hotkey_refs_[hotkey_id_] = hotkey_ref;
184 }
185
186 void GlobalShortcutListenerMac::UnregisterHotKey(
187 const ui::Accelerator& accelerator) {
188 // Get the ref corresponding to this accelerator.
189 int id = hotkey_ids_[accelerator];
190 EventHotKeyRef ref = id_hotkey_refs_[id];
191 // Unregister the event hot key.
192 UnregisterEventHotKey(ref);
193
194 // Remove the event from the mapping.
195 id_hotkey_refs_.erase(id);
196 }
197
198 void GlobalShortcutListenerMac::StartWatchingMediaKeys() {
199 VLOG(0) << "StartWatchingMediaKeys";
200 // Make sure there's no existing event tap.
201 DCHECK(event_tap_ == NULL);
202
203 // Add an event tap to intercept the system defined media key events.
204 event_tap_ = CGEventTapCreate(kCGSessionEventTap,
205 kCGHeadInsertEventTap,
206 kCGEventTapOptionDefault,
207 CGEventMaskBit(NX_SYSDEFINED),
208 EventTapCallback,
209 this);
210 if (event_tap_ == NULL) {
211 LOG(ERROR) << "Error: failed to create event tap.";
212 return;
213 }
214
215 event_tap_source_ = CFMachPortCreateRunLoopSource(kCFAllocatorSystemDefault,
216 event_tap_, 0);
217 if (event_tap_source_ == NULL) {
218 LOG(ERROR) << "Error: failed to create new run loop source.";
219 return;
220 }
221
222 CFRunLoopAddSource(CFRunLoopGetCurrent(), event_tap_source_,
223 kCFRunLoopCommonModes);
224 }
225
226 void GlobalShortcutListenerMac::StopWatchingMediaKeys() {
227 VLOG(0) << "StopWatchingMediaKeys";
228 // Invalidate the event tap.
229 DCHECK(event_tap_ != NULL);
230 CFMachPortInvalidate(event_tap_);
231 CFRelease(event_tap_);
232 event_tap_ = NULL;
233
234 // Release the event tap source.
235 DCHECK(event_tap_source_ != NULL);
236 CFRelease(event_tap_source_);
237 event_tap_source_ = NULL;
238 }
239
240 ui::KeyboardCode GlobalShortcutListenerMac::MediaKeyCodeToKeyboardCode(
241 int keyCode) {
242 switch (keyCode) {
243 case NX_KEYTYPE_PLAY:
244 return ui::VKEY_MEDIA_PLAY_PAUSE;
245 case NX_KEYTYPE_PREVIOUS:
246 case NX_KEYTYPE_REWIND:
247 return ui::VKEY_MEDIA_PREV_TRACK;
248 case NX_KEYTYPE_NEXT:
249 case NX_KEYTYPE_FAST:
250 return ui::VKEY_MEDIA_NEXT_TRACK;
251 }
252 return ui::VKEY_UNKNOWN;
253 }
254
255 // TODO(smus): switch over to the cross-platform version of this method.
zhchbin 2013/11/22 08:08:16 Check in my CL just now: https://codereview.chromi
smus 2013/11/22 20:48:09 Thanks, switched to it.
256 bool GlobalShortcutListenerMac::IsMediaKey(const ui::Accelerator& accelerator) {
257 // Assume all keys are hot keys unless they have a modifier.
258 return accelerator.modifiers() == 0;
259 }
260
261 bool GlobalShortcutListenerMac::AreMediaKeysRegistered() {
262 // Iterate through registered accelerators, looking for media keys.
263 HotKeyIdMap::iterator iter;
264 for (iter = hotkey_ids_.begin(); iter != hotkey_ids_.end(); ++iter) {
265 if (IsMediaKey(iter->first))
266 return true;
267 }
268 return false;
269 }
270
271 void GlobalShortcutListenerMac::EnableTap() {
272 CGEventTapEnable(event_tap_, TRUE);
273 }
274
275 // Processed events should propagate if they aren't handled by any listeners.
276 // For events that don't matter, this handler should return as quickly as
277 // possible.
278
Robert Sesek 2013/11/22 16:49:59 nit: remove blank line (or insert // to keep it as
smus 2013/11/22 20:48:09 Done.
279 // Returning event causes the event to propagate to other applications.
280 // Returning NULL prevents the event from propagating.
281 CGEventRef GlobalShortcutListenerMac::EventTapCallback(
Robert Sesek 2013/11/22 16:49:59 // static above this
smus 2013/11/22 20:48:09 Done.
282 CGEventTapProxy proxy, CGEventType type, CGEventRef event, void* refcon) {
283 GlobalShortcutListenerMac* shortcut_listener =
284 static_cast<GlobalShortcutListenerMac*>(refcon);
285
286 // Handle the timeout case by re-enabling the tap.
287 if (type == kCGEventTapDisabledByTimeout) {
288 LOG(INFO) << "Event tap was disabled by a timeout.";
289 shortcut_listener->EnableTap();
290 return event;
291 }
292
293 // TODO(smus): do some error handling since eventWithCGEvent can fail.
294 NSEvent* ns_event = [NSEvent eventWithCGEvent:event];
295
296 // Ignore events that are not system defined media keys.
297 if (type != NX_SYSDEFINED ||
298 [ns_event subtype] != kSystemDefinedEventMediaKeys) {
299 return event;
300 }
301
302 NSInteger data1 = [ns_event data1];
303 // Ignore media keys that aren't previous, next and play/pause.
304 int key_code = ((data1 & 0xFFFF0000) >> 16);
305 if (key_code != NX_KEYTYPE_PLAY && key_code != NX_KEYTYPE_NEXT &&
306 key_code != NX_KEYTYPE_PREVIOUS && key_code != NX_KEYTYPE_FAST &&
307 key_code != NX_KEYTYPE_REWIND) {
308 return event;
309 }
310
311 int key_flags = (data1 & 0x0000FFFF);
312 bool is_key_pressed = (((key_flags & 0xFF00) >> 8)) == 0xA;
313
314 // If the key wasn't pressed (eg. was released), ignore this event.
315 if (!is_key_pressed)
316 return event;
317
318 // Now we have a media key that we care about. Send it to the caller.
319 bool was_handled = shortcut_listener->OnMediaKeyEvent(key_code);
320
321 // Prevent event from proagating to other apps if handled by Chrome.
322 if (was_handled)
323 return NULL;
324
325 // By default, pass the event through.
326 return event;
327 }
328
329 } // namespace extensions
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698