FLEXExplorerViewController.m 48 KB

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