FLEXExplorerViewController.m 35 KB

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