FLEXExplorerViewController.m 40 KB

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