FLEXExplorerViewController.m 29 KB

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