FLEXKeyPathSearchController.m 14 KB

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