FLEXFileBrowserTableViewController.m 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. //
  2. // FLEXFileBrowserTableViewController.m
  3. // Flipboard
  4. //
  5. // Created by Ryan Olson on 6/9/14.
  6. //
  7. //
  8. #import "FLEXFileBrowserTableViewController.h"
  9. #import "FLEXUtility.h"
  10. #import "FLEXWebViewController.h"
  11. #import "FLEXImagePreviewViewController.h"
  12. #import "FLEXTableListViewController.h"
  13. #import "FLEXObjectExplorerFactory.h"
  14. #import "FLEXObjectExplorerViewController.h"
  15. @interface FLEXFileBrowserTableViewCell : UITableViewCell
  16. @end
  17. @interface FLEXFileBrowserTableViewController () <FLEXFileBrowserSearchOperationDelegate>
  18. @property (nonatomic, copy) NSString *path;
  19. @property (nonatomic, copy) NSArray<NSString *> *childPaths;
  20. @property (nonatomic) NSArray<NSString *> *searchPaths;
  21. @property (nonatomic) NSNumber *recursiveSize;
  22. @property (nonatomic) NSNumber *searchPathsSize;
  23. @property (nonatomic) NSOperationQueue *operationQueue;
  24. @property (nonatomic) UIDocumentInteractionController *documentController;
  25. @end
  26. @implementation FLEXFileBrowserTableViewController
  27. - (id)init
  28. {
  29. return [self initWithPath:NSHomeDirectory()];
  30. }
  31. - (id)initWithPath:(NSString *)path
  32. {
  33. self = [super init];
  34. if (self) {
  35. self.path = path;
  36. self.title = [path lastPathComponent];
  37. self.operationQueue = [NSOperationQueue new];
  38. //computing path size
  39. FLEXFileBrowserTableViewController *__weak weakSelf = self;
  40. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  41. NSFileManager *fileManager = NSFileManager.defaultManager;
  42. NSDictionary<NSString *, id> *attributes = [fileManager attributesOfItemAtPath:path error:NULL];
  43. uint64_t totalSize = [attributes fileSize];
  44. for (NSString *fileName in [fileManager enumeratorAtPath:path]) {
  45. attributes = [fileManager attributesOfItemAtPath:[path stringByAppendingPathComponent:fileName] error:NULL];
  46. totalSize += [attributes fileSize];
  47. // Bail if the interested view controller has gone away.
  48. if (!weakSelf) {
  49. return;
  50. }
  51. }
  52. dispatch_async(dispatch_get_main_queue(), ^{
  53. FLEXFileBrowserTableViewController *__strong strongSelf = weakSelf;
  54. strongSelf.recursiveSize = @(totalSize);
  55. [strongSelf.tableView reloadData];
  56. });
  57. });
  58. [self reloadCurrentPath];
  59. }
  60. return self;
  61. }
  62. #pragma mark - UIViewController
  63. - (void)viewDidLoad
  64. {
  65. [super viewDidLoad];
  66. self.showsSearchBar = YES;
  67. self.searchBarDebounceInterval = kFLEXDebounceForAsyncSearch;
  68. }
  69. #pragma mark - FLEXGlobalsEntry
  70. + (NSString *)globalsEntryTitle:(FLEXGlobalsRow)row {
  71. switch (row) {
  72. case FLEXGlobalsRowBrowseBundle: return @"📁 Browse Bundle Directory";
  73. case FLEXGlobalsRowBrowseContainer: return @"📁 Browse Container Directory";
  74. default: return nil;
  75. }
  76. }
  77. + (UIViewController *)globalsEntryViewController:(FLEXGlobalsRow)row {
  78. switch (row) {
  79. case FLEXGlobalsRowBrowseBundle: return [[self alloc] initWithPath:NSBundle.mainBundle.bundlePath];
  80. case FLEXGlobalsRowBrowseContainer: return [[self alloc] initWithPath:NSHomeDirectory()];
  81. default: return [self new];
  82. }
  83. }
  84. #pragma mark - FLEXFileBrowserSearchOperationDelegate
  85. - (void)fileBrowserSearchOperationResult:(NSArray<NSString *> *)searchResult size:(uint64_t)size
  86. {
  87. self.searchPaths = searchResult;
  88. self.searchPathsSize = @(size);
  89. [self.tableView reloadData];
  90. }
  91. #pragma mark - Search bar
  92. - (void)updateSearchResults:(NSString *)newText
  93. {
  94. [self reloadDisplayedPaths];
  95. }
  96. #pragma mark UISearchControllerDelegate
  97. - (void)willDismissSearchController:(UISearchController *)searchController
  98. {
  99. [self.operationQueue cancelAllOperations];
  100. [self reloadCurrentPath];
  101. [self.tableView reloadData];
  102. }
  103. #pragma mark - Table view data source
  104. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  105. {
  106. return 1;
  107. }
  108. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  109. {
  110. return self.searchController.isActive ? self.searchPaths.count : self.childPaths.count;
  111. }
  112. - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
  113. {
  114. BOOL isSearchActive = self.searchController.isActive;
  115. NSNumber *currentSize = isSearchActive ? self.searchPathsSize : self.recursiveSize;
  116. NSArray<NSString *> *currentPaths = isSearchActive ? self.searchPaths : self.childPaths;
  117. NSString *sizeString = nil;
  118. if (!currentSize) {
  119. sizeString = @"Computing size…";
  120. } else {
  121. sizeString = [NSByteCountFormatter stringFromByteCount:[currentSize longLongValue] countStyle:NSByteCountFormatterCountStyleFile];
  122. }
  123. return [NSString stringWithFormat:@"%lu files (%@)", (unsigned long)currentPaths.count, sizeString];
  124. }
  125. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  126. {
  127. NSString *fullPath = [self filePathAtIndexPath:indexPath];
  128. NSDictionary<NSString *, id> *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:fullPath error:NULL];
  129. BOOL isDirectory = [attributes.fileType isEqual:NSFileTypeDirectory];
  130. NSString *subtitle = nil;
  131. if (isDirectory) {
  132. NSUInteger count = [NSFileManager.defaultManager contentsOfDirectoryAtPath:fullPath error:NULL].count;
  133. subtitle = [NSString stringWithFormat:@"%lu item%@", (unsigned long)count, (count == 1 ? @"" : @"s")];
  134. } else {
  135. NSString *sizeString = [NSByteCountFormatter stringFromByteCount:attributes.fileSize countStyle:NSByteCountFormatterCountStyleFile];
  136. subtitle = [NSString stringWithFormat:@"%@ - %@", sizeString, attributes.fileModificationDate ?: @"Never modified"];
  137. }
  138. static NSString *textCellIdentifier = @"textCell";
  139. static NSString *imageCellIdentifier = @"imageCell";
  140. UITableViewCell *cell = nil;
  141. // Separate image and text only cells because otherwise the separator lines get out-of-whack on image cells reused with text only.
  142. UIImage *image = [UIImage imageWithContentsOfFile:fullPath];
  143. NSString *cellIdentifier = image ? imageCellIdentifier : textCellIdentifier;
  144. if (!cell) {
  145. cell = [[FLEXFileBrowserTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
  146. cell.textLabel.font = [FLEXUtility defaultTableViewCellLabelFont];
  147. cell.detailTextLabel.font = [FLEXUtility defaultTableViewCellLabelFont];
  148. cell.detailTextLabel.textColor = UIColor.grayColor;
  149. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  150. }
  151. NSString *cellTitle = [fullPath lastPathComponent];
  152. cell.textLabel.text = cellTitle;
  153. cell.detailTextLabel.text = subtitle;
  154. if (image) {
  155. cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
  156. cell.imageView.image = image;
  157. }
  158. return cell;
  159. }
  160. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  161. {
  162. [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
  163. NSString *fullPath = [self filePathAtIndexPath:indexPath];
  164. NSString *subpath = fullPath.lastPathComponent;
  165. NSString *pathExtension = subpath.pathExtension;
  166. BOOL isDirectory = NO;
  167. BOOL stillExists = [NSFileManager.defaultManager fileExistsAtPath:fullPath isDirectory:&isDirectory];
  168. UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  169. UIImage *image = cell.imageView.image;
  170. if (!stillExists) {
  171. [FLEXAlert showAlert:@"File Not Found" message:@"The file at the specified path no longer exists." from:self];
  172. [self reloadDisplayedPaths];
  173. return;
  174. }
  175. UIViewController *drillInViewController = nil;
  176. if (isDirectory) {
  177. drillInViewController = [[[self class] alloc] initWithPath:fullPath];
  178. } else if (image) {
  179. drillInViewController = [[FLEXImagePreviewViewController alloc] initWithImage:image];
  180. } else {
  181. NSData *fileData = [NSData dataWithContentsOfFile:fullPath];
  182. if (!fileData.length) {
  183. [FLEXAlert showAlert:@"Empty File" message:@"No data returned from the file." from:self];
  184. return;
  185. }
  186. // Special case keyed archives, json, and plists to get more readable data.
  187. NSString *prettyString = nil;
  188. if ([pathExtension isEqualToString:@"json"]) {
  189. prettyString = [FLEXUtility prettyJSONStringFromData:fileData];
  190. } else {
  191. // Regardless of file extension...
  192. id object = nil;
  193. @try {
  194. // Try to decode an archived object regardless of file extension
  195. object = [NSKeyedUnarchiver unarchiveObjectWithData:fileData];
  196. } @catch (NSException *e) { }
  197. // Try to decode other things instead
  198. object = object
  199. ?: [NSPropertyListSerialization propertyListWithData:fileData
  200. options:0
  201. format:NULL
  202. error:NULL]
  203. ?: [NSDictionary dictionaryWithContentsOfFile:fullPath]
  204. ?: [NSArray arrayWithContentsOfFile:fullPath];
  205. if (object) {
  206. drillInViewController = [FLEXObjectExplorerFactory explorerViewControllerForObject:object];
  207. }
  208. }
  209. if (prettyString.length) {
  210. drillInViewController = [[FLEXWebViewController alloc] initWithText:prettyString];
  211. } else if ([FLEXWebViewController supportsPathExtension:pathExtension]) {
  212. drillInViewController = [[FLEXWebViewController alloc] initWithURL:[NSURL fileURLWithPath:fullPath]];
  213. } else if ([FLEXTableListViewController supportsExtension:pathExtension]) {
  214. drillInViewController = [[FLEXTableListViewController alloc] initWithPath:fullPath];
  215. }
  216. else if (!drillInViewController) {
  217. NSString *fileString = [NSString stringWithUTF8String:fileData.bytes];
  218. if (fileString.length) {
  219. drillInViewController = [[FLEXWebViewController alloc] initWithText:fileString];
  220. }
  221. }
  222. }
  223. if (drillInViewController) {
  224. drillInViewController.title = subpath.lastPathComponent;
  225. [self.navigationController pushViewController:drillInViewController animated:YES];
  226. } else {
  227. // Share the file otherwise
  228. [self openFileController:fullPath];
  229. }
  230. }
  231. - (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath
  232. {
  233. UIMenuItem *rename = [[UIMenuItem alloc] initWithTitle:@"Rename" action:@selector(fileBrowserRename:)];
  234. UIMenuItem *delete = [[UIMenuItem alloc] initWithTitle:@"Delete" action:@selector(fileBrowserDelete:)];
  235. UIMenuItem *copyPath = [[UIMenuItem alloc] initWithTitle:@"Copy Path" action:@selector(fileBrowserCopyPath:)];
  236. UIMenuItem *share = [[UIMenuItem alloc] initWithTitle:@"Share" action:@selector(fileBrowserShare:)];
  237. UIMenuController.sharedMenuController.menuItems = @[rename, delete, copyPath, share];
  238. return YES;
  239. }
  240. - (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender
  241. {
  242. return action == @selector(fileBrowserDelete:)
  243. || action == @selector(fileBrowserRename:)
  244. || action == @selector(fileBrowserCopyPath:)
  245. || action == @selector(fileBrowserShare:);
  246. }
  247. - (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender
  248. {
  249. // Empty, but has to exist for the menu to show
  250. // The table view only calls this method for actions in the UIResponderStandardEditActions informal protocol.
  251. // Since our actions are outside of that protocol, we need to manually handle the action forwarding from the cells.
  252. }
  253. #if FLEX_AT_LEAST_IOS13_SDK
  254. - (UIContextMenuConfiguration *)tableView:(UITableView *)tableView contextMenuConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath point:(CGPoint)point __IOS_AVAILABLE(13.0)
  255. {
  256. __weak typeof(self) weakSelf = self;
  257. return [UIContextMenuConfiguration configurationWithIdentifier:nil
  258. previewProvider:nil
  259. actionProvider:^UIMenu * _Nullable(NSArray<UIMenuElement *> * _Nonnull suggestedActions) {
  260. UITableViewCell * const cell = [tableView cellForRowAtIndexPath:indexPath];
  261. UIAction *rename = [UIAction actionWithTitle:@"Rename"
  262. image:nil
  263. identifier:@"Rename"
  264. handler:^(__kindof UIAction * _Nonnull action) {
  265. [weakSelf fileBrowserRename:cell];
  266. }];
  267. UIAction *delete = [UIAction actionWithTitle:@"Delete"
  268. image:nil
  269. identifier:@"Delete"
  270. handler:^(__kindof UIAction * _Nonnull action) {
  271. [weakSelf fileBrowserDelete:cell];
  272. }];
  273. UIAction *copyPath = [UIAction actionWithTitle:@"Copy Path"
  274. image:nil
  275. identifier:@"Copy Path"
  276. handler:^(__kindof UIAction * _Nonnull action) {
  277. [weakSelf fileBrowserCopyPath:cell];
  278. }];
  279. UIAction *share = [UIAction actionWithTitle:@"Share"
  280. image:nil
  281. identifier:@"Share"
  282. handler:^(__kindof UIAction * _Nonnull action) {
  283. [weakSelf fileBrowserShare:cell];
  284. }];
  285. return [UIMenu menuWithTitle:@"Manage File" image:nil identifier:@"Manage File" options:UIMenuOptionsDisplayInline children:@[rename, delete, copyPath, share]];
  286. }];
  287. }
  288. #endif
  289. - (void)openFileController:(NSString *)fullPath
  290. {
  291. UIDocumentInteractionController *controller = [UIDocumentInteractionController new];
  292. controller.URL = [NSURL fileURLWithPath:fullPath];
  293. [controller presentOptionsMenuFromRect:self.view.bounds inView:self.view animated:YES];
  294. self.documentController = controller;
  295. }
  296. - (void)fileBrowserRename:(UITableViewCell *)sender
  297. {
  298. NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
  299. NSString *fullPath = [self filePathAtIndexPath:indexPath];
  300. BOOL stillExists = [NSFileManager.defaultManager fileExistsAtPath:self.path isDirectory:NULL];
  301. if (stillExists) {
  302. [FLEXAlert makeAlert:^(FLEXAlert *make) {
  303. make.title([NSString stringWithFormat:@"Rename %@?", fullPath.lastPathComponent]);
  304. make.configuredTextField(^(UITextField *textField) {
  305. textField.placeholder = @"New file name";
  306. textField.text = fullPath.lastPathComponent;
  307. });
  308. make.button(@"Rename").handler(^(NSArray<NSString *> *strings) {
  309. NSString *newFileName = strings.firstObject;
  310. NSString *newPath = [fullPath.stringByDeletingLastPathComponent stringByAppendingPathComponent:newFileName];
  311. [NSFileManager.defaultManager moveItemAtPath:fullPath toPath:newPath error:NULL];
  312. [self reloadDisplayedPaths];
  313. });
  314. make.button(@"Cancel").cancelStyle();
  315. } showFrom:self];
  316. } else {
  317. [FLEXAlert showAlert:@"File Removed" message:@"The file at the specified path no longer exists." from:self];
  318. }
  319. }
  320. - (void)fileBrowserDelete:(UITableViewCell *)sender
  321. {
  322. NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
  323. NSString *fullPath = [self filePathAtIndexPath:indexPath];
  324. BOOL isDirectory = NO;
  325. BOOL stillExists = [NSFileManager.defaultManager fileExistsAtPath:fullPath isDirectory:&isDirectory];
  326. if (stillExists) {
  327. [FLEXAlert makeAlert:^(FLEXAlert *make) {
  328. make.title(@"Confirm Deletion");
  329. make.message([NSString stringWithFormat:
  330. @"The %@ '%@' will be deleted. This operation cannot be undone",
  331. (isDirectory ? @"directory" : @"file"), fullPath.lastPathComponent
  332. ]);
  333. make.button(@"Delete").destructiveStyle().handler(^(NSArray<NSString *> *strings) {
  334. [NSFileManager.defaultManager removeItemAtPath:fullPath error:NULL];
  335. [self reloadDisplayedPaths];
  336. });
  337. make.button(@"Cancel").cancelStyle();
  338. } showFrom:self];
  339. } else {
  340. [FLEXAlert showAlert:@"File Removed" message:@"The file at the specified path no longer exists." from:self];
  341. }
  342. }
  343. - (void)fileBrowserCopyPath:(UITableViewCell *)sender
  344. {
  345. NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
  346. NSString *fullPath = [self filePathAtIndexPath:indexPath];
  347. UIPasteboard.generalPasteboard.string = fullPath;
  348. }
  349. - (void)fileBrowserShare:(UITableViewCell *)sender
  350. {
  351. NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
  352. NSString *pathString = [self filePathAtIndexPath:indexPath];
  353. NSURL *filePath = [NSURL fileURLWithPath:pathString];
  354. BOOL isDirectory = NO;
  355. [NSFileManager.defaultManager fileExistsAtPath:pathString isDirectory:&isDirectory];
  356. if (isDirectory) {
  357. // UIDocumentInteractionController for folders
  358. [self openFileController:pathString];
  359. } else {
  360. // Share sheet for files
  361. UIActivityViewController *shareSheet = [[UIActivityViewController alloc] initWithActivityItems:@[filePath] applicationActivities:nil];
  362. [self presentViewController:shareSheet animated:true completion:nil];
  363. }
  364. }
  365. - (void)reloadDisplayedPaths
  366. {
  367. if (self.searchController.isActive) {
  368. [self updateSearchPaths];
  369. } else {
  370. [self reloadCurrentPath];
  371. [self.tableView reloadData];
  372. }
  373. }
  374. - (void)reloadCurrentPath
  375. {
  376. NSMutableArray<NSString *> *childPaths = [NSMutableArray array];
  377. NSArray<NSString *> *subpaths = [NSFileManager.defaultManager contentsOfDirectoryAtPath:self.path error:NULL];
  378. for (NSString *subpath in subpaths) {
  379. [childPaths addObject:[self.path stringByAppendingPathComponent:subpath]];
  380. }
  381. self.childPaths = childPaths;
  382. }
  383. - (void)updateSearchPaths
  384. {
  385. self.searchPaths = nil;
  386. self.searchPathsSize = nil;
  387. //clear pre search request and start a new one
  388. [self.operationQueue cancelAllOperations];
  389. FLEXFileBrowserSearchOperation *newOperation = [[FLEXFileBrowserSearchOperation alloc] initWithPath:self.path searchString:self.searchText];
  390. newOperation.delegate = self;
  391. [self.operationQueue addOperation:newOperation];
  392. }
  393. - (NSString *)filePathAtIndexPath:(NSIndexPath *)indexPath
  394. {
  395. return self.searchController.isActive ? self.searchPaths[indexPath.row] : self.childPaths[indexPath.row];
  396. }
  397. @end
  398. @implementation FLEXFileBrowserTableViewCell
  399. - (void)forwardAction:(SEL)action withSender:(id)sender
  400. {
  401. id target = [self.nextResponder targetForAction:action withSender:sender];
  402. [UIApplication.sharedApplication sendAction:action to:target from:self forEvent:nil];
  403. }
  404. - (void)fileBrowserRename:(UIMenuController *)sender
  405. {
  406. [self forwardAction:_cmd withSender:sender];
  407. }
  408. - (void)fileBrowserDelete:(UIMenuController *)sender
  409. {
  410. [self forwardAction:_cmd withSender:sender];
  411. }
  412. - (void)fileBrowserCopyPath:(UIMenuController *)sender
  413. {
  414. [self forwardAction:_cmd withSender:sender];
  415. }
  416. - (void)fileBrowserShare:(UIMenuController *)sender
  417. {
  418. [self forwardAction:_cmd withSender:sender];
  419. }
  420. @end