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.

310 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, strong) NSString *_modifiedInput;
  15. @property (nonatomic, strong) NSString *_unmodifiedInput;
  16. @property (nonatomic, assign) UIKeyModifierFlags _modifierFlags;
  17. @property (nonatomic, assign) BOOL _isKeyDown;
  18. @property (nonatomic, assign) long _keyCode;
  19. @end
  20. @interface FLEXKeyInput : NSObject <NSCopying>
  21. @property (nonatomic, copy, readonly) NSString *key;
  22. @property (nonatomic, assign, 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 alloc] init];
  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, strong) NSMutableDictionary<FLEXKeyInput *, dispatch_block_t> *actionsForKeyInputs;
  95. @property (nonatomic, assign, getter=isPressingShift) BOOL pressingShift;
  96. @property (nonatomic, assign, getter=isPressingCommand) BOOL pressingCommand;
  97. @property (nonatomic, assign, 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 class] alloc] init];
  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 FLEX_AT_LEAST_IOS11_SDK
  136. if (@available(iOS 9.0, *)) {
  137. for (UITouch *touch in [event allTouches]) {
  138. double adjustedPressureLevel = pressureLevel * 20 * touch.maximumPossibleForce;
  139. [touch setValue:@(adjustedPressureLevel) forKey:@"_pressure"];
  140. }
  141. }
  142. #endif
  143. }
  144. }
  145. ((void(*)(id, SEL, id))objc_msgSend)(slf, swizzledSendEventSelector, event);
  146. };
  147. [FLEXUtility replaceImplementationOfKnownSelector:originalSendEventSelector onClass:[UIApplication class] withBlock:sendEventSwizzleBlock swizzledSelector:swizzledSendEventSelector];
  148. SEL originalSupportsTouchPressureSelector = NSSelectorFromString(@"_supportsForceTouch");
  149. SEL swizzledSupportsTouchPressureSelector = [FLEXUtility swizzledSelectorForSelector:originalSupportsTouchPressureSelector];
  150. BOOL (^supportsTouchPressureSwizzleBlock)(UIDevice *) = ^BOOL(UIDevice *slf) {
  151. return YES;
  152. };
  153. [FLEXUtility replaceImplementationOfKnownSelector:originalSupportsTouchPressureSelector onClass:[UIDevice class] withBlock:supportsTouchPressureSwizzleBlock swizzledSelector:swizzledSupportsTouchPressureSelector];
  154. }
  155. }
  156. - (instancetype)init
  157. {
  158. self = [super init];
  159. if (self) {
  160. _actionsForKeyInputs = [NSMutableDictionary dictionary];
  161. _enabled = YES;
  162. }
  163. return self;
  164. }
  165. - (void)registerSimulatorShortcutWithKey:(NSString *)key modifiers:(UIKeyModifierFlags)modifiers action:(dispatch_block_t)action description:(NSString *)description
  166. {
  167. FLEXKeyInput *keyInput = [FLEXKeyInput keyInputForKey:key flags:modifiers helpDescription:description];
  168. [self.actionsForKeyInputs setObject:action forKey:keyInput];
  169. }
  170. static const long kFLEXControlKeyCode = 0xe0;
  171. static const long kFLEXShiftKeyCode = 0xe1;
  172. static const long kFLEXCommandKeyCode = 0xe3;
  173. - (void)handleKeyboardEvent:(UIEvent *)event
  174. {
  175. if (!self.enabled) {
  176. return;
  177. }
  178. NSString *modifiedInput = nil;
  179. NSString *unmodifiedInput = nil;
  180. UIKeyModifierFlags flags = 0;
  181. BOOL isKeyDown = NO;
  182. if ([event respondsToSelector:@selector(_modifiedInput)]) {
  183. modifiedInput = [event _modifiedInput];
  184. }
  185. if ([event respondsToSelector:@selector(_unmodifiedInput)]) {
  186. unmodifiedInput = [event _unmodifiedInput];
  187. }
  188. if ([event respondsToSelector:@selector(_modifierFlags)]) {
  189. flags = [event _modifierFlags];
  190. }
  191. if ([event respondsToSelector:@selector(_isKeyDown)]) {
  192. isKeyDown = [event _isKeyDown];
  193. }
  194. BOOL interactionEnabled = ![[UIApplication sharedApplication] isIgnoringInteractionEvents];
  195. BOOL hasFirstResponder = NO;
  196. if (isKeyDown && [modifiedInput length] > 0 && interactionEnabled) {
  197. UIResponder *firstResponder = nil;
  198. for (UIWindow *window in [FLEXUtility allWindows]) {
  199. firstResponder = [window valueForKey:@"firstResponder"];
  200. if (firstResponder) {
  201. hasFirstResponder = YES;
  202. break;
  203. }
  204. }
  205. // Ignore key commands (except escape) when there's an active responder
  206. if (firstResponder) {
  207. if ([unmodifiedInput isEqual:UIKeyInputEscape]) {
  208. [firstResponder resignFirstResponder];
  209. }
  210. } else {
  211. FLEXKeyInput *exactMatch = [FLEXKeyInput keyInputForKey:unmodifiedInput flags:flags];
  212. dispatch_block_t actionBlock = self.actionsForKeyInputs[exactMatch];
  213. if (!actionBlock) {
  214. FLEXKeyInput *shiftMatch = [FLEXKeyInput keyInputForKey:modifiedInput flags:flags&(~UIKeyModifierShift)];
  215. actionBlock = self.actionsForKeyInputs[shiftMatch];
  216. }
  217. if (!actionBlock) {
  218. FLEXKeyInput *capitalMatch = [FLEXKeyInput keyInputForKey:[unmodifiedInput uppercaseString] flags:flags];
  219. actionBlock = self.actionsForKeyInputs[capitalMatch];
  220. }
  221. if (actionBlock) {
  222. actionBlock();
  223. }
  224. }
  225. }
  226. // Calling _keyCode on events from the simulator keyboard will crash.
  227. // It is only safe to call _keyCode when there's not an active responder.
  228. if (!hasFirstResponder && [event respondsToSelector:@selector(_keyCode)]) {
  229. long keyCode = [event _keyCode];
  230. if (keyCode == kFLEXControlKeyCode) {
  231. self.pressingControl = isKeyDown;
  232. } else if (keyCode == kFLEXCommandKeyCode) {
  233. self.pressingCommand = isKeyDown;
  234. } else if (keyCode == kFLEXShiftKeyCode) {
  235. self.pressingShift = isKeyDown;
  236. }
  237. }
  238. }
  239. - (NSString *)keyboardShortcutsDescription
  240. {
  241. NSMutableString *description = [NSMutableString string];
  242. NSArray<FLEXKeyInput *> *keyInputs = [[self.actionsForKeyInputs allKeys] sortedArrayUsingComparator:^NSComparisonResult(FLEXKeyInput *_Nonnull input1, FLEXKeyInput *_Nonnull input2) {
  243. return [input1.key caseInsensitiveCompare:input2.key];
  244. }];
  245. for (FLEXKeyInput *keyInput in keyInputs) {
  246. [description appendFormat:@"%@\n", keyInput];
  247. }
  248. return [description copy];
  249. }
  250. @end
  251. #endif