FLEXShortcutsSection.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. //
  2. // FLEXShortcutsSection.m
  3. // FLEX
  4. //
  5. // Created by Tanner Bennett on 8/29/19.
  6. // Copyright © 2020 FLEX Team. All rights reserved.
  7. //
  8. #import "FLEXShortcutsSection.h"
  9. #import "FLEXTableView.h"
  10. #import "FLEXTableViewCell.h"
  11. #import "FLEXUtility.h"
  12. #import "FLEXShortcut.h"
  13. #import "FLEXProperty.h"
  14. #import "FLEXPropertyAttributes.h"
  15. #import "FLEXIvar.h"
  16. #import "FLEXMethod.h"
  17. #import "FLEXRuntime+UIKitHelpers.h"
  18. #import "FLEXObjectExplorer.h"
  19. #pragma mark Private
  20. @interface FLEXShortcutsSection ()
  21. @property (nonatomic, copy) NSArray<NSString *> *titles;
  22. @property (nonatomic, copy) NSArray<NSString *> *subtitles;
  23. @property (nonatomic, copy) NSArray<NSString *> *allTitles;
  24. @property (nonatomic, copy) NSArray<NSString *> *allSubtitles;
  25. // Shortcuts are not used if initialized with static titles and subtitles
  26. @property (nonatomic, copy) NSArray<id<FLEXShortcut>> *shortcuts;
  27. @property (nonatomic, readonly) NSArray<id<FLEXShortcut>> *allShortcuts;
  28. @end
  29. @implementation FLEXShortcutsSection
  30. #pragma mark Initialization
  31. + (instancetype)forObject:(id)objectOrClass rowTitles:(NSArray<NSString *> *)titles {
  32. return [self forObject:objectOrClass rowTitles:titles rowSubtitles:nil];
  33. }
  34. + (instancetype)forObject:(id)objectOrClass
  35. rowTitles:(NSArray<NSString *> *)titles
  36. rowSubtitles:(NSArray<NSString *> *)subtitles {
  37. return [[self alloc] initWithObject:objectOrClass titles:titles subtitles:subtitles];
  38. }
  39. + (instancetype)forObject:(id)objectOrClass rows:(NSArray *)rows {
  40. return [[self alloc] initWithObject:objectOrClass rows:rows];
  41. }
  42. + (instancetype)forObject:(id)objectOrClass additionalRows:(NSArray *)toPrepend {
  43. NSArray *rows = [FLEXShortcutsFactory shortcutsForObjectOrClass:objectOrClass];
  44. NSArray *allRows = [toPrepend arrayByAddingObjectsFromArray:rows] ?: rows;
  45. return [self forObject:objectOrClass rows:allRows];
  46. }
  47. + (instancetype)forObject:(id)objectOrClass {
  48. return [self forObject:objectOrClass additionalRows:nil];
  49. }
  50. - (id)initWithObject:(id)object
  51. titles:(NSArray<NSString *> *)titles
  52. subtitles:(NSArray<NSString *> *)subtitles {
  53. NSParameterAssert(titles.count == subtitles.count || !subtitles);
  54. NSParameterAssert(titles.count);
  55. self = [super init];
  56. if (self) {
  57. _object = object;
  58. _allTitles = titles.copy;
  59. _allSubtitles = subtitles.copy;
  60. _numberOfLines = 1;
  61. }
  62. return self;
  63. }
  64. - (id)initWithObject:object rows:(NSArray *)rows {
  65. self = [super init];
  66. if (self) {
  67. _object = object;
  68. _allShortcuts = [rows flex_mapped:^id(id obj, NSUInteger idx) {
  69. return [FLEXShortcut shortcutFor:obj];
  70. }];
  71. _numberOfLines = 1;
  72. // Populate titles and subtitles
  73. [self reloadData];
  74. }
  75. return self;
  76. }
  77. #pragma mark - Public
  78. - (void)setCacheSubtitles:(BOOL)cacheSubtitles {
  79. if (_cacheSubtitles == cacheSubtitles) return;
  80. // cacheSubtitles only applies if we have shortcut objects
  81. if (self.allShortcuts) {
  82. _cacheSubtitles = cacheSubtitles;
  83. [self reloadData];
  84. } else {
  85. NSLog(@"Warning: setting 'cacheSubtitles' on a shortcut section with static subtitles");
  86. }
  87. }
  88. #pragma mark - Overrides
  89. - (UITableViewCellAccessoryType)accessoryTypeForRow:(NSInteger)row {
  90. if (_allShortcuts) {
  91. return [self.shortcuts[row] accessoryTypeWith:self.object];
  92. }
  93. return UITableViewCellAccessoryNone;
  94. }
  95. - (void)setFilterText:(NSString *)filterText {
  96. super.filterText = filterText;
  97. NSAssert(
  98. self.allTitles.count == self.allSubtitles.count,
  99. @"Each title needs a (possibly empty) subtitle"
  100. );
  101. if (filterText.length) {
  102. // Tally up indexes of titles and subtitles matching the filter
  103. NSMutableIndexSet *filterMatches = [NSMutableIndexSet new];
  104. id filterBlock = ^BOOL(NSString *obj, NSUInteger idx) {
  105. if ([obj localizedCaseInsensitiveContainsString:filterText]) {
  106. [filterMatches addIndex:idx];
  107. return YES;
  108. }
  109. return NO;
  110. };
  111. // Get all matching indexes, including subtitles
  112. [self.allTitles flex_forEach:filterBlock];
  113. [self.allSubtitles flex_forEach:filterBlock];
  114. // Filter to matching indexes only
  115. self.titles = [self.allTitles objectsAtIndexes:filterMatches];
  116. self.subtitles = [self.allSubtitles objectsAtIndexes:filterMatches];
  117. self.shortcuts = [self.allShortcuts objectsAtIndexes:filterMatches];
  118. } else {
  119. self.shortcuts = self.allShortcuts;
  120. self.titles = self.allTitles;
  121. self.subtitles = [self.allSubtitles flex_filtered:^BOOL(NSString *sub, NSUInteger idx) {
  122. return sub.length > 0;
  123. }];
  124. }
  125. }
  126. - (void)reloadData {
  127. [FLEXObjectExplorer configureDefaultsForItems:self.allShortcuts];
  128. // Generate all (sub)titles from shortcuts
  129. if (self.allShortcuts) {
  130. self.allTitles = [self.allShortcuts flex_mapped:^id(FLEXShortcut *s, NSUInteger idx) {
  131. return [s titleWith:self.object];
  132. }];
  133. self.allSubtitles = [self.allShortcuts flex_mapped:^id(FLEXShortcut *s, NSUInteger idx) {
  134. return [s subtitleWith:self.object] ?: @"";
  135. }];
  136. }
  137. // Re-generate filtered (sub)titles and shortcuts
  138. self.filterText = self.filterText;
  139. }
  140. - (NSString *)title {
  141. return @"Shortcuts";
  142. }
  143. - (NSInteger)numberOfRows {
  144. return self.titles.count;
  145. }
  146. - (BOOL)canSelectRow:(NSInteger)row {
  147. UITableViewCellAccessoryType type = [self.shortcuts[row] accessoryTypeWith:self.object];
  148. BOOL hasDisclosure = NO;
  149. hasDisclosure |= type == UITableViewCellAccessoryDisclosureIndicator;
  150. #if !TARGET_OS_TV
  151. hasDisclosure |= type == UITableViewCellAccessoryDetailDisclosureButton;
  152. #endif
  153. return hasDisclosure;
  154. }
  155. - (void (^)(__kindof UIViewController *))didSelectRowAction:(NSInteger)row {
  156. return [self.shortcuts[row] didSelectActionWith:self.object];
  157. }
  158. - (UIViewController *)viewControllerToPushForRow:(NSInteger)row {
  159. /// Nil if shortcuts is nil, i.e. if initialized with forObject:rowTitles:rowSubtitles:
  160. return [self.shortcuts[row] viewerWith:self.object];
  161. }
  162. - (void (^)(__kindof UIViewController *))didPressInfoButtonAction:(NSInteger)row {
  163. id<FLEXShortcut> shortcut = self.shortcuts[row];
  164. if ([shortcut respondsToSelector:@selector(editorWith:forSection:)]) {
  165. id object = self.object;
  166. return ^(UIViewController *host) {
  167. UIViewController *editor = [shortcut editorWith:object forSection:self];
  168. [host.navigationController pushViewController:editor animated:YES];
  169. };
  170. }
  171. return nil;
  172. }
  173. - (NSString *)reuseIdentifierForRow:(NSInteger)row {
  174. FLEXTableViewCellReuseIdentifier defaultReuse = kFLEXDetailCell;
  175. if (@available(iOS 11, *)) {
  176. defaultReuse = kFLEXMultilineDetailCell;
  177. }
  178. return [self.shortcuts[row] customReuseIdentifierWith:self.object] ?: defaultReuse;
  179. }
  180. - (void)configureCell:(__kindof FLEXTableViewCell *)cell forRow:(NSInteger)row {
  181. cell.titleLabel.text = [self titleForRow:row];
  182. cell.titleLabel.numberOfLines = self.numberOfLines;
  183. cell.subtitleLabel.text = [self subtitleForRow:row];
  184. cell.subtitleLabel.numberOfLines = self.numberOfLines;
  185. cell.accessoryType = [self accessoryTypeForRow:row];
  186. }
  187. - (NSString *)titleForRow:(NSInteger)row {
  188. return self.titles[row];
  189. }
  190. - (NSString *)subtitleForRow:(NSInteger)row {
  191. // Case: dynamic, uncached subtitles
  192. if (!self.cacheSubtitles) {
  193. NSString *subtitle = [self.shortcuts[row] subtitleWith:self.object];
  194. return subtitle.length ? subtitle : nil;
  195. }
  196. // Case: static subtitles, or cached subtitles
  197. return self.subtitles[row];
  198. }
  199. @end
  200. #pragma mark - Global shortcut registration
  201. @interface FLEXShortcutsFactory () {
  202. BOOL _append, _prepend, _replace, _notInstance;
  203. NSArray<NSString *> *_properties, *_ivars, *_methods;
  204. }
  205. @end
  206. #define NewAndSet(ivar) ({ FLEXShortcutsFactory *r = [self sharedFactory]; r->ivar = YES; r; })
  207. #define SetIvar(ivar) ({ self->ivar = YES; self; })
  208. #define SetParamBlock(ivar) ^(NSArray *p) { self->ivar = p; return self; }
  209. typedef NSMutableDictionary<Class, NSMutableArray<id<FLEXRuntimeMetadata>> *> RegistrationBuckets;
  210. @implementation FLEXShortcutsFactory {
  211. // Class buckets
  212. RegistrationBuckets *cProperties;
  213. RegistrationBuckets *cIvars;
  214. RegistrationBuckets *cMethods;
  215. // Metaclass buckets
  216. RegistrationBuckets *mProperties;
  217. RegistrationBuckets *mMethods;
  218. }
  219. + (instancetype)sharedFactory {
  220. static FLEXShortcutsFactory *shared = nil;
  221. static dispatch_once_t onceToken;
  222. dispatch_once(&onceToken, ^{
  223. shared = [self new];
  224. });
  225. return shared;
  226. }
  227. - (id)init {
  228. self = [super init];
  229. if (self) {
  230. cProperties = [NSMutableDictionary new];
  231. cIvars = [NSMutableDictionary new];
  232. cMethods = [NSMutableDictionary new];
  233. mProperties = [NSMutableDictionary new];
  234. mMethods = [NSMutableDictionary new];
  235. }
  236. return self;
  237. }
  238. + (NSArray<id<FLEXRuntimeMetadata>> *)shortcutsForObjectOrClass:(id)objectOrClass {
  239. return [[self sharedFactory] shortcutsForObjectOrClass:objectOrClass];
  240. }
  241. - (NSArray<id<FLEXRuntimeMetadata>> *)shortcutsForObjectOrClass:(id)objectOrClass {
  242. NSMutableArray<id<FLEXRuntimeMetadata>> *shortcuts = [NSMutableArray new];
  243. BOOL isClass = object_isClass(objectOrClass);
  244. // The -class does not give you a metaclass, and we want a metaclass
  245. // if a class is passed in, or a class if an object is passed in
  246. Class classKey = object_getClass(objectOrClass);
  247. RegistrationBuckets *propertyBucket = isClass ? mProperties : cProperties;
  248. RegistrationBuckets *methodBucket = isClass ? mMethods : cMethods;
  249. RegistrationBuckets *ivarBucket = isClass ? nil : cIvars;
  250. BOOL stop = NO;
  251. while (!stop && classKey) {
  252. NSArray *properties = propertyBucket[classKey];
  253. NSArray *ivars = ivarBucket[classKey];
  254. NSArray *methods = methodBucket[classKey];
  255. // Stop if we found anything
  256. stop = properties || ivars || methods;
  257. if (stop) {
  258. // Add things we found to the list
  259. [shortcuts addObjectsFromArray:properties];
  260. [shortcuts addObjectsFromArray:ivars];
  261. [shortcuts addObjectsFromArray:methods];
  262. } else {
  263. classKey = class_getSuperclass(classKey);
  264. }
  265. }
  266. [FLEXObjectExplorer configureDefaultsForItems:shortcuts];
  267. return shortcuts;
  268. }
  269. + (FLEXShortcutsFactory *)append {
  270. return NewAndSet(_append);
  271. }
  272. + (FLEXShortcutsFactory *)prepend {
  273. return NewAndSet(_prepend);
  274. }
  275. + (FLEXShortcutsFactory *)replace {
  276. return NewAndSet(_replace);
  277. }
  278. - (void)_register:(NSArray<id<FLEXRuntimeMetadata>> *)items to:(RegistrationBuckets *)global class:(Class)key {
  279. @synchronized (self) {
  280. // Get (or initialize) the bucket for this class
  281. NSMutableArray *bucket = ({
  282. id bucket = global[key];
  283. if (!bucket) {
  284. bucket = [NSMutableArray new];
  285. global[(id)key] = bucket;
  286. }
  287. bucket;
  288. });
  289. if (self->_append) { [bucket addObjectsFromArray:items]; }
  290. if (self->_replace) { [bucket setArray:items]; }
  291. if (self->_prepend) {
  292. if (bucket.count) {
  293. // Set new items as array, add old items behind them
  294. id copy = bucket.copy;
  295. [bucket setArray:items];
  296. [bucket addObjectsFromArray:copy];
  297. } else {
  298. [bucket addObjectsFromArray:items];
  299. }
  300. }
  301. [self reset];
  302. }
  303. }
  304. - (void)reset {
  305. _append = NO;
  306. _prepend = NO;
  307. _replace = NO;
  308. _notInstance = NO;
  309. _properties = nil;
  310. _ivars = nil;
  311. _methods = nil;
  312. }
  313. - (FLEXShortcutsFactory *)class {
  314. return SetIvar(_notInstance);
  315. }
  316. - (FLEXShortcutsFactoryNames)properties {
  317. NSAssert(!_notInstance, @"Do not try to set properties+classProperties at the same time");
  318. return SetParamBlock(_properties);
  319. }
  320. - (FLEXShortcutsFactoryNames)classProperties {
  321. _notInstance = YES;
  322. return SetParamBlock(_properties);
  323. }
  324. - (FLEXShortcutsFactoryNames)ivars {
  325. return SetParamBlock(_ivars);
  326. }
  327. - (FLEXShortcutsFactoryNames)methods {
  328. NSAssert(!_notInstance, @"Do not try to set methods+classMethods at the same time");
  329. return SetParamBlock(_methods);
  330. }
  331. - (FLEXShortcutsFactoryNames)classMethods {
  332. _notInstance = YES;
  333. return SetParamBlock(_methods);
  334. }
  335. - (FLEXShortcutsFactoryTarget)forClass {
  336. return ^(Class cls) {
  337. NSAssert(
  338. ( self->_append && !self->_prepend && !self->_replace) ||
  339. (!self->_append && self->_prepend && !self->_replace) ||
  340. (!self->_append && !self->_prepend && self->_replace),
  341. @"You can only do one of [append, prepend, replace]"
  342. );
  343. /// Whether the metadata we're about to add is instance or
  344. /// class metadata, i.e. class properties vs instance properties
  345. BOOL instanceMetadata = !self->_notInstance;
  346. /// Whether the given class is a metaclass or not; we need to switch to
  347. /// the metaclass to add class metadata if we are given the normal class object
  348. BOOL isMeta = class_isMetaClass(cls);
  349. /// Whether the shortcuts we're about to add should appear for classes or instances
  350. BOOL instanceShortcut = !isMeta;
  351. if (instanceMetadata) {
  352. NSAssert(!isMeta,
  353. @"Instance metadata can only be added as an instance shortcut"
  354. );
  355. }
  356. Class metaclass = isMeta ? cls : object_getClass(cls);
  357. Class clsForMetadata = instanceMetadata ? cls : metaclass;
  358. // The factory is a singleton so we don't need to worry about "leaking" it
  359. #pragma clang diagnostic push
  360. #pragma clang diagnostic ignored "-Wimplicit-retain-self"
  361. RegistrationBuckets *propertyBucket = instanceShortcut ? cProperties : mProperties;
  362. RegistrationBuckets *methodBucket = instanceShortcut ? cMethods : mMethods;
  363. RegistrationBuckets *ivarBucket = instanceShortcut ? cIvars : nil;
  364. #pragma clang diagnostic pop
  365. if (self->_properties) {
  366. NSArray *items = [self->_properties flex_mapped:^id(NSString *name, NSUInteger idx) {
  367. return [FLEXProperty named:name onClass:clsForMetadata];
  368. }];
  369. [self _register:items to:propertyBucket class:cls];
  370. }
  371. if (self->_methods) {
  372. NSArray *items = [self->_methods flex_mapped:^id(NSString *name, NSUInteger idx) {
  373. return [FLEXMethod selector:NSSelectorFromString(name) class:clsForMetadata];
  374. }];
  375. [self _register:items to:methodBucket class:cls];
  376. }
  377. if (self->_ivars) {
  378. NSAssert(instanceMetadata, @"Instance metadata can only be added as an instance shortcut (%@)", cls);
  379. NSArray *items = [self->_ivars flex_mapped:^id(NSString *name, NSUInteger idx) {
  380. return [FLEXIvar named:name onClass:clsForMetadata];
  381. }];
  382. [self _register:items to:ivarBucket class:cls];
  383. }
  384. };
  385. }
  386. @end