FLEXObjectExplorerViewController.m 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. //
  2. // FLEXObjectExplorerViewController.m
  3. // Flipboard
  4. //
  5. // Created by Ryan Olson on 2014-05-03.
  6. // Copyright (c) 2020 FLEX Team. All rights reserved.
  7. //
  8. #import "FLEXObjectExplorerViewController.h"
  9. #import "FLEXUtility.h"
  10. #import "FLEXRuntimeUtility.h"
  11. #import "UIBarButtonItem+FLEX.h"
  12. #import "FLEXMultilineTableViewCell.h"
  13. #import "FLEXObjectExplorerFactory.h"
  14. #import "FLEXFieldEditorViewController.h"
  15. #import "FLEXMethodCallingViewController.h"
  16. #import "FLEXObjectListViewController.h"
  17. #import "FLEXTabsViewController.h"
  18. #import "FLEXBookmarkManager.h"
  19. #import "FLEXTableView.h"
  20. #import "FLEXResources.h"
  21. #import "FLEXTableViewCell.h"
  22. #import "FLEXScopeCarousel.h"
  23. #import "FLEXMetadataSection.h"
  24. #import "FLEXSingleRowSection.h"
  25. #import "FLEXShortcutsSection.h"
  26. #import "NSUserDefaults+FLEX.h"
  27. #import <objc/runtime.h>
  28. #import <TargetConditionals.h>
  29. #pragma mark - Private properties
  30. @interface FLEXObjectExplorerViewController () <UIGestureRecognizerDelegate>{
  31. BOOL _addedSwipeGestures;
  32. }
  33. @property (nonatomic, readonly) FLEXSingleRowSection *descriptionSection;
  34. @property (nonatomic, readonly) FLEXTableViewSection *customSection;
  35. @property (nonatomic) NSIndexSet *customSectionVisibleIndexes;
  36. @property (nonatomic, readonly) NSArray<NSString *> *observedNotifications;
  37. @end
  38. @implementation FLEXObjectExplorerViewController
  39. #pragma mark - Initialization
  40. + (instancetype)exploringObject:(id)target {
  41. return [self exploringObject:target customSection:[FLEXShortcutsSection forObject:target]];
  42. }
  43. + (instancetype)exploringObject:(id)target customSection:(FLEXTableViewSection *)section {
  44. return [[self alloc]
  45. initWithObject:target
  46. explorer:[FLEXObjectExplorer forObject:target]
  47. customSection:section
  48. ];
  49. }
  50. - (id)initWithObject:(id)target
  51. explorer:(__kindof FLEXObjectExplorer *)explorer
  52. customSection:(FLEXTableViewSection *)customSection {
  53. NSParameterAssert(target);
  54. self = [super initWithStyle:UITableViewStyleGrouped];
  55. if (self) {
  56. _object = target;
  57. _explorer = explorer;
  58. _customSection = customSection;
  59. }
  60. return self;
  61. }
  62. - (NSArray<NSString *> *)observedNotifications {
  63. return @[
  64. kFLEXDefaultsHidePropertyIvarsKey,
  65. kFLEXDefaultsHidePropertyMethodsKey,
  66. kFLEXDefaultsHideMethodOverridesKey,
  67. kFLEXDefaultsHideVariablePreviewsKey,
  68. ];
  69. }
  70. #pragma mark - View controller lifecycle
  71. - (void)viewDidLoad {
  72. [super viewDidLoad];
  73. self.showsShareToolbarItem = YES;
  74. self.wantsSectionIndexTitles = YES;
  75. // Use [object class] here rather than object_getClass
  76. // to avoid the KVO prefix for observed objects
  77. self.title = [[self.object class] description];
  78. // Search
  79. self.showsSearchBar = YES;
  80. self.searchBarDebounceInterval = kFLEXDebounceInstant;
  81. self.showsCarousel = YES;
  82. // Carousel scope bar
  83. [self.explorer reloadClassHierarchy];
  84. self.carousel.items = [self.explorer.classHierarchyClasses flex_mapped:^id(Class cls, NSUInteger idx) {
  85. return NSStringFromClass(cls);
  86. }];
  87. // ... button for extra options
  88. [self addToolbarItems:@[[UIBarButtonItem
  89. flex_itemWithImage:FLEXResources.moreIcon target:self action:@selector(moreButtonPressed:)
  90. ]]];
  91. // Swipe gestures to swipe between classes in the hierarchy
  92. UISwipeGestureRecognizer *leftSwipe = [[UISwipeGestureRecognizer alloc]
  93. initWithTarget:self action:@selector(handleSwipeGesture:)
  94. ];
  95. UISwipeGestureRecognizer *rightSwipe = [[UISwipeGestureRecognizer alloc]
  96. initWithTarget:self action:@selector(handleSwipeGesture:)
  97. ];
  98. leftSwipe.direction = UISwipeGestureRecognizerDirectionLeft;
  99. rightSwipe.direction = UISwipeGestureRecognizerDirectionRight;
  100. leftSwipe.delegate = self;
  101. rightSwipe.delegate = self;
  102. [self.tableView addGestureRecognizer:leftSwipe];
  103. [self.tableView addGestureRecognizer:rightSwipe];
  104. // Observe preferences which may change on other screens
  105. //
  106. // "If your app targets iOS 9.0 and later or macOS 10.11 and later,
  107. // you don't need to unregister an observer in its dealloc method."
  108. for (NSString *pref in self.observedNotifications) {
  109. [NSNotificationCenter.defaultCenter
  110. addObserver:self
  111. selector:@selector(fullyReloadData)
  112. name:pref
  113. object:nil
  114. ];
  115. }
  116. #if TARGET_OS_TV
  117. [self addlongPressGestureRecognizer];
  118. //[self addSwipeGestureRecognizers];
  119. #endif
  120. }
  121. - (void)addlongPressGestureRecognizer {
  122. UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
  123. longPress.allowedPressTypes = @[[NSNumber numberWithInteger:UIPressTypePlayPause],[NSNumber numberWithInteger:UIPressTypeSelect]];
  124. [self.tableView addGestureRecognizer:longPress];
  125. }
  126. - (void)swipedLeft {
  127. NSLog(@"[FLEXInjected] swipedLeft!");
  128. //go to previous carousel item if possible
  129. NSInteger currentIndex = self.carousel.selectedIndex;
  130. if (currentIndex == 0) return;
  131. if (self.selectedScope > 0) {
  132. self.selectedScope -= 1;
  133. }
  134. NSInteger newIndex = currentIndex - 1;
  135. [self.carousel setSelectedIndex:newIndex];
  136. }
  137. - (void)swipedRight {
  138. NSLog(@"[FLEXInjected] swipedRight!");
  139. //go to next carousel item if possible
  140. NSInteger currentIndex = self.carousel.selectedIndex;
  141. NSInteger newIndex = currentIndex + 1;
  142. if (newIndex <= self.carousel.items.count - 1){
  143. if (self.selectedScope != self.explorer.classHierarchy.count - 1) {
  144. self.selectedScope += 1;
  145. }
  146. NSLog(@"[FLEXInjected] count: %lu new index: %lu", self.carousel.items.count, currentIndex);
  147. [self.carousel setSelectedIndex:newIndex];
  148. }
  149. }
  150. - (void)swipeGestureRecognized:(UISwipeGestureRecognizer *)gestureRecognizer{
  151. NSLog(@"[FLEXInjected] gesture recognized: %lu", gestureRecognizer.direction);
  152. switch (gestureRecognizer.direction) {
  153. case UISwipeGestureRecognizerDirectionLeft:
  154. [self swipedLeft];
  155. break;
  156. case UISwipeGestureRecognizerDirectionRight:
  157. [self swipedRight];
  158. break;
  159. default:
  160. break;
  161. }
  162. }
  163. - (void)addSwipeGestureRecognizers {
  164. if (_addedSwipeGestures == YES) return;
  165. UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGestureRecognized:)];
  166. swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
  167. [self.view addGestureRecognizer:swipeLeft];
  168. self.view.userInteractionEnabled = YES;
  169. swipeLeft.delegate = self;
  170. UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGestureRecognized:)];
  171. swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
  172. [self.view addGestureRecognizer:swipeRight];
  173. self.view.userInteractionEnabled = YES;
  174. swipeRight.delegate = self;
  175. _addedSwipeGestures = YES;
  176. }
  177. - (void)longPress:(UILongPressGestureRecognizer*)gesture {
  178. if ( gesture.state == UIGestureRecognizerStateEnded) {
  179. NSLog(@"do something different for long press!");
  180. UITableView *tv = [self tableView];
  181. //naughty naughty
  182. NSIndexPath *focus = [tv valueForKey:@"_focusedCellIndexPath"];
  183. NSLog(@"[FLEX] focusedIndexPath: %@", focus);
  184. [self tableView:self.tableView accessoryButtonTappedForRowWithIndexPath:focus];
  185. }
  186. }
  187. - (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView {
  188. #if !TARGET_OS_TV
  189. [self.navigationController setToolbarHidden:NO animated:YES];
  190. #endif
  191. return YES;
  192. }
  193. #pragma mark - Overrides
  194. /// Override to hide the description section when searching
  195. - (NSArray<FLEXTableViewSection *> *)nonemptySections {
  196. if (self.shouldShowDescription) {
  197. return super.nonemptySections;
  198. }
  199. return [super.nonemptySections flex_filtered:^BOOL(FLEXTableViewSection *section, NSUInteger idx) {
  200. return section != self.descriptionSection;
  201. }];
  202. }
  203. - (NSArray<FLEXTableViewSection *> *)makeSections {
  204. FLEXObjectExplorer *explorer = self.explorer;
  205. // Description section is only for instances
  206. if (self.explorer.objectIsInstance) {
  207. _descriptionSection = [FLEXSingleRowSection
  208. title:@"Description" reuse:kFLEXMultilineCell cell:^(FLEXTableViewCell *cell) {
  209. cell.titleLabel.font = UIFont.flex_defaultTableCellFont;
  210. cell.titleLabel.text = explorer.objectDescription;
  211. }
  212. ];
  213. self.descriptionSection.filterMatcher = ^BOOL(NSString *filterText) {
  214. return [explorer.objectDescription localizedCaseInsensitiveContainsString:filterText];
  215. };
  216. }
  217. // Object graph section
  218. FLEXSingleRowSection *referencesSection = [FLEXSingleRowSection
  219. title:@"Object Graph" reuse:kFLEXDefaultCell cell:^(FLEXTableViewCell *cell) {
  220. cell.titleLabel.text = @"See Objects with References to This Object";
  221. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  222. }
  223. ];
  224. referencesSection.selectionAction = ^(UIViewController *host) {
  225. UIViewController *references = [FLEXObjectListViewController
  226. objectsWithReferencesToObject:explorer.object
  227. ];
  228. [host.navigationController pushViewController:references animated:YES];
  229. };
  230. NSMutableArray *sections = [NSMutableArray arrayWithArray:@[
  231. [FLEXMetadataSection explorer:self.explorer kind:FLEXMetadataKindProperties],
  232. [FLEXMetadataSection explorer:self.explorer kind:FLEXMetadataKindClassProperties],
  233. [FLEXMetadataSection explorer:self.explorer kind:FLEXMetadataKindIvars],
  234. [FLEXMetadataSection explorer:self.explorer kind:FLEXMetadataKindMethods],
  235. [FLEXMetadataSection explorer:self.explorer kind:FLEXMetadataKindClassMethods],
  236. [FLEXMetadataSection explorer:self.explorer kind:FLEXMetadataKindClassHierarchy],
  237. [FLEXMetadataSection explorer:self.explorer kind:FLEXMetadataKindProtocols],
  238. [FLEXMetadataSection explorer:self.explorer kind:FLEXMetadataKindOther],
  239. referencesSection
  240. ]];
  241. if (self.customSection) {
  242. [sections insertObject:self.customSection atIndex:0];
  243. }
  244. if (self.descriptionSection) {
  245. [sections insertObject:self.descriptionSection atIndex:0];
  246. }
  247. return sections.copy;
  248. }
  249. /// In our case, all this does is reload the table view,
  250. /// or reload the sections' data if we changed places
  251. /// in the class hierarchy. Doesn't refresh \c self.explorer
  252. - (void)reloadData {
  253. // Check to see if class scope changed, update accordingly
  254. if (self.explorer.classScope != self.selectedScope) {
  255. self.explorer.classScope = self.selectedScope;
  256. [self reloadSections];
  257. }
  258. [super reloadData];
  259. }
  260. - (void)shareButtonPressed:(UIBarButtonItem *)sender {
  261. [FLEXAlert makeSheet:^(FLEXAlert *make) {
  262. make.button(@"Add to Bookmarks").handler(^(NSArray<NSString *> *strings) {
  263. [FLEXBookmarkManager.bookmarks addObject:self.object];
  264. });
  265. make.button(@"Copy Description").handler(^(NSArray<NSString *> *strings) {
  266. #if !TARGET_OS_TV
  267. UIPasteboard.generalPasteboard.string = self.explorer.objectDescription;
  268. #endif
  269. });
  270. make.button(@"Copy Address").handler(^(NSArray<NSString *> *strings) {
  271. #if !TARGET_OS_TV
  272. UIPasteboard.generalPasteboard.string = [FLEXUtility addressOfObject:self.object];
  273. #endif
  274. });
  275. make.button(@"Cancel").cancelStyle();
  276. } showFrom:self source:sender];
  277. }
  278. #pragma mark - Private
  279. /// Unlike \c -reloadData, this refreshes everything, including the explorer.
  280. - (void)fullyReloadData {
  281. [self.explorer reloadMetadata];
  282. [self reloadSections];
  283. [self reloadData];
  284. }
  285. - (void)handleSwipeGesture:(UISwipeGestureRecognizer *)gesture {
  286. if (gesture.state == UIGestureRecognizerStateEnded) {
  287. switch (gesture.direction) {
  288. case UISwipeGestureRecognizerDirectionRight:
  289. if (self.selectedScope > 0) {
  290. self.selectedScope -= 1;
  291. [self.tableView reloadData];
  292. }
  293. break;
  294. case UISwipeGestureRecognizerDirectionLeft:
  295. if (self.selectedScope != self.explorer.classHierarchy.count - 1) {
  296. self.selectedScope += 1;
  297. [self.tableView reloadData];
  298. }
  299. break;
  300. default:
  301. break;
  302. }
  303. }
  304. }
  305. - (BOOL)gestureRecognizer:(UIGestureRecognizer *)g1 shouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer *)g2 {
  306. // Prioritize important pan gestures over our swipe gesture
  307. #if !TARGET_OS_TV
  308. if ([g2 isKindOfClass:[UIPanGestureRecognizer class]]) {
  309. if (g2 == self.navigationController.interactivePopGestureRecognizer ||
  310. g2 == self.navigationController.barHideOnSwipeGestureRecognizer ||
  311. g2 == self.tableView.panGestureRecognizer) {
  312. return NO;
  313. }
  314. }
  315. #else
  316. if ([g2 isKindOfClass:[UIPanGestureRecognizer class]]) {
  317. if (g2 == self.tableView.panGestureRecognizer) {
  318. return NO;
  319. }
  320. }
  321. #endif
  322. return YES;
  323. }
  324. - (BOOL)gestureRecognizerShouldBegin:(UISwipeGestureRecognizer *)gesture {
  325. // Don't allow swiping from the carousel
  326. CGPoint location = [gesture locationInView:self.tableView];
  327. if ([self.carousel hitTest:location withEvent:nil]) {
  328. return NO;
  329. }
  330. return YES;
  331. }
  332. - (void)moreButtonPressed:(UIBarButtonItem *)sender {
  333. NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
  334. // Maps preference keys to a description of what they affect
  335. NSDictionary<NSString *, NSString *> *explorerToggles = @{
  336. kFLEXDefaultsHidePropertyIvarsKey: @"Property-Backing Ivars",
  337. kFLEXDefaultsHidePropertyMethodsKey: @"Property-Backing Methods",
  338. kFLEXDefaultsHideMethodOverridesKey: @"Method Overrides",
  339. kFLEXDefaultsHideVariablePreviewsKey: @"Variable Previews"
  340. };
  341. // Maps the key of the action itself to a map of a description
  342. // of the action ("hide X") mapped to the current state.
  343. //
  344. // So keys that are hidden by default have NO mapped to "Show"
  345. NSDictionary<NSString *, NSDictionary *> *nextStateDescriptions = @{
  346. kFLEXDefaultsHidePropertyIvarsKey: @{ @NO: @"Hide ", @YES: @"Show " },
  347. kFLEXDefaultsHidePropertyMethodsKey: @{ @NO: @"Hide ", @YES: @"Show " },
  348. kFLEXDefaultsHideMethodOverridesKey: @{ @NO: @"Show ", @YES: @"Hide " },
  349. kFLEXDefaultsHideVariablePreviewsKey: @{ @NO: @"Hide ", @YES: @"Show " },
  350. };
  351. [FLEXAlert makeSheet:^(FLEXAlert *make) {
  352. make.title(@"Options");
  353. for (NSString *option in explorerToggles.allKeys) {
  354. BOOL current = [defaults boolForKey:option];
  355. NSString *title = [nextStateDescriptions[option][@(current)]
  356. stringByAppendingString:explorerToggles[option]
  357. ];
  358. make.button(title).handler(^(NSArray<NSString *> *strings) {
  359. [NSUserDefaults.standardUserDefaults flex_toggleBoolForKey:option];
  360. [self fullyReloadData];
  361. });
  362. }
  363. make.button(@"Cancel").cancelStyle();
  364. } showFrom:self source:sender];
  365. }
  366. #pragma mark - Description
  367. - (BOOL)shouldShowDescription {
  368. // Hide if we have filter text; it is rarely
  369. // useful to see the description when searching
  370. // since it's already at the top of the screen
  371. if (self.filterText.length) {
  372. return NO;
  373. }
  374. return YES;
  375. }
  376. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  377. // For the description section, we want that nice slim/snug looking row.
  378. // Other rows use the automatic size.
  379. FLEXTableViewSection *section = self.filterDelegate.sections[indexPath.section];
  380. if (section == self.descriptionSection) {
  381. NSAttributedString *attributedText = [[NSAttributedString alloc]
  382. initWithString:self.explorer.objectDescription
  383. attributes:@{ NSFontAttributeName : UIFont.flex_defaultTableCellFont }
  384. ];
  385. return [FLEXMultilineTableViewCell
  386. preferredHeightWithAttributedText:attributedText
  387. maxWidth:tableView.frame.size.width - tableView.separatorInset.right
  388. style:tableView.style
  389. showsAccessory:NO
  390. ];
  391. }
  392. return UITableViewAutomaticDimension;
  393. }
  394. - (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath {
  395. return self.filterDelegate.sections[indexPath.section] == self.descriptionSection;
  396. }
  397. - (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
  398. // Only the description section has "actions"
  399. if (self.filterDelegate.sections[indexPath.section] == self.descriptionSection) {
  400. return action == @selector(copy:);
  401. }
  402. return NO;
  403. }
  404. - (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
  405. if (action == @selector(copy:)) {
  406. #if !TARGET_OS_TV
  407. UIPasteboard.generalPasteboard.string = self.explorer.objectDescription;
  408. #endif
  409. }
  410. }
  411. @end