FLEXExplorerViewController.m 37 KB

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