FLEXExplorerViewController.m 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  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 "FLEXNavigationController.h"
  13. #import "FLEXHierarchyViewController.h"
  14. #import "FLEXGlobalsTableViewController.h"
  15. #import "FLEXObjectExplorerViewController.h"
  16. #import "FLEXObjectExplorerFactory.h"
  17. #import "FLEXNetworkHistoryTableViewController.h"
  18. static NSString *const kFLEXToolbarTopMarginDefaultsKey = @"com.flex.FLEXToolbar.topMargin";
  19. typedef NS_ENUM(NSUInteger, FLEXExplorerMode) {
  20. FLEXExplorerModeDefault,
  21. FLEXExplorerModeSelect,
  22. FLEXExplorerModeMove
  23. };
  24. @interface FLEXExplorerViewController () <FLEXHierarchyDelegate, UIAdaptivePresentationControllerDelegate>
  25. @property (nonatomic) FLEXExplorerToolbar *explorerToolbar;
  26. /// Tracks the currently active tool/mode
  27. @property (nonatomic) FLEXExplorerMode currentMode;
  28. /// Gesture recognizer for dragging a view in move mode
  29. @property (nonatomic) UIPanGestureRecognizer *movePanGR;
  30. /// Gesture recognizer for showing additional details on the selected view
  31. @property (nonatomic) UITapGestureRecognizer *detailsTapGR;
  32. /// Only valid while a move pan gesture is in progress.
  33. @property (nonatomic) CGRect selectedViewFrameBeforeDragging;
  34. /// Only valid while a toolbar drag pan gesture is in progress.
  35. @property (nonatomic) CGRect toolbarFrameBeforeDragging;
  36. /// Borders of all the visible views in the hierarchy at the selection point.
  37. /// The keys are NSValues with the corresponding view (nonretained).
  38. @property (nonatomic) NSDictionary<NSValue *, UIView *> *outlineViewsForVisibleViews;
  39. /// The actual views at the selection point with the deepest view last.
  40. @property (nonatomic) NSArray<UIView *> *viewsAtTapPoint;
  41. /// The view that we're currently highlighting with an overlay and displaying details for.
  42. @property (nonatomic) UIView *selectedView;
  43. /// A colored transparent overlay to indicate that the view is selected.
  44. @property (nonatomic) UIView *selectedViewOverlay;
  45. /// Tracked so we can restore the key window after dismissing a modal.
  46. /// We need to become key after modal presentation so we can correctly capture input.
  47. /// 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.
  48. @property (nonatomic) UIWindow *previousKeyWindow;
  49. /// All views that we're KVOing. Used to help us clean up properly.
  50. @property (nonatomic) NSMutableSet<UIView *> *observedViews;
  51. /// Used to preserve the target app's UIMenuController items.
  52. @property (nonatomic) NSArray<UIMenuItem *> *appMenuItems;
  53. @end
  54. @implementation FLEXExplorerViewController
  55. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
  56. {
  57. self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  58. if (self) {
  59. self.observedViews = [NSMutableSet set];
  60. }
  61. return self;
  62. }
  63. - (void)dealloc
  64. {
  65. for (UIView *view in _observedViews) {
  66. [self stopObservingView:view];
  67. }
  68. }
  69. - (void)viewDidLoad
  70. {
  71. [super viewDidLoad];
  72. // Toolbar
  73. self.explorerToolbar = [FLEXExplorerToolbar new];
  74. // Start the toolbar off below any bars that may be at the top of the view.
  75. id toolbarOriginYDefault = [[NSUserDefaults standardUserDefaults] objectForKey:kFLEXToolbarTopMarginDefaultsKey];
  76. CGFloat toolbarOriginY = toolbarOriginYDefault ? [toolbarOriginYDefault doubleValue] : 100;
  77. CGRect safeArea = [self viewSafeArea];
  78. CGSize toolbarSize = [self.explorerToolbar sizeThatFits:CGSizeMake(CGRectGetWidth(self.view.bounds), CGRectGetHeight(safeArea))];
  79. [self updateToolbarPositionWithUnconstrainedFrame:CGRectMake(CGRectGetMinX(safeArea), toolbarOriginY, toolbarSize.width, toolbarSize.height)];
  80. self.explorerToolbar.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin;
  81. [self.view addSubview:self.explorerToolbar];
  82. [self setupToolbarActions];
  83. [self setupToolbarGestures];
  84. // View selection
  85. UITapGestureRecognizer *selectionTapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSelectionTap:)];
  86. [self.view addGestureRecognizer:selectionTapGR];
  87. // View moving
  88. self.movePanGR = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleMovePan:)];
  89. self.movePanGR.enabled = self.currentMode == FLEXExplorerModeMove;
  90. [self.view addGestureRecognizer:self.movePanGR];
  91. }
  92. - (void)viewWillAppear:(BOOL)animated
  93. {
  94. [super viewWillAppear:animated];
  95. [self updateButtonStates];
  96. }
  97. #pragma mark - Rotation
  98. - (UIViewController *)viewControllerForRotationAndOrientation
  99. {
  100. UIWindow *window = self.previousKeyWindow ?: [UIApplication.sharedApplication keyWindow];
  101. UIViewController *viewController = window.rootViewController;
  102. // Obfuscating selector _viewControllerForSupportedInterfaceOrientations
  103. NSString *viewControllerSelectorString = [@[@"_vie", @"wContro", @"llerFor", @"Supported", @"Interface", @"Orientations"] componentsJoinedByString:@""];
  104. SEL viewControllerSelector = NSSelectorFromString(viewControllerSelectorString);
  105. if ([viewController respondsToSelector:viewControllerSelector]) {
  106. viewController = [viewController valueForKey:viewControllerSelectorString];
  107. }
  108. return viewController;
  109. }
  110. - (UIInterfaceOrientationMask)supportedInterfaceOrientations
  111. {
  112. UIViewController *viewControllerToAsk = [self viewControllerForRotationAndOrientation];
  113. UIInterfaceOrientationMask supportedOrientations = [FLEXUtility infoPlistSupportedInterfaceOrientationsMask];
  114. if (viewControllerToAsk && ![viewControllerToAsk isKindOfClass:[self class]]) {
  115. supportedOrientations = [viewControllerToAsk supportedInterfaceOrientations];
  116. }
  117. // The UIViewController docs state that this method must not return zero.
  118. // If we weren't able to get a valid value for the supported interface
  119. // orientations, default to all supported.
  120. if (supportedOrientations == 0) {
  121. supportedOrientations = UIInterfaceOrientationMaskAll;
  122. }
  123. return supportedOrientations;
  124. }
  125. - (BOOL)shouldAutorotate
  126. {
  127. UIViewController *viewControllerToAsk = [self viewControllerForRotationAndOrientation];
  128. BOOL shouldAutorotate = YES;
  129. if (viewControllerToAsk && viewControllerToAsk != self) {
  130. shouldAutorotate = [viewControllerToAsk shouldAutorotate];
  131. }
  132. return shouldAutorotate;
  133. }
  134. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  135. {
  136. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  137. [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  138. for (UIView *outlineView in self.outlineViewsForVisibleViews.allValues) {
  139. outlineView.hidden = YES;
  140. }
  141. self.selectedViewOverlay.hidden = YES;
  142. } completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  143. for (UIView *view in self.viewsAtTapPoint) {
  144. NSValue *key = [NSValue valueWithNonretainedObject:view];
  145. UIView *outlineView = self.outlineViewsForVisibleViews[key];
  146. outlineView.frame = [self frameInLocalCoordinatesForView:view];
  147. if (self.currentMode == FLEXExplorerModeSelect) {
  148. outlineView.hidden = NO;
  149. }
  150. }
  151. if (self.selectedView) {
  152. self.selectedViewOverlay.frame = [self frameInLocalCoordinatesForView:self.selectedView];
  153. self.selectedViewOverlay.hidden = NO;
  154. }
  155. }];
  156. }
  157. #pragma mark - Setter Overrides
  158. - (void)setSelectedView:(UIView *)selectedView
  159. {
  160. if (![_selectedView isEqual:selectedView]) {
  161. if (![self.viewsAtTapPoint containsObject:_selectedView]) {
  162. [self stopObservingView:_selectedView];
  163. }
  164. _selectedView = selectedView;
  165. [self beginObservingView:selectedView];
  166. // Update the toolbar and selected overlay
  167. self.explorerToolbar.selectedViewDescription = [FLEXUtility descriptionForView:selectedView includingFrame:YES];
  168. self.explorerToolbar.selectedViewOverlayColor = [FLEXUtility consistentRandomColorForObject:selectedView];
  169. if (selectedView) {
  170. if (!self.selectedViewOverlay) {
  171. self.selectedViewOverlay = [UIView new];
  172. [self.view addSubview:self.selectedViewOverlay];
  173. self.selectedViewOverlay.layer.borderWidth = 1.0;
  174. }
  175. UIColor *outlineColor = [FLEXUtility consistentRandomColorForObject:selectedView];
  176. self.selectedViewOverlay.backgroundColor = [outlineColor colorWithAlphaComponent:0.2];
  177. self.selectedViewOverlay.layer.borderColor = outlineColor.CGColor;
  178. self.selectedViewOverlay.frame = [self.view convertRect:selectedView.bounds fromView:selectedView];
  179. // Make sure the selected overlay is in front of all the other subviews except the toolbar, which should always stay on top.
  180. [self.view bringSubviewToFront:self.selectedViewOverlay];
  181. [self.view bringSubviewToFront:self.explorerToolbar];
  182. } else {
  183. [self.selectedViewOverlay removeFromSuperview];
  184. self.selectedViewOverlay = nil;
  185. }
  186. // Some of the button states depend on whether we have a selected view.
  187. [self updateButtonStates];
  188. }
  189. }
  190. - (void)setViewsAtTapPoint:(NSArray<UIView *> *)viewsAtTapPoint
  191. {
  192. if (![_viewsAtTapPoint isEqual:viewsAtTapPoint]) {
  193. for (UIView *view in _viewsAtTapPoint) {
  194. if (view != self.selectedView) {
  195. [self stopObservingView:view];
  196. }
  197. }
  198. _viewsAtTapPoint = viewsAtTapPoint;
  199. for (UIView *view in viewsAtTapPoint) {
  200. [self beginObservingView:view];
  201. }
  202. }
  203. }
  204. - (void)setCurrentMode:(FLEXExplorerMode)currentMode
  205. {
  206. if (_currentMode != currentMode) {
  207. _currentMode = currentMode;
  208. switch (currentMode) {
  209. case FLEXExplorerModeDefault:
  210. [self removeAndClearOutlineViews];
  211. self.viewsAtTapPoint = nil;
  212. self.selectedView = nil;
  213. break;
  214. case FLEXExplorerModeSelect:
  215. // Make sure the outline views are unhidden in case we came from the move mode.
  216. for (NSValue *key in self.outlineViewsForVisibleViews) {
  217. UIView *outlineView = self.outlineViewsForVisibleViews[key];
  218. outlineView.hidden = NO;
  219. }
  220. break;
  221. case FLEXExplorerModeMove:
  222. // Hide all the outline views to focus on the selected view, which is the only one that will move.
  223. for (NSValue *key in self.outlineViewsForVisibleViews) {
  224. UIView *outlineView = self.outlineViewsForVisibleViews[key];
  225. outlineView.hidden = YES;
  226. }
  227. break;
  228. }
  229. self.movePanGR.enabled = currentMode == FLEXExplorerModeMove;
  230. [self updateButtonStates];
  231. }
  232. }
  233. #pragma mark - View Tracking
  234. - (void)beginObservingView:(UIView *)view
  235. {
  236. // Bail if we're already observing this view or if there's nothing to observe.
  237. if (!view || [self.observedViews containsObject:view]) {
  238. return;
  239. }
  240. for (NSString *keyPath in self.viewKeyPathsToTrack) {
  241. [view addObserver:self forKeyPath:keyPath options:0 context:NULL];
  242. }
  243. [self.observedViews addObject:view];
  244. }
  245. - (void)stopObservingView:(UIView *)view
  246. {
  247. if (!view) {
  248. return;
  249. }
  250. for (NSString *keyPath in self.viewKeyPathsToTrack) {
  251. [view removeObserver:self forKeyPath:keyPath];
  252. }
  253. [self.observedViews removeObject:view];
  254. }
  255. - (NSArray<NSString *> *)viewKeyPathsToTrack
  256. {
  257. static NSArray<NSString *> *trackedViewKeyPaths = nil;
  258. static dispatch_once_t onceToken;
  259. dispatch_once(&onceToken, ^{
  260. NSString *frameKeyPath = NSStringFromSelector(@selector(frame));
  261. trackedViewKeyPaths = @[frameKeyPath];
  262. });
  263. return trackedViewKeyPaths;
  264. }
  265. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *, id> *)change context:(void *)context
  266. {
  267. [self updateOverlayAndDescriptionForObjectIfNeeded:object];
  268. }
  269. - (void)updateOverlayAndDescriptionForObjectIfNeeded:(id)object
  270. {
  271. NSUInteger indexOfView = [self.viewsAtTapPoint indexOfObject:object];
  272. if (indexOfView != NSNotFound) {
  273. UIView *view = self.viewsAtTapPoint[indexOfView];
  274. NSValue *key = [NSValue valueWithNonretainedObject:view];
  275. UIView *outline = self.outlineViewsForVisibleViews[key];
  276. if (outline) {
  277. outline.frame = [self frameInLocalCoordinatesForView:view];
  278. }
  279. }
  280. if (object == self.selectedView) {
  281. // Update the selected view description since we show the frame value there.
  282. self.explorerToolbar.selectedViewDescription = [FLEXUtility descriptionForView:self.selectedView includingFrame:YES];
  283. CGRect selectedViewOutlineFrame = [self frameInLocalCoordinatesForView:self.selectedView];
  284. self.selectedViewOverlay.frame = selectedViewOutlineFrame;
  285. }
  286. }
  287. - (CGRect)frameInLocalCoordinatesForView:(UIView *)view
  288. {
  289. // First convert to window coordinates since the view may be in a different window than our view.
  290. CGRect frameInWindow = [view convertRect:view.bounds toView:nil];
  291. // Then convert from the window to our view's coordinate space.
  292. return [self.view convertRect:frameInWindow fromView:nil];
  293. }
  294. #pragma mark - Toolbar Buttons
  295. - (void)setupToolbarActions
  296. {
  297. [self.explorerToolbar.selectItem addTarget:self action:@selector(selectButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
  298. [self.explorerToolbar.hierarchyItem addTarget:self action:@selector(hierarchyButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
  299. [self.explorerToolbar.moveItem addTarget:self action:@selector(moveButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
  300. [self.explorerToolbar.globalsItem addTarget:self action:@selector(globalsButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
  301. [self.explorerToolbar.closeItem addTarget:self action:@selector(closeButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
  302. }
  303. - (void)selectButtonTapped:(FLEXToolbarItem *)sender
  304. {
  305. [self toggleSelectTool];
  306. }
  307. - (void)hierarchyButtonTapped:(FLEXToolbarItem *)sender
  308. {
  309. [self toggleViewsTool];
  310. }
  311. - (UIWindow *)statusWindow
  312. {
  313. NSString *statusBarString = [NSString stringWithFormat:@"%@arWindow", @"_statusB"];
  314. return [UIApplication.sharedApplication valueForKey:statusBarString];
  315. }
  316. - (void)moveButtonTapped:(FLEXToolbarItem *)sender
  317. {
  318. [self toggleMoveTool];
  319. }
  320. - (void)globalsButtonTapped:(FLEXToolbarItem *)sender
  321. {
  322. [self toggleMenuTool];
  323. }
  324. - (void)closeButtonTapped:(FLEXToolbarItem *)sender
  325. {
  326. self.currentMode = FLEXExplorerModeDefault;
  327. [self.delegate explorerViewControllerDidFinish:self];
  328. }
  329. - (void)updateButtonStates
  330. {
  331. // Move and details only active when an object is selected.
  332. BOOL hasSelectedObject = self.selectedView != nil;
  333. self.explorerToolbar.moveItem.enabled = hasSelectedObject;
  334. self.explorerToolbar.selectItem.selected = self.currentMode == FLEXExplorerModeSelect;
  335. self.explorerToolbar.moveItem.selected = self.currentMode == FLEXExplorerModeMove;
  336. }
  337. #pragma mark - Toolbar Dragging
  338. - (void)setupToolbarGestures
  339. {
  340. // Pan gesture for dragging.
  341. UIPanGestureRecognizer *panGR = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleToolbarPanGesture:)];
  342. [self.explorerToolbar.dragHandle addGestureRecognizer:panGR];
  343. // Tap gesture for hinting.
  344. UITapGestureRecognizer *hintTapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleToolbarHintTapGesture:)];
  345. [self.explorerToolbar.dragHandle addGestureRecognizer:hintTapGR];
  346. // Tap gesture for showing additional details
  347. self.detailsTapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleToolbarDetailsTapGesture:)];
  348. [self.explorerToolbar.selectedViewDescriptionContainer addGestureRecognizer:self.detailsTapGR];
  349. }
  350. - (void)handleToolbarPanGesture:(UIPanGestureRecognizer *)panGR
  351. {
  352. switch (panGR.state) {
  353. case UIGestureRecognizerStateBegan:
  354. self.toolbarFrameBeforeDragging = self.explorerToolbar.frame;
  355. [self updateToolbarPositionWithDragGesture:panGR];
  356. break;
  357. case UIGestureRecognizerStateChanged:
  358. case UIGestureRecognizerStateEnded:
  359. [self updateToolbarPositionWithDragGesture:panGR];
  360. break;
  361. default:
  362. break;
  363. }
  364. }
  365. - (void)updateToolbarPositionWithDragGesture:(UIPanGestureRecognizer *)panGR
  366. {
  367. CGPoint translation = [panGR translationInView:self.view];
  368. CGRect newToolbarFrame = self.toolbarFrameBeforeDragging;
  369. newToolbarFrame.origin.y += translation.y;
  370. [self updateToolbarPositionWithUnconstrainedFrame:newToolbarFrame];
  371. }
  372. - (void)updateToolbarPositionWithUnconstrainedFrame:(CGRect)unconstrainedFrame
  373. {
  374. CGRect safeArea = [self viewSafeArea];
  375. // We only constrain the Y-axis because We want the toolbar to handle the X-axis safeArea layout by itself
  376. CGFloat minY = CGRectGetMinY(safeArea);
  377. CGFloat maxY = CGRectGetMaxY(safeArea) - unconstrainedFrame.size.height;
  378. if (unconstrainedFrame.origin.y < minY) {
  379. unconstrainedFrame.origin.y = minY;
  380. } else if (unconstrainedFrame.origin.y > maxY) {
  381. unconstrainedFrame.origin.y = maxY;
  382. }
  383. self.explorerToolbar.frame = unconstrainedFrame;
  384. [[NSUserDefaults standardUserDefaults] setDouble:unconstrainedFrame.origin.y forKey:kFLEXToolbarTopMarginDefaultsKey];
  385. }
  386. - (void)handleToolbarHintTapGesture:(UITapGestureRecognizer *)tapGR
  387. {
  388. // Bounce the toolbar to indicate that it is draggable.
  389. // TODO: make it bouncier.
  390. if (tapGR.state == UIGestureRecognizerStateRecognized) {
  391. CGRect originalToolbarFrame = self.explorerToolbar.frame;
  392. const NSTimeInterval kHalfwayDuration = 0.2;
  393. const CGFloat kVerticalOffset = 30.0;
  394. [UIView animateWithDuration:kHalfwayDuration delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
  395. CGRect newToolbarFrame = self.explorerToolbar.frame;
  396. newToolbarFrame.origin.y += kVerticalOffset;
  397. self.explorerToolbar.frame = newToolbarFrame;
  398. } completion:^(BOOL finished) {
  399. [UIView animateWithDuration:kHalfwayDuration delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
  400. self.explorerToolbar.frame = originalToolbarFrame;
  401. } completion:nil];
  402. }];
  403. }
  404. }
  405. - (void)handleToolbarDetailsTapGesture:(UITapGestureRecognizer *)tapGR
  406. {
  407. if (tapGR.state == UIGestureRecognizerStateRecognized && self.selectedView) {
  408. UIViewController *topStackVC = [FLEXObjectExplorerFactory explorerViewControllerForObject:self.selectedView];
  409. UINavigationController *navigationController = [[FLEXNavigationController alloc] initWithRootViewController:topStackVC];
  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 - Modal Dismissal
  599. - (void)presentationControllerDidDismiss:(UIPresentationController *)presentationController
  600. {
  601. [self presentedViewControllerDidDismiss];
  602. }
  603. - (void)presentedViewControllerDidDismiss
  604. {
  605. [self resignKeyAndDismissViewControllerAnimated:YES completion:nil];
  606. }
  607. #pragma mark - Modal Presentation and Window Management
  608. - (void)makeKeyAndPresentViewController:(UINavigationController *)toPresent animated:(BOOL)animated completion:(void (^)(void))completion
  609. {
  610. // Save the current key window so we can restore it following dismissal.
  611. self.previousKeyWindow = UIApplication.sharedApplication.keyWindow;
  612. // Make our window key to correctly handle input.
  613. [self.view.window makeKeyWindow];
  614. // Move the status bar on top of FLEX so we can get scroll to top behavior for taps.
  615. if (!@available(iOS 13, *)) {
  616. [self statusWindow].windowLevel = self.view.window.windowLevel + 1.0;
  617. }
  618. // Back up and replace the UIMenuController items
  619. self.appMenuItems = UIMenuController.sharedMenuController.menuItems;
  620. // Initialize custom menu items for explorer screen
  621. UIMenuItem *copyObjectAddress = [[UIMenuItem alloc]
  622. initWithTitle:@"Copy Address"
  623. action:NSSelectorFromString(@"copyObjectAddress:")
  624. ];
  625. UIMenuController.sharedMenuController.menuItems = @[copyObjectAddress];
  626. [UIMenuController.sharedMenuController update];
  627. // Add the "Done" button to the navigation controller's view controller if it doesn't have one
  628. // (the hierarchy screen adds it's own done button in order to pass data between us)
  629. if (!toPresent.topViewController.navigationItem.rightBarButtonItem) {
  630. toPresent.topViewController.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
  631. initWithBarButtonSystemItem:UIBarButtonSystemItemDone
  632. target:self
  633. action:@selector(presentedViewControllerDidDismiss)
  634. ];
  635. }
  636. // Make myself the delegate for sheets presented modally so we can do the
  637. // proper cleanup when sheets are dragged to dismiss without the done button
  638. if (@available(iOS 13, *)) {
  639. toPresent.presentationController.delegate = self;
  640. }
  641. // Show the view controller.
  642. [self presentViewController:toPresent animated:animated completion:completion];
  643. }
  644. - (void)resignKeyAndDismissViewControllerAnimated:(BOOL)animated completion:(void (^)(void))completion
  645. {
  646. UIWindow *previousKeyWindow = self.previousKeyWindow;
  647. self.previousKeyWindow = nil;
  648. [previousKeyWindow makeKeyWindow];
  649. [previousKeyWindow.rootViewController setNeedsStatusBarAppearanceUpdate];
  650. // Restore previous UIMenuController items
  651. // Back up and replace the UIMenuController items
  652. UIMenuController.sharedMenuController.menuItems = self.appMenuItems;
  653. [UIMenuController.sharedMenuController update];
  654. self.appMenuItems = nil;
  655. // Restore the status bar window's normal window level.
  656. // We want it above FLEX while a modal is presented for scroll to top, but below FLEX otherwise for exploration.
  657. [self statusWindow].windowLevel = UIWindowLevelStatusBar;
  658. [self dismissViewControllerAnimated:animated completion:completion];
  659. }
  660. - (BOOL)wantsWindowToBecomeKey
  661. {
  662. return self.previousKeyWindow != nil;
  663. }
  664. - (void)toggleToolWithViewControllerProvider:(UINavigationController *(^)(void))future completion:(void(^)(void))completion
  665. {
  666. if (self.presentedViewController) {
  667. [self resignKeyAndDismissViewControllerAnimated:YES completion:completion];
  668. } else if (future) {
  669. [self makeKeyAndPresentViewController:future() animated:YES completion:completion];
  670. }
  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. FLEXGlobalsTableViewController *globalsViewController = [FLEXGlobalsTableViewController new];
  715. [FLEXGlobalsTableViewController setApplicationWindow:[UIApplication.sharedApplication keyWindow]];
  716. return [[FLEXNavigationController alloc] initWithRootViewController:globalsViewController];
  717. } completion:nil];
  718. }
  719. - (BOOL)handleDownArrowKeyPressed
  720. {
  721. if (self.currentMode == FLEXExplorerModeMove) {
  722. CGRect frame = self.selectedView.frame;
  723. frame.origin.y += 1.0 / UIScreen.mainScreen.scale;
  724. self.selectedView.frame = frame;
  725. } else if (self.currentMode == FLEXExplorerModeSelect && self.viewsAtTapPoint.count > 0) {
  726. NSInteger selectedViewIndex = [self.viewsAtTapPoint indexOfObject:self.selectedView];
  727. if (selectedViewIndex > 0) {
  728. self.selectedView = [self.viewsAtTapPoint objectAtIndex:selectedViewIndex - 1];
  729. }
  730. } else {
  731. return NO;
  732. }
  733. return YES;
  734. }
  735. - (BOOL)handleUpArrowKeyPressed
  736. {
  737. if (self.currentMode == FLEXExplorerModeMove) {
  738. CGRect frame = self.selectedView.frame;
  739. frame.origin.y -= 1.0 / UIScreen.mainScreen.scale;
  740. self.selectedView.frame = frame;
  741. } else if (self.currentMode == FLEXExplorerModeSelect && self.viewsAtTapPoint.count > 0) {
  742. NSInteger selectedViewIndex = [self.viewsAtTapPoint indexOfObject:self.selectedView];
  743. if (selectedViewIndex < self.viewsAtTapPoint.count - 1) {
  744. self.selectedView = [self.viewsAtTapPoint objectAtIndex:selectedViewIndex + 1];
  745. }
  746. } else {
  747. return NO;
  748. }
  749. return YES;
  750. }
  751. - (BOOL)handleRightArrowKeyPressed
  752. {
  753. if (self.currentMode == FLEXExplorerModeMove) {
  754. CGRect frame = self.selectedView.frame;
  755. frame.origin.x += 1.0 / UIScreen.mainScreen.scale;
  756. self.selectedView.frame = frame;
  757. return YES;
  758. }
  759. return NO;
  760. }
  761. - (BOOL)handleLeftArrowKeyPressed
  762. {
  763. if (self.currentMode == FLEXExplorerModeMove) {
  764. CGRect frame = self.selectedView.frame;
  765. frame.origin.x -= 1.0 / UIScreen.mainScreen.scale;
  766. self.selectedView.frame = frame;
  767. return YES;
  768. }
  769. return NO;
  770. }
  771. @end