FLEXExplorerViewController.m 35 KB

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