FLEXExplorerViewController.m 45 KB

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