Index: chrome/browser/extensions/global_shortcut_listener_mac.mm |
=================================================================== |
--- chrome/browser/extensions/global_shortcut_listener_mac.mm (revision 0) |
+++ chrome/browser/extensions/global_shortcut_listener_mac.mm (working copy) |
@@ -0,0 +1,382 @@ |
+// Copyright (c) 2013 The Chromium Authors. All rights reserved. |
+// Use of this source code is governed by a BSD-style license that can be |
+// found in the LICENSE file. |
+ |
+#include "chrome/browser/extensions/global_shortcut_listener_mac.h" |
+ |
+#import <Cocoa/Cocoa.h> |
Robert Sesek
2013/11/19 18:34:58
#include and using blocks should be alphabetized.
smus
2013/11/20 04:28:51
Done.
|
+#include <IOKit/hidsystem/ev_keymap.h> |
+#include <ApplicationServices/ApplicationServices.h> |
+ |
+#include "content/public/browser/browser_thread.h" |
+#include "ui/events/event.h" |
+#include "ui/base/accelerators/accelerator.h" |
+#import "ui/events/keycodes/keyboard_code_conversion_mac.h" |
+ |
+const int SYSTEM_DEFINED_EVENT_MEDIA_KEYS = 8; |
+ |
+#define EVENT_KEY @"event" |
Robert Sesek
2013/11/19 18:34:58
These are still #defines. This should be:
namespa
smus
2013/11/20 04:28:51
Done.
|
+#define HANDLED_KEY @"handled" |
+ |
+using extensions::GlobalShortcutListenerMac; |
Robert Sesek
2013/11/19 18:34:58
Alphabetize.
smus
2013/11/20 04:28:51
Done.
|
+using content::BrowserThread; |
+ |
+@interface GlobalShortcutListenerTap : NSObject { |
+ |
+ @private |
Robert Sesek
2013/11/19 18:34:58
nit: one space indent, just like C++
smus
2013/11/20 04:28:51
Done.
|
+ CFMachPortRef eventTap_; |
+ CFRunLoopSourceRef eventTapSource_; |
+ CFRunLoopRef tapThreadRunLoop_; |
+ GlobalShortcutListenerMac* shortcutListener_; |
+} |
+ |
+- (id)initWithShortcutListener:(GlobalShortcutListenerMac*)shortcutListener; |
+- (void)startWatchingMediaKeys; |
+- (void)stopWatchingMediaKeys; |
+- (void)handleMediaKeyEvent:(NSEvent*)event; |
+- (BOOL)performEventHandlerOnMainThread:(SEL)selector withEvent:(NSEvent*)event; |
+- (void)enableTap; |
+ |
+@end |
+ |
+// Processed events should propagate if they aren't handled by any listeners. |
+// Returning event causes the event to propagate to other applications. |
+// Returning NULL prevents the event from propagating. |
+CGEventRef TapEventCallback( |
Robert Sesek
2013/11/19 18:34:58
Actually, this should probably be EventTapCallback
smus
2013/11/20 04:28:51
Done.
|
+ CGEventTapProxy proxy, CGEventType type, CGEventRef event, void* refcon) { |
+ NSAutoreleasePool* pool = [NSAutoreleasePool new]; |
+ CGEventRef out_event = event; |
+ |
+ GlobalShortcutListenerTap* self = |
+ static_cast<GlobalShortcutListenerTap*>(refcon); |
+ |
+ // Handle the timeout case by re-enabling the tap. |
+ if (type == kCGEventTapDisabledByTimeout) { |
+ LOG(INFO) << "Event tap was disabled by a timeout."; |
+ [self enableTap]; |
+ // Release the event as soon as possible. |
+ return out_event; |
+ } |
+ |
+ // TODO(smus): do some error handling since eventWithCGEvent can fail. |
+ NSEvent* ns_event = [NSEvent eventWithCGEvent:event]; |
+ |
+ // Handle media keys (PlayPause, NextTrack, PreviousTrack). |
+ if (type != NX_SYSDEFINED || |
+ [ns_event subtype] != SYSTEM_DEFINED_EVENT_MEDIA_KEYS) { |
+ int key_code = (([ns_event data1] & 0xFFFF0000) >> 16); |
+ if (key_code != NX_KEYTYPE_PLAY && key_code != NX_KEYTYPE_NEXT && |
+ key_code != NX_KEYTYPE_PREVIOUS && key_code != NX_KEYTYPE_FAST && |
+ key_code != NX_KEYTYPE_REWIND) { |
+ // Release the event as soon as possible. |
+ return out_event; |
+ } |
+ } |
+ |
+ // If we got here, we are dealing with a real media key event. |
+ BOOL was_handled = [self |
+ performEventHandlerOnMainThread:@selector(handleMediaKeyEvent:) |
+ withEvent:ns_event]; |
+ // Prevent the event from proagating to other mac applications if it was |
+ // handled by Chrome. |
+ if (was_handled) |
+ out_event = NULL; |
+ |
+ [pool drain]; |
+ // By default, pass the event through. |
+ return out_event; |
+} |
+ |
+OSStatus HotKeyHandler(EventHandlerCallRef next_handler, EventRef event, |
Finnur
2013/11/19 13:10:05
nit: I think style-wise we prefer:
void func(
F
smus
2013/11/20 04:28:51
Done.
|
+ void *user_data) { |
+ VLOG(0) << "HotKeyHandler fired with event: " << event; |
+ // Extract the hotkey from the event. |
+ EventHotKeyID hotkey_id; |
+ int result = GetEventParameter(event, kEventParamDirectObject, |
+ typeEventHotKeyID, NULL, sizeof(hotkey_id), NULL, &hotkey_id); |
+ if (result != noErr) { |
+ return result; |
+ } |
Finnur
2013/11/19 13:10:05
nit: Single line if.
smus
2013/11/20 04:28:51
Done.
|
+ |
+ // Callback to the parent class. |
+ GlobalShortcutListenerMac* shortcutListener = |
+ static_cast<GlobalShortcutListenerMac*>(user_data); |
+ shortcutListener->OnKeyEvent(hotkey_id); |
+ return noErr; |
+} |
+ |
+@implementation GlobalShortcutListenerTap |
+ |
+- (id)initWithShortcutListener:(GlobalShortcutListenerMac*)shortcutListener{ |
+ if ((self = [super init])) { |
+ shortcutListener_ = shortcutListener; |
+ } |
Finnur
2013/11/19 13:10:05
nit: Single line if.
smus
2013/11/20 04:28:51
Done.
|
+ return self; |
+} |
+ |
+- (void)eventTapThread { |
+ tapThreadRunLoop_ = CFRunLoopGetCurrent(); |
+ CFRunLoopAddSource(tapThreadRunLoop_, eventTapSource_, |
+ kCFRunLoopCommonModes); |
+ CFRunLoopRun(); |
+} |
+ |
+- (BOOL)performEventHandlerOnMainThread:(SEL)selector |
+ withEvent:(NSEvent*)event { |
+ NSMutableDictionary* dict = [[NSMutableDictionary alloc] init]; |
+ [dict setObject:event forKey:EVENT_KEY]; |
+ [self performSelectorOnMainThread:selector |
+ withObject:dict waitUntilDone:YES]; |
+ // Keep track of the result from the main thread to know if the event has |
+ // been handled. |
+ BOOL was_handled = [[dict objectForKey:HANDLED_KEY] boolValue]; |
+ [dict release]; |
+ return was_handled; |
+} |
+ |
+- (ui::KeyboardCode)mediaKeyCodeToKeyboardCode:(int)keyCode { |
+ switch (keyCode) { |
+ case NX_KEYTYPE_PLAY: |
+ return ui::VKEY_MEDIA_PLAY_PAUSE; |
+ case NX_KEYTYPE_PREVIOUS: |
+ case NX_KEYTYPE_REWIND: |
+ return ui::VKEY_MEDIA_PREV_TRACK; |
+ case NX_KEYTYPE_NEXT: |
+ case NX_KEYTYPE_FAST: |
+ return ui::VKEY_MEDIA_NEXT_TRACK; |
+ } |
+ return ui::VKEY_UNKNOWN; |
+} |
+ |
+- (void)startWatchingMediaKeys { |
+ // Make sure there's no existing event tap. |
+ if (eventTap_ != NULL) { |
+ LOG(ERROR) << "Error watching media keys: existing event tap found."; |
+ return; |
+ } |
+ |
+ // Add an event tap to intercept the system defined media key events. |
+ eventTap_ = CGEventTapCreate(kCGSessionEventTap, |
+ kCGHeadInsertEventTap, |
+ kCGEventTapOptionDefault, |
+ CGEventMaskBit(NX_SYSDEFINED), |
+ TapEventCallback, |
+ self); |
+ if (eventTap_ == NULL) { |
+ LOG(ERROR) << "Error watching media keys: failed to create event tap."; |
+ return; |
+ } |
+ |
+ eventTapSource_ = CFMachPortCreateRunLoopSource(kCFAllocatorSystemDefault, |
+ eventTap_, 0); |
+ if (eventTapSource_ == NULL) { |
+ LOG(ERROR) << |
+ "Error watching media keys: failed to create new run loop source."; |
+ return; |
+ } |
+ |
+ VLOG(0) << "Starting media key event tap."; |
+ // Run the event tap in separate thread to prevent blocking UI. |
+ [NSThread detachNewThreadSelector:@selector(eventTapThread) |
+ toTarget:self withObject:nil]; |
+} |
+ |
+- (void)stopWatchingMediaKeys { |
+ if (tapThreadRunLoop_) { |
Finnur
2013/11/19 13:10:05
Under what circumstances can these be nil when you
smus
2013/11/20 04:28:51
Done.
|
+ CFRunLoopStop(tapThreadRunLoop_); |
+ tapThreadRunLoop_ = nil; |
+ } |
+ |
+ if (eventTap_) { |
+ CFMachPortInvalidate(eventTap_); |
+ CFRelease(eventTap_); |
+ eventTap_ = nil; |
+ } |
+ |
+ if (eventTapSource_) { |
+ CFRelease(eventTapSource_); |
+ eventTapSource_ = nil; |
+ } |
+} |
+ |
+// Event will have been retained in the other thread. |
+- (void)handleMediaKeyEvent:(NSMutableDictionary*)dict { |
+ NSEvent* event = [dict objectForKey:EVENT_KEY]; |
+ |
+ int key_code = (([event data1] & 0xFFFF0000) >> 16); |
+ int key_flags = ([event data1] & 0x0000FFFF); |
+ BOOL is_key_pressed = (((key_flags & 0xFF00) >> 8)) == 0xA; |
+ |
+ bool result = false; |
+ if (is_key_pressed) { |
+ result = shortcutListener_->OnMediaKeyEvent( |
+ [self mediaKeyCodeToKeyboardCode:key_code]); |
+ } |
+ |
+ [dict setObject:[NSNumber numberWithBool:result] forKey:HANDLED_KEY]; |
+} |
+ |
+- (void)enableTap { |
+ CGEventTapEnable(eventTap_, TRUE); |
+} |
+ |
+@end |
+ |
+namespace { |
+ |
+static base::LazyInstance<extensions::GlobalShortcutListenerMac> g_instance = |
+ LAZY_INSTANCE_INITIALIZER; |
+ |
+} // namespace |
+ |
+namespace extensions { |
+ |
+// static |
+GlobalShortcutListener* GlobalShortcutListener::GetInstance() { |
+ CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); |
+ return g_instance.Pointer(); |
+} |
+ |
+GlobalShortcutListenerMac::GlobalShortcutListenerMac() |
+ : is_listening_(false) { |
+ CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); |
+ |
+ tap_.reset([[GlobalShortcutListenerTap alloc] initWithShortcutListener:this]); |
+} |
+ |
+GlobalShortcutListenerMac::~GlobalShortcutListenerMac() { |
+ if (is_listening_) |
+ StopListening(); |
+} |
+ |
+void GlobalShortcutListenerMac::StartListening() { |
+ DCHECK(!is_listening_); // Don't start twice. |
+ DCHECK(!hotkey_ids_.empty()); // Don't start if no hotkey registered. |
+ DCHECK(!id_hotkeys_.empty()); |
+ DCHECK(!id_hotkey_refs_.empty()); |
+ is_listening_ = true; |
+ |
+ // Start an event tap for observing media keys. Regular keyboard shortcuts |
+ // are registered via RegisterEventHotKey. |
+ [tap_ startWatchingMediaKeys]; |
+} |
+ |
+void GlobalShortcutListenerMac::StopListening() { |
+ DCHECK(is_listening_); // No point if we are not already listening. |
+ DCHECK(hotkey_ids_.empty()); // Make sure the set is clean. |
+ DCHECK(id_hotkeys_.empty()); |
+ DCHECK(id_hotkey_refs_.empty()); |
+ is_listening_ = false; |
+ |
+ [tap_ stopWatchingMediaKeys]; |
+} |
+ |
+void GlobalShortcutListenerMac::RegisterAccelerator( |
+ const ui::Accelerator& accelerator, |
+ GlobalShortcutListener::Observer* observer) { |
+ VLOG(0) << "Registered keyCode: " << accelerator.key_code() |
+ << ", modifiers: " << accelerator.modifiers(); |
+ // Register hotkey if they are keyboard shortcuts. |
Finnur
2013/11/19 13:10:05
nit: MediaKeys are keyboard shortcuts, are they no
smus
2013/11/20 04:28:51
Done.
|
+ if (!IsMediaKey(accelerator)) |
+ RegisterHotKey(accelerator); |
+ |
+ // Store the hotkey-ID mappings we will need for lookup later. |
+ id_hotkeys_[hotkey_id_] = accelerator; |
+ hotkey_ids_[accelerator] = hotkey_id_; |
+ hotkey_id_ += 1; |
+ GlobalShortcutListener::RegisterAccelerator(accelerator, observer); |
+} |
+ |
+void GlobalShortcutListenerMac::UnregisterAccelerator( |
+ const ui::Accelerator& accelerator, |
+ GlobalShortcutListener::Observer* observer) { |
+ // Unregister the hotkey if it's a keyboard shortcut. |
+ if (!IsMediaKey(accelerator)) |
+ UnregisterHotKey(accelerator); |
+ |
+ // Remove hotkey from the mappings. |
+ int id = hotkey_ids_[accelerator]; |
+ id_hotkeys_.erase(id); |
+ hotkey_ids_.erase(accelerator); |
+ GlobalShortcutListener::UnregisterAccelerator(accelerator, observer); |
+} |
+ |
+bool GlobalShortcutListenerMac::OnKeyEvent(EventHotKeyID hotKeyID) { |
+ // Look up the accelerator based on this hot key ID. |
+ VLOG(0) << "OnKeyEvent! hotKeyID: " << hotKeyID.id; |
+ ui::Accelerator accelerator = id_hotkeys_[hotKeyID.id]; |
+ VLOG(0) << "Key code: " << accelerator.key_code() << |
+ " modifiers: " << accelerator.modifiers(); |
+ NotifyKeyPressed(accelerator); |
+ return true; |
+} |
+ |
+bool GlobalShortcutListenerMac::IsMediaKey(const ui::Accelerator& accelerator) { |
+ // Assume all keys are hot keys unless they have a modifier. |
+ return accelerator.modifiers() == 0; |
+} |
+ |
+// Returns true iff event was handled. |
+bool GlobalShortcutListenerMac::OnMediaKeyEvent(ui::KeyboardCode keyCode) { |
+ VLOG(0) << "OnMediaKeyEvent! keyCode: " << keyCode; |
+ // Create an accelerator corresponding to the keyCode. |
+ ui::Accelerator accelerator(keyCode, 0); |
+ // Look for a match with a bound hotkey. |
+ if (hotkey_ids_.find(accelerator) != hotkey_ids_.end()) { |
+ // If matched, callback to the event handling system. |
+ NotifyKeyPressed(accelerator); |
+ return true; |
+ } |
+ return false; |
+} |
+ |
+void GlobalShortcutListenerMac::RegisterHotKey( |
+ const ui::Accelerator& accelerator) { |
+ VLOG(0) << "Registering hotkey. Windows keycode: " << accelerator.key_code(); |
+ EventHotKeyRef hotkey_ref; |
+ EventHotKeyID event_hotkey_id; |
+ EventHandlerUPP hotkey_function = NewEventHandlerUPP(HotKeyHandler); |
+ |
+ EventTypeSpec event_type; |
+ event_type.eventClass = kEventClassKeyboard; |
+ event_type.eventKind = kEventHotKeyPressed; |
+ InstallApplicationEventHandler(hotkey_function, 1, &event_type, this, NULL); |
+ |
+ // Signature uniquely identifies the application that owns this hotkey. |
+ event_hotkey_id.signature = 'chro'; |
+ event_hotkey_id.id = hotkey_id_; |
+ |
+ // Translate ui::Accelerator modifiers to cmdKey, altKey, etc. |
+ int modifiers = 0; |
+ modifiers += (accelerator.IsShiftDown() ? shiftKey : 0); |
+ modifiers += (accelerator.IsCtrlDown() ? controlKey : 0); |
+ modifiers += (accelerator.IsAltDown() ? optionKey : 0); |
+ modifiers += (accelerator.IsCmdDown() ? cmdKey : 0); |
+ |
+ unichar character; |
+ unichar character_nomods; |
+ int key_code = ui::MacKeyCodeForWindowsKeyCode(accelerator.key_code(), 0, |
+ &character, &character_nomods); |
+ VLOG(0) << "RegisterHotKey. Code: " << key_code << " modifier: " << modifiers; |
+ |
+ // Register the event hot key. |
+ RegisterEventHotKey(key_code, modifiers, event_hotkey_id, |
+ GetApplicationEventTarget(), 0, &hotkey_ref); |
+ |
+ // Note: hotkey_id_ will be incremented in the caller (RegisterAccelerator). |
+ id_hotkey_refs_[hotkey_id_] = hotkey_ref; |
+} |
+ |
+void GlobalShortcutListenerMac::UnregisterHotKey( |
+ const ui::Accelerator& accelerator) { |
+ // Get the ref corresponding to this accelerator. |
+ int id = hotkey_ids_[accelerator]; |
+ EventHotKeyRef ref = id_hotkey_refs_[id]; |
+ // Unregister the event hot key. |
+ UnregisterEventHotKey(ref); |
+ |
+ // Remove the event from the mapping. |
+ id_hotkey_refs_.erase(id); |
+} |
+ |
+} // namespace extensions |