FLEXFileBrowserTableViewController.m 15 KB

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