FLEXExplorerViewController.m 35 KB

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