TBKeyPathSearchController.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. //
  2. // FLEXKeyPathSearchController.m
  3. // FLEX
  4. //
  5. // Created by Tanner on 3/23/17.
  6. // Copyright © 2017 Tanner Bennett. All rights reserved.
  7. //
  8. #import "TBKeyPathSearchController.h"
  9. #import "TBKeyPathTokenizer.h"
  10. #import "TBRuntimeController.h"
  11. #import "NSString+FLEX.h"
  12. #import "NSArray+Functional.h"
  13. #import "UITextField+Range.h"
  14. #import "NSTimer+Blocks.h"
  15. #import "FLEXTableView.h"
  16. #import "FLEXUtility.h"
  17. #import "FLEXObjectExplorerFactory.h"
  18. @interface TBKeyPathSearchController ()
  19. @property (nonatomic, readonly, weak) id<TBKeyPathSearchControllerDelegate> delegate;
  20. @property (nonatomic) NSTimer *timer;
  21. @property (nonatomic) NSArray<NSString*> *bundlesOrClasses;
  22. @property (nonatomic) TBKeyPath *keyPath;
  23. /// Used to track which methods go with which classes. This is used in
  24. /// two scenarios: (1) when the target class is absolute and has classes,
  25. /// (this list will include the "leaf" class as well as parent classes in this case)
  26. /// or (2) when the class key is a wildcard and we're searching methods in many
  27. /// classes at once. Each list in \c classesToMethods correspnds to a class here.
  28. @property (nonatomic) NSArray<NSString *> *classes;
  29. /// A filtered version of \c classes used when searching for a specific attribute.
  30. /// Classes with no matching ivars/properties/methods are not shown.
  31. @property (nonatomic) NSArray<NSString *> *filteredClasses;
  32. // We use this regardless of whether the target class is absolute, just as above
  33. @property (nonatomic) NSArray<NSArray<FLEXMethod *> *> *classesToMethods;
  34. @end
  35. #warning TODO there's no code to handle refreshing the table after manually appending ".bar" to "Bundle"
  36. @implementation TBKeyPathSearchController
  37. + (instancetype)delegate:(id<TBKeyPathSearchControllerDelegate>)delegate {
  38. TBKeyPathSearchController *controller = [self new];
  39. controller->_bundlesOrClasses = [TBRuntimeController allBundleNames];
  40. controller->_delegate = delegate;
  41. NSParameterAssert(delegate.tableView);
  42. NSParameterAssert(delegate.searchController);
  43. delegate.tableView.delegate = controller;
  44. delegate.tableView.dataSource = controller;
  45. delegate.searchController.searchBar.delegate = controller;
  46. return controller;
  47. }
  48. - (void)scrollViewDidScroll:(UIScrollView *)scrollView {
  49. if (scrollView.isTracking || scrollView.isDragging || scrollView.isDecelerating) {
  50. [self.delegate.searchController.searchBar resignFirstResponder];
  51. }
  52. }
  53. - (void)setToolbar:(TBKeyPathToolbar *)toolbar {
  54. _toolbar = toolbar;
  55. self.delegate.searchController.searchBar.inputAccessoryView = toolbar;
  56. }
  57. - (NSArray<NSString *> *)classesOf:(NSString *)className {
  58. Class baseClass = NSClassFromString(className);
  59. if (!baseClass) {
  60. return @[];
  61. }
  62. // Find classes
  63. NSMutableArray<NSString*> *classes = [NSMutableArray arrayWithObject:className];
  64. while ([baseClass superclass]) {
  65. [classes addObject:NSStringFromClass([baseClass superclass])];
  66. baseClass = [baseClass superclass];
  67. }
  68. return classes;
  69. }
  70. #pragma mark Key path stuff
  71. - (void)didSelectKeyPathOption:(NSString *)text {
  72. [_timer invalidate]; // Still might be waiting to refresh when method is selected
  73. // Change "Bundle.fooba" to "Bundle.foobar."
  74. NSString *orig = self.delegate.searchController.searchBar.text;
  75. NSString *keyPath = [orig stringByReplacingLastKeyPathComponent:text];
  76. self.delegate.searchController.searchBar.text = keyPath;
  77. self.keyPath = [TBKeyPathTokenizer tokenizeString:keyPath];
  78. // Get classes if class was selected
  79. if (self.keyPath.classKey.isAbsolute && self.keyPath.methodKey.isAny) {
  80. [self didSelectAbsoluteClass:text];
  81. } else {
  82. self.classes = nil;
  83. self.filteredClasses = nil;
  84. }
  85. [self updateTable];
  86. }
  87. - (void)didSelectAbsoluteClass:(NSString *)name {
  88. self.classes = [self classesOf:name];
  89. self.filteredClasses = self.classes;
  90. self.bundlesOrClasses = nil;
  91. self.classesToMethods = nil;
  92. }
  93. - (void)didPressButton:(NSString *)text insertInto:(UISearchBar *)searchBar {
  94. // Available since at least iOS 9, still present in iOS 13
  95. UITextField *field = [searchBar valueForKey:@"_searchBarTextField"];
  96. if ([self searchBar:searchBar shouldChangeTextInRange:field.selectedRange replacementText:text]) {
  97. [field replaceRange:field.selectedTextRange withText:text];
  98. }
  99. }
  100. #pragma mark - Filtering + UISearchBarDelegate
  101. - (void)updateTable {
  102. // Compute the method, class, or bundle lists on a background thread
  103. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  104. if (self.classes) {
  105. // Here, our class key is 'absolute'; .classes is a list of superclasses
  106. // and we want to show the methods for those classes specifically
  107. // TODO: add caching to this somehow
  108. NSMutableArray *methods = [TBRuntimeController
  109. methodsForToken:self.keyPath.methodKey
  110. instance:self.keyPath.instanceMethods
  111. inClasses:self.classes
  112. ].mutableCopy;
  113. // Remove classes without results if we're searching for a method
  114. TBToken *methodKey = self.keyPath.methodKey;
  115. if (methodKey && !methodKey.isAny) {
  116. [self setNonEmptyMethodLists:methods withClasses:self.classes.mutableCopy];
  117. } else {
  118. self.filteredClasses = self.classes;
  119. }
  120. }
  121. else {
  122. TBKeyPath *keyPath = self.keyPath;
  123. NSArray *models = [TBRuntimeController dataForKeyPath:keyPath];
  124. if (keyPath.methodKey) { // We're looking at methods
  125. self.bundlesOrClasses = nil;
  126. NSMutableArray *methods = models.mutableCopy;
  127. NSMutableArray *classes = [TBRuntimeController classesForKeyPath:keyPath];
  128. self.classes = classes.copy;
  129. [self setNonEmptyMethodLists:methods withClasses:classes];
  130. } else { // We're looking at bundles or classes
  131. self.bundlesOrClasses = models;
  132. self.classesToMethods = nil;
  133. }
  134. }
  135. // Finally, reload the table on the main thread
  136. dispatch_async(dispatch_get_main_queue(), ^{
  137. [self.delegate.tableView reloadData];
  138. });
  139. });
  140. }
  141. /// Assign assign .filteredClasses and .classesToMethods after removing empty sections
  142. - (void)setNonEmptyMethodLists:(NSMutableArray<NSArray *> *)methods withClasses:(NSMutableArray *)classes {
  143. // Remove sections with no methods
  144. NSIndexSet *allEmpty = [methods indexesOfObjectsPassingTest:^BOOL(NSArray *list, NSUInteger idx, BOOL *stop) {
  145. return list.count == 0;
  146. }];
  147. [methods removeObjectsAtIndexes:allEmpty];
  148. [classes removeObjectsAtIndexes:allEmpty];
  149. self.filteredClasses = classes;
  150. self.classesToMethods = methods;
  151. }
  152. - (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
  153. // Check if character is even legal
  154. if (![TBKeyPathTokenizer allowedInKeyPath:text]) {
  155. return NO;
  156. }
  157. BOOL terminatedToken = NO;
  158. BOOL isAppending = range.length == 0 && range.location == searchBar.text.length;
  159. if (isAppending && [text isEqualToString:@"."]) {
  160. terminatedToken = YES;
  161. }
  162. // Actually parse input
  163. @try {
  164. text = [searchBar.text stringByReplacingCharactersInRange:range withString:text] ?: text;
  165. self.keyPath = [TBKeyPathTokenizer tokenizeString:text];
  166. if (self.keyPath.classKey.isAbsolute && terminatedToken) {
  167. [self didSelectAbsoluteClass:self.keyPath.classKey.string];
  168. }
  169. } @catch (id e) {
  170. return NO;
  171. }
  172. return YES;
  173. }
  174. - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
  175. [_timer invalidate];
  176. // Update toolbar buttons
  177. [self.toolbar setKeyPath:self.keyPath animated:YES];
  178. // Schedule update timer
  179. if (searchText.length) {
  180. if (!self.keyPath.methodKey) {
  181. self.classes = nil;
  182. self.filteredClasses = nil;
  183. }
  184. self.timer = [NSTimer fireSecondsFromNow:0.15 block:^{
  185. [self updateTable];
  186. }];
  187. }
  188. // ... or remove all rows
  189. else {
  190. _bundlesOrClasses = [TBRuntimeController allBundleNames];
  191. _classesToMethods = nil;
  192. _classes = nil;
  193. _keyPath = nil;
  194. [self.delegate.tableView reloadData];
  195. }
  196. }
  197. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
  198. self.keyPath = [TBKeyPath empty];
  199. [self updateTable];
  200. }
  201. /// Restore key path when going "back" and activating search bar again
  202. - (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
  203. searchBar.text = self.keyPath.description;
  204. }
  205. - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
  206. [_timer invalidate];
  207. [searchBar resignFirstResponder];
  208. [self updateTable];
  209. }
  210. #pragma mark UITableViewDataSource
  211. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  212. return self.filteredClasses.count ?: 1;
  213. }
  214. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  215. return self.filteredClasses.count ? 1 : self.bundlesOrClasses.count;
  216. }
  217. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  218. UITableViewCell *cell = [tableView
  219. dequeueReusableCellWithIdentifier:kFLEXMultilineDetailCell
  220. forIndexPath:indexPath
  221. ];
  222. if (self.bundlesOrClasses.count) {
  223. cell.accessoryType = UITableViewCellAccessoryDetailButton;
  224. cell.textLabel.text = self.bundlesOrClasses[indexPath.row];
  225. cell.detailTextLabel.text = nil;
  226. if (self.keyPath.classKey) {
  227. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  228. }
  229. }
  230. // One row per section
  231. else if (self.filteredClasses.count) {
  232. NSArray<FLEXMethod *> *methods = self.classesToMethods[indexPath.section];
  233. NSMutableString *summary = [NSMutableString new];
  234. [methods enumerateObjectsUsingBlock:^(FLEXMethod *method, NSUInteger idx, BOOL *stop) {
  235. NSString *format = nil;
  236. if (idx == methods.count-1) {
  237. format = @"%@%@";
  238. *stop = YES;
  239. } else if (idx < 3) {
  240. format = @"%@%@\n";
  241. } else {
  242. format = @"%@%@\n…";
  243. *stop = YES;
  244. }
  245. [summary appendFormat:format, method.isInstanceMethod ? @"-" : @"+", method.selectorString];
  246. }];
  247. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  248. cell.textLabel.text = self.filteredClasses[indexPath.section];
  249. cell.detailTextLabel.text = summary.length ? summary : nil;
  250. }
  251. else {
  252. @throw NSInternalInconsistencyException;
  253. }
  254. return cell;
  255. }
  256. - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
  257. if (self.filteredClasses || self.keyPath.methodKey) {
  258. return @" ";
  259. } else if (self.bundlesOrClasses) {
  260. NSInteger count = self.bundlesOrClasses.count;
  261. if (self.keyPath.classKey) {
  262. return FLEXPluralString(count, @"classes", @"class");
  263. } else {
  264. return FLEXPluralString(count, @"bundles", @"bundle");
  265. }
  266. }
  267. return [self.delegate tableView:tableView titleForHeaderInSection:section];
  268. }
  269. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
  270. if (self.filteredClasses || self.keyPath.methodKey) {
  271. if (section == 0) {
  272. return 55;
  273. }
  274. return 0;
  275. }
  276. return 55;
  277. }
  278. #pragma mark UITableViewDelegate
  279. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  280. if (self.bundlesOrClasses) {
  281. NSString *bundleSuffixOrClass = self.bundlesOrClasses[indexPath.row];
  282. if (self.keyPath.classKey) {
  283. NSParameterAssert(NSClassFromString(bundleSuffixOrClass));
  284. [self.delegate didSelectClass:NSClassFromString(bundleSuffixOrClass)];
  285. } else {
  286. // Selected a bundle
  287. [self didSelectKeyPathOption:bundleSuffixOrClass];
  288. }
  289. } else {
  290. if (self.filteredClasses.count) {
  291. Class cls = NSClassFromString(self.filteredClasses[indexPath.section]);
  292. NSParameterAssert(cls);
  293. [self.delegate didSelectClass:cls];
  294. } else {
  295. @throw NSInternalInconsistencyException;
  296. }
  297. }
  298. }
  299. - (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
  300. NSString *bundleSuffixOrClass = self.bundlesOrClasses[indexPath.row];
  301. NSString *imagePath = [TBRuntimeController imagePathWithShortName:bundleSuffixOrClass];
  302. NSBundle *bundle = [NSBundle bundleWithPath:imagePath.stringByDeletingLastPathComponent];
  303. if (bundle) {
  304. [self.delegate didSelectBundle:bundle];
  305. } else {
  306. [self.delegate didSelectImagePath:imagePath shortName:bundleSuffixOrClass];
  307. }
  308. }
  309. @end