FLEXExplorerViewController.m 38 KB

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