1// Copyright 2015-present 650 Industries. All rights reserved.
2
3#import "EXEnvironment.h"
4#import "EXKernelDevKeyCommands.h"
5#import "EXKernel.h"
6#import "EXKernelAppRegistry.h"
7#import "EXReactAppManager.h"
8
9#import <React/RCTDefines.h>
10#import <React/RCTUtils.h>
11
12#import <UIKit/UIKit.h>
13
14@interface EXKeyCommand : NSObject <NSCopying>
15
16@property (nonatomic, strong) UIKeyCommand *keyCommand;
17@property (nonatomic, copy) void (^block)(UIKeyCommand *);
18
19@end
20
21@implementation EXKeyCommand
22
23- (instancetype)initWithKeyCommand:(UIKeyCommand *)keyCommand
24                             block:(void (^)(UIKeyCommand *))block
25{
26  if ((self = [super init])) {
27    _keyCommand = keyCommand;
28    _block = block;
29  }
30  return self;
31}
32
33RCT_NOT_IMPLEMENTED(- (instancetype)init)
34
35- (id)copyWithZone:(__unused NSZone *)zone
36{
37  return self;
38}
39
40- (NSUInteger)hash
41{
42  return _keyCommand.input.hash ^ _keyCommand.modifierFlags;
43}
44
45- (BOOL)isEqual:(EXKeyCommand *)object
46{
47  if (![object isKindOfClass:[EXKeyCommand class]]) {
48    return NO;
49  }
50  return [self matchesInput:object.keyCommand.input
51                      flags:object.keyCommand.modifierFlags];
52}
53
54- (BOOL)matchesInput:(NSString *)input flags:(UIKeyModifierFlags)flags
55{
56  return [_keyCommand.input isEqual:input] && _keyCommand.modifierFlags == flags;
57}
58
59- (NSString *)description
60{
61  return [NSString stringWithFormat:@"<%@:%p input=\"%@\" flags=%zd hasBlock=%@>",
62          [self class], self, _keyCommand.input, _keyCommand.modifierFlags,
63          _block ? @"YES" : @"NO"];
64}
65
66@end
67
68@interface EXKernelDevKeyCommands ()
69
70@property (nonatomic, strong) NSMutableSet<EXKeyCommand *> *commands;
71+ (void)handleKeyboardEvent:(UIEvent *)event;
72
73@end
74
75#if TARGET_IPHONE_SIMULATOR
76@interface UIEvent (UIPhysicalKeyboardEvent)
77
78@property (nonatomic) NSString *_modifiedInput;
79@property (nonatomic) NSString *_unmodifiedInput;
80@property (nonatomic) UIKeyModifierFlags _modifierFlags;
81@property (nonatomic) BOOL _isKeyDown;
82@property (nonatomic) long _keyCode;
83
84@end
85
86@implementation UIApplication (EXKeyCommands)
87
88- (void)EX_handleKeyUIEventSwizzle:(UIEvent *)event
89{
90  BOOL interactionEnabled = !UIApplication.sharedApplication.isIgnoringInteractionEvents;
91  BOOL hasFirstResponder = NO;
92
93  if (interactionEnabled) {
94    UIResponder *firstResponder = nil;
95    for (UIWindow *window in [self windows]) {
96      firstResponder = [window valueForKey:@"firstResponder"];
97      if (firstResponder) {
98        hasFirstResponder = YES;
99        break;
100      }
101    }
102
103
104    // Call the original swizzled method
105    [self EX_handleKeyUIEventSwizzle:event];
106
107    if (firstResponder) {
108      BOOL isTextField = [firstResponder isKindOfClass: [UITextField class]] || [firstResponder isKindOfClass: [UITextView class]];
109
110      // this is a runtime header that is not publicly exported from the Webkit.framework
111      Class WKContentView = NSClassFromString(@"WKContentView");
112
113      BOOL isWebView = [firstResponder isKindOfClass:[WKContentView class]];
114
115      if (!isTextField && !isWebView) {
116        [EXKernelDevKeyCommands handleKeyboardEvent:event];
117      }
118    }
119  }
120};
121
122@end
123#endif
124
125@implementation UIResponder (EXKeyCommands)
126
127- (NSArray<UIKeyCommand *> *)EX_keyCommands
128{
129  NSSet<EXKeyCommand *> *commands = [EXKernelDevKeyCommands sharedInstance].commands;
130  return [[commands valueForKeyPath:@"keyCommand"] allObjects];
131}
132
133- (void)EX_handleKeyCommand:(UIKeyCommand *)key
134{
135  // NOTE: throttle the key handler because on iOS 9 the handleKeyCommand:
136  // method gets called repeatedly if the command key is held down.
137  static NSTimeInterval lastCommand = 0;
138  if (CACurrentMediaTime() - lastCommand > 0.5) {
139    for (EXKeyCommand *command in [EXKernelDevKeyCommands sharedInstance].commands) {
140      if ([command.keyCommand.input isEqualToString:key.input] &&
141          command.keyCommand.modifierFlags == key.modifierFlags) {
142        if (command.block) {
143          command.block(key);
144          lastCommand = CACurrentMediaTime();
145        }
146      }
147    }
148  }
149}
150
151@end
152
153@implementation EXKernelDevKeyCommands
154
155+ (instancetype)sharedInstance
156{
157  static EXKernelDevKeyCommands *instance;
158  static dispatch_once_t once;
159  dispatch_once(&once, ^{
160    if (!instance) {
161      instance = [[EXKernelDevKeyCommands alloc] init];
162    }
163  });
164  return instance;
165}
166
167+ (void)initialize
168{
169  // capture keycommands across all bridges.
170  // this is the same approach taken by RCTKeyCommands,
171  // but that class is disabled in the expo react native fork
172  // since there may be many instances of it.
173  RCTSwapInstanceMethods([UIResponder class],
174                         @selector(keyCommands),
175                         @selector(EX_keyCommands));
176
177#if TARGET_IPHONE_SIMULATOR
178  SEL originalKeyboardSelector = NSSelectorFromString(@"handleKeyUIEvent:");
179  RCTSwapInstanceMethods([UIApplication class],
180                         originalKeyboardSelector,
181                         @selector(EX_handleKeyUIEventSwizzle:));
182#endif
183}
184
185#if TARGET_IPHONE_SIMULATOR
186+(void)handleKeyboardEvent:(UIEvent *)event
187{
188  static NSTimeInterval lastCommand = 0;
189
190  if (event._isKeyDown) {
191    if (CACurrentMediaTime() - lastCommand > 0.5) {
192      NSString *input = event._modifiedInput;
193      if ([input isEqualToString: @"r"]) {
194        [[EXKernel sharedInstance] reloadVisibleApp];
195      }
196
197      lastCommand = CACurrentMediaTime();
198    }
199  }
200}
201#endif
202
203- (instancetype)init
204{
205  if ((self = [super init])) {
206    _commands = [NSMutableSet set];
207  }
208  return self;
209}
210
211#pragma mark - expo dev commands
212
213- (void)registerDevCommands
214{
215  __weak typeof(self) weakSelf = self;
216  [self registerKeyCommandWithInput:@"d"
217                      modifierFlags:UIKeyModifierCommand
218                             action:^(__unused UIKeyCommand *_) {
219                               [weakSelf _handleMenuCommand];
220                             }];
221  [self registerKeyCommandWithInput:@"r"
222                      modifierFlags:UIKeyModifierCommand
223                             action:^(__unused UIKeyCommand *_) {
224                               [weakSelf _handleRefreshCommand];
225                             }];
226  [self registerKeyCommandWithInput:@"n"
227                      modifierFlags:UIKeyModifierCommand
228                             action:^(__unused UIKeyCommand *_) {
229                               [weakSelf _handleDisableDebuggingCommand];
230                             }];
231  [self registerKeyCommandWithInput:@"i"
232                      modifierFlags:UIKeyModifierCommand
233                             action:^(__unused UIKeyCommand *_) {
234                               [weakSelf _handleToggleInspectorCommand];
235                             }];
236  [self registerKeyCommandWithInput:@"k"
237                      modifierFlags:UIKeyModifierCommand | UIKeyModifierControl
238                             action:^(__unused UIKeyCommand *_) {
239                               [weakSelf _handleKernelMenuCommand];
240                             }];
241
242}
243
244- (void)_handleMenuCommand
245{
246  if ([EXEnvironment sharedEnvironment].isDetached) {
247    [[EXKernel sharedInstance].visibleApp.appManager showDevMenu];
248  } else {
249    [[EXKernel sharedInstance] switchTasks];
250  }
251}
252
253- (void)_handleRefreshCommand
254{
255  // This reloads only JS
256  //  [[EXKernel sharedInstance].visibleApp.appManager reloadBridge];
257
258  // This reloads manifest and JS
259  [[EXKernel sharedInstance] reloadVisibleApp];
260}
261
262- (void)_handleDisableDebuggingCommand
263{
264  [[EXKernel sharedInstance].visibleApp.appManager disableRemoteDebugging];
265}
266
267- (void)_handleToggleRemoteDebuggingCommand
268{
269  [[EXKernel sharedInstance].visibleApp.appManager toggleRemoteDebugging];
270  // This reloads manifest and JS
271  [[EXKernel sharedInstance] reloadVisibleApp];
272}
273
274- (void)_handleTogglePerformanceMonitorCommand
275{
276  [[EXKernel sharedInstance].visibleApp.appManager togglePerformanceMonitor];
277}
278
279- (void)_handleToggleInspectorCommand
280{
281  [[EXKernel sharedInstance].visibleApp.appManager toggleElementInspector];
282}
283
284- (void)_handleKernelMenuCommand
285{
286  if ([EXKernel sharedInstance].visibleApp == [EXKernel sharedInstance].appRegistry.homeAppRecord) {
287    [[EXKernel sharedInstance].appRegistry.homeAppRecord.appManager showDevMenu];
288  }
289}
290
291#pragma mark - managing list of commands
292
293- (void)registerKeyCommandWithInput:(NSString *)input
294                      modifierFlags:(UIKeyModifierFlags)flags
295                             action:(void (^)(UIKeyCommand *))block
296{
297  RCTAssertMainQueue();
298
299  UIKeyCommand *command = [UIKeyCommand keyCommandWithInput:input
300                                              modifierFlags:flags
301                                                     action:@selector(EX_handleKeyCommand:)];
302
303  EXKeyCommand *keyCommand = [[EXKeyCommand alloc] initWithKeyCommand:command block:block];
304  [_commands removeObject:keyCommand];
305  [_commands addObject:keyCommand];
306}
307
308- (void)unregisterKeyCommandWithInput:(NSString *)input
309                        modifierFlags:(UIKeyModifierFlags)flags
310{
311  RCTAssertMainQueue();
312
313  for (EXKeyCommand *command in _commands.allObjects) {
314    if ([command matchesInput:input flags:flags]) {
315      [_commands removeObject:command];
316      break;
317    }
318  }
319}
320
321- (BOOL)isKeyCommandRegisteredForInput:(NSString *)input
322                         modifierFlags:(UIKeyModifierFlags)flags
323{
324  RCTAssertMainQueue();
325
326  for (EXKeyCommand *command in _commands) {
327    if ([command matchesInput:input flags:flags]) {
328      return YES;
329    }
330  }
331  return NO;
332}
333
334@end
335
336