FLEXExplorerViewController.m 48 KB

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