FLEXExplorerViewController.m 48 KB

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