Chromium Code Reviews| 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,403 @@ |
| +// 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> |
| +#include <ApplicationServices/ApplicationServices.h> |
|
Robert Sesek
2013/11/20 16:23:57
nit: alphabetize by header name, not by #include v
smus
2013/11/20 17:50:54
Done.
|
| +#include <IOKit/hidsystem/ev_keymap.h> |
| + |
| +#import "ui/events/keycodes/keyboard_code_conversion_mac.h" |
| +#include "content/public/browser/browser_thread.h" |
| +#include "ui/base/accelerators/accelerator.h" |
| +#include "ui/events/event.h" |
| + |
| +namespace { |
| + // The media keys subtype. |
|
Robert Sesek
2013/11/20 16:23:57
nit: no indenting in namespaces, and blank lines b
smus
2013/11/20 17:50:54
Done.
|
| + const int SYSTEM_DEFINED_EVENT_MEDIA_KEYS = 8; |
| + // A key for the media key NSEvent that is passed. |
| + NSString* const kShortcutListenerEventKey = @"event"; |
| + // A key for whether or not the media event was handled. |
| + NSString* const kShortcutListenerHandledKey = @"handled"; |
| +} |
| + |
| +using content::BrowserThread; |
| +using extensions::GlobalShortcutListenerMac; |
| + |
| +@interface GlobalShortcutListenerTap : NSObject { |
| + |
|
Robert Sesek
2013/11/20 16:23:57
nit: no blank line
smus
2013/11/20 17:50:54
Done.
|
| + @private |
| + 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 EventTapCallback( |
|
Robert Sesek
2013/11/20 16:23:57
These should be in the anonymous namespace, too.
smus
2013/11/20 17:50:54
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, 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; |
| + |
| + // Callback to the parent class. |
| + GlobalShortcutListenerMac* shortcutListener = |
|
Robert Sesek
2013/11/20 16:23:57
naming: shortcut_listener
smus
2013/11/20 17:50:54
Done.
|
| + static_cast<GlobalShortcutListenerMac*>(user_data); |
| + shortcutListener->OnKeyEvent(hotkey_id); |
| + return noErr; |
| +} |
| + |
| +@implementation GlobalShortcutListenerTap |
| + |
| +- (id)initWithShortcutListener:(GlobalShortcutListenerMac*)shortcutListener{ |
| + if ((self = [super init])) |
| + shortcutListener_ = shortcutListener; |
| + 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:kShortcutListenerEventKey]; |
| + [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:kShortcutListenerHandledKey] 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), |
| + EventTapCallback, |
| + 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 { |
| + // Stop the event tap thread. |
| + DCHECK(tapThreadRunLoop_ != nil); |
| + CFRunLoopStop(tapThreadRunLoop_); |
| + tapThreadRunLoop_ = nil; |
| + |
| + // Invalidate the event tap. |
| + DCHECK(eventTap_ != nil); |
| + CFMachPortInvalidate(eventTap_); |
| + CFRelease(eventTap_); |
| + eventTap_ = nil; |
| + |
| + // Release the event tap source. |
| + DCHECK(eventTapSource_ != nil); |
| + CFRelease(eventTapSource_); |
| + eventTapSource_ = nil; |
| +} |
| + |
| +// Event will have been retained in the other thread. |
| +- (void)handleMediaKeyEvent:(NSMutableDictionary*)dict { |
| + NSEvent* event = [dict objectForKey:kShortcutListenerEventKey]; |
| + |
| + int key_code = (([event data1] & 0xFFFF0000) >> 16); |
|
Robert Sesek
2013/11/20 16:23:57
naming: in ObjC use camelCase, so keyCode
smus
2013/11/20 17:50:54
Done.
|
| + 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:kShortcutListenerHandledKey]; |
| +} |
| + |
| +- (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()); |
| + is_listening_ = true; |
| +} |
| + |
| +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()); |
| + is_listening_ = false; |
| +} |
| + |
| +void GlobalShortcutListenerMac::RegisterAccelerator( |
| + const ui::Accelerator& accelerator, |
| + GlobalShortcutListener::Observer* observer) { |
| + VLOG(0) << "Registered keyCode: " << accelerator.key_code() |
| + << ", modifiers: " << accelerator.modifiers(); |
| + |
| + // If this is the first media key registered, start the event tap. |
| + if (IsMediaKey(accelerator) && !AreMediaKeysRegistered()) { |
| + VLOG(0) << "Registered the first media key, so starting event tap."; |
| + [tap_ startWatchingMediaKeys]; |
| + } |
| + |
| + // Register hotkey if they are non-media keyboard shortcuts. |
| + 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); |
| + |
| + // Now if no media keys are registered, stop the media key tap. |
| + if (!AreMediaKeysRegistered()) { |
| + VLOG(0) << "Unregistered the last media key, stopping event tap."; |
| + [tap_ stopWatchingMediaKeys]; |
| + } |
| +} |
| + |
| +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; |
| +} |
| + |
| +// TODO(smus): switch over to the cross-platform version of this method. |
| +bool GlobalShortcutListenerMac::IsMediaKey(const ui::Accelerator& accelerator) { |
| + // Assume all keys are hot keys unless they have a modifier. |
| + return accelerator.modifiers() == 0; |
| +} |
| + |
| +bool GlobalShortcutListenerMac::AreMediaKeysRegistered() { |
| + // Iterate through registered accelerators, looking for media keys. |
| + HotKeyIdMap::iterator iter; |
| + for (iter = hotkey_ids_.begin(); iter != hotkey_ids_.end(); ++iter) { |
| + if (IsMediaKey(iter->first)) { |
| + return true; |
| + } |
|
Finnur
2013/11/20 12:33:55
nit: Single-line if. Hard habit to break, eh? :)
smus
2013/11/20 17:50:54
Done.
|
| + } |
| + return false; |
| +} |
| + |
| +// 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 |