FLEXExplorerViewController.m 38 KB

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