FLEXExplorerViewController.m 45 KB

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