FLEXFileBrowserTableViewController.m 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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. // Regardless of file extension...
  183. id object = nil;
  184. @try {
  185. // Try to decode an archived object regardless of file extension
  186. object = [NSKeyedUnarchiver unarchiveObjectWithData:fileData];
  187. } @catch (NSException *e) { }
  188. // Try to decode other things instead
  189. object = object
  190. ?: [NSPropertyListSerialization propertyListWithData:fileData
  191. options:0
  192. format:NULL
  193. error:NULL]
  194. ?: [NSDictionary dictionaryWithContentsOfFile:fullPath]
  195. ?: [NSArray arrayWithContentsOfFile:fullPath];
  196. if (object) {
  197. drillInViewController = [FLEXObjectExplorerFactory explorerViewControllerForObject:object];
  198. }
  199. }
  200. if (prettyString.length) {
  201. drillInViewController = [[FLEXWebViewController alloc] initWithText:prettyString];
  202. } else if ([FLEXWebViewController supportsPathExtension:pathExtension]) {
  203. drillInViewController = [[FLEXWebViewController alloc] initWithURL:[NSURL fileURLWithPath:fullPath]];
  204. } else if ([FLEXTableListViewController supportsExtension:pathExtension]) {
  205. drillInViewController = [[FLEXTableListViewController alloc] initWithPath:fullPath];
  206. }
  207. else if (!drillInViewController) {
  208. NSString *fileString = [NSString stringWithUTF8String:fileData.bytes];
  209. if (fileString.length) {
  210. drillInViewController = [[FLEXWebViewController alloc] initWithText:fileString];
  211. }
  212. }
  213. }
  214. if (drillInViewController) {
  215. drillInViewController.title = subpath.lastPathComponent;
  216. [self.navigationController pushViewController:drillInViewController animated:YES];
  217. } else {
  218. // Share the file otherwise
  219. [self openFileController:fullPath];
  220. }
  221. }
  222. - (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath
  223. {
  224. UIMenuItem *rename = [[UIMenuItem alloc] initWithTitle:@"Rename" action:@selector(fileBrowserRename:)];
  225. UIMenuItem *delete = [[UIMenuItem alloc] initWithTitle:@"Delete" action:@selector(fileBrowserDelete:)];
  226. UIMenuItem *copyPath = [[UIMenuItem alloc] initWithTitle:@"Copy Path" action:@selector(fileBrowserCopyPath:)];
  227. UIMenuItem *share = [[UIMenuItem alloc] initWithTitle:@"Share" action:@selector(fileBrowserShare:)];
  228. [UIMenuController sharedMenuController].menuItems = @[rename, delete, copyPath, share];
  229. return YES;
  230. }
  231. - (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender
  232. {
  233. return action == @selector(fileBrowserDelete:)
  234. || action == @selector(fileBrowserRename:)
  235. || action == @selector(fileBrowserCopyPath:)
  236. || action == @selector(fileBrowserShare:);
  237. }
  238. - (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender
  239. {
  240. // Empty, but has to exist for the menu to show
  241. // The table view only calls this method for actions in the UIResponderStandardEditActions informal protocol.
  242. // Since our actions are outside of that protocol, we need to manually handle the action forwarding from the cells.
  243. }
  244. #pragma mark - FLEXFileBrowserFileOperationControllerDelegate
  245. - (void)fileOperationControllerDidDismiss:(id<FLEXFileBrowserFileOperationController>)controller
  246. {
  247. [self reloadDisplayedPaths];
  248. }
  249. - (void)openFileController:(NSString *)fullPath
  250. {
  251. UIDocumentInteractionController *controller = [UIDocumentInteractionController new];
  252. controller.URL = [NSURL fileURLWithPath:fullPath];
  253. [controller presentOptionsMenuFromRect:self.view.bounds inView:self.view animated:YES];
  254. self.documentController = controller;
  255. }
  256. - (void)fileBrowserRename:(UITableViewCell *)sender
  257. {
  258. NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
  259. NSString *fullPath = [self filePathAtIndexPath:indexPath];
  260. self.fileOperationController = [[FLEXFileBrowserFileRenameOperationController alloc] initWithPath:fullPath];
  261. self.fileOperationController.delegate = self;
  262. [self.fileOperationController show];
  263. }
  264. - (void)fileBrowserDelete:(UITableViewCell *)sender
  265. {
  266. NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
  267. NSString *fullPath = [self filePathAtIndexPath:indexPath];
  268. self.fileOperationController = [[FLEXFileBrowserFileDeleteOperationController alloc] initWithPath:fullPath];
  269. self.fileOperationController.delegate = self;
  270. [self.fileOperationController show];
  271. }
  272. - (void)fileBrowserCopyPath:(UITableViewCell *)sender
  273. {
  274. NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
  275. NSString *fullPath = [self filePathAtIndexPath:indexPath];
  276. [UIPasteboard generalPasteboard].string = fullPath;
  277. }
  278. - (void)fileBrowserShare:(UITableViewCell *)sender
  279. {
  280. NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
  281. NSString *pathString = [self filePathAtIndexPath:indexPath];
  282. NSURL *filePath = [NSURL fileURLWithPath:pathString];
  283. BOOL isDirectory = NO;
  284. [[NSFileManager defaultManager] fileExistsAtPath:pathString isDirectory:&isDirectory];
  285. if (isDirectory) {
  286. // UIDocumentInteractionController for folders
  287. [self openFileController:pathString];
  288. } else {
  289. // Share sheet for files
  290. UIActivityViewController *shareSheet = [[UIActivityViewController alloc] initWithActivityItems:@[filePath] applicationActivities:nil];
  291. [self presentViewController:shareSheet animated:true completion:nil];
  292. }
  293. }
  294. - (void)reloadDisplayedPaths
  295. {
  296. if (self.searchController.isActive) {
  297. [self updateSearchPaths];
  298. } else {
  299. [self reloadCurrentPath];
  300. [self.tableView reloadData];
  301. }
  302. }
  303. - (void)reloadCurrentPath
  304. {
  305. NSMutableArray<NSString *> *childPaths = [NSMutableArray array];
  306. NSArray<NSString *> *subpaths = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:self.path error:NULL];
  307. for (NSString *subpath in subpaths) {
  308. [childPaths addObject:[self.path stringByAppendingPathComponent:subpath]];
  309. }
  310. self.childPaths = childPaths;
  311. }
  312. - (void)updateSearchPaths
  313. {
  314. self.searchPaths = nil;
  315. self.searchPathsSize = nil;
  316. //clear pre search request and start a new one
  317. [self.operationQueue cancelAllOperations];
  318. FLEXFileBrowserSearchOperation *newOperation = [[FLEXFileBrowserSearchOperation alloc] initWithPath:self.path searchString:self.searchText];
  319. newOperation.delegate = self;
  320. [self.operationQueue addOperation:newOperation];
  321. }
  322. - (NSString *)filePathAtIndexPath:(NSIndexPath *)indexPath
  323. {
  324. return self.searchController.isActive ? self.searchPaths[indexPath.row] : self.childPaths[indexPath.row];
  325. }
  326. @end
  327. @implementation FLEXFileBrowserTableViewCell
  328. - (void)forwardAction:(SEL)action withSender:(id)sender
  329. {
  330. id target = [self.nextResponder targetForAction:action withSender:sender];
  331. [[UIApplication sharedApplication] sendAction:action to:target from:self forEvent:nil];
  332. }
  333. - (void)fileBrowserRename:(UIMenuController *)sender
  334. {
  335. [self forwardAction:_cmd withSender:sender];
  336. }
  337. - (void)fileBrowserDelete:(UIMenuController *)sender
  338. {
  339. [self forwardAction:_cmd withSender:sender];
  340. }
  341. - (void)fileBrowserCopyPath:(UIMenuController *)sender
  342. {
  343. [self forwardAction:_cmd withSender:sender];
  344. }
  345. - (void)fileBrowserShare:(UIMenuController *)sender
  346. {
  347. [self forwardAction:_cmd withSender:sender];
  348. }
  349. @end