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