FLEXExplorerViewController.m 32 KB

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