FLEXFileBrowserTableViewController.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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. @interface FLEXFileBrowserTableViewCell : UITableViewCell
  15. @end
  16. @interface FLEXFileBrowserTableViewController () <FLEXFileBrowserFileOperationControllerDelegate, FLEXFileBrowserSearchOperationDelegate, UISearchResultsUpdating, UISearchControllerDelegate>
  17. @property (nonatomic, copy) NSString *path;
  18. @property (nonatomic, copy) NSArray<NSString *> *childPaths;
  19. @property (nonatomic, strong) NSArray<NSString *> *searchPaths;
  20. @property (nonatomic, strong) NSNumber *recursiveSize;
  21. @property (nonatomic, strong) NSNumber *searchPathsSize;
  22. @property (nonatomic, strong) UISearchController *searchController;
  23. @property (nonatomic) NSOperationQueue *operationQueue;
  24. @property (nonatomic, strong) UIDocumentInteractionController *documentController;
  25. @property (nonatomic, strong) id<FLEXFileBrowserFileOperationController> fileOperationController;
  26. @end
  27. @implementation FLEXFileBrowserTableViewController
  28. - (id)initWithStyle:(UITableViewStyle)style
  29. {
  30. return [self initWithPath:NSHomeDirectory()];
  31. }
  32. - (id)initWithPath:(NSString *)path
  33. {
  34. self = [super initWithStyle:UITableViewStyleGrouped];
  35. if (self) {
  36. self.path = path;
  37. self.title = [path lastPathComponent];
  38. self.operationQueue = [NSOperationQueue new];
  39. self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  40. self.searchController.searchResultsUpdater = self;
  41. self.searchController.delegate = self;
  42. self.searchController.dimsBackgroundDuringPresentation = NO;
  43. self.tableView.tableHeaderView = self.searchController.searchBar;
  44. //computing path size
  45. FLEXFileBrowserTableViewController *__weak weakSelf = self;
  46. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  47. NSFileManager *fileManager = [NSFileManager defaultManager];
  48. NSDictionary<NSString *, id> *attributes = [fileManager attributesOfItemAtPath:path error:NULL];
  49. uint64_t totalSize = [attributes fileSize];
  50. for (NSString *fileName in [fileManager enumeratorAtPath:path]) {
  51. attributes = [fileManager attributesOfItemAtPath:[path stringByAppendingPathComponent:fileName] error:NULL];
  52. totalSize += [attributes fileSize];
  53. // Bail if the interested view controller has gone away.
  54. if (!weakSelf) {
  55. return;
  56. }
  57. }
  58. dispatch_async(dispatch_get_main_queue(), ^{
  59. FLEXFileBrowserTableViewController *__strong strongSelf = weakSelf;
  60. strongSelf.recursiveSize = @(totalSize);
  61. [strongSelf.tableView reloadData];
  62. });
  63. });
  64. [self reloadChildPaths];
  65. }
  66. return self;
  67. }
  68. #pragma mark - UIViewController
  69. - (void)viewDidLoad
  70. {
  71. [super viewDidLoad];
  72. }
  73. #pragma mark - Misc
  74. - (void)alert:(NSString *)title message:(NSString *)message {
  75. [[[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
  76. }
  77. #pragma mark - FLEXFileBrowserSearchOperationDelegate
  78. - (void)fileBrowserSearchOperationResult:(NSArray<NSString *> *)searchResult size:(uint64_t)size
  79. {
  80. self.searchPaths = searchResult;
  81. self.searchPathsSize = @(size);
  82. [self.tableView reloadData];
  83. }
  84. #pragma mark - UISearchResultsUpdating
  85. - (void)updateSearchResultsForSearchController:(UISearchController *)searchController
  86. {
  87. [self reloadDisplayedPaths];
  88. }
  89. #pragma mark - UISearchControllerDelegate
  90. - (void)willDismissSearchController:(UISearchController *)searchController
  91. {
  92. [self.operationQueue cancelAllOperations];
  93. [self reloadChildPaths];
  94. [self.tableView reloadData];
  95. }
  96. #pragma mark - Table view data source
  97. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  98. {
  99. return 1;
  100. }
  101. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  102. {
  103. return self.searchController.isActive ? [self.searchPaths count] : [self.childPaths count];
  104. }
  105. - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
  106. {
  107. BOOL isSearchActive = self.searchController.isActive;
  108. NSNumber *currentSize = isSearchActive ? self.searchPathsSize : self.recursiveSize;
  109. NSArray<NSString *> *currentPaths = isSearchActive ? self.searchPaths : self.childPaths;
  110. NSString *sizeString = nil;
  111. if (!currentSize) {
  112. sizeString = @"Computing size…";
  113. } else {
  114. sizeString = [NSByteCountFormatter stringFromByteCount:[currentSize longLongValue] countStyle:NSByteCountFormatterCountStyleFile];
  115. }
  116. return [NSString stringWithFormat:@"%lu files (%@)", (unsigned long)[currentPaths count], sizeString];
  117. }
  118. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  119. {
  120. NSString *fullPath = [self filePathAtIndexPath:indexPath];
  121. NSDictionary<NSString *, id> *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:fullPath error:NULL];
  122. BOOL isDirectory = [[attributes fileType] isEqual:NSFileTypeDirectory];
  123. NSString *subtitle = nil;
  124. if (isDirectory) {
  125. NSUInteger count = [[[NSFileManager defaultManager] contentsOfDirectoryAtPath:fullPath error:NULL] count];
  126. subtitle = [NSString stringWithFormat:@"%lu file%@", (unsigned long)count, (count == 1 ? @"" : @"s")];
  127. } else {
  128. NSString *sizeString = [NSByteCountFormatter stringFromByteCount:[attributes fileSize] countStyle:NSByteCountFormatterCountStyleFile];
  129. subtitle = [NSString stringWithFormat:@"%@ - %@", sizeString, [attributes fileModificationDate]];
  130. }
  131. static NSString *textCellIdentifier = @"textCell";
  132. static NSString *imageCellIdentifier = @"imageCell";
  133. UITableViewCell *cell = nil;
  134. // Separate image and text only cells because otherwise the separator lines get out-of-whack on image cells reused with text only.
  135. BOOL showImagePreview = [FLEXUtility isImagePathExtension:[fullPath pathExtension]];
  136. NSString *cellIdentifier = showImagePreview ? imageCellIdentifier : textCellIdentifier;
  137. if (!cell) {
  138. cell = [[FLEXFileBrowserTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
  139. cell.textLabel.font = [FLEXUtility defaultTableViewCellLabelFont];
  140. cell.detailTextLabel.font = [FLEXUtility defaultTableViewCellLabelFont];
  141. cell.detailTextLabel.textColor = [UIColor grayColor];
  142. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  143. }
  144. NSString *cellTitle = [fullPath lastPathComponent];
  145. cell.textLabel.text = cellTitle;
  146. cell.detailTextLabel.text = subtitle;
  147. if (showImagePreview) {
  148. cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
  149. cell.imageView.image = [UIImage imageWithContentsOfFile:fullPath];
  150. }
  151. return cell;
  152. }
  153. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  154. {
  155. [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
  156. NSString *fullPath = [self filePathAtIndexPath:indexPath];
  157. NSString *subpath = fullPath.lastPathComponent;
  158. NSString *pathExtension = subpath.pathExtension;
  159. BOOL isDirectory = NO;
  160. BOOL stillExists = [[NSFileManager defaultManager] fileExistsAtPath:fullPath isDirectory:&isDirectory];
  161. if (!stillExists) {
  162. [self alert:@"File Not Found" message:@"The file at the specified path no longer exists."];
  163. [self reloadDisplayedPaths];
  164. return;
  165. }
  166. UIViewController *drillInViewController = nil;
  167. if (isDirectory) {
  168. drillInViewController = [[[self class] alloc] initWithPath:fullPath];
  169. } else if ([FLEXUtility isImagePathExtension:pathExtension]) {
  170. UIImage *image = [UIImage imageWithContentsOfFile:fullPath];
  171. drillInViewController = [[FLEXImagePreviewViewController alloc] initWithImage:image];
  172. } else {
  173. NSData *fileData = [NSData dataWithContentsOfFile:fullPath];
  174. if (!fileData.length) {
  175. [self alert:@"Empty File" message:@"No data returned from the file."];
  176. return;
  177. }
  178. // Special case keyed archives, json, and plists to get more readable data.
  179. NSString *prettyString = nil;
  180. if ([pathExtension isEqual:@"archive"] || [pathExtension isEqual:@"coded"]) {
  181. prettyString = [[NSKeyedUnarchiver unarchiveObjectWithData:fileData] description];
  182. } else if ([pathExtension isEqualToString:@"json"]) {
  183. prettyString = [FLEXUtility prettyJSONStringFromData:fileData];
  184. } else if ([pathExtension isEqualToString:@"plist"]) {
  185. prettyString = [[NSPropertyListSerialization propertyListWithData:fileData options:0 format:NULL error:NULL] description];
  186. }
  187. if (prettyString.length) {
  188. drillInViewController = [[FLEXWebViewController alloc] initWithText:prettyString];
  189. } else if ([FLEXWebViewController supportsPathExtension:pathExtension]) {
  190. drillInViewController = [[FLEXWebViewController alloc] initWithURL:[NSURL fileURLWithPath:fullPath]];
  191. } else if ([FLEXTableListViewController supportsExtension:pathExtension]) {
  192. drillInViewController = [[FLEXTableListViewController alloc] initWithPath:fullPath];
  193. }
  194. else {
  195. NSString *fileString = [NSString stringWithUTF8String:fileData.bytes];
  196. if (fileString.length) {
  197. drillInViewController = [[FLEXWebViewController alloc] initWithText:fileString];
  198. }
  199. }
  200. }
  201. if (drillInViewController) {
  202. drillInViewController.title = subpath.lastPathComponent;
  203. [self.navigationController pushViewController:drillInViewController animated:YES];
  204. } else {
  205. // Share the file otherwise
  206. [self openFileController:fullPath];
  207. }
  208. }
  209. - (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath
  210. {
  211. UIMenuItem *renameMenuItem = [[UIMenuItem alloc] initWithTitle:@"Rename" action:@selector(fileBrowserRename:)];
  212. UIMenuItem *deleteMenuItem = [[UIMenuItem alloc] initWithTitle:@"Delete" action:@selector(fileBrowserDelete:)];
  213. NSMutableArray *menus = [NSMutableArray arrayWithObjects:renameMenuItem, deleteMenuItem, nil];
  214. NSString *fullPath = [self filePathAtIndexPath:indexPath];
  215. NSError *error = nil;
  216. NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:fullPath error:&error];
  217. if (error == nil && [attributes fileType] != NSFileTypeDirectory) {
  218. UIMenuItem *shareMenuItem = [[UIMenuItem alloc] initWithTitle:@"Share" action:@selector(fileBrowserShare:)];
  219. [menus addObject:shareMenuItem];
  220. }
  221. [UIMenuController sharedMenuController].menuItems = menus;
  222. return YES;
  223. }
  224. - (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender
  225. {
  226. return action == @selector(fileBrowserDelete:) || action == @selector(fileBrowserRename:) || action == @selector(fileBrowserShare:);
  227. }
  228. - (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender
  229. {
  230. // Empty, but has to exist for the menu to show
  231. // The table view only calls this method for actions in the UIResponderStandardEditActions informal protocol.
  232. // Since our actions are outside of that protocol, we need to manually handle the action forwarding from the cells.
  233. }
  234. #pragma mark - FLEXFileBrowserFileOperationControllerDelegate
  235. - (void)fileOperationControllerDidDismiss:(id<FLEXFileBrowserFileOperationController>)controller
  236. {
  237. [self reloadDisplayedPaths];
  238. }
  239. - (void)openFileController:(NSString *)fullPath
  240. {
  241. UIDocumentInteractionController *controller = [UIDocumentInteractionController new];
  242. controller.URL = [[NSURL alloc] initFileURLWithPath:fullPath];
  243. [controller presentOptionsMenuFromRect:self.view.bounds inView:self.view animated:YES];
  244. self.documentController = controller;
  245. }
  246. - (void)fileBrowserRename:(UITableViewCell *)sender
  247. {
  248. NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
  249. NSString *fullPath = [self filePathAtIndexPath:indexPath];
  250. self.fileOperationController = [[FLEXFileBrowserFileRenameOperationController alloc] initWithPath:fullPath];
  251. self.fileOperationController.delegate = self;
  252. [self.fileOperationController show];
  253. }
  254. - (void)fileBrowserDelete:(UITableViewCell *)sender
  255. {
  256. NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
  257. NSString *fullPath = [self filePathAtIndexPath:indexPath];
  258. self.fileOperationController = [[FLEXFileBrowserFileDeleteOperationController alloc] initWithPath:fullPath];
  259. self.fileOperationController.delegate = self;
  260. [self.fileOperationController show];
  261. }
  262. - (void)fileBrowserShare:(UITableViewCell *)sender
  263. {
  264. NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
  265. NSString *fullPath = [self filePathAtIndexPath:indexPath];
  266. UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:@[fullPath] applicationActivities:nil];
  267. [self presentViewController:activityViewController animated:true completion:nil];
  268. }
  269. - (void)reloadDisplayedPaths
  270. {
  271. if (self.searchController.isActive) {
  272. [self reloadSearchPaths];
  273. } else {
  274. [self reloadChildPaths];
  275. }
  276. [self.tableView reloadData];
  277. }
  278. - (void)reloadChildPaths
  279. {
  280. NSMutableArray<NSString *> *childPaths = [NSMutableArray array];
  281. NSArray<NSString *> *subpaths = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:self.path error:NULL];
  282. for (NSString *subpath in subpaths) {
  283. [childPaths addObject:[self.path stringByAppendingPathComponent:subpath]];
  284. }
  285. self.childPaths = childPaths;
  286. }
  287. - (void)reloadSearchPaths
  288. {
  289. self.searchPaths = nil;
  290. self.searchPathsSize = nil;
  291. //clear pre search request and start a new one
  292. [self.operationQueue cancelAllOperations];
  293. FLEXFileBrowserSearchOperation *newOperation = [[FLEXFileBrowserSearchOperation alloc] initWithPath:self.path searchString:self.searchController.searchBar.text];
  294. newOperation.delegate = self;
  295. [self.operationQueue addOperation:newOperation];
  296. }
  297. - (NSString *)filePathAtIndexPath:(NSIndexPath *)indexPath
  298. {
  299. return self.searchController.isActive ? self.searchPaths[indexPath.row] : self.childPaths[indexPath.row];
  300. }
  301. @end
  302. @implementation FLEXFileBrowserTableViewCell
  303. - (void)fileBrowserRename:(UIMenuController *)sender
  304. {
  305. id target = [self.nextResponder targetForAction:_cmd withSender:sender];
  306. [[UIApplication sharedApplication] sendAction:_cmd to:target from:self forEvent:nil];
  307. }
  308. - (void)fileBrowserDelete:(UIMenuController *)sender
  309. {
  310. id target = [self.nextResponder targetForAction:_cmd withSender:sender];
  311. [[UIApplication sharedApplication] sendAction:_cmd to:target from:self forEvent:nil];
  312. }
  313. - (void)fileBrowserShare:(UIMenuController *)sender
  314. {
  315. id target = [self.nextResponder targetForAction:_cmd withSender:sender];
  316. [[UIApplication sharedApplication] sendAction:_cmd to:target from:self forEvent:nil];
  317. }
  318. @end