FLEXExplorerViewController.m 35 KB

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