FLEXExplorerViewController.m 49 KB

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