FLEXExplorerViewController.m 32 KB

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