VLCLibraryViewController.m 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432
  1. /*****************************************************************************
  2. * VLCLibraryViewController.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2013-2017 VideoLAN. All rights reserved.
  6. * $Id$
  7. *
  8. * Authors: Felix Paul Kühne <fkuehne # videolan.org>
  9. * Gleb Pinigin <gpinigin # gmail.com>
  10. * Tamas Timar <ttimar.vlc # gmail.com>
  11. * Carola Nitz <nitz.carola # gmail.com>
  12. * Tobias Conradi <videolan # tobias-conradi.de>
  13. * Mike JS. Choi <mkchoi212 # icloud.com>
  14. *
  15. * Refer to the COPYING file of the official project for license.
  16. *****************************************************************************/
  17. #import "VLCLibraryViewController.h"
  18. #import "LXReorderableCollectionViewFlowLayout.h"
  19. #import "VLCActivityViewControllerVendor.h"
  20. #import "VLCAppDelegate.h"
  21. #import "VLCBugreporter.h"
  22. #import "VLCEmptyLibraryView.h"
  23. #import "VLCFolderCollectionViewFlowLayout.h"
  24. #import "VLCMediaDataSource.h"
  25. #import "VLCLibrarySearchDisplayDataSource.h"
  26. #import "VLCMovieViewController.h"
  27. #import "VLCPlaylistCollectionViewCell.h"
  28. #import "VLCPlaylistTableViewCell.h"
  29. #import "VLCPlaybackController+MediaLibrary.h"
  30. #import "VLC_iOS-Swift.h"
  31. #import <CoreSpotlight/CoreSpotlight.h>
  32. /* prefs keys */
  33. static NSString *kDisplayedFirstSteps = @"Did we display the first steps tutorial?";
  34. static NSString *kUsingTableViewToShowData = @"UsingTableViewToShowData";
  35. @interface VLCLibraryViewController () <VLCFolderCollectionViewDelegateFlowLayout, LXReorderableCollectionViewDataSource, LXReorderableCollectionViewDelegateFlowLayout, UITableViewDataSource, UITableViewDelegate, MLMediaLibrary, VLCMediaListDelegate, UISearchResultsUpdating, UISearchControllerDelegate> {
  36. VLCLibraryMode _libraryMode;
  37. VLCLibraryMode _previousLibraryMode;
  38. UIBarButtonItem *_menuButton;
  39. NSMutableArray *_indexPaths;
  40. id _folderObject;
  41. VLCFolderCollectionViewFlowLayout *_folderLayout;
  42. LXReorderableCollectionViewFlowLayout *_reorderLayout;
  43. BOOL _inFolder;
  44. BOOL _isSelected;
  45. BOOL _deleteFromTableView;
  46. UILongPressGestureRecognizer *_longPressGestureRecognizer;
  47. VLCLibrarySearchDisplayDataSource *_searchDataSource;
  48. VLCMediaDataSource *_mediaDataSource;
  49. UISearchController *_searchController;
  50. UIBarButtonItem *_selectAllBarButtonItem;
  51. UIBarButtonItem *_createFolderBarButtonItem;
  52. UIBarButtonItem *_shareBarButtonItem;
  53. UIBarButtonItem *_removeFromFolderBarButtonItem;
  54. UIBarButtonItem *_deleteSelectedBarButtonItem;
  55. NSObject *dragAndDropManager;
  56. }
  57. @property (nonatomic, strong) UIBarButtonItem *displayModeBarButtonItem;
  58. @property (nonatomic, strong) UITableView *tableView;
  59. @property (nonatomic, strong) UICollectionView *collectionView;
  60. @property (nonatomic, strong) VLCEmptyLibraryView *emptyLibraryView;
  61. @end
  62. @implementation VLCLibraryViewController
  63. + (void)initialize
  64. {
  65. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  66. [defaults registerDefaults:@{kDisplayedFirstSteps : [NSNumber numberWithBool:NO]}];
  67. [defaults registerDefaults:@{kUsingTableViewToShowData : [NSNumber numberWithBool:UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone]}];
  68. }
  69. - (void)loadView
  70. {
  71. _mediaDataSource = [VLCMediaDataSource new];
  72. _searchDataSource = [VLCLibrarySearchDisplayDataSource new];
  73. self.emptyLibraryView = [[[NSBundle mainBundle] loadNibNamed:@"VLCEmptyLibraryView" owner:self options:nil] lastObject];
  74. _emptyLibraryView.emptyLibraryLongDescriptionLabel.lineBreakMode = NSLineBreakByWordWrapping;
  75. _emptyLibraryView.emptyLibraryLongDescriptionLabel.numberOfLines = 0;
  76. if (@available(iOS 11.0, *)) {
  77. dragAndDropManager = [VLCDragAndDropManager new];
  78. ((VLCDragAndDropManager *)dragAndDropManager).delegate = _mediaDataSource;
  79. UIDropInteraction *dropInteraction = [[UIDropInteraction alloc] initWithDelegate:(VLCDragAndDropManager *)dragAndDropManager];
  80. [_emptyLibraryView addInteraction:dropInteraction];
  81. }
  82. [self setupContentView];
  83. [self setViewFromDeviceOrientation];
  84. [self updateViewsForCurrentDisplayMode];
  85. _libraryMode = VLCLibraryModeAllFiles;
  86. }
  87. - (void)setupContentView
  88. {
  89. CGRect viewDimensions = [UIApplication sharedApplication].keyWindow.bounds;
  90. UIView *contentView = [[UIView alloc] initWithFrame:viewDimensions];
  91. contentView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
  92. contentView.backgroundColor = [UIColor VLCDarkBackgroundColor];
  93. if (!_tableView) {
  94. _tableView = [[UITableView alloc] initWithFrame:viewDimensions style:UITableViewStylePlain];
  95. _tableView.backgroundColor = [UIColor VLCDarkBackgroundColor];
  96. CGRect frame = _tableView.bounds;
  97. frame.origin.y = -frame.size.height;
  98. UIView *topView = [[UIView alloc] initWithFrame:frame];
  99. topView.backgroundColor = [UIColor VLCDarkBackgroundColor];
  100. [_tableView addSubview:topView];
  101. _tableView.rowHeight = [VLCPlaylistTableViewCell heightOfCell];
  102. _tableView.separatorColor = [UIColor VLCDarkBackgroundColor];
  103. _tableView.delegate = self;
  104. _tableView.dataSource = self;
  105. _tableView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
  106. _tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
  107. if (@available(iOS 11.0, *)) {
  108. _tableView.dragDelegate = ((VLCDragAndDropManager *)dragAndDropManager);
  109. _tableView.dropDelegate = ((VLCDragAndDropManager *)dragAndDropManager);
  110. } else {
  111. _tableView.tableHeaderView = _searchController.searchBar;
  112. }
  113. UINib *nib = [UINib nibWithNibName:@"VLCPlaylistTableViewCell" bundle:nil];
  114. [_tableView registerNib:nib forCellReuseIdentifier:VLCPlaylistTableViewCell.cellIdentifier];
  115. }
  116. _tableView.frame = contentView.bounds;
  117. [_tableView reloadData];
  118. if (!_collectionView) {
  119. _folderLayout = [[VLCFolderCollectionViewFlowLayout alloc] init];
  120. _reorderLayout = [[LXReorderableCollectionViewFlowLayout alloc] init];
  121. _collectionView = [[UICollectionView alloc] initWithFrame:viewDimensions collectionViewLayout:_folderLayout];
  122. _collectionView.alwaysBounceVertical = YES;
  123. if (@available(iOS 11.0, *)) {
  124. _collectionView.dragDelegate = ((VLCDragAndDropManager *)dragAndDropManager);
  125. _collectionView.dropDelegate = ((VLCDragAndDropManager *)dragAndDropManager);
  126. }
  127. _collectionView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
  128. _collectionView.delegate = self;
  129. _collectionView.dataSource = self;
  130. _collectionView.backgroundColor = [UIColor VLCDarkBackgroundColor];
  131. _collectionView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
  132. _longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(_collectionViewHandleLongPressGesture:)];
  133. [_collectionView addGestureRecognizer:_longPressGestureRecognizer];
  134. [_collectionView registerNib:[UINib nibWithNibName:@"VLCPlaylistCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:VLCPlaylistCollectionViewCell.cellIdentifier];
  135. }
  136. _collectionView.frame = contentView.bounds;
  137. [_collectionView reloadData];
  138. if (self.usingTableViewToShowData) {
  139. [contentView addSubview:_tableView];
  140. if (@available(iOS 11.0, *))
  141. [self setSearchBar:YES resetContent:NO];
  142. } else {
  143. [contentView addSubview:_collectionView];
  144. [_searchController setActive:NO];
  145. if (@available(iOS 11.0, *))
  146. [self setSearchBar:NO resetContent:NO];
  147. }
  148. self.view = contentView;
  149. }
  150. #pragma mark -
  151. - (void)viewWillLayoutSubviews {
  152. UIScrollView *dataView = self.usingTableViewToShowData ? _tableView : _collectionView;
  153. [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
  154. [dataView setContentInset:UIEdgeInsetsZero];
  155. }
  156. - (void)viewDidLoad
  157. {
  158. [super viewDidLoad];
  159. self.title = NSLocalizedString(@"LIBRARY_ALL_FILES", nil);
  160. self.navigationItem.leftBarButtonItem = _menuButton;
  161. self.editButtonItem.title = NSLocalizedString(@"BUTTON_EDIT", nil);
  162. self.editButtonItem.tintColor = [UIColor whiteColor];
  163. _selectAllBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"BUTTON_ALL", nil) style:UIBarButtonItemStylePlain target:self action:@selector(handleSelection)];
  164. _selectAllBarButtonItem.tintColor = [UIColor whiteColor];
  165. UIFont *font = [UIFont boldSystemFontOfSize:17];
  166. NSDictionary *attributes = @{NSFontAttributeName: font};
  167. [_selectAllBarButtonItem setTitleTextAttributes:attributes forState:UIControlStateNormal];
  168. _emptyLibraryView.emptyLibraryLabel.text = NSLocalizedString(@"EMPTY_LIBRARY", nil);
  169. _emptyLibraryView.emptyLibraryLongDescriptionLabel.text = NSLocalizedString(@"EMPTY_LIBRARY_LONG", nil);
  170. [_emptyLibraryView.emptyLibraryLongDescriptionLabel sizeToFit];
  171. [_emptyLibraryView.learnMoreButton setTitle:NSLocalizedString(@"BUTTON_LEARN_MORE", nil) forState:UIControlStateNormal];
  172. _createFolderBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemOrganize target:self action:@selector(createFolder)];
  173. // Better visual alignment with the action button
  174. _createFolderBarButtonItem.imageInsets = UIEdgeInsetsMake(3, 0, -3, 0);
  175. _createFolderBarButtonItem.landscapeImagePhoneInsets = UIEdgeInsetsMake(2, 0, -2, 0);
  176. _removeFromFolderBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemReply target:self action:@selector(removeFromFolder)];
  177. _removeFromFolderBarButtonItem.imageInsets = UIEdgeInsetsMake(2, 0, -2, 0);
  178. _removeFromFolderBarButtonItem.landscapeImagePhoneInsets = UIEdgeInsetsMake(1, 0, -1, 0);
  179. _removeFromFolderBarButtonItem.enabled = NO;
  180. _shareBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(share:)];
  181. _shareBarButtonItem.enabled = NO;
  182. _deleteSelectedBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(deleteSelection:)];
  183. _deleteFromTableView = NO;
  184. UIBarButtonItem *fixedSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
  185. fixedSpace.width = 20;
  186. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  187. fixedSpace.width *= 2;
  188. }
  189. [self setToolbarItems:@[_shareBarButtonItem,
  190. fixedSpace,
  191. _createFolderBarButtonItem,
  192. [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
  193. [UIBarButtonItem themedDarkToolbarButtonWithTitle:NSLocalizedString(@"BUTTON_RENAME", nil) target:self andSelector:@selector(renameSelection)],
  194. [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
  195. _removeFromFolderBarButtonItem,
  196. fixedSpace,
  197. _deleteSelectedBarButtonItem]];
  198. self.navigationController.toolbar.barStyle = UIBarStyleBlack;
  199. self.navigationController.toolbar.tintColor = [UIColor whiteColor];
  200. [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
  201. self.edgesForExtendedLayout = UIRectEdgeNone;
  202. [self setupSearchController];
  203. }
  204. - (void)setupSearchController
  205. {
  206. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  207. _searchController.searchResultsUpdater = self;
  208. _searchController.dimsBackgroundDuringPresentation = NO;
  209. _searchController.delegate = self;
  210. [self setSearchBar:YES resetContent:YES];
  211. if (!self.usingTableViewToShowData) {
  212. if (@available(iOS 11.0, *))
  213. [self setSearchBar:NO resetContent:NO];
  214. }
  215. }
  216. - (void)viewWillAppear:(BOOL)animated
  217. {
  218. [super viewWillAppear:animated];
  219. [self.collectionView.collectionViewLayout invalidateLayout];
  220. [self setViewFromDeviceOrientation];
  221. [self updateViewsForCurrentDisplayMode];
  222. }
  223. - (void)viewDidAppear:(BOOL)animated
  224. {
  225. [super viewDidAppear:animated];
  226. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  227. if (![[defaults objectForKey:kDisplayedFirstSteps] boolValue]) {
  228. [self.emptyLibraryView performSelector:@selector(learnMore:) withObject:nil afterDelay:1.];
  229. [defaults setObject:[NSNumber numberWithBool:YES] forKey:kDisplayedFirstSteps];
  230. }
  231. if ([_mediaDataSource numberOfFiles] < 1)
  232. [self updateViewContents];
  233. [[MLMediaLibrary sharedMediaLibrary] performSelector:@selector(libraryDidAppear) withObject:nil afterDelay:1.];
  234. }
  235. - (void)viewDidDisappear:(BOOL)animated
  236. {
  237. [super viewDidDisappear:animated];
  238. [[MLMediaLibrary sharedMediaLibrary] libraryDidDisappear];
  239. }
  240. - (BOOL)canBecomeFirstResponder
  241. {
  242. return YES;
  243. }
  244. - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
  245. {
  246. if (motion == UIEventSubtypeMotionShake)
  247. [[VLCBugreporter sharedInstance] handleBugreportRequest];
  248. }
  249. - (void)openMediaObject:(NSManagedObject *)mediaObject
  250. {
  251. if ([mediaObject isKindOfClass:[MLAlbum class]] || [mediaObject isKindOfClass:[MLShow class]]) {
  252. [_mediaDataSource updateContentsForSelection:mediaObject];
  253. BOOL isAlbum = [mediaObject isKindOfClass:[MLAlbum class]];
  254. self.navigationItem.leftBarButtonItem = [UIBarButtonItem themedBackButtonWithTarget:self andSelector:@selector(backToAllItems:)];
  255. if (_libraryMode == VLCLibraryModeAllFiles)
  256. self.navigationItem.leftBarButtonItem.title = NSLocalizedString(@"BUTTON_BACK", nil);
  257. else
  258. [self.navigationItem.leftBarButtonItem setTitle: isAlbum ? NSLocalizedString(@"LIBRARY_MUSIC", nil) : NSLocalizedString(@"LIBRARY_SERIES", nil)];
  259. self.title = [(MLAlbum*)mediaObject name];
  260. [self reloadViews];
  261. } else if ([mediaObject isKindOfClass:[MLLabel class]]) {
  262. [_mediaDataSource updateContentsForSelection:mediaObject];
  263. _inFolder = YES;
  264. if (!self.usingTableViewToShowData) {
  265. if (@available(iOS 11.0, *)) {
  266. } else {
  267. if (![self.collectionView.collectionViewLayout isEqual:_reorderLayout]) {
  268. for (UIGestureRecognizer *recognizer in _collectionView.gestureRecognizers) {
  269. if (recognizer == _folderLayout.panGestureRecognizer || recognizer == _folderLayout.longPressGestureRecognizer || recognizer == _longPressGestureRecognizer)
  270. [self.collectionView removeGestureRecognizer:recognizer];
  271. }
  272. //reloadData before setting a new layout avoids a crash deep in UIKits UICollectionViewData layoutattributs
  273. [self.collectionView reloadData];
  274. [self.collectionView setCollectionViewLayout:_reorderLayout animated:NO];
  275. }
  276. }
  277. }
  278. _libraryMode = VLCLibraryModeFolder;
  279. self.navigationItem.leftBarButtonItem = [UIBarButtonItem themedBackButtonWithTarget:self andSelector:@selector(backToAllItems:)];
  280. self.navigationItem.leftBarButtonItem.title = NSLocalizedString(@"BUTTON_BACK", nil);
  281. self.title = [(MLLabel*)mediaObject name];
  282. _removeFromFolderBarButtonItem.enabled = YES;
  283. _createFolderBarButtonItem.enabled = NO;
  284. [self reloadViews];
  285. return;
  286. } else {
  287. VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
  288. [vpc playMediaLibraryObject:mediaObject];
  289. [self createSpotlightItem:mediaObject];
  290. }
  291. }
  292. - (void)createSpotlightItem:(nonnull NSManagedObject *)mediaObject
  293. {
  294. if (![VLCKeychainCoordinator passcodeLockEnabled]) {
  295. NSURL *uriRepresentation = mediaObject.objectID.URIRepresentation;
  296. if (uriRepresentation == nil) {
  297. return;
  298. }
  299. self.userActivity = [[NSUserActivity alloc] initWithActivityType:kVLCUserActivityPlaying];
  300. MLFile *file = nil;
  301. if ([mediaObject isKindOfClass:[MLAlbumTrack class]]) {
  302. file = [(MLAlbumTrack *)mediaObject anyFileFromTrack];
  303. } else if ([mediaObject isKindOfClass:[MLShowEpisode class]]) {
  304. file = [(MLShowEpisode *)mediaObject anyFileFromEpisode];
  305. } else if ([mediaObject isKindOfClass:[MLFile class]]){
  306. file = (MLFile *)mediaObject;
  307. }
  308. self.userActivity.title = file.title;
  309. self.userActivity.contentAttributeSet = file.coreSpotlightAttributeSet;
  310. self.userActivity.userInfo = @{ @"playingmedia": uriRepresentation};
  311. self.userActivity.eligibleForSearch = YES;
  312. self.userActivity.eligibleForHandoff = YES;
  313. [self.userActivity becomeCurrent];
  314. }
  315. }
  316. - (void)removeMediaObject:(id)managedObject updateDatabase:(BOOL)updateDB
  317. {
  318. [_mediaDataSource removeMediaObject:managedObject];
  319. if (updateDB) {
  320. [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
  321. [self updateViewContents];
  322. }
  323. }
  324. - (void)_displayEmptyLibraryViewIfNeeded
  325. {
  326. if (self.emptyLibraryView.superview)
  327. [self.emptyLibraryView removeFromSuperview];
  328. if ([_mediaDataSource numberOfFiles] == 0) {
  329. _inFolder = (_libraryMode == VLCLibraryModeFolder || _libraryMode == VLCLibraryModeCreateFolder);
  330. self.emptyLibraryView.emptyLibraryLabel.text = _inFolder ? NSLocalizedString(@"FOLDER_EMPTY", nil) : NSLocalizedString(@"EMPTY_LIBRARY", nil);
  331. self.emptyLibraryView.emptyLibraryLongDescriptionLabel.text = _inFolder ? NSLocalizedString(@"FOLDER_EMPTY_LONG", nil) : NSLocalizedString(@"EMPTY_LIBRARY_LONG", nil);
  332. self.emptyLibraryView.learnMoreButton.hidden = _inFolder;
  333. self.emptyLibraryView.frame = self.view.bounds;
  334. [self.view addSubview:self.emptyLibraryView];
  335. self.navigationItem.rightBarButtonItems = nil;
  336. } else {
  337. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  338. UIBarButtonItem *toggleDisplayedView = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"tableViewIcon"] style:UIBarButtonItemStylePlain target:self action:@selector(toggleDisplayedView:)];
  339. self.navigationItem.rightBarButtonItems = @[toggleDisplayedView, self.editButtonItem];
  340. self.displayModeBarButtonItem = toggleDisplayedView;
  341. } else {
  342. self.navigationItem.rightBarButtonItem = self.editButtonItem;
  343. }
  344. }
  345. if (self.usingTableViewToShowData) {
  346. _tableView.separatorStyle = [_mediaDataSource numberOfFiles] > 0 ? UITableViewCellSeparatorStyleSingleLine:
  347. UITableViewCellSeparatorStyleNone;
  348. } else {
  349. [self.collectionView.collectionViewLayout invalidateLayout];
  350. }
  351. [self updateViewsForCurrentDisplayMode];
  352. }
  353. - (void)setViewFromDeviceOrientation
  354. {
  355. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
  356. BOOL isPortrait = YES;
  357. if (self.traitCollection.verticalSizeClass == UIUserInterfaceSizeClassCompact)
  358. isPortrait = NO;
  359. [self setUsingTableViewToShowData:isPortrait];
  360. [self _displayEmptyLibraryViewIfNeeded];
  361. }
  362. }
  363. - (void)setSearchBar:(BOOL)enable resetContent:(BOOL)resetContent
  364. {
  365. if (@available(iOS 11.0, *)) {
  366. _searchController.dimsBackgroundDuringPresentation = NO;
  367. [_searchController.searchBar sizeToFit];
  368. // search bar text field background color
  369. UITextField *searchTextField = [_searchController.searchBar valueForKey:@"searchField"];
  370. UIView *backgroundView = searchTextField.subviews.firstObject;
  371. backgroundView.backgroundColor = UIColor.whiteColor;
  372. backgroundView.layer.cornerRadius = 10;
  373. backgroundView.clipsToBounds = YES;
  374. _searchController.hidesNavigationBarDuringPresentation = NO;
  375. _searchController.obscuresBackgroundDuringPresentation = NO;
  376. self.navigationItem.hidesSearchBarWhenScrolling = YES;
  377. self.navigationItem.searchController = enable ? _searchController : nil;
  378. self.definesPresentationContext = YES;
  379. } else {
  380. _tableView.tableHeaderView = enable ? _searchController.searchBar : nil;
  381. if (resetContent) {
  382. CGPoint contentOffset = _tableView.contentOffset;
  383. contentOffset.y += CGRectGetHeight(_tableView.tableHeaderView.frame);
  384. _tableView.contentOffset = contentOffset;
  385. }
  386. }
  387. }
  388. - (void)libraryUpgradeComplete
  389. {
  390. self.title = NSLocalizedString(@"LIBRARY_ALL_FILES", nil);
  391. self.navigationItem.leftBarButtonItem = _menuButton;
  392. self.emptyLibraryView.emptyLibraryLongDescriptionLabel.hidden = NO;
  393. self.emptyLibraryView.emptyLibraryLabel.text = NSLocalizedString(@"EMPTY_LIBRARY", nil);
  394. [self.emptyLibraryView.activityIndicator stopAnimating];
  395. [self.emptyLibraryView removeFromSuperview];
  396. [self updateViewContents];
  397. }
  398. - (void)updateViewContents
  399. {
  400. self.navigationItem.leftBarButtonItem = _menuButton;
  401. [_mediaDataSource updateContentsForSelection:nil];
  402. _removeFromFolderBarButtonItem.enabled = NO;
  403. switch (_libraryMode) {
  404. case VLCLibraryModeAllAlbums: {
  405. self.title = NSLocalizedString(@"LIBRARY_MUSIC", nil);
  406. _createFolderBarButtonItem.enabled = NO;
  407. [_mediaDataSource addAlbumsInAllAlbumMode:YES];
  408. } break;
  409. case VLCLibraryModeAllSeries: {
  410. self.title = NSLocalizedString(@"LIBRARY_SERIES", nil);
  411. _createFolderBarButtonItem.enabled = NO;
  412. [_mediaDataSource addAllShows];
  413. } break;
  414. //TODO: I'm not sure if updateViewContents should be called in VLCLibraryModeFolder
  415. //Here should maybe be an NSAssert to prevent this but for now due to refactoring these calls would've been made in that case
  416. case VLCLibraryModeAllFiles:
  417. case VLCLibraryModeFolder:
  418. case VLCLibraryModeCreateFolder: {
  419. self.title = NSLocalizedString(@"LIBRARY_ALL_FILES", nil);
  420. _createFolderBarButtonItem.enabled = YES;
  421. [_mediaDataSource addAlbumsInAllAlbumMode:NO];
  422. [_mediaDataSource addAllShows];
  423. [_mediaDataSource addAllFolders];
  424. [_mediaDataSource addRemainingFiles];
  425. }
  426. }
  427. [self reloadViews];
  428. }
  429. - (void)reloadViews
  430. {
  431. // Since this gets can get called at any point and wipe away the selections, we update the actionBarButtonItem here because this can happen if you tap "Save Video" in the UIActivityController and a media access alert view takes away focus (the corresponding 'became active' notification of UIApplication will call this). Or simply try bringing down the notification center to trigger this. Any existing UIActivityViewController session should be safe as it would have copies of the selected file references.
  432. if (self.usingTableViewToShowData) {
  433. [self.tableView reloadData];
  434. [self updateActionBarButtonItemStateWithSelectedIndexPaths:[self.tableView indexPathsForSelectedRows]];
  435. _isSelected = NO;
  436. } else {
  437. [self.collectionView reloadData];
  438. [self updateActionBarButtonItemStateWithSelectedIndexPaths:[self.collectionView indexPathsForSelectedItems]];
  439. if (_libraryMode == VLCLibraryModeAllFiles) {
  440. if (self.collectionView.collectionViewLayout != _folderLayout) {
  441. for (UIGestureRecognizer *recognizer in _collectionView.gestureRecognizers) {
  442. if (recognizer == _reorderLayout.panGestureRecognizer ||
  443. recognizer == _reorderLayout.longPressGestureRecognizer) {
  444. [self.collectionView removeGestureRecognizer:recognizer];
  445. }
  446. }
  447. [self.collectionView setCollectionViewLayout:_folderLayout animated:NO];
  448. [self.collectionView addGestureRecognizer:_longPressGestureRecognizer];
  449. }
  450. }
  451. }
  452. [self _displayEmptyLibraryViewIfNeeded];
  453. }
  454. #pragma mark - Table View
  455. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  456. {
  457. return [_mediaDataSource numberOfFiles];
  458. }
  459. // Customize the appearance of table view cells.
  460. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  461. {
  462. VLCPlaylistTableViewCell *cell = (VLCPlaylistTableViewCell *)[tableView dequeueReusableCellWithIdentifier:VLCPlaylistTableViewCell.cellIdentifier];
  463. UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRightOnTableViewCellGestureAction:)];
  464. [swipeRight setDirection:(UISwipeGestureRecognizerDirectionRight)];
  465. [cell addGestureRecognizer:swipeRight];
  466. cell.mediaObject = [_mediaDataSource objectAtIndex:indexPath.row];
  467. return cell;
  468. }
  469. - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
  470. {
  471. [_mediaDataSource moveObjectFromIndex:fromIndexPath.item toIndex:toIndexPath.item];
  472. }
  473. - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
  474. {
  475. if (@available(iOS 11.0, *)) {
  476. return true;
  477. }
  478. return _inFolder;
  479. }
  480. - (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath
  481. {
  482. if (@available(iOS 11.0, *)) {
  483. return true;
  484. }
  485. return _inFolder;
  486. }
  487. - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  488. {
  489. cell.backgroundColor = (indexPath.row % 2 == 0)? [UIColor blackColor]: [UIColor VLCDarkBackgroundColor];
  490. cell.multipleSelectionBackgroundView.backgroundColor = cell.backgroundColor;
  491. }
  492. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  493. {
  494. if (editingStyle == UITableViewCellEditingStyleDelete) {
  495. NSInteger row = indexPath.row;
  496. _deleteFromTableView = YES;
  497. if (row < [_mediaDataSource numberOfFiles])
  498. [self deleteSelection:indexPath];
  499. }
  500. }
  501. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
  502. {
  503. if (tableView.isEditing) {
  504. [self updateActionBarButtonItemStateWithSelectedIndexPaths:[tableView indexPathsForSelectedRows]];
  505. }
  506. }
  507. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  508. {
  509. VLCPlaylistTableViewCell *playlistTableViewCell = (VLCPlaylistTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
  510. if ([playlistTableViewCell isExpanded]) {
  511. [playlistTableViewCell collapsWithAnimation:YES];
  512. return;
  513. }
  514. for (VLCPlaylistTableViewCell *cell in [tableView visibleCells]) {
  515. if ([cell isExpanded])
  516. [cell collapsWithAnimation:NO];
  517. }
  518. if (tableView.isEditing) {
  519. if (_libraryMode == VLCLibraryModeCreateFolder) {
  520. _folderObject = [_mediaDataSource objectAtIndex:indexPath.row];
  521. _libraryMode = _previousLibraryMode;
  522. [self updateViewContents];
  523. [self createFolderWithName:nil];
  524. } else {
  525. [self updateActionBarButtonItemStateWithSelectedIndexPaths:[tableView indexPathsForSelectedRows]];
  526. }
  527. return;
  528. }
  529. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  530. [self openMediaObject:playlistTableViewCell.mediaObject];
  531. }
  532. #pragma mark - Gesture Action
  533. - (void)swipeRightOnTableViewCellGestureAction:(UIGestureRecognizer *)recognizer
  534. {
  535. [self setEditing:!self.tableView.isEditing animated:YES];
  536. if (!self.tableView.isEditing) {
  537. NSIndexPath *path = [self.tableView indexPathForRowAtPoint:[recognizer locationInView:self.tableView]];
  538. [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:path.row inSection:path.section]
  539. animated:YES
  540. scrollPosition:UITableViewScrollPositionNone];
  541. [self updateActionBarButtonItemStateWithSelectedIndexPaths:[self.tableView indexPathsForSelectedRows]];
  542. }
  543. }
  544. - (void)swipeRightOnCollectionViewCellGestureAction:(UIGestureRecognizer *)recognizer
  545. {
  546. NSIndexPath *path = [self.collectionView indexPathForItemAtPoint:[recognizer locationInView:self.collectionView]];
  547. VLCPlaylistCollectionViewCell *cell = (VLCPlaylistCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:path];
  548. [cell showMetadata:!cell.showsMetaData];
  549. }
  550. #pragma mark - Collection View
  551. - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
  552. {
  553. return [_mediaDataSource numberOfFiles];
  554. }
  555. - (UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
  556. {
  557. VLCPlaylistCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:VLCPlaylistCollectionViewCell.cellIdentifier forIndexPath:indexPath];
  558. cell.mediaObject = [_mediaDataSource objectAtIndex:indexPath.row];
  559. cell.collectionView = _collectionView;
  560. [cell setEditing:self.editing animated:NO];
  561. UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRightOnCollectionViewCellGestureAction:)];
  562. [swipeRight setDirection:(UISwipeGestureRecognizerDirectionRight)];
  563. [cell addGestureRecognizer:swipeRight];
  564. return cell;
  565. }
  566. - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
  567. {
  568. const CGFloat maxCellWidth = [UIScreen mainScreen].bounds.size.width / 3;
  569. const CGFloat aspectRatio = 9.0/16.0;
  570. CGRect windowFrame = [UIApplication sharedApplication].keyWindow.frame;
  571. CGFloat windowWidth = windowFrame.size.width;
  572. int numberOfCellsPerRow = ceil(windowWidth/maxCellWidth);
  573. CGFloat cellWidth = windowWidth/numberOfCellsPerRow;
  574. cellWidth -= 5;
  575. return CGSizeMake(cellWidth, cellWidth * aspectRatio);
  576. }
  577. - (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
  578. {
  579. return UIEdgeInsetsMake(5, 5, 5, 5);
  580. }
  581. - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
  582. {
  583. return 2.5;
  584. }
  585. - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
  586. {
  587. return 0.;
  588. }
  589. - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
  590. {
  591. if (self.editing) {
  592. if (_libraryMode == VLCLibraryModeCreateFolder) {
  593. _folderObject = [_mediaDataSource objectAtIndex:indexPath.item];
  594. [self updateViewContents];
  595. [self createFolderWithName:nil];
  596. _libraryMode = _previousLibraryMode;
  597. } else {
  598. [self updateActionBarButtonItemStateWithSelectedIndexPaths:[collectionView indexPathsForSelectedItems]];
  599. }
  600. [(VLCPlaylistCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath] selectionUpdate];
  601. return;
  602. }
  603. [collectionView deselectItemAtIndexPath:indexPath animated:NO];
  604. NSArray *visibleCells = [[collectionView visibleCells] copy];
  605. NSUInteger cellCount = visibleCells.count;
  606. for (NSUInteger x = 0; x < cellCount; x++) {
  607. VLCPlaylistCollectionViewCell *cell = visibleCells[x];
  608. if ([cell showsMetaData])
  609. [cell showMetadata:NO];
  610. }
  611. NSManagedObject *selectedObject = [_mediaDataSource objectAtIndex:indexPath.row];
  612. if (selectedObject != nil)
  613. [self openMediaObject:selectedObject];
  614. }
  615. - (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
  616. {
  617. if (self.editing) {
  618. [self updateActionBarButtonItemStateWithSelectedIndexPaths:[collectionView indexPathsForSelectedItems]];
  619. }
  620. [(VLCPlaylistCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath] selectionUpdate];
  621. }
  622. - (void)collectionView:(UICollectionView *)collectionView removeItemFromFolderAtIndexPathIfNeeded:(NSIndexPath *)indexPath
  623. {
  624. id mediaObject = [_mediaDataSource objectAtIndex:indexPath.item];
  625. [_mediaDataSource removeMediaObjectFromFolder:mediaObject];
  626. [self backToAllItems:nil];
  627. }
  628. - (void)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)fromIndexPath willMoveToIndexPath:(NSIndexPath *)toIndexPath
  629. {
  630. [_mediaDataSource moveObjectFromIndex:fromIndexPath.item toIndex:toIndexPath.item];
  631. }
  632. - (BOOL)collectionView:(UICollectionView *)collectionView shouldSpringLoadItemAtIndexPath:(NSIndexPath *)indexPath withContext:(id<UISpringLoadedInteractionContext>)context NS_AVAILABLE_IOS(11.0)
  633. {
  634. id mediaObject = [_mediaDataSource objectAtIndex:indexPath.item];
  635. return [mediaObject isKindOfClass:[MLLabel class]];
  636. }
  637. - (void)collectionView:(UICollectionView *)collectionView requestToMoveItemAtIndexPath:(NSIndexPath *)itemPath intoFolderAtIndexPath:(NSIndexPath *)folderPath
  638. {
  639. id folderPathItem = [_mediaDataSource objectAtIndex:folderPath.item];
  640. id itemPathItem = [_mediaDataSource objectAtIndex:itemPath.item];
  641. BOOL validFileTypeAtFolderPath = ([folderPathItem isKindOfClass:[MLFile class]] || [folderPathItem isKindOfClass:[MLLabel class]]) && [itemPathItem isKindOfClass:[MLFile class]];
  642. if (!validFileTypeAtFolderPath) {
  643. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"FOLDER_INVALID_TYPE_TITLE", nil) message:NSLocalizedString(@"FOLDER_INVALID_TYPE_MESSAGE", nil) cancelButtonTitle:nil otherButtonTitles:@[NSLocalizedString(@"BUTTON_OK", nil)]];
  644. alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
  645. [self updateViewContents];
  646. };
  647. [alert show];
  648. return;
  649. }
  650. BOOL isFolder = [folderPathItem isKindOfClass:[MLLabel class]];
  651. if (isFolder){
  652. MLLabel *folder = folderPathItem;
  653. MLFile *file = itemPathItem;
  654. [file setLabels:[[NSSet alloc] initWithObjects:folder, nil]];
  655. file.folderTrackNumber = @([folder.files count] - 1);
  656. [_mediaDataSource removeObjectAtIndex:itemPath.item];
  657. [self updateViewContents];
  658. } else {
  659. _folderObject = folderPathItem;
  660. _indexPaths = [NSMutableArray arrayWithArray:@[itemPath]];
  661. [self showCreateFolderAlert];
  662. }
  663. }
  664. #pragma mark - collection/tableView helper
  665. - (NSArray *)selectedIndexPaths
  666. {
  667. NSArray *indexPaths;
  668. if (self.usingTableViewToShowData)
  669. indexPaths = [self.tableView indexPathsForSelectedRows];
  670. else
  671. indexPaths = [self.collectionView indexPathsForSelectedItems];
  672. return indexPaths ?: [NSArray array];
  673. }
  674. #pragma mark - Folder implementation
  675. - (void)showCreateFolderAlert
  676. {
  677. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"FOLDER_CHOOSE_NAME_TITLE", nil) message:NSLocalizedString(@"FOLDER_CHOOSE_NAME_MESSAGE", nil) cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil) otherButtonTitles:@[NSLocalizedString(@"BUTTON_SAVE", nil)]];
  678. [alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
  679. UITextField *zeroTextField = [alert textFieldAtIndex:0];
  680. [zeroTextField setText:NSLocalizedString(@"FOLDER_NAME_PLACEHOLDER", nil)];
  681. [zeroTextField setClearButtonMode:UITextFieldViewModeAlways];
  682. __weak VLCAlertView *weakAlert = alert;
  683. alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
  684. if (cancelled)
  685. [self updateViewContents];
  686. else
  687. [self createFolderWithName:[weakAlert textFieldAtIndex:0].text];
  688. };
  689. [alert show];
  690. }
  691. - (void)createFolder
  692. {
  693. if (_libraryMode == VLCLibraryModeCreateFolder) {
  694. _libraryMode = _previousLibraryMode;
  695. [self updateViewContents];
  696. [self showCreateFolderAlert];
  697. return;
  698. }
  699. _indexPaths = [NSMutableArray arrayWithArray:[self selectedIndexPaths]];
  700. for (NSInteger i = _indexPaths.count - 1; i >=0; i--) {
  701. NSIndexPath *path = _indexPaths[i];
  702. id mediaObject = [_mediaDataSource objectAtIndex:path.row];
  703. if ([mediaObject isKindOfClass:[MLLabel class]])
  704. [_indexPaths removeObject:path];
  705. }
  706. if ([_indexPaths count] != 0) {
  707. NSArray *folder = [MLLabel allLabels];
  708. //if we already have folders display them
  709. if ([folder count] > 0) {
  710. [_mediaDataSource updateContentsForSelection:nil];
  711. [_mediaDataSource addAllFolders];
  712. self.title = NSLocalizedString(@"SELECT_FOLDER", nil);
  713. _previousLibraryMode = _libraryMode;
  714. _libraryMode = VLCLibraryModeCreateFolder;
  715. [self reloadViews];
  716. return;
  717. }
  718. }
  719. //no selected items or no existing folder ask for foldername
  720. [self showCreateFolderAlert];
  721. }
  722. - (void)removeFromFolder
  723. {
  724. _indexPaths = [NSMutableArray arrayWithArray:[self selectedIndexPaths]];
  725. [_indexPaths sortUsingSelector:@selector(compare:)];
  726. for (NSInteger i = [_indexPaths count] - 1; i >= 0; i--) {
  727. NSIndexPath *path = _indexPaths[i];
  728. id item = [_mediaDataSource objectAtIndex:path.row];
  729. [_mediaDataSource removeMediaObjectFromFolder:item];
  730. [_mediaDataSource removeObjectAtIndex:path.row];
  731. }
  732. [self reloadViews];
  733. }
  734. - (void)createFolderWithName:(NSString *)folderName
  735. {
  736. NSArray *labels = [MLLabel allLabels];
  737. for (MLLabel *label in labels){
  738. if ([label.name isEqualToString:folderName]) {
  739. _folderObject = nil;
  740. _indexPaths = nil;
  741. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"FOLDER_NAME_DUPLICATE_TITLE", nil) message:NSLocalizedString(@"FOLDER_NAME_DUPLICATE_MESSAGE", nil) cancelButtonTitle:nil otherButtonTitles:@[NSLocalizedString(@"BUTTON_OK", nil)]];
  742. alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
  743. [self updateViewContents];
  744. };
  745. [alert show];
  746. return;
  747. }
  748. }
  749. if (_folderObject != nil) {
  750. id mediaObject;
  751. NSUInteger folderIndex = [_mediaDataSource indexOfObject:_folderObject];
  752. if (folderIndex != NSNotFound) {
  753. mediaObject = [_mediaDataSource objectAtIndex:folderIndex];
  754. }
  755. //item got dragged onto item
  756. if ([mediaObject isKindOfClass:[MLFile class]]) {
  757. MLFile *file = (MLFile *)mediaObject;
  758. MLLabel *label = [[MLMediaLibrary sharedMediaLibrary] createObjectForEntity:@"Label"];
  759. label.name = folderName;
  760. file.labels = [NSSet setWithObjects:label,nil];
  761. NSNumber *folderTrackNumber = [NSNumber numberWithInt:(int)[label files].count - 1];
  762. file.folderTrackNumber = folderTrackNumber;
  763. [_mediaDataSource removeObjectAtIndex:folderIndex];
  764. [_mediaDataSource insertObject:label atIndex:folderIndex];
  765. id item = [_mediaDataSource objectAtIndex:((NSIndexPath *)_indexPaths[0]).item];
  766. if (![item isKindOfClass:[MLFile class]])
  767. return;
  768. MLFile *itemFile = (MLFile *)item;
  769. itemFile.labels = file.labels;
  770. [_mediaDataSource removeObjectAtIndex:((NSIndexPath *)_indexPaths[0]).item];
  771. itemFile.folderTrackNumber = @([label files].count - 1);
  772. } else {
  773. //item got dragged onto folder or items should be added to folder
  774. id label = [_mediaDataSource objectAtIndex:folderIndex];
  775. if (![label isKindOfClass:[MLLabel class]])
  776. return;
  777. [_indexPaths sortUsingSelector:@selector(compare:)];
  778. NSUInteger count = [_mediaDataSource numberOfFiles];
  779. for (NSInteger i = [_indexPaths count] - 1; i >= 0; i--) {
  780. NSIndexPath *path = _indexPaths[i];
  781. if (path.row >= count)
  782. continue;
  783. id object = [_mediaDataSource objectAtIndex:path.row];
  784. if (_libraryMode != VLCLibraryModeCreateFolder && ![object isKindOfClass:[MLFile class]])
  785. continue;
  786. if (_libraryMode == VLCLibraryModeCreateFolder)
  787. [self updateViewContents];
  788. id item = [_mediaDataSource objectAtIndex:path.row];
  789. if (![item isKindOfClass:[MLFile class]])
  790. continue;
  791. MLFile *file = (MLFile *)item;
  792. file.labels = [NSSet setWithObjects:label, nil];
  793. [_mediaDataSource removeObjectAtIndex:path.row];
  794. file.folderTrackNumber = @([label files].count - 1);
  795. }
  796. }
  797. _folderObject = nil;
  798. } else {
  799. //create new folder
  800. MLLabel *label = [[MLMediaLibrary sharedMediaLibrary] createObjectForEntity:@"Label"];
  801. label.name = folderName;
  802. //if items were selected
  803. if ([_indexPaths count] != 0) {
  804. [_indexPaths sortUsingSelector:@selector(compare:)];
  805. for (NSInteger i = [_indexPaths count] - 1; i >= 0; i--) {
  806. NSIndexPath *path = _indexPaths[i];
  807. NSUInteger index = self.usingTableViewToShowData ? path.row : path.item;
  808. if (index < [_mediaDataSource numberOfFiles]) {
  809. id item = [_mediaDataSource objectAtIndex:index];
  810. if (![item isKindOfClass:[MLFile class]])
  811. continue;
  812. MLFile *file = (MLFile *)item;
  813. file.labels = [NSSet setWithObjects:label, nil];
  814. file.folderTrackNumber = @([label files].count - 1);
  815. [_mediaDataSource removeObjectAtIndex:index];
  816. }
  817. }
  818. }
  819. }
  820. _indexPaths = nil;
  821. [self setEditing:NO];
  822. [self updateViewContents];
  823. }
  824. - (void)_collectionViewHandleLongPressGesture:(UIGestureRecognizer *) sender
  825. {
  826. if (sender.state == UIGestureRecognizerStateBegan && !self.isEditing)
  827. [self setEditing:YES animated:YES];
  828. }
  829. #pragma mark - UI implementation
  830. - (void)handleSelection
  831. {
  832. if (self.usingTableViewToShowData) {
  833. NSInteger numberOfSections = [self.tableView numberOfSections];
  834. for (NSInteger section = 0; section < numberOfSections; section++) {
  835. NSInteger numberOfRowInSection = [self.tableView numberOfRowsInSection:section];
  836. for (NSInteger row = 0; row < numberOfRowInSection; row++) {
  837. if (!_isSelected)
  838. [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:section] animated:NO scrollPosition:UITableViewScrollPositionNone];
  839. else
  840. [self.tableView deselectRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:section] animated:NO];
  841. }
  842. }
  843. } else {
  844. NSInteger numberOfItems = [self.collectionView numberOfItemsInSection:0];
  845. for (NSInteger item = 0; item < numberOfItems; item++) {
  846. NSIndexPath *indexPath = [NSIndexPath indexPathForRow:item inSection:0];
  847. if (!_isSelected)
  848. [self.collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
  849. else
  850. [self.collectionView deselectItemAtIndexPath:indexPath animated:NO];
  851. [(VLCPlaylistCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath] selectionUpdate];
  852. }
  853. }
  854. _isSelected = !_isSelected;
  855. }
  856. - (void)setEditing:(BOOL)editing animated:(BOOL)animated
  857. {
  858. [super setEditing:editing animated:animated];
  859. _isSelected = NO;
  860. UIBarButtonItem *editButton = self.editButtonItem;
  861. editButton.tintColor = [UIColor whiteColor];
  862. if (!editing && self.navigationItem.rightBarButtonItems.lastObject == _selectAllBarButtonItem)
  863. [self.navigationItem setRightBarButtonItems: [self.navigationItem.rightBarButtonItems subarrayWithRange:NSMakeRange(0, self.navigationItem.rightBarButtonItems.count - 1)]];
  864. else
  865. [self.navigationItem setRightBarButtonItems:editing ? [self.navigationItem.rightBarButtonItems arrayByAddingObject:_selectAllBarButtonItem] : [self.navigationItem rightBarButtonItems] animated:YES];
  866. [self setSearchBar:!editing resetContent:!editing];
  867. self.tableView.allowsMultipleSelectionDuringEditing = editing;
  868. [self.tableView setEditing:editing animated:YES];
  869. NSArray *visibleCells = self.collectionView.visibleCells;
  870. [visibleCells enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  871. VLCPlaylistCollectionViewCell *aCell = (VLCPlaylistCollectionViewCell*)obj;
  872. [aCell setEditing:editing animated:animated];
  873. }];
  874. self.collectionView.allowsMultipleSelection = editing;
  875. /* UIKit doesn't clear the selection automagically if we leave the editing mode
  876. * so we need to do so manually */
  877. if (!editing) {
  878. [self.collectionView addGestureRecognizer:_longPressGestureRecognizer];
  879. NSArray *selectedItems = [self.collectionView indexPathsForSelectedItems];
  880. NSUInteger count = selectedItems.count;
  881. for (NSUInteger x = 0; x < count; x++)
  882. [self.collectionView deselectItemAtIndexPath:selectedItems[x] animated:NO];
  883. } else
  884. [self.collectionView removeGestureRecognizer:_longPressGestureRecognizer];
  885. if (_libraryMode == VLCLibraryModeCreateFolder) {
  886. _libraryMode = _previousLibraryMode;
  887. _indexPaths = nil;
  888. [self updateViewContents];
  889. }
  890. [self.navigationController setToolbarHidden:!editing animated:YES];
  891. [UIView performWithoutAnimation:^{
  892. [editButton setTitle:editing ? NSLocalizedString(@"BUTTON_CANCEL", nil) : NSLocalizedString(@"BUTTON_EDIT", nil)];
  893. }];
  894. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  895. NSMutableArray *rightBarButtonItems = [self.navigationItem.rightBarButtonItems mutableCopy];
  896. UIBarButtonItem *toggleDisplayedView = rightBarButtonItems[0];
  897. toggleDisplayedView.enabled = !editing;
  898. rightBarButtonItems[0] = toggleDisplayedView;
  899. self.navigationItem.rightBarButtonItems = rightBarButtonItems;
  900. }
  901. }
  902. - (void)toggleDisplayedView:(UIBarButtonItem *)button
  903. {
  904. self.usingTableViewToShowData = !self.usingTableViewToShowData;
  905. UIImage *newButtonImage = [UIImage imageNamed: self.usingTableViewToShowData ? @"collectionViewIcon" : @"tableViewIcon"];
  906. [button setImage:newButtonImage];
  907. [self updateViewsForCurrentDisplayMode];
  908. }
  909. - (UITableViewCellEditingStyle)tableView:(UITableView *)aTableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
  910. {
  911. return UITableViewCellEditingStyleDelete;
  912. }
  913. - (IBAction)leftButtonAction:(id)sender
  914. {
  915. if (self.isEditing)
  916. [self setEditing:NO animated:YES];
  917. }
  918. - (IBAction)backToAllItems:(id)sender
  919. {
  920. _inFolder = NO;
  921. NSMutableArray *toolbarItems = [self.toolbarItems mutableCopy];
  922. toolbarItems[2] = _createFolderBarButtonItem;
  923. self.toolbarItems = toolbarItems;
  924. [self setLibraryMode:_previousLibraryMode];
  925. if (!self.isEditing) {
  926. [self setSearchBar:YES resetContent:NO];
  927. }
  928. [self updateViewContents];
  929. }
  930. - (void)_endEditingWithHardReset:(BOOL)hardReset
  931. {
  932. [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
  933. if (hardReset)
  934. [self updateViewContents];
  935. else
  936. [self reloadViews];
  937. [self setEditing:NO animated:YES];
  938. }
  939. - (void)deleteSelection:(id)sender
  940. {
  941. NSArray *indexPaths = [self usingTableViewToShowData] ? [self.tableView indexPathsForSelectedRows] : [self.collectionView indexPathsForSelectedItems];
  942. if ((!indexPaths || [indexPaths count] == 0) && !_deleteFromTableView) {
  943. UIAlertController *invalidSelection = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"DELETE_INVALID_TITLE", nil) message:NSLocalizedString(@"DELETE_INVALID_MESSAGE", nil) preferredStyle:UIAlertControllerStyleAlert];
  944. UIAlertAction *doneAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"BUTTON_OK", nil) style:UIAlertActionStyleDefault handler:nil];
  945. [invalidSelection addAction:doneAction];
  946. [self presentViewController:invalidSelection animated:YES completion:nil];
  947. } else {
  948. UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"DELETE_TITLE", nil) message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  949. UIAlertAction *deleteAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"BUTTON_DELETE", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
  950. if (_deleteFromTableView) {
  951. NSIndexPath *indexPath = (NSIndexPath *)sender;
  952. if (indexPath && indexPath.row < [_mediaDataSource numberOfFiles])
  953. [self removeMediaObject:[_mediaDataSource objectAtIndex:indexPath.row] updateDatabase:YES];
  954. } else
  955. [self deletionAfterConfirmation];
  956. _deleteFromTableView = NO;
  957. }];
  958. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"BUTTON_CANCEL", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  959. _deleteFromTableView ? [self setEditing:NO animated:YES] : [self reloadViews];
  960. _deleteFromTableView = NO;
  961. }];
  962. [alert addAction:deleteAction];
  963. [alert addAction:cancelAction];
  964. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  965. CGRect tmpBounds = self.view.bounds;
  966. [alert setTitle:NSLocalizedString(@"DELETE_TITLE", nil)];
  967. [alert setMessage:NSLocalizedString(@"DELETE_MESSAGE", nil)];
  968. [alert.popoverPresentationController setPermittedArrowDirections:0];
  969. [alert.popoverPresentationController setSourceView:self.view];
  970. [alert.popoverPresentationController setSourceRect:CGRectMake(tmpBounds.size.width / 2.0, tmpBounds.size.height / 2.0, 1.0, 1.0)];
  971. }
  972. [self presentViewController:alert animated:YES completion:nil];
  973. }
  974. }
  975. - (void)deletionAfterConfirmation
  976. {
  977. NSArray *indexPaths;
  978. if (self.usingTableViewToShowData) {
  979. indexPaths = [self.tableView indexPathsForSelectedRows];
  980. } else {
  981. indexPaths = [self.collectionView indexPathsForSelectedItems];
  982. }
  983. NSMutableArray *objects = [[NSMutableArray alloc] initWithCapacity:indexPaths.count];
  984. for (NSIndexPath *indexPath in indexPaths)
  985. [objects addObject:[_mediaDataSource objectAtIndex:indexPath.row]];
  986. for (id object in objects)
  987. [self removeMediaObject:object updateDatabase:NO];
  988. [self _endEditingWithHardReset:YES];
  989. }
  990. - (void)renameSelection
  991. {
  992. NSArray *indexPaths = [self selectedIndexPaths];
  993. if (indexPaths.count < 1) {
  994. [self _endEditingWithHardReset:NO];
  995. return;
  996. }
  997. NSString *itemName;
  998. if (self.usingTableViewToShowData)
  999. itemName = [(VLCPlaylistTableViewCell *)[self.tableView cellForRowAtIndexPath:indexPaths[0]] titleLabel].text;
  1000. else
  1001. itemName = [(VLCPlaylistCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPaths[0]] titleLabel].text;
  1002. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:[NSString stringWithFormat:NSLocalizedString(@"RENAME_MEDIA_TO", nil), itemName] message:nil cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil) otherButtonTitles:@[NSLocalizedString(@"BUTTON_RENAME", nil)]];
  1003. [alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
  1004. [[alert textFieldAtIndex:0] setText:itemName];
  1005. [[alert textFieldAtIndex:0] setClearButtonMode:UITextFieldViewModeAlways];
  1006. __weak VLCAlertView *weakAlert = alert;
  1007. alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
  1008. if (cancelled)
  1009. [self _endEditingWithHardReset:NO];
  1010. else
  1011. [self renameMediaObjectTo:[weakAlert textFieldAtIndex:0].text];
  1012. };
  1013. [alert show];
  1014. }
  1015. - (void)renameMediaObjectTo:(NSString*)newName
  1016. {
  1017. NSArray *indexPaths = [self selectedIndexPaths];
  1018. if (indexPaths.count < 1)
  1019. return;
  1020. NSUInteger row = [indexPaths[0] row];
  1021. id mediaObject = [_mediaDataSource objectAtIndex:row];
  1022. if (!mediaObject) return;
  1023. if ([mediaObject isKindOfClass:[MLAlbum class]] || [mediaObject isKindOfClass:[MLShowEpisode class]] || [mediaObject isKindOfClass:[MLShow class]] || [mediaObject isKindOfClass:[MLLabel class]] )
  1024. [mediaObject setName:newName];
  1025. else
  1026. [mediaObject setTitle:newName];
  1027. if (self.usingTableViewToShowData)
  1028. [self.tableView deselectRowAtIndexPath:indexPaths[0] animated:YES];
  1029. else
  1030. [self.collectionView deselectItemAtIndexPath:indexPaths[0] animated:YES];
  1031. if (indexPaths.count > 1)
  1032. [self renameSelection];
  1033. else
  1034. [self _endEditingWithHardReset:NO];
  1035. }
  1036. - (void)updateViewsForCurrentDisplayMode
  1037. {
  1038. UIImage *newButtonImage = [UIImage imageNamed: self.usingTableViewToShowData ? @"collectionViewIcon" : @"tableViewIcon"];
  1039. [self.displayModeBarButtonItem setImage:newButtonImage];
  1040. }
  1041. #pragma mark - Sharing
  1042. // We take the array of index paths (instead of a count) to actually examine if the content is shareable. Selecting a single folder should not enable the share button.
  1043. - (void)updateActionBarButtonItemStateWithSelectedIndexPaths:(NSArray *)indexPaths
  1044. {
  1045. NSUInteger count = [indexPaths count];
  1046. if (!indexPaths || count == 0) {
  1047. _shareBarButtonItem.enabled = NO;
  1048. } else {
  1049. // Look for at least one MLFile
  1050. for (NSIndexPath *indexPath in indexPaths) {
  1051. id mediaItem = [_mediaDataSource objectAtIndex:[indexPath row]];
  1052. if ([mediaItem isKindOfClass:[MLFile class]] || [mediaItem isKindOfClass:[MLAlbumTrack class]] | [mediaItem isKindOfClass:[MLShowEpisode class]]) {
  1053. _shareBarButtonItem.enabled = YES;
  1054. return;
  1055. }
  1056. }
  1057. }
  1058. }
  1059. - (NSArray *)fileURLsFromSelection
  1060. {
  1061. NSArray *indexPaths = [self selectedIndexPaths];
  1062. if (indexPaths.count == 0) return nil;
  1063. NSMutableArray<NSURL*> *fileURLObjects = [[NSMutableArray alloc] initWithCapacity:indexPaths.count];
  1064. for (NSIndexPath *indexpath in indexPaths) {
  1065. id mediaItem = [_mediaDataSource objectAtIndex:[indexpath row]];
  1066. NSURL *fileURL;
  1067. if ([mediaItem isKindOfClass:[MLFile class]]) {
  1068. fileURL = [(MLFile *) mediaItem url];
  1069. } else if ([mediaItem isKindOfClass:[MLAlbumTrack class]]) {
  1070. fileURL = [[(MLAlbumTrack *) mediaItem anyFileFromTrack] url];
  1071. } else if ([mediaItem isKindOfClass:[MLShowEpisode class]]) {
  1072. fileURL = [[(MLShowEpisode *) mediaItem anyFileFromEpisode] url];
  1073. }
  1074. if ([fileURL isFileURL]) {
  1075. [fileURLObjects addObject:fileURL];
  1076. }
  1077. }
  1078. return [fileURLObjects copy];
  1079. }
  1080. - (void)share:(UIBarButtonItem *)barButtonItem
  1081. {
  1082. NSParameterAssert(barButtonItem);
  1083. if (!barButtonItem) {
  1084. APLog(@"Missing a UIBarButtonItem to present from");
  1085. return;
  1086. }
  1087. //disable any possible changes to selection (or exit from this screen)
  1088. [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
  1089. UIActivityViewController *controller = [VLCActivityViewControllerVendor activityViewControllerForFiles:[self fileURLsFromSelection] presentingButton:barButtonItem presentingViewController:self];
  1090. if (!controller) {
  1091. [[UIApplication sharedApplication] endIgnoringInteractionEvents];
  1092. } else {
  1093. controller.popoverPresentationController.sourceView = self.navigationController.toolbar;
  1094. [self.navigationController presentViewController:controller animated:YES completion:^{
  1095. [[UIApplication sharedApplication] endIgnoringInteractionEvents];
  1096. }];
  1097. }
  1098. }
  1099. #pragma mark - properties
  1100. - (void)setLibraryMode:(VLCLibraryMode)mode
  1101. {
  1102. _libraryMode = mode;
  1103. [self updateViewContents];
  1104. if (mode == VLCLibraryModeAllAlbums ||
  1105. mode == VLCLibraryModeAllSeries ||
  1106. mode == VLCLibraryModeAllFiles) {
  1107. _previousLibraryMode = mode;
  1108. }
  1109. }
  1110. - (BOOL)usingTableViewToShowData
  1111. {
  1112. return [[NSUserDefaults standardUserDefaults] boolForKey:kUsingTableViewToShowData];
  1113. }
  1114. - (void)setUsingTableViewToShowData:(BOOL)usingTableViewToShowData
  1115. {
  1116. [[NSUserDefaults standardUserDefaults] setBool:usingTableViewToShowData forKey:kUsingTableViewToShowData];
  1117. [self updateViewsForCurrentDisplayMode];
  1118. [self setupContentView];
  1119. }
  1120. #pragma mark - autorotation
  1121. // RootController is responsible for supporting interface orientation(iOS6.0+), i.e. navigation controller
  1122. // so this will not work as intended without "voodoo magic"(UINavigationController category, subclassing, etc)
  1123. /* introduced in iOS 6 */
  1124. - (UIInterfaceOrientationMask)supportedInterfaceOrientations
  1125. {
  1126. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1127. return UIInterfaceOrientationMaskAll;
  1128. return ([_mediaDataSource numberOfFiles] > 0)? UIInterfaceOrientationMaskAllButUpsideDown:
  1129. UIInterfaceOrientationMaskPortrait;
  1130. }
  1131. /* introduced in iOS 6 */
  1132. - (BOOL)shouldAutorotate
  1133. {
  1134. return (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) || ([_mediaDataSource numberOfFiles] > 0);
  1135. }
  1136. - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
  1137. {
  1138. [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
  1139. [self setViewFromDeviceOrientation];
  1140. NSArray *visibleCells = [self.tableView visibleCells];
  1141. NSUInteger cellCount = visibleCells.count;
  1142. for (NSUInteger x = 0; x < cellCount; x++) {
  1143. if ([visibleCells[x] isExpanded])
  1144. [visibleCells[x] metaDataLabel].hidden = YES;
  1145. }
  1146. [self.collectionView.collectionViewLayout invalidateLayout];
  1147. }
  1148. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  1149. {
  1150. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  1151. [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) {
  1152. [self setViewFromDeviceOrientation];
  1153. [self.collectionView.collectionViewLayout invalidateLayout];
  1154. } completion:nil];
  1155. }
  1156. #pragma mark - UIScrollViewDelegate
  1157. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  1158. {
  1159. if ([_searchController.searchBar isFirstResponder])
  1160. [_searchController.searchBar resignFirstResponder];
  1161. }
  1162. #pragma mark - SearchController Delegate
  1163. - (void)didPresentSearchController:(UISearchController *)searchController
  1164. {
  1165. _tableView.dataSource = _searchDataSource;
  1166. }
  1167. - (void)didDismissSearchController:(UISearchController *)searchController
  1168. {
  1169. _tableView.dataSource = self;
  1170. }
  1171. #pragma mark - Search Research Updater
  1172. - (void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1173. {
  1174. [_searchDataSource shouldReloadTableForSearchString:searchController.searchBar.text searchableFiles:[_mediaDataSource allObjects]];
  1175. [_tableView reloadData];
  1176. }
  1177. #pragma mark - handoff
  1178. - (void)restoreUserActivityState:(NSUserActivity *)activity
  1179. {
  1180. NSString *userActivityType = activity.activityType;
  1181. if([userActivityType isEqualToString:kVLCUserActivityLibraryMode] ||
  1182. [userActivityType isEqualToString:kVLCUserActivityLibrarySelection]) {
  1183. NSDictionary *dict = activity.userInfo;
  1184. NSString *folderPath = dict[@"folder"];
  1185. if (!folderPath) return;
  1186. NSURL *folderURL = [NSURL URLWithString:folderPath];
  1187. NSUInteger count = [_mediaDataSource numberOfFiles];
  1188. for (NSUInteger i = 0; i < count; i++) {
  1189. NSManagedObject *object = [_mediaDataSource objectAtIndex:i];
  1190. if([object.objectID.URIRepresentation isEqual:folderURL]) {
  1191. [self tableView:self.tableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
  1192. }
  1193. }
  1194. }
  1195. }
  1196. @end