TBKeyPathSearchController.m 14 KB

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