FLEXExplorerViewController.m 31 KB

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