VLCLibraryViewController.m 59 KB

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