FLEXExplorerViewController.m 29 KB

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