FLEXExplorerViewController.m 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  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. self.appMenuItems = UIMenuController.sharedMenuController.menuItems;
  691. // Initialize custom menu items for explorer screen
  692. UIMenuItem *copyObjectAddress = [[UIMenuItem alloc]
  693. initWithTitle:@"Copy Address"
  694. action:NSSelectorFromString(@"copyObjectAddress:")
  695. ];
  696. UIMenuController.sharedMenuController.menuItems = @[copyObjectAddress];
  697. [UIMenuController.sharedMenuController update];
  698. // Show the view controller.
  699. [super presentViewController:toPresent animated:animated completion:completion];
  700. }
  701. - (void)dismissViewControllerAnimated:(BOOL)animated completion:(void (^)(void))completion {
  702. UIWindow *appWindow = self.window.previousKeyWindow;
  703. [appWindow makeKeyWindow];
  704. [appWindow.rootViewController setNeedsStatusBarAppearanceUpdate];
  705. // Restore previous UIMenuController items
  706. // Back up and replace the UIMenuController items
  707. UIMenuController.sharedMenuController.menuItems = self.appMenuItems;
  708. [UIMenuController.sharedMenuController update];
  709. self.appMenuItems = nil;
  710. // Restore the status bar window's normal window level.
  711. // We want it above FLEX while a modal is presented for
  712. // scroll to top, but below FLEX otherwise for exploration.
  713. [self statusWindow].windowLevel = UIWindowLevelStatusBar;
  714. [self updateButtonStates];
  715. [super dismissViewControllerAnimated:animated completion:completion];
  716. }
  717. - (BOOL)wantsWindowToBecomeKey
  718. {
  719. return self.window.previousKeyWindow != nil;
  720. }
  721. - (void)toggleToolWithViewControllerProvider:(UINavigationController *(^)(void))future
  722. completion:(void(^)(void))completion {
  723. if (self.presentedViewController) {
  724. [self dismissViewControllerAnimated:YES completion:completion];
  725. } else if (future) {
  726. [self presentViewController:future() animated:YES completion:completion];
  727. }
  728. }
  729. - (FLEXWindow *)window {
  730. return (id)self.view.window;
  731. }
  732. #pragma mark - Keyboard Shortcut Helpers
  733. - (void)toggleSelectTool {
  734. if (self.currentMode == FLEXExplorerModeSelect) {
  735. self.currentMode = FLEXExplorerModeDefault;
  736. } else {
  737. self.currentMode = FLEXExplorerModeSelect;
  738. }
  739. }
  740. - (void)toggleMoveTool {
  741. if (self.currentMode == FLEXExplorerModeMove) {
  742. self.currentMode = FLEXExplorerModeDefault;
  743. } else {
  744. self.currentMode = FLEXExplorerModeMove;
  745. }
  746. }
  747. - (void)toggleViewsTool {
  748. [self toggleViewsToolWithCompletion:nil];
  749. }
  750. - (void)toggleViewsToolWithCompletion:(void(^)(void))completion {
  751. [self toggleToolWithViewControllerProvider:^UINavigationController *{
  752. if (self.selectedView) {
  753. return [FLEXHierarchyViewController
  754. delegate:self
  755. viewsAtTap:self.viewsAtTapPoint
  756. selectedView:self.selectedView
  757. ];
  758. } else {
  759. return [FLEXHierarchyViewController delegate:self];
  760. }
  761. } completion:^{
  762. if (completion) {
  763. completion();
  764. }
  765. }];
  766. }
  767. - (void)toggleMenuTool {
  768. [self toggleToolWithViewControllerProvider:^UINavigationController *{
  769. return [FLEXNavigationController withRootViewController:[FLEXGlobalsViewController new]];
  770. } completion:nil];
  771. }
  772. - (BOOL)handleDownArrowKeyPressed {
  773. if (self.currentMode == FLEXExplorerModeMove) {
  774. CGRect frame = self.selectedView.frame;
  775. frame.origin.y += 1.0 / UIScreen.mainScreen.scale;
  776. self.selectedView.frame = frame;
  777. } else if (self.currentMode == FLEXExplorerModeSelect && self.viewsAtTapPoint.count > 0) {
  778. NSInteger selectedViewIndex = [self.viewsAtTapPoint indexOfObject:self.selectedView];
  779. if (selectedViewIndex > 0) {
  780. self.selectedView = [self.viewsAtTapPoint objectAtIndex:selectedViewIndex - 1];
  781. }
  782. } else {
  783. return NO;
  784. }
  785. return YES;
  786. }
  787. - (BOOL)handleUpArrowKeyPressed {
  788. if (self.currentMode == FLEXExplorerModeMove) {
  789. CGRect frame = self.selectedView.frame;
  790. frame.origin.y -= 1.0 / UIScreen.mainScreen.scale;
  791. self.selectedView.frame = frame;
  792. } else if (self.currentMode == FLEXExplorerModeSelect && self.viewsAtTapPoint.count > 0) {
  793. NSInteger selectedViewIndex = [self.viewsAtTapPoint indexOfObject:self.selectedView];
  794. if (selectedViewIndex < self.viewsAtTapPoint.count - 1) {
  795. self.selectedView = [self.viewsAtTapPoint objectAtIndex:selectedViewIndex + 1];
  796. }
  797. } else {
  798. return NO;
  799. }
  800. return YES;
  801. }
  802. - (BOOL)handleRightArrowKeyPressed {
  803. if (self.currentMode == FLEXExplorerModeMove) {
  804. CGRect frame = self.selectedView.frame;
  805. frame.origin.x += 1.0 / UIScreen.mainScreen.scale;
  806. self.selectedView.frame = frame;
  807. return YES;
  808. }
  809. return NO;
  810. }
  811. - (BOOL)handleLeftArrowKeyPressed {
  812. if (self.currentMode == FLEXExplorerModeMove) {
  813. CGRect frame = self.selectedView.frame;
  814. frame.origin.x -= 1.0 / UIScreen.mainScreen.scale;
  815. self.selectedView.frame = frame;
  816. return YES;
  817. }
  818. return NO;
  819. }
  820. @end