FLEXExplorerViewController.m 37 KB

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