FLEXFileBrowserTableViewController.m 15 KB

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