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

Unified 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 side-by-side diff with in-line comments
Download patch
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,329 @@
+// 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"
+
+#include <ApplicationServices/ApplicationServices.h>
+#import <Cocoa/Cocoa.h>
+#include <IOKit/hidsystem/ev_keymap.h>
+
+#include "content/public/browser/browser_thread.h"
+#include "ui/base/accelerators/accelerator.h"
+#include "ui/events/event.h"
+#import "ui/events/keycodes/keyboard_code_conversion_mac.h"
+
+using content::BrowserThread;
+using extensions::GlobalShortcutListenerMac;
+
+namespace {
+
+// The media keys subtype.
+const int kSystemDefinedEventMediaKeys = 8;
+
+OSStatus HotKeyHandler(
+ EventHandlerCallRef next_handler, EventRef event, void* user_data) {
+ 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
+ // 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;
+
+ GlobalShortcutListenerMac* shortcut_listener =
+ static_cast<GlobalShortcutListenerMac*>(user_data);
+ shortcut_listener->OnKeyEvent(hotkey_id);
+ return noErr;
+}
+
+static base::LazyInstance<extensions::GlobalShortcutListenerMac> g_instance =
+ LAZY_INSTANCE_INITIALIZER;
+
+} // namespace
Robert Sesek 2013/11/22 16:49:59 nit: two spaces before //
smus 2013/11/22 20:48:09 Done.
+
+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));
+}
+
+GlobalShortcutListenerMac::~GlobalShortcutListenerMac() {
+ if (is_listening_)
+ StopListening();
+
+ // If media keys are still registered, make sure we stop the tap.
+ if (AreMediaKeysRegistered())
+ StopWatchingMediaKeys();
+}
+
+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;
+}
+
+bool GlobalShortcutListenerMac::OnKeyEvent(EventHotKeyID hotkey_id) {
+ // Look up the accelerator based on this hot key ID.
+ VLOG(0) << "OnKeyEvent! hotkey_id: " << hotkey_id.id;
+ 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.
+ VLOG(0) << "Key code: " << accelerator.key_code()
+ << " modifiers: " << accelerator.modifiers();
+ NotifyKeyPressed(accelerator);
+ return true;
+}
+
+bool GlobalShortcutListenerMac::OnMediaKeyEvent(int media_key_code) {
+ ui::KeyboardCode key_code = MediaKeyCodeToKeyboardCode(media_key_code);
+ VLOG(0) << "OnMediaKeyEvent! keyCode: " << key_code;
+ // Create an accelerator corresponding to the keyCode.
+ ui::Accelerator accelerator(key_code, 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::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.";
+ 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_;
+ 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);
+
+ // If we unregistered a media key, and now if no media keys are registered,
+ // stop the media key tap.
+ if (IsMediaKey(accelerator) && !AreMediaKeysRegistered()) {
+ VLOG(0) << "Unregistered the last media key, stopping event tap.";
+ StopWatchingMediaKeys();
+ }
+}
+
+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 = 'rimZ';
+ 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);
+}
+
+void GlobalShortcutListenerMac::StartWatchingMediaKeys() {
+ VLOG(0) << "StartWatchingMediaKeys";
+ // Make sure there's no existing event tap.
+ DCHECK(event_tap_ == NULL);
+
+ // Add an event tap to intercept the system defined media key events.
+ event_tap_ = CGEventTapCreate(kCGSessionEventTap,
+ kCGHeadInsertEventTap,
+ kCGEventTapOptionDefault,
+ CGEventMaskBit(NX_SYSDEFINED),
+ EventTapCallback,
+ this);
+ if (event_tap_ == NULL) {
+ LOG(ERROR) << "Error: failed to create event tap.";
+ return;
+ }
+
+ event_tap_source_ = CFMachPortCreateRunLoopSource(kCFAllocatorSystemDefault,
+ event_tap_, 0);
+ if (event_tap_source_ == NULL) {
+ LOG(ERROR) << "Error: failed to create new run loop source.";
+ return;
+ }
+
+ CFRunLoopAddSource(CFRunLoopGetCurrent(), event_tap_source_,
+ kCFRunLoopCommonModes);
+}
+
+void GlobalShortcutListenerMac::StopWatchingMediaKeys() {
+ VLOG(0) << "StopWatchingMediaKeys";
+ // Invalidate the event tap.
+ DCHECK(event_tap_ != NULL);
+ CFMachPortInvalidate(event_tap_);
+ CFRelease(event_tap_);
+ event_tap_ = NULL;
+
+ // Release the event tap source.
+ DCHECK(event_tap_source_ != NULL);
+ CFRelease(event_tap_source_);
+ event_tap_source_ = NULL;
+}
+
+ui::KeyboardCode GlobalShortcutListenerMac::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;
+}
+
+// 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.
+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;
+ }
+ return false;
+}
+
+void GlobalShortcutListenerMac::EnableTap() {
+ CGEventTapEnable(event_tap_, TRUE);
+}
+
+// Processed events should propagate if they aren't handled by any listeners.
+// For events that don't matter, this handler should return as quickly as
+// possible.
+
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.
+// Returning event causes the event to propagate to other applications.
+// Returning NULL prevents the event from propagating.
+CGEventRef GlobalShortcutListenerMac::EventTapCallback(
Robert Sesek 2013/11/22 16:49:59 // static above this
smus 2013/11/22 20:48:09 Done.
+ CGEventTapProxy proxy, CGEventType type, CGEventRef event, void* refcon) {
+ GlobalShortcutListenerMac* shortcut_listener =
+ static_cast<GlobalShortcutListenerMac*>(refcon);
+
+ // Handle the timeout case by re-enabling the tap.
+ if (type == kCGEventTapDisabledByTimeout) {
+ LOG(INFO) << "Event tap was disabled by a timeout.";
+ shortcut_listener->EnableTap();
+ return event;
+ }
+
+ // TODO(smus): do some error handling since eventWithCGEvent can fail.
+ NSEvent* ns_event = [NSEvent eventWithCGEvent:event];
+
+ // Ignore events that are not system defined media keys.
+ if (type != NX_SYSDEFINED ||
+ [ns_event subtype] != kSystemDefinedEventMediaKeys) {
+ return event;
+ }
+
+ NSInteger data1 = [ns_event data1];
+ // Ignore media keys that aren't previous, next and play/pause.
+ int key_code = ((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) {
+ return event;
+ }
+
+ int key_flags = (data1 & 0x0000FFFF);
+ bool is_key_pressed = (((key_flags & 0xFF00) >> 8)) == 0xA;
+
+ // If the key wasn't pressed (eg. was released), ignore this event.
+ if (!is_key_pressed)
+ return event;
+
+ // Now we have a media key that we care about. Send it to the caller.
+ bool was_handled = shortcut_listener->OnMediaKeyEvent(key_code);
+
+ // Prevent event from proagating to other apps if handled by Chrome.
+ if (was_handled)
+ return NULL;
+
+ // By default, pass the event through.
+ return event;
+}
+
+} // namespace extensions

Powered by Google App Engine
This is Rietveld 408576698