FLEXExplorerViewController.m 36 KB

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