FLEXExplorerViewController.m 35 KB

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