VLCLibraryViewController.m 60 KB

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