FLEXExplorerViewController.m 38 KB

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