FLEXExplorerViewController.m 37 KB

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