You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

308 lines
11 KiB

  1. //
  2. // FLEXKeyboardShortcutManager.m
  3. // FLEX
  4. //
  5. // Created by Ryan Olson on 9/19/15.
  6. // Copyright © 2015 Flipboard. All rights reserved.
  7. //
  8. #import "FLEXKeyboardShortcutManager.h"
  9. #import "FLEXUtility.h"
  10. #import <objc/runtime.h>
  11. #import <objc/message.h>
  12. #if TARGET_OS_SIMULATOR
  13. @interface UIEvent (UIPhysicalKeyboardEvent)
  14. @property (nonatomic) NSString *_modifiedInput;
  15. @property (nonatomic) NSString *_unmodifiedInput;
  16. @property (nonatomic) UIKeyModifierFlags _modifierFlags;
  17. @property (nonatomic) BOOL _isKeyDown;
  18. @property (nonatomic) long _keyCode;
  19. @end
  20. @interface FLEXKeyInput : NSObject <NSCopying>
  21. @property (nonatomic, copy, readonly) NSString *key;
  22. @property (nonatomic, readonly) UIKeyModifierFlags flags;
  23. @property (nonatomic, copy, readonly) NSString *helpDescription;
  24. @end
  25. @implementation FLEXKeyInput
  26. - (BOOL)isEqual:(id)object
  27. {
  28. BOOL isEqual = NO;
  29. if ([object isKindOfClass:[FLEXKeyInput class]]) {
  30. FLEXKeyInput *keyCommand = (FLEXKeyInput *)object;
  31. BOOL equalKeys = self.key == keyCommand.key || [self.key isEqual:keyCommand.key];
  32. BOOL equalFlags = self.flags == keyCommand.flags;
  33. isEqual = equalKeys && equalFlags;
  34. }
  35. return isEqual;
  36. }
  37. - (NSUInteger)hash
  38. {
  39. return [self.key hash] ^ self.flags;
  40. }
  41. - (id)copyWithZone:(NSZone *)zone
  42. {
  43. return [[self class] keyInputForKey:self.key flags:self.flags helpDescription:self.helpDescription];
  44. }
  45. - (NSString *)description
  46. {
  47. NSDictionary<NSString *, NSString *> *keyMappings = @{ UIKeyInputUpArrow : @"↑",
  48. UIKeyInputDownArrow : @"↓",
  49. UIKeyInputLeftArrow : @"←",
  50. UIKeyInputRightArrow : @"→",
  51. UIKeyInputEscape : @"␛",
  52. @" " : @"␠"};
  53. NSString *prettyKey = nil;
  54. if (self.key && keyMappings[self.key]) {
  55. prettyKey = keyMappings[self.key];
  56. } else {
  57. prettyKey = [self.key uppercaseString];
  58. }
  59. NSString *prettyFlags = @"";
  60. if (self.flags & UIKeyModifierControl) {
  61. prettyFlags = [prettyFlags stringByAppendingString:@"⌃"];
  62. }
  63. if (self.flags & UIKeyModifierAlternate) {
  64. prettyFlags = [prettyFlags stringByAppendingString:@"⌥"];
  65. }
  66. if (self.flags & UIKeyModifierShift) {
  67. prettyFlags = [prettyFlags stringByAppendingString:@"⇧"];
  68. }
  69. if (self.flags & UIKeyModifierCommand) {
  70. prettyFlags = [prettyFlags stringByAppendingString:@"⌘"];
  71. }
  72. // Fudging to get easy columns with tabs
  73. if (prettyFlags.length < 2) {
  74. prettyKey = [prettyKey stringByAppendingString:@"\t"];
  75. }
  76. return [NSString stringWithFormat:@"%@%@\t%@", prettyFlags, prettyKey, self.helpDescription];
  77. }
  78. + (instancetype)keyInputForKey:(NSString *)key flags:(UIKeyModifierFlags)flags
  79. {
  80. return [self keyInputForKey:key flags:flags helpDescription:nil];
  81. }
  82. + (instancetype)keyInputForKey:(NSString *)key flags:(UIKeyModifierFlags)flags helpDescription:(NSString *)helpDescription
  83. {
  84. FLEXKeyInput *keyInput = [self new];
  85. if (keyInput) {
  86. keyInput->_key = key;
  87. keyInput->_flags = flags;
  88. keyInput->_helpDescription = helpDescription;
  89. }
  90. return keyInput;
  91. }
  92. @end
  93. @interface FLEXKeyboardShortcutManager ()
  94. @property (nonatomic) NSMutableDictionary<FLEXKeyInput *, dispatch_block_t> *actionsForKeyInputs;
  95. @property (nonatomic, getter=isPressingShift) BOOL pressingShift;
  96. @property (nonatomic, getter=isPressingCommand) BOOL pressingCommand;
  97. @property (nonatomic, getter=isPressingControl) BOOL pressingControl;
  98. @end
  99. @implementation FLEXKeyboardShortcutManager
  100. + (instancetype)sharedManager
  101. {
  102. static FLEXKeyboardShortcutManager *sharedManager = nil;
  103. static dispatch_once_t onceToken;
  104. dispatch_once(&onceToken, ^{
  105. sharedManager = [self new];
  106. });
  107. return sharedManager;
  108. }
  109. + (void)load
  110. {
  111. SEL originalKeyEventSelector = NSSelectorFromString(@"handleKeyUIEvent:");
  112. SEL swizzledKeyEventSelector = [FLEXUtility swizzledSelectorForSelector:originalKeyEventSelector];
  113. void (^handleKeyUIEventSwizzleBlock)(UIApplication *, UIEvent *) = ^(UIApplication *slf, UIEvent *event) {
  114. [[[self class] sharedManager] handleKeyboardEvent:event];
  115. ((void(*)(id, SEL, id))objc_msgSend)(slf, swizzledKeyEventSelector, event);
  116. };
  117. [FLEXUtility replaceImplementationOfKnownSelector:originalKeyEventSelector onClass:[UIApplication class] withBlock:handleKeyUIEventSwizzleBlock swizzledSelector:swizzledKeyEventSelector];
  118. if ([[UITouch class] instancesRespondToSelector:@selector(maximumPossibleForce)]) {
  119. SEL originalSendEventSelector = NSSelectorFromString(@"sendEvent:");
  120. SEL swizzledSendEventSelector = [FLEXUtility swizzledSelectorForSelector:originalSendEventSelector];
  121. void (^sendEventSwizzleBlock)(UIApplication *, UIEvent *) = ^(UIApplication *slf, UIEvent *event) {
  122. if (event.type == UIEventTypeTouches) {
  123. FLEXKeyboardShortcutManager *keyboardManager = [FLEXKeyboardShortcutManager sharedManager];
  124. NSInteger pressureLevel = 0;
  125. if (keyboardManager.isPressingShift) {
  126. pressureLevel++;
  127. }
  128. if (keyboardManager.isPressingCommand) {
  129. pressureLevel++;
  130. }
  131. if (keyboardManager.isPressingControl) {
  132. pressureLevel++;
  133. }
  134. if (pressureLevel > 0) {
  135. if (@available(iOS 9.0, *)) {
  136. for (UITouch *touch in [event allTouches]) {
  137. double adjustedPressureLevel = pressureLevel * 20 * touch.maximumPossibleForce;
  138. [touch setValue:@(adjustedPressureLevel) forKey:@"_pressure"];
  139. }
  140. }
  141. }
  142. }
  143. ((void(*)(id, SEL, id))objc_msgSend)(slf, swizzledSendEventSelector, event);
  144. };
  145. [FLEXUtility replaceImplementationOfKnownSelector:originalSendEventSelector onClass:[UIApplication class] withBlock:sendEventSwizzleBlock swizzledSelector:swizzledSendEventSelector];
  146. SEL originalSupportsTouchPressureSelector = NSSelectorFromString(@"_supportsForceTouch");
  147. SEL swizzledSupportsTouchPressureSelector = [FLEXUtility swizzledSelectorForSelector:originalSupportsTouchPressureSelector];
  148. BOOL (^supportsTouchPressureSwizzleBlock)(UIDevice *) = ^BOOL(UIDevice *slf) {
  149. return YES;
  150. };
  151. [FLEXUtility replaceImplementationOfKnownSelector:originalSupportsTouchPressureSelector onClass:[UIDevice class] withBlock:supportsTouchPressureSwizzleBlock swizzledSelector:swizzledSupportsTouchPressureSelector];
  152. }
  153. }
  154. - (instancetype)init
  155. {
  156. self = [super init];
  157. if (self) {
  158. _actionsForKeyInputs = [NSMutableDictionary dictionary];
  159. _enabled = YES;
  160. }
  161. return self;
  162. }
  163. - (void)registerSimulatorShortcutWithKey:(NSString *)key modifiers:(UIKeyModifierFlags)modifiers action:(dispatch_block_t)action description:(NSString *)description
  164. {
  165. FLEXKeyInput *keyInput = [FLEXKeyInput keyInputForKey:key flags:modifiers helpDescription:description];
  166. [self.actionsForKeyInputs setObject:action forKey:keyInput];
  167. }
  168. static const long kFLEXControlKeyCode = 0xe0;
  169. static const long kFLEXShiftKeyCode = 0xe1;
  170. static const long kFLEXCommandKeyCode = 0xe3;
  171. - (void)handleKeyboardEvent:(UIEvent *)event
  172. {
  173. if (!self.enabled) {
  174. return;
  175. }
  176. NSString *modifiedInput = nil;
  177. NSString *unmodifiedInput = nil;
  178. UIKeyModifierFlags flags = 0;
  179. BOOL isKeyDown = NO;
  180. if ([event respondsToSelector:@selector(_modifiedInput)]) {
  181. modifiedInput = [event _modifiedInput];
  182. }
  183. if ([event respondsToSelector:@selector(_unmodifiedInput)]) {
  184. unmodifiedInput = [event _unmodifiedInput];
  185. }
  186. if ([event respondsToSelector:@selector(_modifierFlags)]) {
  187. flags = [event _modifierFlags];
  188. }
  189. if ([event respondsToSelector:@selector(_isKeyDown)]) {
  190. isKeyDown = [event _isKeyDown];
  191. }
  192. BOOL interactionEnabled = ![UIApplication.sharedApplication isIgnoringInteractionEvents];
  193. BOOL hasFirstResponder = NO;
  194. if (isKeyDown && modifiedInput.length > 0 && interactionEnabled) {
  195. UIResponder *firstResponder = nil;
  196. for (UIWindow *window in [FLEXUtility allWindows]) {
  197. firstResponder = [window valueForKey:@"firstResponder"];
  198. if (firstResponder) {
  199. hasFirstResponder = YES;
  200. break;
  201. }
  202. }
  203. // Ignore key commands (except escape) when there's an active responder
  204. if (firstResponder) {
  205. if ([unmodifiedInput isEqual:UIKeyInputEscape]) {
  206. [firstResponder resignFirstResponder];
  207. }
  208. } else {
  209. FLEXKeyInput *exactMatch = [FLEXKeyInput keyInputForKey:unmodifiedInput flags:flags];
  210. dispatch_block_t actionBlock = self.actionsForKeyInputs[exactMatch];
  211. if (!actionBlock) {
  212. FLEXKeyInput *shiftMatch = [FLEXKeyInput keyInputForKey:modifiedInput flags:flags&(~UIKeyModifierShift)];
  213. actionBlock = self.actionsForKeyInputs[shiftMatch];
  214. }
  215. if (!actionBlock) {
  216. FLEXKeyInput *capitalMatch = [FLEXKeyInput keyInputForKey:[unmodifiedInput uppercaseString] flags:flags];
  217. actionBlock = self.actionsForKeyInputs[capitalMatch];
  218. }
  219. if (actionBlock) {
  220. actionBlock();
  221. }
  222. }
  223. }
  224. // Calling _keyCode on events from the simulator keyboard will crash.
  225. // It is only safe to call _keyCode when there's not an active responder.
  226. if (!hasFirstResponder && [event respondsToSelector:@selector(_keyCode)]) {
  227. long keyCode = [event _keyCode];
  228. if (keyCode == kFLEXControlKeyCode) {
  229. self.pressingControl = isKeyDown;
  230. } else if (keyCode == kFLEXCommandKeyCode) {
  231. self.pressingCommand = isKeyDown;
  232. } else if (keyCode == kFLEXShiftKeyCode) {
  233. self.pressingShift = isKeyDown;
  234. }
  235. }
  236. }
  237. - (NSString *)keyboardShortcutsDescription
  238. {
  239. NSMutableString *description = [NSMutableString string];
  240. NSArray<FLEXKeyInput *> *keyInputs = [self.actionsForKeyInputs.allKeys sortedArrayUsingComparator:^NSComparisonResult(FLEXKeyInput *_Nonnull input1, FLEXKeyInput *_Nonnull input2) {
  241. return [input1.key caseInsensitiveCompare:input2.key];
  242. }];
  243. for (FLEXKeyInput *keyInput in keyInputs) {
  244. [description appendFormat:@"%@\n", keyInput];
  245. }
  246. return [description copy];
  247. }
  248. @end
  249. #endif