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

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

Powered by Google App Engine
This is Rietveld 408576698