diff --git a/Framework/MASShortcutMonitor.h b/Framework/MASShortcutMonitor.h index dc3d458..5538f30 100644 --- a/Framework/MASShortcutMonitor.h +++ b/Framework/MASShortcutMonitor.h @@ -10,7 +10,12 @@ @interface MASShortcutMonitor : NSObject - (instancetype) init __unavailable; +- (instancetype) initWithKeyUp; + (instancetype) sharedMonitor; ++ (instancetype) sharedMonitorWithKeyUp; + +- (OSStatus) installEventHandlersWithKeyup: (BOOL) keyUp; +- (OSStatus) installEventHandlers: (int) itemCount withEventTypeSpecs: (EventTypeSpec *) eventTypeSpecs; /** Register a shortcut along with an action. diff --git a/Framework/MASShortcutMonitor.m b/Framework/MASShortcutMonitor.m index fce8022..deaf5c3 100644 --- a/Framework/MASShortcutMonitor.m +++ b/Framework/MASShortcutMonitor.m @@ -16,9 +16,22 @@ - (instancetype) init { self = [super init]; [self setHotKeys:[NSMutableDictionary dictionary]]; - EventTypeSpec hotKeyPressedSpec = { .eventClass = kEventClassKeyboard, .eventKind = kEventHotKeyPressed }; - OSStatus status = InstallEventHandler(GetEventDispatcherTarget(), MASCarbonEventCallback, - 1, &hotKeyPressedSpec, (__bridge void*)self, &_eventHandlerRef); + + OSStatus status = [self installEventHandlersWithKeyup:NO]; + + if (status != noErr) { + return nil; + } + return self; +} + +- (instancetype) initWithKeyUp +{ + self = [super init]; + [self setHotKeys:[NSMutableDictionary dictionary]]; + + OSStatus status = [self installEventHandlersWithKeyup:YES]; + if (status != noErr) { return nil; } @@ -43,6 +56,50 @@ + (instancetype) sharedMonitor return sharedInstance; } ++ (instancetype) sharedMonitorWithKeyUp +{ + static dispatch_once_t once; + static MASShortcutMonitor *sharedInstance; + dispatch_once(&once, ^{ + sharedInstance = [[self alloc] initWithKeyUp]; + }); + return sharedInstance; +} + +- (OSStatus) installEventHandlersWithKeyup: (BOOL) keyUp +{ + EventTypeSpec hotKeyPressedSpec = { .eventClass = kEventClassKeyboard, .eventKind = kEventHotKeyPressed }; + + + OSStatus status; + + if (keyUp) { + EventTypeSpec hotKeyReleasedSpec = { .eventClass = kEventClassKeyboard, .eventKind = kEventHotKeyReleased }; + struct EventTypeSpec *eventTypeSpecs = malloc(sizeof(struct EventTypeSpec) * 2); + eventTypeSpecs[0] = hotKeyPressedSpec; + eventTypeSpecs[1] = hotKeyReleasedSpec; + + status = [self installEventHandlers:2 withEventTypeSpecs:eventTypeSpecs]; + } else { + status = [self installEventHandlers:1 withEventTypeSpecs:&hotKeyPressedSpec]; + } + + return status; +} + +- (OSStatus) installEventHandlers: (int) itemCount withEventTypeSpecs: (EventTypeSpec *) eventTypeSpecs +{ + OSStatus status = InstallEventHandler(GetEventDispatcherTarget(), + MASCarbonEventCallback, + itemCount, + eventTypeSpecs, + (__bridge void*)self, + &_eventHandlerRef); + + return status; +} + + #pragma mark Registration - (BOOL) registerShortcut: (MASShortcut*) shortcut withAction: (dispatch_block_t) action