FLEXFileBrowserTableViewController.m 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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. [FLEXUtility alert:@"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. [FLEXUtility alert:@"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. - (void)openFileController:(NSString *)fullPath
  254. {
  255. UIDocumentInteractionController *controller = [UIDocumentInteractionController new];
  256. controller.URL = [NSURL fileURLWithPath:fullPath];
  257. [controller presentOptionsMenuFromRect:self.view.bounds inView:self.view animated:YES];
  258. self.documentController = controller;
  259. }
  260. - (void)fileBrowserRename:(UITableViewCell *)sender
  261. {
  262. NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
  263. NSString *fullPath = [self filePathAtIndexPath:indexPath];
  264. BOOL stillExists = [NSFileManager.defaultManager fileExistsAtPath:self.path isDirectory:NULL];
  265. if (stillExists) {
  266. UIAlertController *alert = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"Rename %@?", fullPath.lastPathComponent]
  267. message:nil
  268. preferredStyle:UIAlertControllerStyleAlert];
  269. [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
  270. textField.placeholder = @"New file name";
  271. textField.text = fullPath.lastPathComponent;
  272. }];
  273. __weak typeof(alert) weakAlert = alert;
  274. [alert addAction:[UIAlertAction actionWithTitle:@"Rename" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  275. NSString *newFileName = weakAlert.textFields.firstObject.text;
  276. NSString *newPath = [[fullPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:newFileName];
  277. [NSFileManager.defaultManager moveItemAtPath:fullPath toPath:newPath error:NULL];
  278. [self reloadDisplayedPaths];
  279. }]];
  280. [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]];
  281. [self presentViewController:alert animated:YES completion:nil];
  282. } else {
  283. [FLEXUtility alert:@"File Removed" message:@"The file at the specified path no longer exists." from:self];
  284. }
  285. }
  286. - (void)fileBrowserDelete:(UITableViewCell *)sender
  287. {
  288. NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
  289. NSString *fullPath = [self filePathAtIndexPath:indexPath];
  290. BOOL isDirectory = NO;
  291. BOOL stillExists = [NSFileManager.defaultManager fileExistsAtPath:fullPath isDirectory:&isDirectory];
  292. if (stillExists) {
  293. UIAlertController *alert = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"Delete %@?", fullPath.lastPathComponent]
  294. message:[NSString stringWithFormat:@"The %@ will be deleted. This operation cannot be undone", isDirectory ? @"directory" : @"file"]
  295. preferredStyle:UIAlertControllerStyleAlert];
  296. [alert addAction:[UIAlertAction actionWithTitle:@"Delete" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
  297. [NSFileManager.defaultManager removeItemAtPath:fullPath error:NULL];
  298. [self reloadDisplayedPaths];
  299. }]];
  300. [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]];
  301. [self presentViewController:alert animated:YES completion:nil];
  302. } else {
  303. [FLEXUtility alert:@"File Removed" message:@"The file at the specified path no longer exists." from:self];
  304. }
  305. }
  306. - (void)fileBrowserCopyPath:(UITableViewCell *)sender
  307. {
  308. NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
  309. NSString *fullPath = [self filePathAtIndexPath:indexPath];
  310. UIPasteboard.generalPasteboard.string = fullPath;
  311. }
  312. - (void)fileBrowserShare:(UITableViewCell *)sender
  313. {
  314. NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
  315. NSString *pathString = [self filePathAtIndexPath:indexPath];
  316. NSURL *filePath = [NSURL fileURLWithPath:pathString];
  317. BOOL isDirectory = NO;
  318. [NSFileManager.defaultManager fileExistsAtPath:pathString isDirectory:&isDirectory];
  319. if (isDirectory) {
  320. // UIDocumentInteractionController for folders
  321. [self openFileController:pathString];
  322. } else {
  323. // Share sheet for files
  324. UIActivityViewController *shareSheet = [[UIActivityViewController alloc] initWithActivityItems:@[filePath] applicationActivities:nil];
  325. [self presentViewController:shareSheet animated:true completion:nil];
  326. }
  327. }
  328. - (void)reloadDisplayedPaths
  329. {
  330. if (self.searchController.isActive) {
  331. [self updateSearchPaths];
  332. } else {
  333. [self reloadCurrentPath];
  334. [self.tableView reloadData];
  335. }
  336. }
  337. - (void)reloadCurrentPath
  338. {
  339. NSMutableArray<NSString *> *childPaths = [NSMutableArray array];
  340. NSArray<NSString *> *subpaths = [NSFileManager.defaultManager contentsOfDirectoryAtPath:self.path error:NULL];
  341. for (NSString *subpath in subpaths) {
  342. [childPaths addObject:[self.path stringByAppendingPathComponent:subpath]];
  343. }
  344. self.childPaths = childPaths;
  345. }
  346. - (void)updateSearchPaths
  347. {
  348. self.searchPaths = nil;
  349. self.searchPathsSize = nil;
  350. //clear pre search request and start a new one
  351. [self.operationQueue cancelAllOperations];
  352. FLEXFileBrowserSearchOperation *newOperation = [[FLEXFileBrowserSearchOperation alloc] initWithPath:self.path searchString:self.searchText];
  353. newOperation.delegate = self;
  354. [self.operationQueue addOperation:newOperation];
  355. }
  356. - (NSString *)filePathAtIndexPath:(NSIndexPath *)indexPath
  357. {
  358. return self.searchController.isActive ? self.searchPaths[indexPath.row] : self.childPaths[indexPath.row];
  359. }
  360. @end
  361. @implementation FLEXFileBrowserTableViewCell
  362. - (void)forwardAction:(SEL)action withSender:(id)sender
  363. {
  364. id target = [self.nextResponder targetForAction:action withSender:sender];
  365. [UIApplication.sharedApplication sendAction:action to:target from:self forEvent:nil];
  366. }
  367. - (void)fileBrowserRename:(UIMenuController *)sender
  368. {
  369. [self forwardAction:_cmd withSender:sender];
  370. }
  371. - (void)fileBrowserDelete:(UIMenuController *)sender
  372. {
  373. [self forwardAction:_cmd withSender:sender];
  374. }
  375. - (void)fileBrowserCopyPath:(UIMenuController *)sender
  376. {
  377. [self forwardAction:_cmd withSender:sender];
  378. }
  379. - (void)fileBrowserShare:(UIMenuController *)sender
  380. {
  381. [self forwardAction:_cmd withSender:sender];
  382. }
  383. @end