FLEXExplorerViewController.m 36 KB

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