FLEXExplorerViewController.m 35 KB

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