Add SPMediaKeyTap back (#621)

This commit is contained in:
Mikalai Daronin 2021-01-06 16:46:21 +03:00 committed by GitHub
parent fb634bc2d4
commit 57709413e1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 500 additions and 9 deletions

7
3rdparty/README.md vendored
View File

@ -40,3 +40,10 @@ utf8-cpp
This is 2 header files used by taglib, but kept in a separate directory because it is maintained by others.
URL: http://utfcpp.sourceforge.net/
SPMediaKeyTap
-------------
This is used for macOS only to enable strawberry to grab global shortcuts and can safely be deleted on other
platforms.

11
3rdparty/SPMediaKeyTap/CMakeLists.txt vendored Normal file
View File

@ -0,0 +1,11 @@
set(SPMEDIAKEY-SOURCES
SPMediaKeyTap.m
)
set(SPMEDIAKEY-HEADERS
SPMediaKeyTap.h
)
ADD_LIBRARY(SPMediaKeyTap STATIC
${SPMEDIAKEY-SOURCES}
)

8
3rdparty/SPMediaKeyTap/LICENSE vendored Normal file
View File

@ -0,0 +1,8 @@
Copyright (c) 2011, Joachim Bengtsson
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Neither the name of the organization nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

12
3rdparty/SPMediaKeyTap/README.md vendored Normal file
View File

@ -0,0 +1,12 @@
SPMediaKeyTap
=============
`SPMediaKeyTap` abstracts a `CGEventHook` and other nastiness in order to give you a relatively simple API to receive media key events (prev/next/playpause, on F7 to F9 on modern MacBook Pros) exclusively, without them reaching other applications like iTunes. `SPMediaKeyTap` is clever enough to resign its exclusive lock on media keys by looking for which application was active most recently: if that application is in `SPMediaKeyTap`'s whitelist, it will resign the keys. This is similar to the behavior of Apple's applications collaborating on media key handling exclusivity, but unfortunately, Apple is not exposing any APIs allowing third-parties to join in on this collaboration.
For now, the whitelist is just a hardcoded array in `+[SPMediaKeyTap defaultMediaKeyUserBundleIdentifiers]`. If your app starts using `SPMediaKeyTap`, please [mail me](mailto:nevyn@spotify.com) your bundle ID, and I'll include it in the canonical repository. This is a bad solution; a better solution would be to use distributed notifications to collaborate in creating this whitelist at runtime. Hopefully someone'll have the time and energy to write this soon.
In `Example/SPMediaKeyTapExampleAppDelegate.m` is an example of both how you use `SPMediaKeyTap`, and how you handle the semi-private `NSEvent` subtypes involved in media keys, including on how to fall back to non-event tap handling of these events.
`SPMediaKeyTap` and other `CGEventHook`s on the event type `NSSystemDefined` is known to interfere with each other and applications doing weird stuff with mouse input, because mouse clicks are also part of the `NSSystemDefined` category. The single issue we have had reported here at Spotify is Adobe Fireworks, in which item selection stops working with `SPMediaKeyTap` is active.
`SPMediaKeyTap` requires 10.5 to work, and disables itself on 10.4.

53
3rdparty/SPMediaKeyTap/SPMediaKeyTap.h vendored Normal file
View File

@ -0,0 +1,53 @@
/*
Copyright (c) 2011, Joachim Bengtsson
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Neither the name of the organization nor the names of its contributors may
be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import <Cocoa/Cocoa.h>
#import <IOKit/hidsystem/ev_keymap.h>
// http://overooped.com/post/2593597587/mediakeys
#define SPSystemDefinedEventMediaKeys 8
@interface SPMediaKeyTap : NSObject
- (id)initWithDelegate:(id)delegate;
+ (BOOL)usesGlobalMediaKeyTap;
- (BOOL)startWatchingMediaKeys;
- (void)stopWatchingMediaKeys;
- (void)handleAndReleaseMediaKeyEvent:(NSEvent *)event;
@end
@interface NSObject (SPMediaKeyTapDelegate)
- (void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event;
@end
#ifdef __cplusplus
extern "C" {
#endif
extern NSString *kIgnoreMediaKeysDefaultsKey;
#ifdef __cplusplus
}
#endif

361
3rdparty/SPMediaKeyTap/SPMediaKeyTap.m vendored Normal file
View File

@ -0,0 +1,361 @@
/*
Copyright (c) 2011, Joachim Bengtsson
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Neither the name of the organization nor the names of its contributors may
be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Copyright (c) 2010 Spotify AB
#import "SPMediaKeyTap.h"
// Define to enable app list debug output
// #define DEBUG_SPMEDIAKEY_APPLIST 1
NSString *kIgnoreMediaKeysDefaultsKey = @"SPIgnoreMediaKeys";
@interface SPMediaKeyTap () {
CFMachPortRef _eventPort;
CFRunLoopSourceRef _eventPortSource;
CFRunLoopRef _tapThreadRL;
NSThread *_tapThread;
BOOL _shouldInterceptMediaKeyEvents;
id _delegate;
// The app that is frontmost in this list owns media keys
NSMutableArray<NSRunningApplication *> *_mediaKeyAppList;
}
- (BOOL)shouldInterceptMediaKeyEvents;
- (void)setShouldInterceptMediaKeyEvents:(BOOL)newSetting;
- (void)startWatchingAppSwitching;
- (void)stopWatchingAppSwitching;
- (void)eventTapThread;
@end
static CGEventRef tapEventCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon);
// Inspired by http://gist.github.com/546311
@implementation SPMediaKeyTap
#pragma mark -
#pragma mark Setup and teardown
- (id)initWithDelegate:(id)delegate
{
self = [super init];
if (self) {
_delegate = delegate;
[self startWatchingAppSwitching];
_mediaKeyAppList = [NSMutableArray new];
}
return self;
}
- (void)dealloc
{
[self stopWatchingMediaKeys];
[self stopWatchingAppSwitching];
[super dealloc];
}
- (void)startWatchingAppSwitching
{
// Listen to "app switched" event, so that we don't intercept media keys if we
// weren't the last "media key listening" app to be active
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self
selector:@selector(frontmostAppChanged:)
name:NSWorkspaceDidActivateApplicationNotification
object:nil];
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self
selector:@selector(appTerminated:)
name:NSWorkspaceDidTerminateApplicationNotification
object:nil];
}
- (void)stopWatchingAppSwitching
{
[[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
}
- (BOOL)startWatchingMediaKeys
{
// Prevent having multiple mediaKeys threads
[self stopWatchingMediaKeys];
[self setShouldInterceptMediaKeyEvents:YES];
// Add an event tap to intercept the system defined media key events
_eventPort = CGEventTapCreate(kCGSessionEventTap,
kCGHeadInsertEventTap,
kCGEventTapOptionDefault,
CGEventMaskBit(NX_SYSDEFINED),
tapEventCallback,
(__bridge void * __nullable)(self));
// Can be NULL if the app has no accessibility access permission
if (_eventPort == NULL)
return NO;
_eventPortSource = CFMachPortCreateRunLoopSource(kCFAllocatorSystemDefault, _eventPort, 0);
assert(_eventPortSource != NULL);
if (_eventPortSource == NULL)
return NO;
// Let's do this in a separate thread so that a slow app doesn't lag the event tap
_tapThread = [[NSThread alloc] initWithTarget:self
selector:@selector(eventTapThread)
object:nil];
[_tapThread start];
return YES;
}
- (void)stopWatchingMediaKeys
{
// Shut down tap thread
if(_tapThreadRL){
CFRunLoopStop(_tapThreadRL);
_tapThreadRL = nil;
}
// Remove tap port
if(_eventPort){
CFMachPortInvalidate(_eventPort);
CFRelease(_eventPort);
_eventPort = nil;
}
// Remove tap source
if(_eventPortSource){
CFRelease(_eventPortSource);
_eventPortSource = nil;
}
}
#pragma mark -
#pragma mark Accessors
+ (BOOL)usesGlobalMediaKeyTap
{
#ifdef _DEBUG
// breaking in gdb with a key tap inserted sometimes locks up all mouse and keyboard input forever, forcing reboot
return NO;
#else
// XXX(nevyn): MediaKey event tap doesn't work on 10.4, feel free to figure out why if you have the energy.
return
![[NSUserDefaults standardUserDefaults] boolForKey:kIgnoreMediaKeysDefaultsKey]
&& floor(NSAppKitVersionNumber) >= 949/*NSAppKitVersionNumber10_5*/;
#endif
}
+ (NSArray*)mediaKeyUserBundleIdentifiers
{
return [NSArray arrayWithObjects:
[[NSBundle mainBundle] bundleIdentifier], // your app
@"com.spotify.client",
@"com.apple.iTunes",
@"com.apple.QuickTimePlayerX",
@"com.apple.quicktimeplayer",
@"com.apple.iWork.Keynote",
@"com.apple.iPhoto",
@"org.videolan.vlc",
@"com.apple.Aperture",
@"com.plexsquared.Plex",
@"com.soundcloud.desktop",
@"org.niltsh.MPlayerX",
@"com.ilabs.PandorasHelper",
@"com.mahasoftware.pandabar",
@"com.bitcartel.pandorajam",
@"org.clementine-player.clementine",
@"fm.last.Last.fm",
@"fm.last.Scrobbler",
@"com.beatport.BeatportPro",
@"com.Timenut.SongKey",
@"com.macromedia.fireworks", // the tap messes up their mouse input
@"at.justp.Theremin",
@"ru.ya.themblsha.YandexMusic",
@"com.jriver.MediaCenter18",
@"com.jriver.MediaCenter19",
@"com.jriver.MediaCenter20",
@"co.rackit.mate",
@"com.ttitt.b-music",
@"com.beardedspice.BeardedSpice",
@"com.plug.Plug",
@"com.plug.Plug2",
@"com.netease.163music",
@"org.quodlibet.quodlibet",
nil
];
}
- (BOOL)shouldInterceptMediaKeyEvents
{
BOOL shouldIntercept = NO;
@synchronized(self) {
shouldIntercept = _shouldInterceptMediaKeyEvents;
}
return shouldIntercept;
}
- (void)pauseTapOnTapThread:(NSNumber *)yeahno
{
CGEventTapEnable(self->_eventPort, [yeahno boolValue]);
}
- (void)setShouldInterceptMediaKeyEvents:(BOOL)newSetting
{
BOOL oldSetting;
@synchronized(self) {
oldSetting = _shouldInterceptMediaKeyEvents;
_shouldInterceptMediaKeyEvents = newSetting;
}
if(_tapThreadRL && oldSetting != newSetting) {
[self performSelector:@selector(pauseTapOnTapThread:)
onThread:_tapThread
withObject:@(newSetting)
waitUntilDone:NO];
}
}
#pragma mark -
#pragma mark Event tap callbacks
// Note: method called on background thread
static CGEventRef tapEventCallback2(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon)
{
#pragma unused(proxy)
SPMediaKeyTap *self = (__bridge SPMediaKeyTap *)refcon;
if(type == kCGEventTapDisabledByTimeout) {
NSLog(@"Media key event tap was disabled by timeout");
CGEventTapEnable(self->_eventPort, TRUE);
return event;
} else if(type == kCGEventTapDisabledByUserInput) {
// Was disabled manually by -[pauseTapOnTapThread]
return event;
}
NSEvent *nsEvent = nil;
@try {
nsEvent = [NSEvent eventWithCGEvent:event];
}
@catch (NSException * e) {
NSLog(@"Strange CGEventType: %d: %@", type, e);
assert(0);
return event;
}
if (type != NX_SYSDEFINED || [nsEvent subtype] != SPSystemDefinedEventMediaKeys)
return event;
int keyCode = (([nsEvent data1] & 0xFFFF0000) >> 16);
if (keyCode != NX_KEYTYPE_PLAY && keyCode != NX_KEYTYPE_FAST && keyCode != NX_KEYTYPE_REWIND && keyCode != NX_KEYTYPE_PREVIOUS && keyCode != NX_KEYTYPE_NEXT)
return event;
if (![self shouldInterceptMediaKeyEvents])
return event;
[self performSelectorOnMainThread:@selector(handleAndReleaseMediaKeyEvent:) withObject:nsEvent waitUntilDone:NO];
return NULL;
}
static CGEventRef tapEventCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon)
{
@autoreleasepool {
CGEventRef ret = tapEventCallback2(proxy, type, event, refcon);
return ret;
}
}
- (void)handleAndReleaseMediaKeyEvent:(NSEvent *)event
{
[_delegate mediaKeyTap:self receivedMediaKeyEvent:event];
}
- (void)eventTapThread
{
_tapThreadRL = CFRunLoopGetCurrent();
CFRunLoopAddSource(_tapThreadRL, _eventPortSource, kCFRunLoopCommonModes);
CFRunLoopRun();
}
#pragma mark -
#pragma mark Task switching callbacks
- (void)mediaKeyAppListChanged
{
#ifdef DEBUG_SPMEDIAKEY_APPLIST
[self debugPrintAppList];
#endif
if([_mediaKeyAppList count] == 0)
return;
NSRunningApplication *thisApp = [NSRunningApplication currentApplication];
NSRunningApplication *otherApp = [_mediaKeyAppList firstObject];
BOOL isCurrent = [thisApp isEqual:otherApp];
[self setShouldInterceptMediaKeyEvents:isCurrent];
}
- (void)frontmostAppChanged:(NSNotification *)notification
{
NSRunningApplication *app = [notification.userInfo objectForKey:NSWorkspaceApplicationKey];
if (app.bundleIdentifier == nil)
return;
if (![[SPMediaKeyTap mediaKeyUserBundleIdentifiers] containsObject:app.bundleIdentifier])
return;
[_mediaKeyAppList removeObject:app];
[_mediaKeyAppList insertObject:app atIndex:0];
[self mediaKeyAppListChanged];
}
- (void)appTerminated:(NSNotification *)notification
{
NSRunningApplication *app = [notification.userInfo objectForKey:NSWorkspaceApplicationKey];
[_mediaKeyAppList removeObject:app];
[self mediaKeyAppListChanged];
}
#ifdef DEBUG_SPMEDIAKEY_APPLIST
- (void)debugPrintAppList
{
NSMutableString *list = [NSMutableString stringWithCapacity:255];
for (NSRunningApplication *app in _mediaKeyAppList) {
[list appendFormat:@" - %@\n", app.bundleIdentifier];
}
NSLog(@"List: \n%@", list);
}
#endif
@end

View File

@ -265,6 +265,9 @@ set(SINGLECOREAPPLICATION_LIBRARIES singlecoreapplication)
if(APPLE)
find_library(SPARKLE Sparkle)
add_subdirectory(3rdparty/SPMediaKeyTap)
set(SPMEDIAKEYTAP_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/3rdparty/SPMediaKeyTap)
set(SPMEDIAKEYTAP_LIBRARIES SPMediaKeyTap)
endif(APPLE)
if(NOT SPARKLE AND (APPLE OR WIN32))

5
debian/copyright vendored
View File

@ -359,6 +359,11 @@ Files: src/widgets/qsearchfield_nonmac.cpp
Copyright: 2011, Mike McQuaid <mike@mikemcquaid.com>
License: Expat
Files: 3rdparty/SPMediaKeyTap/*
Copyright: 2010, Spotify AB
2011, Joachim Bengtsson
License: BSD-3-clause
Files: 3rdparty/singleapplication/*
Copyright: 2015-2018, Itay Grudev
License: MIT

View File

@ -1240,6 +1240,7 @@ if(APPLE)
"-framework IOKit"
"-framework ScriptingBridge"
)
target_link_libraries(strawberry_lib PRIVATE ${SPMEDIAKEYTAP_LIBRARIES})
if(HAVE_SPARKLE)
target_include_directories(strawberry_lib SYSTEM PRIVATE ${SPARKLE}/Headers)
target_link_libraries(strawberry_lib PRIVATE ${SPARKLE})

View File

@ -4,11 +4,13 @@
#include "globalshortcuts/globalshortcutbackend-macos.h"
class PlatformInterface;
@class SPMediaKeyTap;
@interface AppDelegate : NSObject<NSApplicationDelegate, NSUserNotificationCenterDelegate> {
PlatformInterface* application_handler_;
NSMenu* dock_menu_;
GlobalShortcutBackendMacOS* shortcut_handler_;
SPMediaKeyTap* key_tap_;
}
@ -27,4 +29,5 @@ class PlatformInterface;
- (void) setDockMenu: (NSMenu*)menu;
- (GlobalShortcutBackendMacOS*) shortcut_handler;
- (void) setShortcutHandler: (GlobalShortcutBackendMacOS*)backend;
- (void) mediaKeyTap: (SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event;
@end

View File

@ -40,6 +40,8 @@
#import <QuartzCore/CALayer.h>
#import "3rdparty/SPMediaKeyTap/SPMediaKeyTap.h"
#include "config.h"
#include "mac_delegate.h"
@ -146,6 +148,19 @@ QDebug operator<<(QDebug dbg, NSObject* object) {
- (void)applicationDidFinishLaunching:(NSNotification*)aNotification {
Q_UNUSED(aNotification);
key_tap_ = [ [SPMediaKeyTap alloc] initWithDelegate:self];
if ([SPMediaKeyTap usesGlobalMediaKeyTap]) {
if ([key_tap_ startWatchingMediaKeys]) {
qLog(Debug) << "Media key monitoring started";
} else {
qLog(Warning) << "Failed to start media key monitoring";
}
}
else {
qLog(Warning) << "Media key monitoring disabled";
}
}
- (BOOL)application:(NSApplication*)app openFile:(NSString*)filename {
@ -171,6 +186,26 @@ QDebug operator<<(QDebug dbg, NSObject* object) {
}
- (void) mediaKeyTap: (SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event {
#pragma unused(keyTap)
[self handleMediaEvent:event];
}
- (BOOL) handleMediaEvent:(NSEvent*)event {
// if it is not a media key event, then ignore
if ([event type] == NSEventTypeSystemDefined && [event subtype] == 8) {
int keyCode = (([event data1] & 0xFFFF0000) >> 16);
int keyFlags = ([event data1] & 0x0000FFFF);
int keyIsReleased = (((keyFlags & 0xFF00) >> 8)) == 0xB;
if (keyIsReleased) {
shortcut_handler_->MacMediaKeyPressed(keyCode);
return YES;
}
}
return NO;
}
- (NSApplicationTerminateReply) applicationShouldTerminate:(NSApplication*) sender {
Q_UNUSED(sender);
return NSTerminateNow;
@ -226,15 +261,7 @@ QDebug operator<<(QDebug dbg, NSObject* object) {
- (void)sendEvent:(NSEvent*)event {
if ([event type] == NSEventTypeSystemDefined && [event subtype] == 8) {
int keyCode = (([event data1] & 0xFFFF0000) >> 16);
int keyFlags = ([event data1] & 0x0000FFFF);
int keyIsReleased = (((keyFlags & 0xFF00) >> 8)) == 0xB;
if (keyIsReleased) {
shortcut_handler_->MacMediaKeyPressed(keyCode);
}
}
[delegate_ handleMediaEvent:event];
[super sendEvent:event];
}