FLEXExplorerViewController.m 34 KB

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