FLEXExplorerViewController.m 49 KB

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