FLEXFileBrowserTableViewController.m 16 KB

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