FLEXShortcutsSection.m 13 KB

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