FLEXFileBrowserTableViewController.m 15 KB

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