FLEXExplorerViewController.m 47 KB

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