FLEXExplorerViewController.m 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251
  1. //
  2. // FLEXExplorerViewController.m
  3. // Flipboard
  4. //
  5. // Created by Ryan Olson on 4/4/14.
  6. // Copyright (c) 2020 FLEX Team. All rights reserved.
  7. //
  8. #import "FLEXExplorerViewController.h"
  9. #import "FLEXExplorerToolbarItem.h"
  10. #import "FLEXUtility.h"
  11. #import "FLEXWindow.h"
  12. #import "FLEXTabList.h"
  13. #import "FLEXNavigationController.h"
  14. #import "FLEXHierarchyViewController.h"
  15. #import "FLEXGlobalsViewController.h"
  16. #import "FLEXObjectExplorerViewController.h"
  17. #import "FLEXObjectExplorerFactory.h"
  18. #import "FLEXNetworkMITMViewController.h"
  19. #import "FLEXTabsViewController.h"
  20. #import "FLEXWindowManagerController.h"
  21. #import "FLEXViewControllersViewController.h"
  22. #import "NSUserDefaults+FLEX.h"
  23. #import "FLEXManager.h"
  24. typedef NS_ENUM(NSUInteger, FLEXExplorerMode) {
  25. FLEXExplorerModeDefault,
  26. FLEXExplorerModeSelect,
  27. FLEXExplorerModeMove
  28. };
  29. @interface FLEXExplorerViewController () <FLEXHierarchyDelegate, UIAdaptivePresentationControllerDelegate>{
  30. UIImageView *cursorView;
  31. }
  32. /// Tracks the currently active tool/mode
  33. @property (nonatomic) FLEXExplorerMode currentMode;
  34. /// Gesture recognizer for dragging a view in move mode
  35. @property (nonatomic) UIPanGestureRecognizer *movePanGR;
  36. /// Gesture recognizer for showing additional details on the selected view
  37. @property (nonatomic) UITapGestureRecognizer *detailsTapGR;
  38. /// Only valid while a move pan gesture is in progress.
  39. @property (nonatomic) CGRect selectedViewFrameBeforeDragging;
  40. /// Only valid while a toolbar drag pan gesture is in progress.
  41. @property (nonatomic) CGRect toolbarFrameBeforeDragging;
  42. /// Only valid while a selected view pan gesture is in progress.
  43. @property (nonatomic) CGFloat selectedViewLastPanX;
  44. /// Borders of all the visible views in the hierarchy at the selection point.
  45. /// The keys are NSValues with the corresponding view (nonretained).
  46. @property (nonatomic) NSDictionary<NSValue *, UIView *> *outlineViewsForVisibleViews;
  47. /// The actual views at the selection point with the deepest view last.
  48. @property (nonatomic) NSArray<UIView *> *viewsAtTapPoint;
  49. /// The view that we're currently highlighting with an overlay and displaying details for.
  50. @property (nonatomic) UIView *selectedView;
  51. /// A colored transparent overlay to indicate that the view is selected.
  52. @property (nonatomic) UIView *selectedViewOverlay;
  53. /// Used to actuate changes in view selection on iOS 10+
  54. @property (nonatomic, readonly) UISelectionFeedbackGenerator *selectionFBG API_AVAILABLE(ios(10.0));
  55. /// self.view.window as a \c FLEXWindow
  56. @property (nonatomic, readonly) FLEXWindow *window;
  57. /// All views that we're KVOing. Used to help us clean up properly.
  58. @property (nonatomic) NSMutableSet<UIView *> *observedViews;
  59. #if !TARGET_OS_TV
  60. /// Used to preserve the target app's UIMenuController items.
  61. @property (nonatomic) NSArray<UIMenuItem *> *appMenuItems;
  62. #endif
  63. @property CGPoint lastTouchLocation;
  64. @end
  65. @implementation FLEXExplorerViewController
  66. #pragma mark - Cursor Input
  67. #if TARGET_OS_TV
  68. - (void)pressesBegan:(NSSet<UIPress *> *)presses withEvent:(UIPressesEvent *)event
  69. {
  70. for (UIPress *press in presses) {
  71. if (press.type == UIPressTypeMenu) {
  72. } else {
  73. [super pressesBegan:presses withEvent:event];
  74. }
  75. }
  76. }
  77. -(void)pressesEnded:(NSSet<UIPress *> *)presses withEvent:(UIPressesEvent *)event {
  78. if (self.currentMode != FLEXExplorerModeSelect && self.currentMode != FLEXExplorerModeMove){
  79. [super pressesEnded:presses withEvent:event];
  80. return;
  81. }
  82. CGPoint point = [self.view convertPoint:cursorView.frame.origin toView:nil];
  83. NSLog(@"[FLEXInjected] clicked point: %@", NSStringFromCGPoint(point));
  84. if (self.currentMode == FLEXExplorerModeSelect){
  85. [self updateOutlineViewsForSelectionPoint:point];
  86. }
  87. if (presses.anyObject.type == UIPressTypeMenu) {
  88. if (self.currentMode == FLEXExplorerModeMove){
  89. self.currentMode = FLEXExplorerModeSelect;
  90. cursorView.hidden = false;
  91. } else if (self.currentMode == FLEXExplorerModeSelect){
  92. self.currentMode = FLEXExplorerModeDefault;
  93. cursorView.hidden = true;
  94. [self enableToolbar];
  95. }
  96. } else if (presses.anyObject.type == UIPressTypeUpArrow) {
  97. } else if (presses.anyObject.type == UIPressTypeDownArrow) {
  98. } else if (presses.anyObject.type == UIPressTypeSelect) {
  99. } else if (presses.anyObject.type == UIPressTypePlayPause){
  100. }
  101. }
  102. - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
  103. {
  104. self.lastTouchLocation = CGPointMake(-1, -1);
  105. }
  106. - (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
  107. {
  108. for (UITouch *touch in touches)
  109. {
  110. CGPoint location = [touch locationInView:self.view];
  111. if(self.lastTouchLocation.x == -1 && self.lastTouchLocation.y == -1)
  112. {
  113. // Prevent cursor from recentering
  114. self.lastTouchLocation = location;
  115. }
  116. else
  117. {
  118. CGFloat xDiff = location.x - self.lastTouchLocation.x;
  119. CGFloat yDiff = location.y - self.lastTouchLocation.y;
  120. CGRect rect = cursorView.frame;
  121. if(rect.origin.x + xDiff >= 0 && rect.origin.x + xDiff <= 1920)
  122. rect.origin.x += xDiff;//location.x - self.startPos.x;//+= xDiff; //location.x;
  123. if(rect.origin.y + yDiff >= 0 && rect.origin.y + yDiff <= 1080)
  124. rect.origin.y += yDiff;//location.y - self.startPos.y;//+= yDiff; //location.y;
  125. cursorView.frame = rect;
  126. self.lastTouchLocation = location;
  127. }
  128. // We only use one touch, break the loop
  129. break;
  130. }
  131. }
  132. #endif
  133. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
  134. self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  135. if (self) {
  136. self.observedViews = [NSMutableSet new];
  137. }
  138. return self;
  139. }
  140. - (void)dealloc {
  141. for (UIView *view in _observedViews) {
  142. [self stopObservingView:view];
  143. }
  144. }
  145. - (void)viewDidLoad {
  146. [super viewDidLoad];
  147. // Toolbar
  148. _explorerToolbar = [FLEXExplorerToolbar new];
  149. // Start the toolbar off below any bars that may be at the top of the view.
  150. CGFloat toolbarOriginY = NSUserDefaults.standardUserDefaults.flex_toolbarTopMargin;
  151. CGRect safeArea = [self viewSafeArea];
  152. CGSize toolbarSize = [self.explorerToolbar sizeThatFits:CGSizeMake(
  153. CGRectGetWidth(self.view.bounds), CGRectGetHeight(safeArea)
  154. )];
  155. [self updateToolbarPositionWithUnconstrainedFrame:CGRectMake(
  156. CGRectGetMinX(safeArea), toolbarOriginY, toolbarSize.width, toolbarSize.height
  157. )];
  158. self.explorerToolbar.autoresizingMask = UIViewAutoresizingFlexibleWidth |
  159. UIViewAutoresizingFlexibleBottomMargin |
  160. UIViewAutoresizingFlexibleTopMargin;
  161. [self.view addSubview:self.explorerToolbar];
  162. [self setupToolbarActions];
  163. [self setupToolbarGestures];
  164. // View selection
  165. UITapGestureRecognizer *selectionTapGR = [[UITapGestureRecognizer alloc]
  166. initWithTarget:self action:@selector(handleSelectionTap:)
  167. ];
  168. [self.view addGestureRecognizer:selectionTapGR];
  169. // View moving
  170. self.movePanGR = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleMovePan:)];
  171. self.movePanGR.enabled = self.currentMode == FLEXExplorerModeMove;
  172. [self.view addGestureRecognizer:self.movePanGR];
  173. // Feedback
  174. if (@available(iOS 10.0, *)) {
  175. _selectionFBG = [UISelectionFeedbackGenerator new];
  176. }
  177. #if TARGET_OS_TV
  178. cursorView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 64, 64)];
  179. cursorView.center = CGPointMake(CGRectGetMidX([UIScreen mainScreen].bounds), CGRectGetMidY([UIScreen mainScreen].bounds));
  180. cursorView.image = [UIImage imageNamed:@"Cursor"];
  181. cursorView.backgroundColor = [UIColor clearColor];
  182. cursorView.hidden = YES;
  183. UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
  184. longPress.allowedPressTypes = @[[NSNumber numberWithInteger:UIPressTypePlayPause]];
  185. [self.view addGestureRecognizer:longPress];
  186. [self.view addSubview:cursorView];
  187. UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTap:)];
  188. doubleTap.allowedPressTypes = @[[NSNumber numberWithInteger:UIPressTypePlayPause], [NSNumber numberWithInteger:UIPressTypeSelect]];
  189. doubleTap.numberOfTapsRequired = 2;
  190. [self.view addGestureRecognizer:doubleTap];
  191. #endif
  192. }
  193. - (void)doubleTap:(UITapGestureRecognizer *)gesture {
  194. if (gesture.state == UIGestureRecognizerStateEnded) {
  195. if (self.currentMode == FLEXExplorerModeSelect || self.currentMode == FLEXExplorerModeMove){
  196. NSLog(@"[FLEXInjected] doubleTap: toggle views tool!");
  197. [self showTVOSOptionsAlert];
  198. }
  199. }
  200. }
  201. - (void)showObjectControllerForSelectedView {
  202. FLEXObjectExplorerViewController *viewExplorer = [FLEXObjectExplorerFactory explorerViewControllerForObject:self.selectedView];
  203. NSLog(@"[FLEXInjected] showObjectControllerForSelectedView: %@", viewExplorer);
  204. if (!viewExplorer) return;
  205. if ([self presentedViewController]){
  206. FLEXHierarchyViewController *vc = (FLEXHierarchyViewController*)[self presentedViewController];
  207. if ([vc respondsToSelector:@selector(pushViewController:animated:)]){
  208. [vc pushViewController:viewExplorer animated:true];
  209. }
  210. } else {
  211. [self toggleViewsToolWithCompletion:^{
  212. FLEXHierarchyViewController *vc = (FLEXHierarchyViewController*)[self presentedViewController];
  213. if ([vc respondsToSelector:@selector(pushViewController:animated:)]){
  214. [vc pushViewController:viewExplorer animated:true];
  215. }
  216. }];
  217. }
  218. }
  219. - (void)showTVOSOptionsAlert {
  220. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"What would you like to do?" message:nil preferredStyle:UIAlertControllerStyleAlert];
  221. UIAlertAction *details = [UIAlertAction actionWithTitle:@"Show Details" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  222. [self showObjectControllerForSelectedView];
  223. [[FLEXManager sharedManager] showExplorer];
  224. }];
  225. [alertController addAction:details];
  226. if (self.currentMode == FLEXExplorerModeMove){
  227. UIAlertAction *selection = [UIAlertAction actionWithTitle:@"Select View" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  228. self.currentMode = FLEXExplorerModeSelect;
  229. cursorView.hidden = false;
  230. [[FLEXManager sharedManager] showExplorer];
  231. }];
  232. [alertController addAction:selection];
  233. } else if (self.currentMode == FLEXExplorerModeSelect){
  234. UIAlertAction *movement = [UIAlertAction actionWithTitle:@"Move View" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  235. self.currentMode = FLEXExplorerModeMove;
  236. cursorView.hidden = true;
  237. [[FLEXManager sharedManager] showExplorer];
  238. }];
  239. [alertController addAction:movement];
  240. }
  241. UIAlertAction *showViews = [UIAlertAction actionWithTitle:@"Show Views" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  242. [self toggleViewsTool];
  243. [[FLEXManager sharedManager] showExplorer];
  244. }];
  245. [alertController addAction:showViews];
  246. [alertController addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  247. [[FLEXManager sharedManager] showExplorer];
  248. }]];
  249. [self presentViewController:alertController animated:true completion:nil];
  250. }
  251. - (void)longPress:(UILongPressGestureRecognizer*)gesture {
  252. if ( gesture.state == UIGestureRecognizerStateEnded) {
  253. [self toggleSelectTool];
  254. }
  255. }
  256. - (void)viewWillAppear:(BOOL)animated {
  257. [super viewWillAppear:animated];
  258. [self updateButtonStates];
  259. }
  260. #pragma mark - Rotation
  261. - (UIViewController *)viewControllerForRotationAndOrientation {
  262. UIViewController *viewController = FLEXUtility.appKeyWindow.rootViewController;
  263. // Obfuscating selector _viewControllerForSupportedInterfaceOrientations
  264. NSString *viewControllerSelectorString = [@[
  265. @"_vie", @"wContro", @"llerFor", @"Supported", @"Interface", @"Orientations"
  266. ] componentsJoinedByString:@""];
  267. SEL viewControllerSelector = NSSelectorFromString(viewControllerSelectorString);
  268. if ([viewController respondsToSelector:viewControllerSelector]) {
  269. viewController = [viewController valueForKey:viewControllerSelectorString];
  270. }
  271. return viewController;
  272. }
  273. - (UIInterfaceOrientationMask)supportedInterfaceOrientations {
  274. // Commenting this out until I can figure out a better way to solve this
  275. // if (self.window.isKeyWindow) {
  276. // [self.window resignKeyWindow];
  277. // }
  278. UIViewController *viewControllerToAsk = [self viewControllerForRotationAndOrientation];
  279. UIInterfaceOrientationMask supportedOrientations = FLEXUtility.infoPlistSupportedInterfaceOrientationsMask;
  280. if (viewControllerToAsk && ![viewControllerToAsk isKindOfClass:[self class]]) {
  281. supportedOrientations = [viewControllerToAsk supportedInterfaceOrientations];
  282. }
  283. // The UIViewController docs state that this method must not return zero.
  284. // If we weren't able to get a valid value for the supported interface
  285. // orientations, default to all supported.
  286. if (supportedOrientations == 0) {
  287. supportedOrientations = UIInterfaceOrientationMaskAll;
  288. }
  289. return supportedOrientations;
  290. }
  291. - (BOOL)shouldAutorotate {
  292. UIViewController *viewControllerToAsk = [self viewControllerForRotationAndOrientation];
  293. BOOL shouldAutorotate = YES;
  294. if (viewControllerToAsk && viewControllerToAsk != self) {
  295. shouldAutorotate = [viewControllerToAsk shouldAutorotate];
  296. }
  297. return shouldAutorotate;
  298. }
  299. - (void)viewWillTransitionToSize:(CGSize)size
  300. withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
  301. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  302. [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  303. for (UIView *outlineView in self.outlineViewsForVisibleViews.allValues) {
  304. outlineView.hidden = YES;
  305. }
  306. self.selectedViewOverlay.hidden = YES;
  307. } completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  308. for (UIView *view in self.viewsAtTapPoint) {
  309. NSValue *key = [NSValue valueWithNonretainedObject:view];
  310. UIView *outlineView = self.outlineViewsForVisibleViews[key];
  311. outlineView.frame = [self frameInLocalCoordinatesForView:view];
  312. if (self.currentMode == FLEXExplorerModeSelect) {
  313. outlineView.hidden = NO;
  314. }
  315. }
  316. if (self.selectedView) {
  317. self.selectedViewOverlay.frame = [self frameInLocalCoordinatesForView:self.selectedView];
  318. self.selectedViewOverlay.hidden = NO;
  319. }
  320. }];
  321. }
  322. #pragma mark - Setter Overrides
  323. - (void)setSelectedView:(UIView *)selectedView {
  324. if (![_selectedView isEqual:selectedView]) {
  325. if (![self.viewsAtTapPoint containsObject:_selectedView]) {
  326. [self stopObservingView:_selectedView];
  327. }
  328. _selectedView = selectedView;
  329. [self beginObservingView:selectedView];
  330. // Update the toolbar and selected overlay
  331. self.explorerToolbar.selectedViewDescription = [FLEXUtility
  332. descriptionForView:selectedView includingFrame:YES
  333. ];
  334. self.explorerToolbar.selectedViewOverlayColor = [FLEXUtility
  335. consistentRandomColorForObject:selectedView
  336. ];
  337. if (selectedView) {
  338. if (!self.selectedViewOverlay) {
  339. self.selectedViewOverlay = [UIView new];
  340. [self.view addSubview:self.selectedViewOverlay];
  341. self.selectedViewOverlay.layer.borderWidth = 1.0;
  342. }
  343. UIColor *outlineColor = [FLEXUtility consistentRandomColorForObject:selectedView];
  344. self.selectedViewOverlay.backgroundColor = [outlineColor colorWithAlphaComponent:0.2];
  345. self.selectedViewOverlay.layer.borderColor = outlineColor.CGColor;
  346. self.selectedViewOverlay.frame = [self.view convertRect:selectedView.bounds fromView:selectedView];
  347. // Make sure the selected overlay is in front of all the other subviews
  348. // except the toolbar, which should always stay on top.
  349. [self.view bringSubviewToFront:self.selectedViewOverlay];
  350. [self.view bringSubviewToFront:self.explorerToolbar];
  351. } else {
  352. [self.selectedViewOverlay removeFromSuperview];
  353. self.selectedViewOverlay = nil;
  354. }
  355. // Some of the button states depend on whether we have a selected view.
  356. [self updateButtonStates];
  357. }
  358. }
  359. - (void)setViewsAtTapPoint:(NSArray<UIView *> *)viewsAtTapPoint {
  360. if (![_viewsAtTapPoint isEqual:viewsAtTapPoint]) {
  361. for (UIView *view in _viewsAtTapPoint) {
  362. if (view != self.selectedView) {
  363. [self stopObservingView:view];
  364. }
  365. }
  366. _viewsAtTapPoint = viewsAtTapPoint;
  367. for (UIView *view in viewsAtTapPoint) {
  368. [self beginObservingView:view];
  369. }
  370. }
  371. }
  372. - (void)setCurrentMode:(FLEXExplorerMode)currentMode {
  373. if (_currentMode != currentMode) {
  374. _currentMode = currentMode;
  375. switch (currentMode) {
  376. case FLEXExplorerModeDefault:
  377. [self removeAndClearOutlineViews];
  378. self.viewsAtTapPoint = nil;
  379. self.selectedView = nil;
  380. break;
  381. case FLEXExplorerModeSelect:
  382. // Make sure the outline views are unhidden in case we came from the move mode.
  383. for (NSValue *key in self.outlineViewsForVisibleViews) {
  384. UIView *outlineView = self.outlineViewsForVisibleViews[key];
  385. outlineView.hidden = NO;
  386. }
  387. break;
  388. case FLEXExplorerModeMove:
  389. // Hide all the outline views to focus on the selected view,
  390. // which is the only one that will move.
  391. for (NSValue *key in self.outlineViewsForVisibleViews) {
  392. UIView *outlineView = self.outlineViewsForVisibleViews[key];
  393. outlineView.hidden = YES;
  394. }
  395. break;
  396. }
  397. self.movePanGR.enabled = currentMode == FLEXExplorerModeMove;
  398. [self updateButtonStates];
  399. }
  400. }
  401. #pragma mark - View Tracking
  402. - (void)beginObservingView:(UIView *)view {
  403. // Bail if we're already observing this view or if there's nothing to observe.
  404. if (!view || [self.observedViews containsObject:view]) {
  405. return;
  406. }
  407. for (NSString *keyPath in self.viewKeyPathsToTrack) {
  408. [view addObserver:self forKeyPath:keyPath options:0 context:NULL];
  409. }
  410. [self.observedViews addObject:view];
  411. }
  412. - (void)stopObservingView:(UIView *)view {
  413. if (!view) {
  414. return;
  415. }
  416. for (NSString *keyPath in self.viewKeyPathsToTrack) {
  417. [view removeObserver:self forKeyPath:keyPath];
  418. }
  419. [self.observedViews removeObject:view];
  420. }
  421. - (NSArray<NSString *> *)viewKeyPathsToTrack {
  422. static NSArray<NSString *> *trackedViewKeyPaths = nil;
  423. static dispatch_once_t onceToken;
  424. dispatch_once(&onceToken, ^{
  425. NSString *frameKeyPath = NSStringFromSelector(@selector(frame));
  426. trackedViewKeyPaths = @[frameKeyPath];
  427. });
  428. return trackedViewKeyPaths;
  429. }
  430. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
  431. change:(NSDictionary<NSString *, id> *)change
  432. context:(void *)context {
  433. [self updateOverlayAndDescriptionForObjectIfNeeded:object];
  434. }
  435. - (void)updateOverlayAndDescriptionForObjectIfNeeded:(id)object {
  436. NSUInteger indexOfView = [self.viewsAtTapPoint indexOfObject:object];
  437. if (indexOfView != NSNotFound) {
  438. UIView *view = self.viewsAtTapPoint[indexOfView];
  439. NSValue *key = [NSValue valueWithNonretainedObject:view];
  440. UIView *outline = self.outlineViewsForVisibleViews[key];
  441. if (outline) {
  442. outline.frame = [self frameInLocalCoordinatesForView:view];
  443. }
  444. }
  445. if (object == self.selectedView) {
  446. // Update the selected view description since we show the frame value there.
  447. self.explorerToolbar.selectedViewDescription = [FLEXUtility
  448. descriptionForView:self.selectedView includingFrame:YES
  449. ];
  450. CGRect selectedViewOutlineFrame = [self frameInLocalCoordinatesForView:self.selectedView];
  451. self.selectedViewOverlay.frame = selectedViewOutlineFrame;
  452. }
  453. }
  454. - (CGRect)frameInLocalCoordinatesForView:(UIView *)view {
  455. // Convert to window coordinates since the view may be in a different window than our view
  456. CGRect frameInWindow = [view convertRect:view.bounds toView:nil];
  457. // Convert from the window to our view's coordinate space
  458. return [self.view convertRect:frameInWindow fromView:nil];
  459. }
  460. #pragma mark - Toolbar Buttons
  461. - (void)setupToolbarActions {
  462. FLEXExplorerToolbar *toolbar = self.explorerToolbar;
  463. NSDictionary<NSString *, FLEXExplorerToolbarItem *> *actionsToItems = @{
  464. NSStringFromSelector(@selector(selectButtonTapped:)): toolbar.selectItem,
  465. NSStringFromSelector(@selector(hierarchyButtonTapped:)): toolbar.hierarchyItem,
  466. NSStringFromSelector(@selector(recentButtonTapped:)): toolbar.recentItem,
  467. NSStringFromSelector(@selector(moveButtonTapped:)): toolbar.moveItem,
  468. NSStringFromSelector(@selector(globalsButtonTapped:)): toolbar.globalsItem,
  469. NSStringFromSelector(@selector(closeButtonTapped:)): toolbar.closeItem,
  470. };
  471. [actionsToItems enumerateKeysAndObjectsUsingBlock:^(NSString *sel, FLEXExplorerToolbarItem *item, BOOL *stop) {
  472. #if !TARGET_OS_TV
  473. [item addTarget:self action:NSSelectorFromString(sel) forControlEvents:UIControlEventTouchUpInside];
  474. #else
  475. [item addTarget:self action:NSSelectorFromString(sel) forControlEvents:UIControlEventPrimaryActionTriggered];
  476. #endif
  477. }];
  478. }
  479. - (void)selectButtonTapped:(FLEXExplorerToolbarItem *)sender {
  480. [self toggleSelectTool];
  481. }
  482. - (void)hierarchyButtonTapped:(FLEXExplorerToolbarItem *)sender {
  483. [self toggleViewsTool];
  484. }
  485. - (UIWindow *)statusWindow {
  486. NSString *statusBarString = [NSString stringWithFormat:@"%@arWindow", @"_statusB"];
  487. return [UIApplication.sharedApplication valueForKey:statusBarString];
  488. }
  489. - (void)recentButtonTapped:(FLEXExplorerToolbarItem *)sender {
  490. NSAssert(FLEXTabList.sharedList.activeTab, @"Must have active tab");
  491. [self presentViewController:FLEXTabList.sharedList.activeTab animated:YES completion:nil];
  492. }
  493. - (void)moveButtonTapped:(FLEXExplorerToolbarItem *)sender {
  494. [self toggleMoveTool];
  495. }
  496. - (void)globalsButtonTapped:(FLEXExplorerToolbarItem *)sender {
  497. [self toggleMenuTool];
  498. }
  499. - (void)closeButtonTapped:(FLEXExplorerToolbarItem *)sender {
  500. self.currentMode = FLEXExplorerModeDefault;
  501. [self.delegate explorerViewControllerDidFinish:self];
  502. }
  503. - (void)updateButtonStates {
  504. FLEXExplorerToolbar *toolbar = self.explorerToolbar;
  505. toolbar.selectItem.selected = self.currentMode == FLEXExplorerModeSelect;
  506. // Move only enabled when an object is selected.
  507. BOOL hasSelectedObject = self.selectedView != nil;
  508. toolbar.moveItem.enabled = hasSelectedObject;
  509. toolbar.moveItem.selected = self.currentMode == FLEXExplorerModeMove;
  510. // Recent only enabled when we have a last active tab
  511. toolbar.recentItem.enabled = FLEXTabList.sharedList.activeTab != nil;
  512. }
  513. #pragma mark - Toolbar Dragging
  514. - (void)setupToolbarGestures {
  515. FLEXExplorerToolbar *toolbar = self.explorerToolbar;
  516. // Pan gesture for dragging.
  517. [toolbar.dragHandle addGestureRecognizer:[[UIPanGestureRecognizer alloc]
  518. initWithTarget:self action:@selector(handleToolbarPanGesture:)
  519. ]];
  520. // Tap gesture for hinting.
  521. [toolbar.dragHandle addGestureRecognizer:[[UITapGestureRecognizer alloc]
  522. initWithTarget:self action:@selector(handleToolbarHintTapGesture:)
  523. ]];
  524. // Tap gesture for showing additional details
  525. self.detailsTapGR = [[UITapGestureRecognizer alloc]
  526. initWithTarget:self action:@selector(handleToolbarDetailsTapGesture:)
  527. ];
  528. [toolbar.selectedViewDescriptionContainer addGestureRecognizer:self.detailsTapGR];
  529. // Swipe gestures for selecting deeper / higher views at a point
  530. UIPanGestureRecognizer *leftSwipe = [[UIPanGestureRecognizer alloc]
  531. initWithTarget:self action:@selector(handleChangeViewAtPointGesture:)
  532. ];
  533. // UIPanGestureRecognizer *rightSwipe = [[UIPanGestureRecognizer alloc]
  534. // initWithTarget:self action:@selector(handleChangeViewAtPointGesture:)
  535. // ];
  536. // leftSwipe.direction = UISwipeGestureRecognizerDirectionLeft;
  537. // rightSwipe.direction = UISwipeGestureRecognizerDirectionRight;
  538. [toolbar.selectedViewDescriptionContainer addGestureRecognizer:leftSwipe];
  539. // [toolbar.selectedViewDescriptionContainer addGestureRecognizer:rightSwipe];
  540. // Long press gesture to present tabs manager
  541. [toolbar.globalsItem addGestureRecognizer:[[UILongPressGestureRecognizer alloc]
  542. initWithTarget:self action:@selector(handleToolbarShowTabsGesture:)
  543. ]];
  544. // Long press gesture to present window manager
  545. [toolbar.selectItem addGestureRecognizer:[[UILongPressGestureRecognizer alloc]
  546. initWithTarget:self action:@selector(handleToolbarWindowManagerGesture:)
  547. ]];
  548. // Long press gesture to present view controllers at tap
  549. [toolbar.hierarchyItem addGestureRecognizer:[[UILongPressGestureRecognizer alloc]
  550. initWithTarget:self action:@selector(handleToolbarShowViewControllersGesture:)
  551. ]];
  552. }
  553. - (void)handleToolbarPanGesture:(UIPanGestureRecognizer *)panGR {
  554. switch (panGR.state) {
  555. case UIGestureRecognizerStateBegan:
  556. self.toolbarFrameBeforeDragging = self.explorerToolbar.frame;
  557. [self updateToolbarPositionWithDragGesture:panGR];
  558. break;
  559. case UIGestureRecognizerStateChanged:
  560. case UIGestureRecognizerStateEnded:
  561. [self updateToolbarPositionWithDragGesture:panGR];
  562. break;
  563. default:
  564. break;
  565. }
  566. }
  567. - (void)updateToolbarPositionWithDragGesture:(UIPanGestureRecognizer *)panGR {
  568. CGPoint translation = [panGR translationInView:self.view];
  569. CGRect newToolbarFrame = self.toolbarFrameBeforeDragging;
  570. newToolbarFrame.origin.y += translation.y;
  571. [self updateToolbarPositionWithUnconstrainedFrame:newToolbarFrame];
  572. }
  573. - (void)updateToolbarPositionWithUnconstrainedFrame:(CGRect)unconstrainedFrame {
  574. CGRect safeArea = [self viewSafeArea];
  575. // We only constrain the Y-axis because we want the toolbar
  576. // to handle the X-axis safeArea layout by itself
  577. CGFloat minY = CGRectGetMinY(safeArea);
  578. CGFloat maxY = CGRectGetMaxY(safeArea) - unconstrainedFrame.size.height;
  579. if (unconstrainedFrame.origin.y < minY) {
  580. unconstrainedFrame.origin.y = minY;
  581. } else if (unconstrainedFrame.origin.y > maxY) {
  582. unconstrainedFrame.origin.y = maxY;
  583. }
  584. self.explorerToolbar.frame = unconstrainedFrame;
  585. NSUserDefaults.standardUserDefaults.flex_toolbarTopMargin = unconstrainedFrame.origin.y;
  586. }
  587. - (void)handleToolbarHintTapGesture:(UITapGestureRecognizer *)tapGR {
  588. // Bounce the toolbar to indicate that it is draggable.
  589. // TODO: make it bouncier.
  590. if (tapGR.state == UIGestureRecognizerStateRecognized) {
  591. CGRect originalToolbarFrame = self.explorerToolbar.frame;
  592. const NSTimeInterval kHalfwayDuration = 0.2;
  593. const CGFloat kVerticalOffset = 30.0;
  594. [UIView animateWithDuration:kHalfwayDuration delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
  595. CGRect newToolbarFrame = self.explorerToolbar.frame;
  596. newToolbarFrame.origin.y += kVerticalOffset;
  597. self.explorerToolbar.frame = newToolbarFrame;
  598. } completion:^(BOOL finished) {
  599. [UIView animateWithDuration:kHalfwayDuration delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
  600. self.explorerToolbar.frame = originalToolbarFrame;
  601. } completion:nil];
  602. }];
  603. }
  604. }
  605. - (void)handleToolbarDetailsTapGesture:(UITapGestureRecognizer *)tapGR {
  606. if (tapGR.state == UIGestureRecognizerStateRecognized && self.selectedView) {
  607. UIViewController *topStackVC = [FLEXObjectExplorerFactory explorerViewControllerForObject:self.selectedView];
  608. [self presentViewController:
  609. [FLEXNavigationController withRootViewController:topStackVC]
  610. animated:YES completion:nil];
  611. }
  612. }
  613. - (void)handleToolbarShowTabsGesture:(UILongPressGestureRecognizer *)sender {
  614. if (sender.state == UIGestureRecognizerStateBegan) {
  615. // Back up the UIMenuController items since dismissViewController: will attempt to replace them
  616. #if !TARGET_OS_TV
  617. self.appMenuItems = UIMenuController.sharedMenuController.menuItems;
  618. #endif
  619. // Don't use FLEXNavigationController because the tab viewer itself is not a tab
  620. [super presentViewController:[[UINavigationController alloc]
  621. initWithRootViewController:[FLEXTabsViewController new]
  622. ] animated:YES completion:nil];
  623. }
  624. }
  625. - (void)handleToolbarWindowManagerGesture:(UILongPressGestureRecognizer *)sender {
  626. if (sender.state == UIGestureRecognizerStateBegan) {
  627. // Back up the UIMenuController items since dismissViewController: will attempt to replace them
  628. #if !TARGET_OS_TV
  629. self.appMenuItems = UIMenuController.sharedMenuController.menuItems;
  630. #endif
  631. [super presentViewController:[FLEXNavigationController
  632. withRootViewController:[FLEXWindowManagerController new]
  633. ] animated:YES completion:nil];
  634. }
  635. }
  636. - (void)handleToolbarShowViewControllersGesture:(UILongPressGestureRecognizer *)sender {
  637. if (sender.state == UIGestureRecognizerStateBegan && self.viewsAtTapPoint.count) {
  638. // Back up the UIMenuController items since dismissViewController: will attempt to replace them
  639. #if !TARGET_OS_TV
  640. self.appMenuItems = UIMenuController.sharedMenuController.menuItems;
  641. #endif
  642. UIViewController *list = [FLEXViewControllersViewController
  643. controllersForViews:self.viewsAtTapPoint
  644. ];
  645. [self presentViewController:
  646. [FLEXNavigationController withRootViewController:list
  647. ] animated:YES completion:nil];
  648. }
  649. }
  650. #pragma mark - View Selection
  651. - (void)handleSelectionTap:(UITapGestureRecognizer *)tapGR {
  652. // Only if we're in selection mode
  653. if (self.currentMode == FLEXExplorerModeSelect && tapGR.state == UIGestureRecognizerStateRecognized) {
  654. // Note that [tapGR locationInView:nil] is broken in iOS 8,
  655. // so we have to do a two step conversion to window coordinates.
  656. // Thanks to @lascorbe for finding this: https://github.com/Flipboard/FLEX/pull/31
  657. CGPoint tapPointInView = [tapGR locationInView:self.view];
  658. CGPoint tapPointInWindow = [self.view convertPoint:tapPointInView toView:nil];
  659. [self updateOutlineViewsForSelectionPoint:tapPointInWindow];
  660. }
  661. }
  662. - (void)handleChangeViewAtPointGesture:(UIPanGestureRecognizer *)sender {
  663. NSInteger max = self.viewsAtTapPoint.count - 1;
  664. NSInteger currentIdx = [self.viewsAtTapPoint indexOfObject:self.selectedView];
  665. CGFloat locationX = [sender locationInView:self.view].x;
  666. // Track the pan gesture: every N points we move along the X axis,
  667. // actuate some haptic feedback and move up or down the hierarchy.
  668. // We only store the "last" location when we've met the threshold.
  669. // We only change the view and actuate feedback if the view selection
  670. // changes; that is, as long as we don't go outside or under the array.
  671. switch (sender.state) {
  672. case UIGestureRecognizerStateBegan: {
  673. self.selectedViewLastPanX = locationX;
  674. break;
  675. }
  676. case UIGestureRecognizerStateChanged: {
  677. static CGFloat kNextLevelThreshold = 20.f;
  678. CGFloat lastX = self.selectedViewLastPanX;
  679. NSInteger newSelection = currentIdx;
  680. // Left, go down the hierarchy
  681. if (locationX < lastX && (lastX - locationX) >= kNextLevelThreshold) {
  682. // Choose a new view index up to the max index
  683. newSelection = MIN(max, currentIdx + 1);
  684. self.selectedViewLastPanX = locationX;
  685. }
  686. // Right, go up the hierarchy
  687. else if (lastX < locationX && (locationX - lastX) >= kNextLevelThreshold) {
  688. // Choose a new view index down to the min index
  689. newSelection = MAX(0, currentIdx - 1);
  690. self.selectedViewLastPanX = locationX;
  691. }
  692. if (currentIdx != newSelection) {
  693. self.selectedView = self.viewsAtTapPoint[newSelection];
  694. [self actuateSelectionChangedFeedback];
  695. }
  696. break;
  697. }
  698. default: break;
  699. }
  700. }
  701. - (void)actuateSelectionChangedFeedback {
  702. if (@available(iOS 10.0, *)) {
  703. [self.selectionFBG selectionChanged];
  704. }
  705. }
  706. - (void)updateOutlineViewsForSelectionPoint:(CGPoint)selectionPointInWindow {
  707. [self removeAndClearOutlineViews];
  708. // Include hidden views in the "viewsAtTapPoint" array so we can show them in the hierarchy list.
  709. self.viewsAtTapPoint = [self viewsAtPoint:selectionPointInWindow skipHiddenViews:NO];
  710. // For outlined views and the selected view, only use visible views.
  711. // Outlining hidden views adds clutter and makes the selection behavior confusing.
  712. NSArray<UIView *> *visibleViewsAtTapPoint = [self viewsAtPoint:selectionPointInWindow skipHiddenViews:YES];
  713. NSMutableDictionary<NSValue *, UIView *> *newOutlineViewsForVisibleViews = [NSMutableDictionary new];
  714. for (UIView *view in visibleViewsAtTapPoint) {
  715. UIView *outlineView = [self outlineViewForView:view];
  716. [self.view addSubview:outlineView];
  717. NSValue *key = [NSValue valueWithNonretainedObject:view];
  718. [newOutlineViewsForVisibleViews setObject:outlineView forKey:key];
  719. }
  720. self.outlineViewsForVisibleViews = newOutlineViewsForVisibleViews;
  721. self.selectedView = [self viewForSelectionAtPoint:selectionPointInWindow];
  722. // Make sure the explorer toolbar doesn't end up behind the newly added outline views.
  723. [self.view bringSubviewToFront:self.explorerToolbar];
  724. [self updateButtonStates];
  725. }
  726. - (UIView *)outlineViewForView:(UIView *)view {
  727. CGRect outlineFrame = [self frameInLocalCoordinatesForView:view];
  728. UIView *outlineView = [[UIView alloc] initWithFrame:outlineFrame];
  729. outlineView.backgroundColor = UIColor.clearColor;
  730. outlineView.layer.borderColor = [FLEXUtility consistentRandomColorForObject:view].CGColor;
  731. outlineView.layer.borderWidth = 1.0;
  732. return outlineView;
  733. }
  734. - (void)removeAndClearOutlineViews {
  735. for (NSValue *key in self.outlineViewsForVisibleViews) {
  736. UIView *outlineView = self.outlineViewsForVisibleViews[key];
  737. [outlineView removeFromSuperview];
  738. }
  739. self.outlineViewsForVisibleViews = nil;
  740. }
  741. - (NSArray<UIView *> *)viewsAtPoint:(CGPoint)tapPointInWindow skipHiddenViews:(BOOL)skipHidden {
  742. NSMutableArray<UIView *> *views = [NSMutableArray new];
  743. for (UIWindow *window in FLEXUtility.allWindows) {
  744. // Don't include the explorer's own window or subviews.
  745. if (window != self.view.window && [window pointInside:tapPointInWindow withEvent:nil]) {
  746. [views addObject:window];
  747. [views addObjectsFromArray:[self
  748. recursiveSubviewsAtPoint:tapPointInWindow inView:window skipHiddenViews:skipHidden
  749. ]];
  750. }
  751. }
  752. return views;
  753. }
  754. - (UIView *)viewForSelectionAtPoint:(CGPoint)tapPointInWindow {
  755. // Select in the window that would handle the touch, but don't just use the result of
  756. // hitTest:withEvent: so we can still select views with interaction disabled.
  757. // Default to the the application's key window if none of the windows want the touch.
  758. UIWindow *windowForSelection = UIApplication.sharedApplication.keyWindow;
  759. for (UIWindow *window in FLEXUtility.allWindows.reverseObjectEnumerator) {
  760. // Ignore the explorer's own window.
  761. if (window != self.view.window) {
  762. if ([window hitTest:tapPointInWindow withEvent:nil]) {
  763. windowForSelection = window;
  764. break;
  765. }
  766. }
  767. }
  768. // Select the deepest visible view at the tap point. This generally corresponds to what the user wants to select.
  769. return [self recursiveSubviewsAtPoint:tapPointInWindow inView:windowForSelection skipHiddenViews:YES].lastObject;
  770. }
  771. - (NSArray<UIView *> *)recursiveSubviewsAtPoint:(CGPoint)pointInView
  772. inView:(UIView *)view
  773. skipHiddenViews:(BOOL)skipHidden {
  774. NSMutableArray<UIView *> *subviewsAtPoint = [NSMutableArray new];
  775. for (UIView *subview in view.subviews) {
  776. BOOL isHidden = subview.hidden || subview.alpha < 0.01;
  777. if (skipHidden && isHidden) {
  778. continue;
  779. }
  780. BOOL subviewContainsPoint = CGRectContainsPoint(subview.frame, pointInView);
  781. if (subviewContainsPoint) {
  782. [subviewsAtPoint addObject:subview];
  783. }
  784. // If this view doesn't clip to its bounds, we need to check its subviews even if it
  785. // doesn't contain the selection point. They may be visible and contain the selection point.
  786. if (subviewContainsPoint || !subview.clipsToBounds) {
  787. CGPoint pointInSubview = [view convertPoint:pointInView toView:subview];
  788. [subviewsAtPoint addObjectsFromArray:[self
  789. recursiveSubviewsAtPoint:pointInSubview inView:subview skipHiddenViews:skipHidden
  790. ]];
  791. }
  792. }
  793. return subviewsAtPoint;
  794. }
  795. #pragma mark - Selected View Moving
  796. - (void)handleMovePan:(UIPanGestureRecognizer *)movePanGR {
  797. switch (movePanGR.state) {
  798. case UIGestureRecognizerStateBegan:
  799. self.selectedViewFrameBeforeDragging = self.selectedView.frame;
  800. [self updateSelectedViewPositionWithDragGesture:movePanGR];
  801. break;
  802. case UIGestureRecognizerStateChanged:
  803. case UIGestureRecognizerStateEnded:
  804. [self updateSelectedViewPositionWithDragGesture:movePanGR];
  805. break;
  806. default:
  807. break;
  808. }
  809. }
  810. - (void)updateSelectedViewPositionWithDragGesture:(UIPanGestureRecognizer *)movePanGR {
  811. CGPoint translation = [movePanGR translationInView:self.selectedView.superview];
  812. CGRect newSelectedViewFrame = self.selectedViewFrameBeforeDragging;
  813. newSelectedViewFrame.origin.x = FLEXFloor(newSelectedViewFrame.origin.x + translation.x);
  814. newSelectedViewFrame.origin.y = FLEXFloor(newSelectedViewFrame.origin.y + translation.y);
  815. self.selectedView.frame = newSelectedViewFrame;
  816. }
  817. #pragma mark - Safe Area Handling
  818. - (CGRect)viewSafeArea {
  819. CGRect safeArea = self.view.bounds;
  820. if (@available(iOS 11.0, *)) {
  821. safeArea = UIEdgeInsetsInsetRect(self.view.bounds, self.view.safeAreaInsets);
  822. }
  823. return safeArea;
  824. }
  825. - (void)viewSafeAreaInsetsDidChange {
  826. if (@available(iOS 11.0, *)) {
  827. [super viewSafeAreaInsetsDidChange];
  828. CGRect safeArea = [self viewSafeArea];
  829. CGSize toolbarSize = [self.explorerToolbar sizeThatFits:CGSizeMake(
  830. CGRectGetWidth(self.view.bounds), CGRectGetHeight(safeArea)
  831. )];
  832. [self updateToolbarPositionWithUnconstrainedFrame:CGRectMake(
  833. CGRectGetMinX(self.explorerToolbar.frame),
  834. CGRectGetMinY(self.explorerToolbar.frame),
  835. toolbarSize.width,
  836. toolbarSize.height)
  837. ];
  838. }
  839. }
  840. #pragma mark - Touch Handling
  841. - (BOOL)shouldReceiveTouchAtWindowPoint:(CGPoint)pointInWindowCoordinates {
  842. BOOL shouldReceiveTouch = NO;
  843. CGPoint pointInLocalCoordinates = [self.view convertPoint:pointInWindowCoordinates fromView:nil];
  844. // Always if it's on the toolbar
  845. if (CGRectContainsPoint(self.explorerToolbar.frame, pointInLocalCoordinates)) {
  846. shouldReceiveTouch = YES;
  847. }
  848. // Always if we're in selection mode
  849. if (!shouldReceiveTouch && self.currentMode == FLEXExplorerModeSelect) {
  850. shouldReceiveTouch = YES;
  851. }
  852. // Always in move mode too
  853. if (!shouldReceiveTouch && self.currentMode == FLEXExplorerModeMove) {
  854. shouldReceiveTouch = YES;
  855. }
  856. // Always if we have a modal presented
  857. if (!shouldReceiveTouch && self.presentedViewController) {
  858. shouldReceiveTouch = YES;
  859. }
  860. return shouldReceiveTouch;
  861. }
  862. #pragma mark - FLEXHierarchyDelegate
  863. - (void)viewHierarchyDidDismiss:(UIView *)selectedView {
  864. // Note that we need to wait until the view controller is dismissed to calculate the frame
  865. // of the outline view, otherwise the coordinate conversion doesn't give the correct result.
  866. [self toggleViewsToolWithCompletion:^{
  867. // If the selected view is outside of the tap point array (selected from "Full Hierarchy"),
  868. // then clear out the tap point array and remove all the outline views.
  869. if (![self.viewsAtTapPoint containsObject:selectedView]) {
  870. self.viewsAtTapPoint = nil;
  871. [self removeAndClearOutlineViews];
  872. }
  873. // If we now have a selected view and we didn't have one previously, go to "select" mode.
  874. if (self.currentMode == FLEXExplorerModeDefault && selectedView) {
  875. //self.currentMode = FLEXExplorerModeSelect;
  876. [self toggleSelectTool];
  877. }
  878. // The selected view setter will also update the selected view overlay appropriately.
  879. self.selectedView = selectedView;
  880. }];
  881. }
  882. #pragma mark - Modal Presentation and Window Management
  883. - (void)presentViewController:(UIViewController *)toPresent
  884. animated:(BOOL)animated
  885. completion:(void (^)(void))completion {
  886. // Make our window key to correctly handle input.
  887. [self.view.window makeKeyWindow];
  888. // Move the status bar on top of FLEX so we can get scroll to top behavior for taps.
  889. if (!@available(iOS 13, *)) {
  890. [self statusWindow].windowLevel = self.view.window.windowLevel + 1.0;
  891. }
  892. #if !TARGET_OS_TV
  893. // Back up and replace the UIMenuController items
  894. // Edit: no longer replacing the items, but still backing them
  895. // up in case we start replacing them again in the future
  896. self.appMenuItems = UIMenuController.sharedMenuController.menuItems;
  897. #endif
  898. // Show the view controller
  899. [super presentViewController:toPresent animated:animated completion:completion];
  900. }
  901. - (void)dismissViewControllerAnimated:(BOOL)animated completion:(void (^)(void))completion {
  902. UIWindow *appWindow = self.window.previousKeyWindow;
  903. [appWindow makeKeyWindow];
  904. #if !TARGET_OS_TV
  905. [appWindow.rootViewController setNeedsStatusBarAppearanceUpdate];
  906. // Restore previous UIMenuController items
  907. // Back up and replace the UIMenuController items
  908. UIMenuController.sharedMenuController.menuItems = self.appMenuItems;
  909. [UIMenuController.sharedMenuController update];
  910. self.appMenuItems = nil;
  911. #endif
  912. // Restore the status bar window's normal window level.
  913. // We want it above FLEX while a modal is presented for
  914. // scroll to top, but below FLEX otherwise for exploration.
  915. [self statusWindow].windowLevel = UIWindowLevelStatusBar;
  916. [self updateButtonStates];
  917. [super dismissViewControllerAnimated:animated completion:completion];
  918. }
  919. - (BOOL)wantsWindowToBecomeKey
  920. {
  921. return self.window.previousKeyWindow != nil;
  922. }
  923. - (void)toggleToolWithViewControllerProvider:(UINavigationController *(^)(void))future
  924. completion:(void(^)(void))completion {
  925. if (self.presentedViewController) {
  926. [self dismissViewControllerAnimated:YES completion:completion];
  927. } else if (future) {
  928. [self presentViewController:future() animated:YES completion:completion];
  929. }
  930. }
  931. - (FLEXWindow *)window {
  932. return (id)self.view.window;
  933. }
  934. - (void)disableToolbar {
  935. [self.explorerToolbar setUserInteractionEnabled:false];
  936. [self.explorerToolbar setAlpha:0.5];
  937. [self setNeedsFocusUpdate];
  938. [self updateFocusIfNeeded];
  939. }
  940. - (void)enableToolbar {
  941. [self.explorerToolbar setUserInteractionEnabled:true];
  942. [self.explorerToolbar setAlpha:1.0];
  943. [self setNeedsFocusUpdate];
  944. [self updateFocusIfNeeded];
  945. }
  946. #pragma mark - Keyboard Shortcut Helpers
  947. - (void)toggleSelectTool {
  948. if (self.currentMode == FLEXExplorerModeSelect) {
  949. self.currentMode = FLEXExplorerModeDefault;
  950. cursorView.hidden = true;
  951. [self enableToolbar];
  952. } else {
  953. self.currentMode = FLEXExplorerModeSelect;
  954. cursorView.hidden = false;
  955. [self disableToolbar];
  956. }
  957. }
  958. - (void)toggleMoveTool {
  959. if (self.currentMode == FLEXExplorerModeMove) {
  960. self.currentMode = FLEXExplorerModeSelect;
  961. } else if (self.currentMode == FLEXExplorerModeSelect && self.selectedView) {
  962. self.currentMode = FLEXExplorerModeMove;
  963. }
  964. }
  965. - (void)toggleViewsTool {
  966. [self toggleViewsToolWithCompletion:nil];
  967. }
  968. - (void)toggleViewsToolWithCompletion:(void(^)(void))completion {
  969. [self toggleToolWithViewControllerProvider:^UINavigationController *{
  970. if (self.selectedView) {
  971. NSLog(@"[FLEXInjected] we have a selected view still: %@", self.selectedView);
  972. return [FLEXHierarchyViewController
  973. delegate:self
  974. viewsAtTap:self.viewsAtTapPoint
  975. selectedView:self.selectedView
  976. ];
  977. } else {
  978. return [FLEXHierarchyViewController delegate:self];
  979. }
  980. } completion:^{
  981. if (completion) {
  982. completion();
  983. }
  984. }];
  985. }
  986. - (void)toggleMenuTool {
  987. [self toggleToolWithViewControllerProvider:^UINavigationController *{
  988. return [FLEXNavigationController withRootViewController:[FLEXGlobalsViewController new]];
  989. } completion:nil];
  990. }
  991. - (BOOL)handleDownArrowKeyPressed {
  992. if (self.currentMode == FLEXExplorerModeMove) {
  993. CGRect frame = self.selectedView.frame;
  994. frame.origin.y += 1.0 / UIScreen.mainScreen.scale;
  995. self.selectedView.frame = frame;
  996. } else if (self.currentMode == FLEXExplorerModeSelect && self.viewsAtTapPoint.count > 0) {
  997. NSInteger selectedViewIndex = [self.viewsAtTapPoint indexOfObject:self.selectedView];
  998. if (selectedViewIndex > 0) {
  999. self.selectedView = [self.viewsAtTapPoint objectAtIndex:selectedViewIndex - 1];
  1000. }
  1001. } else {
  1002. return NO;
  1003. }
  1004. return YES;
  1005. }
  1006. - (BOOL)handleUpArrowKeyPressed {
  1007. if (self.currentMode == FLEXExplorerModeMove) {
  1008. CGRect frame = self.selectedView.frame;
  1009. frame.origin.y -= 1.0 / UIScreen.mainScreen.scale;
  1010. self.selectedView.frame = frame;
  1011. } else if (self.currentMode == FLEXExplorerModeSelect && self.viewsAtTapPoint.count > 0) {
  1012. NSInteger selectedViewIndex = [self.viewsAtTapPoint indexOfObject:self.selectedView];
  1013. if (selectedViewIndex < self.viewsAtTapPoint.count - 1) {
  1014. self.selectedView = [self.viewsAtTapPoint objectAtIndex:selectedViewIndex + 1];
  1015. }
  1016. } else {
  1017. return NO;
  1018. }
  1019. return YES;
  1020. }
  1021. - (BOOL)handleRightArrowKeyPressed {
  1022. if (self.currentMode == FLEXExplorerModeMove) {
  1023. CGRect frame = self.selectedView.frame;
  1024. frame.origin.x += 1.0 / UIScreen.mainScreen.scale;
  1025. self.selectedView.frame = frame;
  1026. return YES;
  1027. }
  1028. return NO;
  1029. }
  1030. - (BOOL)handleLeftArrowKeyPressed {
  1031. if (self.currentMode == FLEXExplorerModeMove) {
  1032. CGRect frame = self.selectedView.frame;
  1033. frame.origin.x -= 1.0 / UIScreen.mainScreen.scale;
  1034. self.selectedView.frame = frame;
  1035. return YES;
  1036. }
  1037. return NO;
  1038. }
  1039. @end