FLEXFileBrowserController.m 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. //
  2. // FLEXFileBrowserController.m
  3. // Flipboard
  4. //
  5. // Created by Ryan Olson on 6/9/14.
  6. //
  7. //
  8. #import "FLEXFileBrowserController.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. #import <mach-o/loader.h>
  16. @interface FLEXFileBrowserTableViewCell : UITableViewCell
  17. @end
  18. @interface FLEXFileBrowserController () <FLEXFileBrowserSearchOperationDelegate>
  19. @property (nonatomic, copy) NSString *path;
  20. @property (nonatomic, copy) NSArray<NSString *> *childPaths;
  21. @property (nonatomic) NSArray<NSString *> *searchPaths;
  22. @property (nonatomic) NSNumber *recursiveSize;
  23. @property (nonatomic) NSNumber *searchPathsSize;
  24. @property (nonatomic) NSOperationQueue *operationQueue;
  25. @property (nonatomic) UIDocumentInteractionController *documentController;
  26. @end
  27. @implementation FLEXFileBrowserController
  28. + (instancetype)path:(NSString *)path {
  29. return [[self alloc] initWithPath:path];
  30. }
  31. - (id)init {
  32. return [self initWithPath:NSHomeDirectory()];
  33. }
  34. - (id)initWithPath:(NSString *)path {
  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. FLEXFileBrowserController *__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. FLEXFileBrowserController *__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. [super viewDidLoad];
  67. self.showsSearchBar = YES;
  68. self.searchBarDebounceInterval = kFLEXDebounceForAsyncSearch;
  69. }
  70. #pragma mark - FLEXGlobalsEntry
  71. + (NSString *)globalsEntryTitle:(FLEXGlobalsRow)row {
  72. switch (row) {
  73. case FLEXGlobalsRowBrowseBundle: return @"📁 Browse Bundle Directory";
  74. case FLEXGlobalsRowBrowseContainer: return @"📁 Browse Container Directory";
  75. default: return nil;
  76. }
  77. }
  78. + (UIViewController *)globalsEntryViewController:(FLEXGlobalsRow)row {
  79. switch (row) {
  80. case FLEXGlobalsRowBrowseBundle: return [[self alloc] initWithPath:NSBundle.mainBundle.bundlePath];
  81. case FLEXGlobalsRowBrowseContainer: return [[self alloc] initWithPath:NSHomeDirectory()];
  82. default: return [self new];
  83. }
  84. }
  85. #pragma mark - FLEXFileBrowserSearchOperationDelegate
  86. - (void)fileBrowserSearchOperationResult:(NSArray<NSString *> *)searchResult size:(uint64_t)size {
  87. self.searchPaths = searchResult;
  88. self.searchPathsSize = @(size);
  89. [self.tableView reloadData];
  90. }
  91. #pragma mark - Search bar
  92. - (void)updateSearchResults:(NSString *)newText {
  93. [self reloadDisplayedPaths];
  94. }
  95. #pragma mark UISearchControllerDelegate
  96. - (void)willDismissSearchController:(UISearchController *)searchController {
  97. [self.operationQueue cancelAllOperations];
  98. [self reloadCurrentPath];
  99. [self.tableView reloadData];
  100. }
  101. #pragma mark - Table view data source
  102. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  103. return 1;
  104. }
  105. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  106. return self.searchController.isActive ? self.searchPaths.count : self.childPaths.count;
  107. }
  108. - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
  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. NSString *fullPath = [self filePathAtIndexPath:indexPath];
  122. NSDictionary<NSString *, id> *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:fullPath error:NULL];
  123. BOOL isDirectory = [attributes.fileType isEqual:NSFileTypeDirectory];
  124. NSString *subtitle = nil;
  125. if (isDirectory) {
  126. NSUInteger count = [NSFileManager.defaultManager contentsOfDirectoryAtPath:fullPath error:NULL].count;
  127. subtitle = [NSString stringWithFormat:@"%lu item%@", (unsigned long)count, (count == 1 ? @"" : @"s")];
  128. } else {
  129. NSString *sizeString = [NSByteCountFormatter stringFromByteCount:attributes.fileSize countStyle:NSByteCountFormatterCountStyleFile];
  130. subtitle = [NSString stringWithFormat:@"%@ - %@", sizeString, attributes.fileModificationDate ?: @"Never modified"];
  131. }
  132. static NSString *textCellIdentifier = @"textCell";
  133. static NSString *imageCellIdentifier = @"imageCell";
  134. UITableViewCell *cell = nil;
  135. // Separate image and text only cells because otherwise the separator lines get out-of-whack on image cells reused with text only.
  136. UIImage *image = [UIImage imageWithContentsOfFile:fullPath];
  137. NSString *cellIdentifier = image ? imageCellIdentifier : textCellIdentifier;
  138. if (!cell) {
  139. cell = [[FLEXFileBrowserTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
  140. cell.textLabel.font = UIFont.flex_defaultTableCellFont;
  141. cell.detailTextLabel.font = UIFont.flex_defaultTableCellFont;
  142. cell.detailTextLabel.textColor = UIColor.grayColor;
  143. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  144. }
  145. NSString *cellTitle = [fullPath lastPathComponent];
  146. cell.textLabel.text = cellTitle;
  147. cell.detailTextLabel.text = subtitle;
  148. if (image) {
  149. cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
  150. cell.imageView.image = image;
  151. }
  152. return cell;
  153. }
  154. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  155. [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
  156. NSString *fullPath = [self filePathAtIndexPath:indexPath];
  157. NSString *subpath = fullPath.lastPathComponent;
  158. NSString *pathExtension = subpath.pathExtension;
  159. BOOL isDirectory = NO;
  160. BOOL stillExists = [NSFileManager.defaultManager fileExistsAtPath:fullPath isDirectory:&isDirectory];
  161. UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  162. UIImage *image = cell.imageView.image;
  163. if (!stillExists) {
  164. [FLEXAlert showAlert:@"File Not Found" message:@"The file at the specified path no longer exists." from:self];
  165. [self reloadDisplayedPaths];
  166. return;
  167. }
  168. UIViewController *drillInViewController = nil;
  169. if (isDirectory) {
  170. drillInViewController = [[[self class] alloc] initWithPath:fullPath];
  171. } else if (image) {
  172. drillInViewController = [FLEXImagePreviewViewController forImage:image];
  173. } else {
  174. NSData *fileData = [NSData dataWithContentsOfFile:fullPath];
  175. if (!fileData.length) {
  176. [FLEXAlert showAlert:@"Empty File" message:@"No data returned from the file." from:self];
  177. return;
  178. }
  179. // Special case keyed archives, json, and plists to get more readable data.
  180. NSString *prettyString = nil;
  181. if ([pathExtension isEqualToString:@"json"]) {
  182. prettyString = [FLEXUtility prettyJSONStringFromData:fileData];
  183. } else {
  184. // Regardless of file extension...
  185. id object = nil;
  186. @try {
  187. // Try to decode an archived object regardless of file extension
  188. object = [NSKeyedUnarchiver unarchiveObjectWithData:fileData];
  189. } @catch (NSException *e) { }
  190. // Try to decode other things instead
  191. object = object ?: [NSPropertyListSerialization
  192. propertyListWithData:fileData
  193. options:0
  194. format:NULL
  195. error:NULL
  196. ] ?: [NSDictionary dictionaryWithContentsOfFile:fullPath]
  197. ?: [NSArray arrayWithContentsOfFile:fullPath];
  198. if (object) {
  199. drillInViewController = [FLEXObjectExplorerFactory explorerViewControllerForObject:object];
  200. } else {
  201. // Is it possibly a mach-O file?
  202. if (fileData.length > sizeof(struct mach_header_64)) {
  203. struct mach_header_64 header;
  204. [fileData getBytes:&header length:sizeof(struct mach_header_64)];
  205. // Does it have the mach header magic number?
  206. if (header.magic == MH_MAGIC_64) {
  207. // See if we can get some classes out of it...
  208. unsigned int count = 0;
  209. const char **classList = objc_copyClassNamesForImage(
  210. fullPath.UTF8String, &count
  211. );
  212. if (count > 0) {
  213. NSArray<NSString *> *classNames = [NSArray flex_forEachUpTo:count map:^id(NSUInteger i) {
  214. return objc_getClass(classList[i]);
  215. }];
  216. drillInViewController = [FLEXObjectExplorerFactory explorerViewControllerForObject:classNames];
  217. }
  218. }
  219. }
  220. }
  221. }
  222. if (prettyString.length) {
  223. drillInViewController = [[FLEXWebViewController alloc] initWithText:prettyString];
  224. } else if ([FLEXWebViewController supportsPathExtension:pathExtension]) {
  225. drillInViewController = [[FLEXWebViewController alloc] initWithURL:[NSURL fileURLWithPath:fullPath]];
  226. } else if ([FLEXTableListViewController supportsExtension:pathExtension]) {
  227. drillInViewController = [[FLEXTableListViewController alloc] initWithPath:fullPath];
  228. }
  229. else if (!drillInViewController) {
  230. NSString *fileString = [NSString stringWithUTF8String:fileData.bytes];
  231. if (fileString.length) {
  232. drillInViewController = [[FLEXWebViewController alloc] initWithText:fileString];
  233. }
  234. }
  235. }
  236. if (drillInViewController) {
  237. drillInViewController.title = subpath.lastPathComponent;
  238. [self.navigationController pushViewController:drillInViewController animated:YES];
  239. } else {
  240. // Share the file otherwise
  241. [self openFileController:fullPath];
  242. }
  243. }
  244. - (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath {
  245. UIMenuItem *rename = [[UIMenuItem alloc] initWithTitle:@"Rename" action:@selector(fileBrowserRename:)];
  246. UIMenuItem *delete = [[UIMenuItem alloc] initWithTitle:@"Delete" action:@selector(fileBrowserDelete:)];
  247. UIMenuItem *copyPath = [[UIMenuItem alloc] initWithTitle:@"Copy Path" action:@selector(fileBrowserCopyPath:)];
  248. UIMenuItem *share = [[UIMenuItem alloc] initWithTitle:@"Share" action:@selector(fileBrowserShare:)];
  249. UIMenuController.sharedMenuController.menuItems = @[rename, delete, copyPath, share];
  250. return YES;
  251. }
  252. - (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
  253. return action == @selector(fileBrowserDelete:)
  254. || action == @selector(fileBrowserRename:)
  255. || action == @selector(fileBrowserCopyPath:)
  256. || action == @selector(fileBrowserShare:);
  257. }
  258. - (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
  259. // Empty, but has to exist for the menu to show
  260. // The table view only calls this method for actions in the UIResponderStandardEditActions informal protocol.
  261. // Since our actions are outside of that protocol, we need to manually handle the action forwarding from the cells.
  262. }
  263. #if FLEX_AT_LEAST_IOS13_SDK
  264. - (UIContextMenuConfiguration *)tableView:(UITableView *)tableView contextMenuConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath point:(CGPoint)point __IOS_AVAILABLE(13.0) {
  265. __weak typeof(self) weakSelf = self;
  266. return [UIContextMenuConfiguration configurationWithIdentifier:nil
  267. previewProvider:nil
  268. actionProvider:^UIMenu * _Nullable(NSArray<UIMenuElement *> * _Nonnull suggestedActions) {
  269. UITableViewCell * const cell = [tableView cellForRowAtIndexPath:indexPath];
  270. UIAction *rename = [UIAction actionWithTitle:@"Rename"
  271. image:nil
  272. identifier:@"Rename"
  273. handler:^(__kindof UIAction * _Nonnull action) {
  274. [weakSelf fileBrowserRename:cell];
  275. }];
  276. UIAction *delete = [UIAction actionWithTitle:@"Delete"
  277. image:nil
  278. identifier:@"Delete"
  279. handler:^(__kindof UIAction * _Nonnull action) {
  280. [weakSelf fileBrowserDelete:cell];
  281. }];
  282. UIAction *copyPath = [UIAction actionWithTitle:@"Copy Path"
  283. image:nil
  284. identifier:@"Copy Path"
  285. handler:^(__kindof UIAction * _Nonnull action) {
  286. [weakSelf fileBrowserCopyPath:cell];
  287. }];
  288. UIAction *share = [UIAction actionWithTitle:@"Share"
  289. image:nil
  290. identifier:@"Share"
  291. handler:^(__kindof UIAction * _Nonnull action) {
  292. [weakSelf fileBrowserShare:cell];
  293. }];
  294. return [UIMenu menuWithTitle:@"Manage File" image:nil identifier:@"Manage File" options:UIMenuOptionsDisplayInline children:@[rename, delete, copyPath, share]];
  295. }];
  296. }
  297. #endif
  298. - (void)openFileController:(NSString *)fullPath {
  299. UIDocumentInteractionController *controller = [UIDocumentInteractionController new];
  300. controller.URL = [NSURL fileURLWithPath:fullPath];
  301. [controller presentOptionsMenuFromRect:self.view.bounds inView:self.view animated:YES];
  302. self.documentController = controller;
  303. }
  304. - (void)fileBrowserRename:(UITableViewCell *)sender {
  305. NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
  306. NSString *fullPath = [self filePathAtIndexPath:indexPath];
  307. BOOL stillExists = [NSFileManager.defaultManager fileExistsAtPath:self.path isDirectory:NULL];
  308. if (stillExists) {
  309. [FLEXAlert makeAlert:^(FLEXAlert *make) {
  310. make.title([NSString stringWithFormat:@"Rename %@?", fullPath.lastPathComponent]);
  311. make.configuredTextField(^(UITextField *textField) {
  312. textField.placeholder = @"New file name";
  313. textField.text = fullPath.lastPathComponent;
  314. });
  315. make.button(@"Rename").handler(^(NSArray<NSString *> *strings) {
  316. NSString *newFileName = strings.firstObject;
  317. NSString *newPath = [fullPath.stringByDeletingLastPathComponent stringByAppendingPathComponent:newFileName];
  318. [NSFileManager.defaultManager moveItemAtPath:fullPath toPath:newPath error:NULL];
  319. [self reloadDisplayedPaths];
  320. });
  321. make.button(@"Cancel").cancelStyle();
  322. } showFrom:self];
  323. } else {
  324. [FLEXAlert showAlert:@"File Removed" message:@"The file at the specified path no longer exists." from:self];
  325. }
  326. }
  327. - (void)fileBrowserDelete:(UITableViewCell *)sender {
  328. NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
  329. NSString *fullPath = [self filePathAtIndexPath:indexPath];
  330. BOOL isDirectory = NO;
  331. BOOL stillExists = [NSFileManager.defaultManager fileExistsAtPath:fullPath isDirectory:&isDirectory];
  332. if (stillExists) {
  333. [FLEXAlert makeAlert:^(FLEXAlert *make) {
  334. make.title(@"Confirm Deletion");
  335. make.message([NSString stringWithFormat:
  336. @"The %@ '%@' will be deleted. This operation cannot be undone",
  337. (isDirectory ? @"directory" : @"file"), fullPath.lastPathComponent
  338. ]);
  339. make.button(@"Delete").destructiveStyle().handler(^(NSArray<NSString *> *strings) {
  340. [NSFileManager.defaultManager removeItemAtPath:fullPath error:NULL];
  341. [self reloadDisplayedPaths];
  342. });
  343. make.button(@"Cancel").cancelStyle();
  344. } showFrom:self];
  345. } else {
  346. [FLEXAlert showAlert:@"File Removed" message:@"The file at the specified path no longer exists." from:self];
  347. }
  348. }
  349. - (void)fileBrowserCopyPath:(UITableViewCell *)sender {
  350. NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
  351. NSString *fullPath = [self filePathAtIndexPath:indexPath];
  352. UIPasteboard.generalPasteboard.string = fullPath;
  353. }
  354. - (void)fileBrowserShare:(UITableViewCell *)sender {
  355. NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
  356. NSString *pathString = [self filePathAtIndexPath:indexPath];
  357. NSURL *filePath = [NSURL fileURLWithPath:pathString];
  358. BOOL isDirectory = NO;
  359. [NSFileManager.defaultManager fileExistsAtPath:pathString isDirectory:&isDirectory];
  360. if (isDirectory) {
  361. // UIDocumentInteractionController for folders
  362. [self openFileController:pathString];
  363. } else {
  364. // Share sheet for files
  365. UIActivityViewController *shareSheet = [[UIActivityViewController alloc] initWithActivityItems:@[filePath] applicationActivities:nil];
  366. [self presentViewController:shareSheet animated:true completion:nil];
  367. }
  368. }
  369. - (void)reloadDisplayedPaths {
  370. if (self.searchController.isActive) {
  371. [self updateSearchPaths];
  372. } else {
  373. [self reloadCurrentPath];
  374. [self.tableView reloadData];
  375. }
  376. }
  377. - (void)reloadCurrentPath {
  378. NSMutableArray<NSString *> *childPaths = [NSMutableArray new];
  379. NSArray<NSString *> *subpaths = [NSFileManager.defaultManager contentsOfDirectoryAtPath:self.path error:NULL];
  380. for (NSString *subpath in subpaths) {
  381. [childPaths addObject:[self.path stringByAppendingPathComponent:subpath]];
  382. }
  383. self.childPaths = childPaths;
  384. }
  385. - (void)updateSearchPaths {
  386. self.searchPaths = nil;
  387. self.searchPathsSize = nil;
  388. //clear pre search request and start a new one
  389. [self.operationQueue cancelAllOperations];
  390. FLEXFileBrowserSearchOperation *newOperation = [[FLEXFileBrowserSearchOperation alloc] initWithPath:self.path searchString:self.searchText];
  391. newOperation.delegate = self;
  392. [self.operationQueue addOperation:newOperation];
  393. }
  394. - (NSString *)filePathAtIndexPath:(NSIndexPath *)indexPath {
  395. return self.searchController.isActive ? self.searchPaths[indexPath.row] : self.childPaths[indexPath.row];
  396. }
  397. @end
  398. @implementation FLEXFileBrowserTableViewCell
  399. - (void)forwardAction:(SEL)action withSender:(id)sender {
  400. id target = [self.nextResponder targetForAction:action withSender:sender];
  401. [UIApplication.sharedApplication sendAction:action to:target from:self forEvent:nil];
  402. }
  403. - (void)fileBrowserRename:(UIMenuController *)sender {
  404. [self forwardAction:_cmd withSender:sender];
  405. }
  406. - (void)fileBrowserDelete:(UIMenuController *)sender {
  407. [self forwardAction:_cmd withSender:sender];
  408. }
  409. - (void)fileBrowserCopyPath:(UIMenuController *)sender {
  410. [self forwardAction:_cmd withSender:sender];
  411. }
  412. - (void)fileBrowserShare:(UIMenuController *)sender {
  413. [self forwardAction:_cmd withSender:sender];
  414. }
  415. @end