FLEXExplorerViewController.m 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  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, FLEXGlobalsTableViewControllerDelegate>
  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. FLEXObjectExplorerViewController *selectedViewExplorer = [FLEXObjectExplorerFactory explorerViewControllerForObject:self.selectedView];
  408. selectedViewExplorer.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(selectedViewExplorerFinished:)];
  409. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:selectedViewExplorer];
  410. [self makeKeyAndPresentViewController:navigationController animated:YES completion:nil];
  411. }
  412. }
  413. #pragma mark - View Selection
  414. - (void)handleSelectionTap:(UITapGestureRecognizer *)tapGR
  415. {
  416. // Only if we're in selection mode
  417. if (self.currentMode == FLEXExplorerModeSelect && tapGR.state == UIGestureRecognizerStateRecognized) {
  418. // Note that [tapGR locationInView:nil] is broken in iOS 8, so we have to do a two step conversion to window coordinates.
  419. // Thanks to @lascorbe for finding this: https://github.com/Flipboard/FLEX/pull/31
  420. CGPoint tapPointInView = [tapGR locationInView:self.view];
  421. CGPoint tapPointInWindow = [self.view convertPoint:tapPointInView toView:nil];
  422. [self updateOutlineViewsForSelectionPoint:tapPointInWindow];
  423. }
  424. }
  425. - (void)updateOutlineViewsForSelectionPoint:(CGPoint)selectionPointInWindow
  426. {
  427. [self removeAndClearOutlineViews];
  428. // Include hidden views in the "viewsAtTapPoint" array so we can show them in the hierarchy list.
  429. self.viewsAtTapPoint = [self viewsAtPoint:selectionPointInWindow skipHiddenViews:NO];
  430. // For outlined views and the selected view, only use visible views.
  431. // Outlining hidden views adds clutter and makes the selection behavior confusing.
  432. NSArray<UIView *> *visibleViewsAtTapPoint = [self viewsAtPoint:selectionPointInWindow skipHiddenViews:YES];
  433. NSMutableDictionary<NSValue *, UIView *> *newOutlineViewsForVisibleViews = [NSMutableDictionary dictionary];
  434. for (UIView *view in visibleViewsAtTapPoint) {
  435. UIView *outlineView = [self outlineViewForView:view];
  436. [self.view addSubview:outlineView];
  437. NSValue *key = [NSValue valueWithNonretainedObject:view];
  438. [newOutlineViewsForVisibleViews setObject:outlineView forKey:key];
  439. }
  440. self.outlineViewsForVisibleViews = newOutlineViewsForVisibleViews;
  441. self.selectedView = [self viewForSelectionAtPoint:selectionPointInWindow];
  442. // Make sure the explorer toolbar doesn't end up behind the newly added outline views.
  443. [self.view bringSubviewToFront:self.explorerToolbar];
  444. [self updateButtonStates];
  445. }
  446. - (UIView *)outlineViewForView:(UIView *)view
  447. {
  448. CGRect outlineFrame = [self frameInLocalCoordinatesForView:view];
  449. UIView *outlineView = [[UIView alloc] initWithFrame:outlineFrame];
  450. outlineView.backgroundColor = UIColor.clearColor;
  451. outlineView.layer.borderColor = [FLEXUtility consistentRandomColorForObject:view].CGColor;
  452. outlineView.layer.borderWidth = 1.0;
  453. return outlineView;
  454. }
  455. - (void)removeAndClearOutlineViews
  456. {
  457. for (NSValue *key in self.outlineViewsForVisibleViews) {
  458. UIView *outlineView = self.outlineViewsForVisibleViews[key];
  459. [outlineView removeFromSuperview];
  460. }
  461. self.outlineViewsForVisibleViews = nil;
  462. }
  463. - (NSArray<UIView *> *)viewsAtPoint:(CGPoint)tapPointInWindow skipHiddenViews:(BOOL)skipHidden
  464. {
  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 recursiveSubviewsAtPoint:tapPointInWindow inView:window skipHiddenViews:skipHidden]];
  471. }
  472. }
  473. return views;
  474. }
  475. - (UIView *)viewForSelectionAtPoint:(CGPoint)tapPointInWindow
  476. {
  477. // 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.
  478. // Default to the the application's key window if none of the windows want the touch.
  479. UIWindow *windowForSelection = [UIApplication.sharedApplication keyWindow];
  480. for (UIWindow *window in [FLEXUtility allWindows].reverseObjectEnumerator) {
  481. // Ignore the explorer's own window.
  482. if (window != self.view.window) {
  483. if ([window hitTest:tapPointInWindow withEvent:nil]) {
  484. windowForSelection = window;
  485. break;
  486. }
  487. }
  488. }
  489. // Select the deepest visible view at the tap point. This generally corresponds to what the user wants to select.
  490. return [self recursiveSubviewsAtPoint:tapPointInWindow inView:windowForSelection skipHiddenViews:YES].lastObject;
  491. }
  492. - (NSArray<UIView *> *)recursiveSubviewsAtPoint:(CGPoint)pointInView inView:(UIView *)view skipHiddenViews:(BOOL)skipHidden
  493. {
  494. NSMutableArray<UIView *> *subviewsAtPoint = [NSMutableArray array];
  495. for (UIView *subview in view.subviews) {
  496. BOOL isHidden = subview.hidden || subview.alpha < 0.01;
  497. if (skipHidden && isHidden) {
  498. continue;
  499. }
  500. BOOL subviewContainsPoint = CGRectContainsPoint(subview.frame, pointInView);
  501. if (subviewContainsPoint) {
  502. [subviewsAtPoint addObject:subview];
  503. }
  504. // If this view doesn't clip to its bounds, we need to check its subviews even if it doesn't contain the selection point.
  505. // They may be visible and contain the selection point.
  506. if (subviewContainsPoint || !subview.clipsToBounds) {
  507. CGPoint pointInSubview = [view convertPoint:pointInView toView:subview];
  508. [subviewsAtPoint addObjectsFromArray:[self recursiveSubviewsAtPoint:pointInSubview inView:subview skipHiddenViews:skipHidden]];
  509. }
  510. }
  511. return subviewsAtPoint;
  512. }
  513. #pragma mark - Selected View Moving
  514. - (void)handleMovePan:(UIPanGestureRecognizer *)movePanGR
  515. {
  516. switch (movePanGR.state) {
  517. case UIGestureRecognizerStateBegan:
  518. self.selectedViewFrameBeforeDragging = self.selectedView.frame;
  519. [self updateSelectedViewPositionWithDragGesture:movePanGR];
  520. break;
  521. case UIGestureRecognizerStateChanged:
  522. case UIGestureRecognizerStateEnded:
  523. [self updateSelectedViewPositionWithDragGesture:movePanGR];
  524. break;
  525. default:
  526. break;
  527. }
  528. }
  529. - (void)updateSelectedViewPositionWithDragGesture:(UIPanGestureRecognizer *)movePanGR
  530. {
  531. CGPoint translation = [movePanGR translationInView:self.selectedView.superview];
  532. CGRect newSelectedViewFrame = self.selectedViewFrameBeforeDragging;
  533. newSelectedViewFrame.origin.x = FLEXFloor(newSelectedViewFrame.origin.x + translation.x);
  534. newSelectedViewFrame.origin.y = FLEXFloor(newSelectedViewFrame.origin.y + translation.y);
  535. self.selectedView.frame = newSelectedViewFrame;
  536. }
  537. #pragma mark - Safe Area Handling
  538. - (CGRect)viewSafeArea
  539. {
  540. CGRect safeArea = self.view.bounds;
  541. if (@available(iOS 11.0, *)) {
  542. safeArea = UIEdgeInsetsInsetRect(self.view.bounds, self.view.safeAreaInsets);
  543. }
  544. return safeArea;
  545. }
  546. - (void)viewSafeAreaInsetsDidChange
  547. {
  548. if (@available(iOS 11.0, *)) {
  549. [super viewSafeAreaInsetsDidChange];
  550. CGRect safeArea = [self viewSafeArea];
  551. CGSize toolbarSize = [self.explorerToolbar sizeThatFits:CGSizeMake(CGRectGetWidth(self.view.bounds), CGRectGetHeight(safeArea))];
  552. [self updateToolbarPositionWithUnconstrainedFrame:CGRectMake(CGRectGetMinX(self.explorerToolbar.frame), CGRectGetMinY(self.explorerToolbar.frame), toolbarSize.width, toolbarSize.height)];
  553. }
  554. }
  555. #pragma mark - Touch Handling
  556. - (BOOL)shouldReceiveTouchAtWindowPoint:(CGPoint)pointInWindowCoordinates
  557. {
  558. BOOL shouldReceiveTouch = NO;
  559. CGPoint pointInLocalCoordinates = [self.view convertPoint:pointInWindowCoordinates fromView:nil];
  560. // Always if it's on the toolbar
  561. if (CGRectContainsPoint(self.explorerToolbar.frame, pointInLocalCoordinates)) {
  562. shouldReceiveTouch = YES;
  563. }
  564. // Always if we're in selection mode
  565. if (!shouldReceiveTouch && self.currentMode == FLEXExplorerModeSelect) {
  566. shouldReceiveTouch = YES;
  567. }
  568. // Always in move mode too
  569. if (!shouldReceiveTouch && self.currentMode == FLEXExplorerModeMove) {
  570. shouldReceiveTouch = YES;
  571. }
  572. // Always if we have a modal presented
  573. if (!shouldReceiveTouch && self.presentedViewController) {
  574. shouldReceiveTouch = YES;
  575. }
  576. return shouldReceiveTouch;
  577. }
  578. #pragma mark - FLEXHierarchyDelegate
  579. - (void)viewHierarchyDidDismiss:(UIView *)selectedView
  580. {
  581. // Note that we need to wait until the view controller is dismissed to calculated the frame of the outline view.
  582. // Otherwise the coordinate conversion doesn't give the correct result.
  583. [self toggleViewsToolWithCompletion:^{
  584. // If the selected view is outside of the tap point array (selected from "Full Hierarchy"),
  585. // then clear out the tap point array and remove all the outline views.
  586. if (![self.viewsAtTapPoint containsObject:selectedView]) {
  587. self.viewsAtTapPoint = nil;
  588. [self removeAndClearOutlineViews];
  589. }
  590. // If we now have a selected view and we didn't have one previously, go to "select" mode.
  591. if (self.currentMode == FLEXExplorerModeDefault && selectedView) {
  592. self.currentMode = FLEXExplorerModeSelect;
  593. }
  594. // The selected view setter will also update the selected view overlay appropriately.
  595. self.selectedView = selectedView;
  596. }];
  597. }
  598. #pragma mark - FLEXGlobalsViewControllerDelegate
  599. - (void)globalsViewControllerDidFinish:(FLEXGlobalsTableViewController *)globalsViewController
  600. {
  601. [self resignKeyAndDismissViewControllerAnimated:YES completion:nil];
  602. }
  603. #pragma mark - FLEXObjectExplorerViewController Done Action
  604. - (void)selectedViewExplorerFinished:(id)sender
  605. {
  606. [self resignKeyAndDismissViewControllerAnimated:YES completion:nil];
  607. }
  608. #pragma mark - Modal Presentation and Window Management
  609. - (void)makeKeyAndPresentViewController:(UIViewController *)viewController animated:(BOOL)animated completion:(void (^)(void))completion
  610. {
  611. // Save the current key window so we can restore it following dismissal.
  612. self.previousKeyWindow = UIApplication.sharedApplication.keyWindow;
  613. // Make our window key to correctly handle input.
  614. [self.view.window makeKeyWindow];
  615. // Move the status bar on top of FLEX so we can get scroll to top behavior for taps.
  616. if (!@available(iOS 13, *)) {
  617. [self statusWindow].windowLevel = self.view.window.windowLevel + 1.0;
  618. }
  619. // Back up and replace the UIMenuController items
  620. self.appMenuItems = UIMenuController.sharedMenuController.menuItems;
  621. // Initialize custom menu items for explorer screen
  622. UIMenuItem *copyObjectAddress = [[UIMenuItem alloc]
  623. initWithTitle:@"Copy Address"
  624. action:NSSelectorFromString(@"copyObjectAddress:")
  625. ];
  626. UIMenuController.sharedMenuController.menuItems = @[copyObjectAddress];
  627. [UIMenuController.sharedMenuController update];
  628. // Show the view controller.
  629. [self presentViewController:viewController animated:animated completion:completion];
  630. }
  631. - (void)resignKeyAndDismissViewControllerAnimated:(BOOL)animated completion:(void (^)(void))completion
  632. {
  633. UIWindow *previousKeyWindow = self.previousKeyWindow;
  634. self.previousKeyWindow = nil;
  635. [previousKeyWindow makeKeyWindow];
  636. [previousKeyWindow.rootViewController setNeedsStatusBarAppearanceUpdate];
  637. // Restore previous UIMenuController items
  638. // Back up and replace the UIMenuController items
  639. UIMenuController.sharedMenuController.menuItems = self.appMenuItems;
  640. [UIMenuController.sharedMenuController update];
  641. self.appMenuItems = nil;
  642. // Restore the status bar window's normal window level.
  643. // We want it above FLEX while a modal is presented for scroll to top, but below FLEX otherwise for exploration.
  644. [self statusWindow].windowLevel = UIWindowLevelStatusBar;
  645. [self dismissViewControllerAnimated:animated completion:completion];
  646. }
  647. - (BOOL)wantsWindowToBecomeKey
  648. {
  649. return self.previousKeyWindow != nil;
  650. }
  651. - (void)toggleToolWithViewControllerProvider:(UIViewController *(^)(void))future completion:(void(^)(void))completion
  652. {
  653. if (self.presentedViewController) {
  654. [self resignKeyAndDismissViewControllerAnimated:YES completion:completion];
  655. } else if (future) {
  656. [self makeKeyAndPresentViewController:future() animated:YES completion:completion];
  657. }
  658. }
  659. #pragma mark - Keyboard Shortcut Helpers
  660. - (void)toggleSelectTool
  661. {
  662. if (self.currentMode == FLEXExplorerModeSelect) {
  663. self.currentMode = FLEXExplorerModeDefault;
  664. } else {
  665. self.currentMode = FLEXExplorerModeSelect;
  666. }
  667. }
  668. - (void)toggleMoveTool
  669. {
  670. if (self.currentMode == FLEXExplorerModeMove) {
  671. self.currentMode = FLEXExplorerModeDefault;
  672. } else {
  673. self.currentMode = FLEXExplorerModeMove;
  674. }
  675. }
  676. - (void)toggleViewsTool
  677. {
  678. [self toggleViewsToolWithCompletion:nil];
  679. }
  680. - (void)toggleViewsToolWithCompletion:(void(^)(void))completion
  681. {
  682. [self toggleToolWithViewControllerProvider:^UIViewController *{
  683. if (self.selectedView) {
  684. return [FLEXHierarchyViewController
  685. delegate:self
  686. viewsAtTap:self.viewsAtTapPoint
  687. selectedView:self.selectedView
  688. ];
  689. } else {
  690. return [FLEXHierarchyViewController delegate:self];
  691. }
  692. } completion:^{
  693. if (completion) {
  694. completion();
  695. }
  696. }];
  697. }
  698. - (void)toggleMenuTool
  699. {
  700. [self toggleToolWithViewControllerProvider:^UIViewController *{
  701. FLEXGlobalsTableViewController *globalsViewController = [FLEXGlobalsTableViewController new];
  702. globalsViewController.delegate = self;
  703. [FLEXGlobalsTableViewController setApplicationWindow:[UIApplication.sharedApplication keyWindow]];
  704. return [[UINavigationController alloc] initWithRootViewController:globalsViewController];
  705. } completion:nil];
  706. }
  707. - (void)handleDownArrowKeyPressed
  708. {
  709. if (self.currentMode == FLEXExplorerModeMove) {
  710. CGRect frame = self.selectedView.frame;
  711. frame.origin.y += 1.0 / UIScreen.mainScreen.scale;
  712. self.selectedView.frame = frame;
  713. } else if (self.currentMode == FLEXExplorerModeSelect && self.viewsAtTapPoint.count > 0) {
  714. NSInteger selectedViewIndex = [self.viewsAtTapPoint indexOfObject:self.selectedView];
  715. if (selectedViewIndex > 0) {
  716. self.selectedView = [self.viewsAtTapPoint objectAtIndex:selectedViewIndex - 1];
  717. }
  718. }
  719. }
  720. - (void)handleUpArrowKeyPressed
  721. {
  722. if (self.currentMode == FLEXExplorerModeMove) {
  723. CGRect frame = self.selectedView.frame;
  724. frame.origin.y -= 1.0 / UIScreen.mainScreen.scale;
  725. self.selectedView.frame = frame;
  726. } else if (self.currentMode == FLEXExplorerModeSelect && self.viewsAtTapPoint.count > 0) {
  727. NSInteger selectedViewIndex = [self.viewsAtTapPoint indexOfObject:self.selectedView];
  728. if (selectedViewIndex < self.viewsAtTapPoint.count - 1) {
  729. self.selectedView = [self.viewsAtTapPoint objectAtIndex:selectedViewIndex + 1];
  730. }
  731. }
  732. }
  733. - (void)handleRightArrowKeyPressed
  734. {
  735. if (self.currentMode == FLEXExplorerModeMove) {
  736. CGRect frame = self.selectedView.frame;
  737. frame.origin.x += 1.0 / UIScreen.mainScreen.scale;
  738. self.selectedView.frame = frame;
  739. }
  740. }
  741. - (void)handleLeftArrowKeyPressed
  742. {
  743. if (self.currentMode == FLEXExplorerModeMove) {
  744. CGRect frame = self.selectedView.frame;
  745. frame.origin.x -= 1.0 / UIScreen.mainScreen.scale;
  746. self.selectedView.frame = frame;
  747. }
  748. }
  749. @end