FLEXExplorerViewController.m 35 KB

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