FLEXExplorerViewController.m 33 KB

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