FLEXFileBrowserTableViewController.m 16 KB

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