FLEXObjectExplorerViewController.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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. #endif
  119. }
  120. - (void)addlongPressGestureRecognizer {
  121. UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
  122. longPress.allowedPressTypes = @[[NSNumber numberWithInteger:UIPressTypePlayPause],[NSNumber numberWithInteger:UIPressTypeSelect]];
  123. [self.tableView addGestureRecognizer:longPress];
  124. }
  125. - (void)longPress:(UILongPressGestureRecognizer*)gesture {
  126. if ( gesture.state == UIGestureRecognizerStateEnded) {
  127. NSLog(@"do something different for long press!");
  128. UITableView *tv = [self tableView];
  129. //naughty naughty
  130. NSIndexPath *focus = [tv valueForKey:@"_focusedCellIndexPath"];
  131. NSLog(@"[FLEX] focusedIndexPath: %@", focus);
  132. [self tableView:self.tableView accessoryButtonTappedForRowWithIndexPath:focus];
  133. }
  134. }
  135. - (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView {
  136. #if !TARGET_OS_TV
  137. [self.navigationController setToolbarHidden:NO animated:YES];
  138. #endif
  139. return YES;
  140. }
  141. #pragma mark - Overrides
  142. /// Override to hide the description section when searching
  143. - (NSArray<FLEXTableViewSection *> *)nonemptySections {
  144. if (self.shouldShowDescription) {
  145. return super.nonemptySections;
  146. }
  147. return [super.nonemptySections flex_filtered:^BOOL(FLEXTableViewSection *section, NSUInteger idx) {
  148. return section != self.descriptionSection;
  149. }];
  150. }
  151. - (NSArray<FLEXTableViewSection *> *)makeSections {
  152. FLEXObjectExplorer *explorer = self.explorer;
  153. // Description section is only for instances
  154. if (self.explorer.objectIsInstance) {
  155. _descriptionSection = [FLEXSingleRowSection
  156. title:@"Description" reuse:kFLEXMultilineCell cell:^(FLEXTableViewCell *cell) {
  157. cell.titleLabel.font = UIFont.flex_defaultTableCellFont;
  158. cell.titleLabel.text = explorer.objectDescription;
  159. }
  160. ];
  161. self.descriptionSection.filterMatcher = ^BOOL(NSString *filterText) {
  162. return [explorer.objectDescription localizedCaseInsensitiveContainsString:filterText];
  163. };
  164. }
  165. // Object graph section
  166. FLEXSingleRowSection *referencesSection = [FLEXSingleRowSection
  167. title:@"Object Graph" reuse:kFLEXDefaultCell cell:^(FLEXTableViewCell *cell) {
  168. cell.titleLabel.text = @"See Objects with References to This Object";
  169. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  170. }
  171. ];
  172. referencesSection.selectionAction = ^(UIViewController *host) {
  173. UIViewController *references = [FLEXObjectListViewController
  174. objectsWithReferencesToObject:explorer.object
  175. ];
  176. [host.navigationController pushViewController:references animated:YES];
  177. };
  178. NSMutableArray *sections = [NSMutableArray arrayWithArray:@[
  179. [FLEXMetadataSection explorer:self.explorer kind:FLEXMetadataKindProperties],
  180. [FLEXMetadataSection explorer:self.explorer kind:FLEXMetadataKindClassProperties],
  181. [FLEXMetadataSection explorer:self.explorer kind:FLEXMetadataKindIvars],
  182. [FLEXMetadataSection explorer:self.explorer kind:FLEXMetadataKindMethods],
  183. [FLEXMetadataSection explorer:self.explorer kind:FLEXMetadataKindClassMethods],
  184. [FLEXMetadataSection explorer:self.explorer kind:FLEXMetadataKindClassHierarchy],
  185. [FLEXMetadataSection explorer:self.explorer kind:FLEXMetadataKindProtocols],
  186. [FLEXMetadataSection explorer:self.explorer kind:FLEXMetadataKindOther],
  187. referencesSection
  188. ]];
  189. if (self.customSection) {
  190. [sections insertObject:self.customSection atIndex:0];
  191. }
  192. if (self.descriptionSection) {
  193. [sections insertObject:self.descriptionSection atIndex:0];
  194. }
  195. return sections.copy;
  196. }
  197. /// In our case, all this does is reload the table view,
  198. /// or reload the sections' data if we changed places
  199. /// in the class hierarchy. Doesn't refresh \c self.explorer
  200. - (void)reloadData {
  201. // Check to see if class scope changed, update accordingly
  202. if (self.explorer.classScope != self.selectedScope) {
  203. self.explorer.classScope = self.selectedScope;
  204. [self reloadSections];
  205. }
  206. [super reloadData];
  207. }
  208. - (void)shareButtonPressed:(UIBarButtonItem *)sender {
  209. [FLEXAlert makeSheet:^(FLEXAlert *make) {
  210. make.button(@"Add to Bookmarks").handler(^(NSArray<NSString *> *strings) {
  211. [FLEXBookmarkManager.bookmarks addObject:self.object];
  212. });
  213. make.button(@"Copy Description").handler(^(NSArray<NSString *> *strings) {
  214. #if !TARGET_OS_TV
  215. UIPasteboard.generalPasteboard.string = self.explorer.objectDescription;
  216. #endif
  217. });
  218. make.button(@"Copy Address").handler(^(NSArray<NSString *> *strings) {
  219. #if !TARGET_OS_TV
  220. UIPasteboard.generalPasteboard.string = [FLEXUtility addressOfObject:self.object];
  221. #endif
  222. });
  223. make.button(@"Cancel").cancelStyle();
  224. } showFrom:self source:sender];
  225. }
  226. #pragma mark - Private
  227. /// Unlike \c -reloadData, this refreshes everything, including the explorer.
  228. - (void)fullyReloadData {
  229. [self.explorer reloadMetadata];
  230. [self reloadSections];
  231. [self reloadData];
  232. }
  233. - (void)handleSwipeGesture:(UISwipeGestureRecognizer *)gesture {
  234. if (gesture.state == UIGestureRecognizerStateEnded) {
  235. switch (gesture.direction) {
  236. case UISwipeGestureRecognizerDirectionRight:
  237. if (self.selectedScope > 0) {
  238. self.selectedScope -= 1;
  239. [self.tableView reloadData];
  240. }
  241. break;
  242. case UISwipeGestureRecognizerDirectionLeft:
  243. if (self.selectedScope != self.explorer.classHierarchy.count - 1) {
  244. self.selectedScope += 1;
  245. [self.tableView reloadData];
  246. }
  247. break;
  248. default:
  249. break;
  250. }
  251. }
  252. }
  253. - (BOOL)gestureRecognizer:(UIGestureRecognizer *)g1 shouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer *)g2 {
  254. // Prioritize important pan gestures over our swipe gesture
  255. #if !TARGET_OS_TV
  256. if ([g2 isKindOfClass:[UIPanGestureRecognizer class]]) {
  257. if (g2 == self.navigationController.interactivePopGestureRecognizer ||
  258. g2 == self.navigationController.barHideOnSwipeGestureRecognizer ||
  259. g2 == self.tableView.panGestureRecognizer) {
  260. return NO;
  261. }
  262. }
  263. #else
  264. if ([g2 isKindOfClass:[UIPanGestureRecognizer class]]) {
  265. if (g2 == self.tableView.panGestureRecognizer) {
  266. return NO;
  267. }
  268. }
  269. #endif
  270. return YES;
  271. }
  272. - (BOOL)gestureRecognizerShouldBegin:(UISwipeGestureRecognizer *)gesture {
  273. // Don't allow swiping from the carousel
  274. CGPoint location = [gesture locationInView:self.tableView];
  275. if ([self.carousel hitTest:location withEvent:nil]) {
  276. return NO;
  277. }
  278. return YES;
  279. }
  280. - (void)moreButtonPressed:(UIBarButtonItem *)sender {
  281. NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
  282. // Maps preference keys to a description of what they affect
  283. NSDictionary<NSString *, NSString *> *explorerToggles = @{
  284. kFLEXDefaultsHidePropertyIvarsKey: @"Property-Backing Ivars",
  285. kFLEXDefaultsHidePropertyMethodsKey: @"Property-Backing Methods",
  286. kFLEXDefaultsHideMethodOverridesKey: @"Method Overrides",
  287. kFLEXDefaultsHideVariablePreviewsKey: @"Variable Previews"
  288. };
  289. // Maps the key of the action itself to a map of a description
  290. // of the action ("hide X") mapped to the current state.
  291. //
  292. // So keys that are hidden by default have NO mapped to "Show"
  293. NSDictionary<NSString *, NSDictionary *> *nextStateDescriptions = @{
  294. kFLEXDefaultsHidePropertyIvarsKey: @{ @NO: @"Hide ", @YES: @"Show " },
  295. kFLEXDefaultsHidePropertyMethodsKey: @{ @NO: @"Hide ", @YES: @"Show " },
  296. kFLEXDefaultsHideMethodOverridesKey: @{ @NO: @"Show ", @YES: @"Hide " },
  297. kFLEXDefaultsHideVariablePreviewsKey: @{ @NO: @"Hide ", @YES: @"Show " },
  298. };
  299. [FLEXAlert makeSheet:^(FLEXAlert *make) {
  300. make.title(@"Options");
  301. for (NSString *option in explorerToggles.allKeys) {
  302. BOOL current = [defaults boolForKey:option];
  303. NSString *title = [nextStateDescriptions[option][@(current)]
  304. stringByAppendingString:explorerToggles[option]
  305. ];
  306. make.button(title).handler(^(NSArray<NSString *> *strings) {
  307. [NSUserDefaults.standardUserDefaults flex_toggleBoolForKey:option];
  308. [self fullyReloadData];
  309. });
  310. }
  311. make.button(@"Cancel").cancelStyle();
  312. } showFrom:self source:sender];
  313. }
  314. #pragma mark - Description
  315. - (BOOL)shouldShowDescription {
  316. // Hide if we have filter text; it is rarely
  317. // useful to see the description when searching
  318. // since it's already at the top of the screen
  319. if (self.filterText.length) {
  320. return NO;
  321. }
  322. return YES;
  323. }
  324. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  325. // For the description section, we want that nice slim/snug looking row.
  326. // Other rows use the automatic size.
  327. FLEXTableViewSection *section = self.filterDelegate.sections[indexPath.section];
  328. if (section == self.descriptionSection) {
  329. NSAttributedString *attributedText = [[NSAttributedString alloc]
  330. initWithString:self.explorer.objectDescription
  331. attributes:@{ NSFontAttributeName : UIFont.flex_defaultTableCellFont }
  332. ];
  333. return [FLEXMultilineTableViewCell
  334. preferredHeightWithAttributedText:attributedText
  335. maxWidth:tableView.frame.size.width - tableView.separatorInset.right
  336. style:tableView.style
  337. showsAccessory:NO
  338. ];
  339. }
  340. return UITableViewAutomaticDimension;
  341. }
  342. - (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath {
  343. return self.filterDelegate.sections[indexPath.section] == self.descriptionSection;
  344. }
  345. - (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
  346. // Only the description section has "actions"
  347. if (self.filterDelegate.sections[indexPath.section] == self.descriptionSection) {
  348. return action == @selector(copy:);
  349. }
  350. return NO;
  351. }
  352. - (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
  353. if (action == @selector(copy:)) {
  354. #if !TARGET_OS_TV
  355. UIPasteboard.generalPasteboard.string = self.explorer.objectDescription;
  356. #endif
  357. }
  358. }
  359. @end