FLEXExplorerViewController.m 36 KB

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