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      if (!isTextField) {
111        [EXKernelDevKeyCommands handleKeyboardEvent:event];
112      }
113    }
114  }
115};
116
117@end
118#endif
119
120@implementation UIResponder (EXKeyCommands)
121
122- (NSArray<UIKeyCommand *> *)EX_keyCommands
123{
124  NSSet<EXKeyCommand *> *commands = [EXKernelDevKeyCommands sharedInstance].commands;
125  return [[commands valueForKeyPath:@"keyCommand"] allObjects];
126}
127
128- (void)EX_handleKeyCommand:(UIKeyCommand *)key
129{
130  // NOTE: throttle the key handler because on iOS 9 the handleKeyCommand:
131  // method gets called repeatedly if the command key is held down.
132  static NSTimeInterval lastCommand = 0;
133  if (CACurrentMediaTime() - lastCommand > 0.5) {
134    for (EXKeyCommand *command in [EXKernelDevKeyCommands sharedInstance].commands) {
135      if ([command.keyCommand.input isEqualToString:key.input] &&
136          command.keyCommand.modifierFlags == key.modifierFlags) {
137        if (command.block) {
138          command.block(key);
139          lastCommand = CACurrentMediaTime();
140        }
141      }
142    }
143  }
144}
145
146@end
147
148@implementation EXKernelDevKeyCommands
149
150+ (instancetype)sharedInstance
151{
152  static EXKernelDevKeyCommands *instance;
153  static dispatch_once_t once;
154  dispatch_once(&once, ^{
155    if (!instance) {
156      instance = [[EXKernelDevKeyCommands alloc] init];
157    }
158  });
159  return instance;
160}
161
162+ (void)initialize
163{
164  // capture keycommands across all bridges.
165  // this is the same approach taken by RCTKeyCommands,
166  // but that class is disabled in the expo react native fork
167  // since there may be many instances of it.
168  RCTSwapInstanceMethods([UIResponder class],
169                         @selector(keyCommands),
170                         @selector(EX_keyCommands));
171
172#if TARGET_IPHONE_SIMULATOR
173  SEL originalKeyboardSelector = NSSelectorFromString(@"handleKeyUIEvent:");
174  RCTSwapInstanceMethods([UIApplication class],
175                         originalKeyboardSelector,
176                         @selector(EX_handleKeyUIEventSwizzle:));
177#endif
178}
179
180#if TARGET_IPHONE_SIMULATOR
181+(void)handleKeyboardEvent:(UIEvent *)event
182{
183  static NSTimeInterval lastCommand = 0;
184
185  if (event._isKeyDown) {
186    if (CACurrentMediaTime() - lastCommand > 0.5) {
187      NSString *input = event._modifiedInput;
188      if ([input isEqualToString: @"r"]) {
189        [[EXKernel sharedInstance] reloadVisibleApp];
190      }
191
192      lastCommand = CACurrentMediaTime();
193    }
194  }
195}
196#endif
197
198- (instancetype)init
199{
200  if ((self = [super init])) {
201    _commands = [NSMutableSet set];
202  }
203  return self;
204}
205
206#pragma mark - expo dev commands
207
208- (void)registerDevCommands
209{
210  __weak typeof(self) weakSelf = self;
211  [self registerKeyCommandWithInput:@"d"
212                      modifierFlags:UIKeyModifierCommand
213                             action:^(__unused UIKeyCommand *_) {
214                               [weakSelf _handleMenuCommand];
215                             }];
216  [self registerKeyCommandWithInput:@"r"
217                      modifierFlags:UIKeyModifierCommand
218                             action:^(__unused UIKeyCommand *_) {
219                               [weakSelf _handleRefreshCommand];
220                             }];
221  [self registerKeyCommandWithInput:@"n"
222                      modifierFlags:UIKeyModifierCommand
223                             action:^(__unused UIKeyCommand *_) {
224                               [weakSelf _handleDisableDebuggingCommand];
225                             }];
226  [self registerKeyCommandWithInput:@"i"
227                      modifierFlags:UIKeyModifierCommand
228                             action:^(__unused UIKeyCommand *_) {
229                               [weakSelf _handleToggleInspectorCommand];
230                             }];
231  [self registerKeyCommandWithInput:@"k"
232                      modifierFlags:UIKeyModifierCommand | UIKeyModifierControl
233                             action:^(__unused UIKeyCommand *_) {
234                               [weakSelf _handleKernelMenuCommand];
235                             }];
236
237}
238
239- (void)_handleMenuCommand
240{
241  if ([EXEnvironment sharedEnvironment].isDetached) {
242    [[EXKernel sharedInstance].visibleApp.appManager showDevMenu];
243  } else {
244    [[EXKernel sharedInstance] switchTasks];
245  }
246}
247
248- (void)_handleRefreshCommand
249{
250  // This reloads only JS
251  //  [[EXKernel sharedInstance].visibleApp.appManager reloadBridge];
252
253  // This reloads manifest and JS
254  [[EXKernel sharedInstance] reloadVisibleApp];
255}
256
257- (void)_handleDisableDebuggingCommand
258{
259  [[EXKernel sharedInstance].visibleApp.appManager disableRemoteDebugging];
260}
261
262- (void)_handleToggleRemoteDebuggingCommand
263{
264  [[EXKernel sharedInstance].visibleApp.appManager toggleRemoteDebugging];
265  // This reloads manifest and JS
266  [[EXKernel sharedInstance] reloadVisibleApp];
267}
268
269- (void)_handleTogglePerformanceMonitorCommand
270{
271  [[EXKernel sharedInstance].visibleApp.appManager togglePerformanceMonitor];
272}
273
274- (void)_handleToggleInspectorCommand
275{
276  [[EXKernel sharedInstance].visibleApp.appManager toggleElementInspector];
277}
278
279- (void)_handleKernelMenuCommand
280{
281  if ([EXKernel sharedInstance].visibleApp == [EXKernel sharedInstance].appRegistry.homeAppRecord) {
282    [[EXKernel sharedInstance].appRegistry.homeAppRecord.appManager showDevMenu];
283  }
284}
285
286#pragma mark - managing list of commands
287
288- (void)registerKeyCommandWithInput:(NSString *)input
289                      modifierFlags:(UIKeyModifierFlags)flags
290                             action:(void (^)(UIKeyCommand *))block
291{
292  RCTAssertMainQueue();
293
294  UIKeyCommand *command = [UIKeyCommand keyCommandWithInput:input
295                                              modifierFlags:flags
296                                                     action:@selector(EX_handleKeyCommand:)];
297
298  EXKeyCommand *keyCommand = [[EXKeyCommand alloc] initWithKeyCommand:command block:block];
299  [_commands removeObject:keyCommand];
300  [_commands addObject:keyCommand];
301}
302
303- (void)unregisterKeyCommandWithInput:(NSString *)input
304                        modifierFlags:(UIKeyModifierFlags)flags
305{
306  RCTAssertMainQueue();
307
308  for (EXKeyCommand *command in _commands.allObjects) {
309    if ([command matchesInput:input flags:flags]) {
310      [_commands removeObject:command];
311      break;
312    }
313  }
314}
315
316- (BOOL)isKeyCommandRegisteredForInput:(NSString *)input
317                         modifierFlags:(UIKeyModifierFlags)flags
318{
319  RCTAssertMainQueue();
320
321  for (EXKeyCommand *command in _commands) {
322    if ([command matchesInput:input flags:flags]) {
323      return YES;
324    }
325  }
326  return NO;
327}
328
329@end
330
331