FLEXFileBrowserTableViewController.m 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. //
  2. // FLEXFileBrowserTableViewController.m
  3. // Flipboard
  4. //
  5. // Created by Ryan Olson on 6/9/14.
  6. //
  7. //
  8. #import "FLEXFileBrowserTableViewController.h"
  9. #import "FLEXUtility.h"
  10. #import "FLEXWebViewController.h"
  11. #import "FLEXImagePreviewViewController.h"
  12. #import "FLEXTableListViewController.h"
  13. #import "FLEXObjectExplorerFactory.h"
  14. #import "FLEXObjectExplorerViewController.h"
  15. @interface FLEXFileBrowserTableViewCell : UITableViewCell
  16. @end
  17. @interface FLEXFileBrowserTableViewController () <FLEXFileBrowserSearchOperationDelegate>
  18. @property (nonatomic, copy) NSString *path;
  19. @property (nonatomic, copy) NSArray<NSString *> *childPaths;
  20. @property (nonatomic) NSArray<NSString *> *searchPaths;
  21. @property (nonatomic) NSNumber *recursiveSize;
  22. @property (nonatomic) NSNumber *searchPathsSize;
  23. @property (nonatomic) NSOperationQueue *operationQueue;
  24. @property (nonatomic) UIDocumentInteractionController *documentController;
  25. @end
  26. @implementation FLEXFileBrowserTableViewController
  27. + (instancetype)path:(NSString *)path {
  28. return [[self alloc] initWithPath:path];
  29. }
  30. - (id)init {
  31. return [self initWithPath:NSHomeDirectory()];
  32. }
  33. - (id)initWithPath:(NSString *)path {
  34. self = [super init];
  35. if (self) {
  36. self.path = path;
  37. self.title = [path lastPathComponent];
  38. self.operationQueue = [NSOperationQueue new];
  39. //computing path size
  40. FLEXFileBrowserTableViewController *__weak weakSelf = self;
  41. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  42. NSFileManager *fileManager = NSFileManager.defaultManager;
  43. NSDictionary<NSString *, id> *attributes = [fileManager attributesOfItemAtPath:path error:NULL];
  44. uint64_t totalSize = [attributes fileSize];
  45. for (NSString *fileName in [fileManager enumeratorAtPath:path]) {
  46. attributes = [fileManager attributesOfItemAtPath:[path stringByAppendingPathComponent:fileName] error:NULL];
  47. totalSize += [attributes fileSize];
  48. // Bail if the interested view controller has gone away.
  49. if (!weakSelf) {
  50. return;
  51. }
  52. }
  53. dispatch_async(dispatch_get_main_queue(), ^{
  54. FLEXFileBrowserTableViewController *__strong strongSelf = weakSelf;
  55. strongSelf.recursiveSize = @(totalSize);
  56. [strongSelf.tableView reloadData];
  57. });
  58. });
  59. [self reloadCurrentPath];
  60. }
  61. return self;
  62. }
  63. #pragma mark - UIViewController
  64. - (void)viewDidLoad {
  65. [super viewDidLoad];
  66. self.showsSearchBar = YES;
  67. self.searchBarDebounceInterval = kFLEXDebounceForAsyncSearch;
  68. }
  69. #pragma mark - FLEXGlobalsEntry
  70. + (NSString *)globalsEntryTitle:(FLEXGlobalsRow)row {
  71. switch (row) {
  72. case FLEXGlobalsRowBrowseBundle: return @"📁 Browse Bundle Directory";
  73. case FLEXGlobalsRowBrowseContainer: return @"📁 Browse Container Directory";
  74. default: return nil;
  75. }
  76. }
  77. + (UIViewController *)globalsEntryViewController:(FLEXGlobalsRow)row {
  78. switch (row) {
  79. case FLEXGlobalsRowBrowseBundle: return [[self alloc] initWithPath:NSBundle.mainBundle.bundlePath];
  80. case FLEXGlobalsRowBrowseContainer: return [[self alloc] initWithPath:NSHomeDirectory()];
  81. default: return [self new];
  82. }
  83. }
  84. #pragma mark - FLEXFileBrowserSearchOperationDelegate
  85. - (void)fileBrowserSearchOperationResult:(NSArray<NSString *> *)searchResult size:(uint64_t)size {
  86. self.searchPaths = searchResult;
  87. self.searchPathsSize = @(size);
  88. [self.tableView reloadData];
  89. }
  90. #pragma mark - Search bar
  91. - (void)updateSearchResults:(NSString *)newText {
  92. [self reloadDisplayedPaths];
  93. }
  94. #pragma mark UISearchControllerDelegate
  95. - (void)willDismissSearchController:(UISearchController *)searchController {
  96. [self.operationQueue cancelAllOperations];
  97. [self reloadCurrentPath];
  98. [self.tableView reloadData];
  99. }
  100. #pragma mark - Table view data source
  101. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  102. return 1;
  103. }
  104. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  105. return self.searchController.isActive ? self.searchPaths.count : self.childPaths.count;
  106. }
  107. - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
  108. BOOL isSearchActive = self.searchController.isActive;
  109. NSNumber *currentSize = isSearchActive ? self.searchPathsSize : self.recursiveSize;
  110. NSArray<NSString *> *currentPaths = isSearchActive ? self.searchPaths : self.childPaths;
  111. NSString *sizeString = nil;
  112. if (!currentSize) {
  113. sizeString = @"Computing size…";
  114. } else {
  115. sizeString = [NSByteCountFormatter stringFromByteCount:[currentSize longLongValue] countStyle:NSByteCountFormatterCountStyleFile];
  116. }
  117. return [NSString stringWithFormat:@"%lu files (%@)", (unsigned long)currentPaths.count, sizeString];
  118. }
  119. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  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 item%@", (unsigned long)count, (count == 1 ? @"" : @"s")];
  127. } else {
  128. NSString *sizeString = [NSByteCountFormatter stringFromByteCount:attributes.fileSize countStyle:NSByteCountFormatterCountStyleFile];
  129. subtitle = [NSString stringWithFormat:@"%@ - %@", sizeString, attributes.fileModificationDate ?: @"Never modified"];
  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. UIImage *image = [UIImage imageWithContentsOfFile:fullPath];
  136. NSString *cellIdentifier = image ? imageCellIdentifier : textCellIdentifier;
  137. if (!cell) {
  138. cell = [[FLEXFileBrowserTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
  139. cell.textLabel.font = UIFont.flex_defaultTableCellFont;
  140. cell.detailTextLabel.font = UIFont.flex_defaultTableCellFont;
  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 (image) {
  148. cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
  149. cell.imageView.image = image;
  150. }
  151. return cell;
  152. }
  153. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  154. [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
  155. NSString *fullPath = [self filePathAtIndexPath:indexPath];
  156. NSString *subpath = fullPath.lastPathComponent;
  157. NSString *pathExtension = subpath.pathExtension;
  158. BOOL isDirectory = NO;
  159. BOOL stillExists = [NSFileManager.defaultManager fileExistsAtPath:fullPath isDirectory:&isDirectory];
  160. UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  161. UIImage *image = cell.imageView.image;
  162. if (!stillExists) {
  163. [FLEXAlert showAlert:@"File Not Found" message:@"The file at the specified path no longer exists." from:self];
  164. [self reloadDisplayedPaths];
  165. return;
  166. }
  167. UIViewController *drillInViewController = nil;
  168. if (isDirectory) {
  169. drillInViewController = [[[self class] alloc] initWithPath:fullPath];
  170. } else if (image) {
  171. drillInViewController = [FLEXImagePreviewViewController forImage:image];
  172. } else {
  173. NSData *fileData = [NSData dataWithContentsOfFile:fullPath];
  174. if (!fileData.length) {
  175. [FLEXAlert showAlert:@"Empty File" message:@"No data returned from the file." from:self];
  176. return;
  177. }
  178. // Special case keyed archives, json, and plists to get more readable data.
  179. NSString *prettyString = nil;
  180. if ([pathExtension isEqualToString:@"json"]) {
  181. prettyString = [FLEXUtility prettyJSONStringFromData:fileData];
  182. } else {
  183. // Regardless of file extension...
  184. id object = nil;
  185. @try {
  186. // Try to decode an archived object regardless of file extension
  187. object = [NSKeyedUnarchiver unarchiveObjectWithData:fileData];
  188. } @catch (NSException *e) { }
  189. // Try to decode other things instead
  190. object = object
  191. ?: [NSPropertyListSerialization propertyListWithData:fileData
  192. options:0
  193. format:NULL
  194. error:NULL]
  195. ?: [NSDictionary dictionaryWithContentsOfFile:fullPath]
  196. ?: [NSArray arrayWithContentsOfFile:fullPath];
  197. if (object) {
  198. drillInViewController = [FLEXObjectExplorerFactory explorerViewControllerForObject:object];
  199. }
  200. }
  201. if (prettyString.length) {
  202. drillInViewController = [[FLEXWebViewController alloc] initWithText:prettyString];
  203. } else if ([FLEXWebViewController supportsPathExtension:pathExtension]) {
  204. drillInViewController = [[FLEXWebViewController alloc] initWithURL:[NSURL fileURLWithPath:fullPath]];
  205. } else if ([FLEXTableListViewController supportsExtension:pathExtension]) {
  206. drillInViewController = [[FLEXTableListViewController alloc] initWithPath:fullPath];
  207. }
  208. else if (!drillInViewController) {
  209. NSString *fileString = [NSString stringWithUTF8String:fileData.bytes];
  210. if (fileString.length) {
  211. drillInViewController = [[FLEXWebViewController alloc] initWithText:fileString];
  212. }
  213. }
  214. }
  215. if (drillInViewController) {
  216. drillInViewController.title = subpath.lastPathComponent;
  217. [self.navigationController pushViewController:drillInViewController animated:YES];
  218. } else {
  219. // Share the file otherwise
  220. [self openFileController:fullPath];
  221. }
  222. }
  223. - (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath {
  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. return action == @selector(fileBrowserDelete:)
  233. || action == @selector(fileBrowserRename:)
  234. || action == @selector(fileBrowserCopyPath:)
  235. || action == @selector(fileBrowserShare:);
  236. }
  237. - (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
  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. #if FLEX_AT_LEAST_IOS13_SDK
  243. - (UIContextMenuConfiguration *)tableView:(UITableView *)tableView contextMenuConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath point:(CGPoint)point __IOS_AVAILABLE(13.0) {
  244. __weak typeof(self) weakSelf = self;
  245. return [UIContextMenuConfiguration configurationWithIdentifier:nil
  246. previewProvider:nil
  247. actionProvider:^UIMenu * _Nullable(NSArray<UIMenuElement *> * _Nonnull suggestedActions) {
  248. UITableViewCell * const cell = [tableView cellForRowAtIndexPath:indexPath];
  249. UIAction *rename = [UIAction actionWithTitle:@"Rename"
  250. image:nil
  251. identifier:@"Rename"
  252. handler:^(__kindof UIAction * _Nonnull action) {
  253. [weakSelf fileBrowserRename:cell];
  254. }];
  255. UIAction *delete = [UIAction actionWithTitle:@"Delete"
  256. image:nil
  257. identifier:@"Delete"
  258. handler:^(__kindof UIAction * _Nonnull action) {
  259. [weakSelf fileBrowserDelete:cell];
  260. }];
  261. UIAction *copyPath = [UIAction actionWithTitle:@"Copy Path"
  262. image:nil
  263. identifier:@"Copy Path"
  264. handler:^(__kindof UIAction * _Nonnull action) {
  265. [weakSelf fileBrowserCopyPath:cell];
  266. }];
  267. UIAction *share = [UIAction actionWithTitle:@"Share"
  268. image:nil
  269. identifier:@"Share"
  270. handler:^(__kindof UIAction * _Nonnull action) {
  271. [weakSelf fileBrowserShare:cell];
  272. }];
  273. return [UIMenu menuWithTitle:@"Manage File" image:nil identifier:@"Manage File" options:UIMenuOptionsDisplayInline children:@[rename, delete, copyPath, share]];
  274. }];
  275. }
  276. #endif
  277. - (void)openFileController:(NSString *)fullPath {
  278. UIDocumentInteractionController *controller = [UIDocumentInteractionController new];
  279. controller.URL = [NSURL fileURLWithPath:fullPath];
  280. [controller presentOptionsMenuFromRect:self.view.bounds inView:self.view animated:YES];
  281. self.documentController = controller;
  282. }
  283. - (void)fileBrowserRename:(UITableViewCell *)sender {
  284. NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
  285. NSString *fullPath = [self filePathAtIndexPath:indexPath];
  286. BOOL stillExists = [NSFileManager.defaultManager fileExistsAtPath:self.path isDirectory:NULL];
  287. if (stillExists) {
  288. [FLEXAlert makeAlert:^(FLEXAlert *make) {
  289. make.title([NSString stringWithFormat:@"Rename %@?", fullPath.lastPathComponent]);
  290. make.configuredTextField(^(UITextField *textField) {
  291. textField.placeholder = @"New file name";
  292. textField.text = fullPath.lastPathComponent;
  293. });
  294. make.button(@"Rename").handler(^(NSArray<NSString *> *strings) {
  295. NSString *newFileName = strings.firstObject;
  296. NSString *newPath = [fullPath.stringByDeletingLastPathComponent stringByAppendingPathComponent:newFileName];
  297. [NSFileManager.defaultManager moveItemAtPath:fullPath toPath:newPath error:NULL];
  298. [self reloadDisplayedPaths];
  299. });
  300. make.button(@"Cancel").cancelStyle();
  301. } showFrom:self];
  302. } else {
  303. [FLEXAlert showAlert:@"File Removed" message:@"The file at the specified path no longer exists." from:self];
  304. }
  305. }
  306. - (void)fileBrowserDelete:(UITableViewCell *)sender {
  307. NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
  308. NSString *fullPath = [self filePathAtIndexPath:indexPath];
  309. BOOL isDirectory = NO;
  310. BOOL stillExists = [NSFileManager.defaultManager fileExistsAtPath:fullPath isDirectory:&isDirectory];
  311. if (stillExists) {
  312. [FLEXAlert makeAlert:^(FLEXAlert *make) {
  313. make.title(@"Confirm Deletion");
  314. make.message([NSString stringWithFormat:
  315. @"The %@ '%@' will be deleted. This operation cannot be undone",
  316. (isDirectory ? @"directory" : @"file"), fullPath.lastPathComponent
  317. ]);
  318. make.button(@"Delete").destructiveStyle().handler(^(NSArray<NSString *> *strings) {
  319. [NSFileManager.defaultManager removeItemAtPath:fullPath error:NULL];
  320. [self reloadDisplayedPaths];
  321. });
  322. make.button(@"Cancel").cancelStyle();
  323. } showFrom:self];
  324. } else {
  325. [FLEXAlert showAlert:@"File Removed" message:@"The file at the specified path no longer exists." from:self];
  326. }
  327. }
  328. - (void)fileBrowserCopyPath:(UITableViewCell *)sender {
  329. NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
  330. NSString *fullPath = [self filePathAtIndexPath:indexPath];
  331. UIPasteboard.generalPasteboard.string = fullPath;
  332. }
  333. - (void)fileBrowserShare:(UITableViewCell *)sender {
  334. NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
  335. NSString *pathString = [self filePathAtIndexPath:indexPath];
  336. NSURL *filePath = [NSURL fileURLWithPath:pathString];
  337. BOOL isDirectory = NO;
  338. [NSFileManager.defaultManager fileExistsAtPath:pathString isDirectory:&isDirectory];
  339. if (isDirectory) {
  340. // UIDocumentInteractionController for folders
  341. [self openFileController:pathString];
  342. } else {
  343. // Share sheet for files
  344. UIActivityViewController *shareSheet = [[UIActivityViewController alloc] initWithActivityItems:@[filePath] applicationActivities:nil];
  345. [self presentViewController:shareSheet animated:true completion:nil];
  346. }
  347. }
  348. - (void)reloadDisplayedPaths {
  349. if (self.searchController.isActive) {
  350. [self updateSearchPaths];
  351. } else {
  352. [self reloadCurrentPath];
  353. [self.tableView reloadData];
  354. }
  355. }
  356. - (void)reloadCurrentPath {
  357. NSMutableArray<NSString *> *childPaths = [NSMutableArray array];
  358. NSArray<NSString *> *subpaths = [NSFileManager.defaultManager contentsOfDirectoryAtPath:self.path error:NULL];
  359. for (NSString *subpath in subpaths) {
  360. [childPaths addObject:[self.path stringByAppendingPathComponent:subpath]];
  361. }
  362. self.childPaths = childPaths;
  363. }
  364. - (void)updateSearchPaths {
  365. self.searchPaths = nil;
  366. self.searchPathsSize = nil;
  367. //clear pre search request and start a new one
  368. [self.operationQueue cancelAllOperations];
  369. FLEXFileBrowserSearchOperation *newOperation = [[FLEXFileBrowserSearchOperation alloc] initWithPath:self.path searchString:self.searchText];
  370. newOperation.delegate = self;
  371. [self.operationQueue addOperation:newOperation];
  372. }
  373. - (NSString *)filePathAtIndexPath:(NSIndexPath *)indexPath {
  374. return self.searchController.isActive ? self.searchPaths[indexPath.row] : self.childPaths[indexPath.row];
  375. }
  376. @end
  377. @implementation FLEXFileBrowserTableViewCell
  378. - (void)forwardAction:(SEL)action withSender:(id)sender {
  379. id target = [self.nextResponder targetForAction:action withSender:sender];
  380. [UIApplication.sharedApplication sendAction:action to:target from:self forEvent:nil];
  381. }
  382. - (void)fileBrowserRename:(UIMenuController *)sender {
  383. [self forwardAction:_cmd withSender:sender];
  384. }
  385. - (void)fileBrowserDelete:(UIMenuController *)sender {
  386. [self forwardAction:_cmd withSender:sender];
  387. }
  388. - (void)fileBrowserCopyPath:(UIMenuController *)sender {
  389. [self forwardAction:_cmd withSender:sender];
  390. }
  391. - (void)fileBrowserShare:(UIMenuController *)sender {
  392. [self forwardAction:_cmd withSender:sender];
  393. }
  394. @end