VLCPlaylistViewController.m 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  1. /*****************************************************************************
  2. * VLCPlaylistViewController.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2013 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. *
  12. * Refer to the COPYING file of the official project for license.
  13. *****************************************************************************/
  14. #import "VLCPlaylistViewController.h"
  15. #import "VLCMovieViewController.h"
  16. #import "VLCPlaylistTableViewCell.h"
  17. #import "VLCPlaylistCollectionViewCell.h"
  18. #import "UINavigationController+Theme.h"
  19. #import "NSString+SupportedMedia.h"
  20. #import "VLCBugreporter.h"
  21. #import "VLCAppDelegate.h"
  22. #import "UIBarButtonItem+Theme.h"
  23. #import "VLCFirstStepsViewController.h"
  24. /* prefs keys */
  25. static NSString *kDisplayedFirstSteps = @"Did we display the first steps tutorial?";
  26. @implementation EmptyLibraryView
  27. - (IBAction)learnMore:(id)sender
  28. {
  29. UIViewController *firstStepsVC = [[VLCFirstStepsViewController alloc] initWithNibName:nil bundle:nil];
  30. UINavigationController *navCon = [[UINavigationController alloc] initWithRootViewController:firstStepsVC];
  31. navCon.modalPresentationStyle = UIModalPresentationFormSheet;
  32. [navCon loadTheme];
  33. [self.window.rootViewController presentViewController:navCon animated:YES completion:nil];
  34. }
  35. @end
  36. @interface VLCPlaylistViewController () <UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UITableViewDataSource, UITableViewDelegate, MLMediaLibrary> {
  37. NSMutableArray *_foundMedia;
  38. VLCLibraryMode _libraryMode;
  39. UIBarButtonItem *_menuButton;
  40. }
  41. @property (nonatomic, strong) UITableView *tableView;
  42. @property (nonatomic, strong) UICollectionView *collectionView;
  43. @property (nonatomic, strong) EmptyLibraryView *emptyLibraryView;
  44. @end
  45. @implementation VLCPlaylistViewController
  46. + (void)initialize
  47. {
  48. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  49. [defaults registerDefaults:@{kDisplayedFirstSteps : [NSNumber numberWithBool:NO]}];
  50. }
  51. - (void)loadView {
  52. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
  53. _tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
  54. _tableView.backgroundColor = [UIColor colorWithWhite:.122 alpha:1.];
  55. _tableView.rowHeight = [VLCPlaylistTableViewCell heightOfCell];
  56. _tableView.separatorColor = [UIColor colorWithWhite:.122 alpha:1.];
  57. _tableView.delegate = self;
  58. _tableView.dataSource = self;
  59. _tableView.opaque = YES;
  60. self.view = _tableView;
  61. if (SYSTEM_RUNS_IOS7_OR_LATER) {
  62. UILongPressGestureRecognizer *gestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(tableViewLongTouchGestureAction:)];
  63. [self.view addGestureRecognizer:gestureRecognizer];
  64. }
  65. } else {
  66. UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
  67. _collectionView = [[UICollectionView alloc] initWithFrame:[UIScreen mainScreen].bounds collectionViewLayout:flowLayout];
  68. _collectionView.alwaysBounceVertical = YES;
  69. _collectionView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
  70. _collectionView.delegate = self;
  71. _collectionView.dataSource = self;
  72. _collectionView.opaque = YES;
  73. _collectionView.backgroundColor = [UIColor colorWithWhite:.122 alpha:1.];
  74. self.view = _collectionView;
  75. if (SYSTEM_RUNS_IOS7_OR_LATER)
  76. [_collectionView registerNib:[UINib nibWithNibName:@"VLCFuturePlaylistCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"PlaylistCell"];
  77. else
  78. [_collectionView registerNib:[UINib nibWithNibName:@"VLCPlaylistCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"PlaylistCell"];
  79. self.view.backgroundColor = [UIColor colorWithWhite:.122 alpha:1.];
  80. }
  81. _libraryMode = VLCLibraryModeAllFiles;
  82. self.view.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
  83. self.emptyLibraryView = [[[NSBundle mainBundle] loadNibNamed:@"VLCEmptyLibraryView" owner:self options:nil] lastObject];
  84. _emptyLibraryView.emptyLibraryLongDescriptionLabel.lineBreakMode = NSLineBreakByWordWrapping;
  85. _emptyLibraryView.emptyLibraryLongDescriptionLabel.numberOfLines = 0;
  86. }
  87. #pragma mark -
  88. - (void)viewDidLoad
  89. {
  90. [super viewDidLoad];
  91. self.title = NSLocalizedString(@"LIBRARY_ALL_FILES", @"");
  92. _menuButton = [UIBarButtonItem themedRevealMenuButtonWithTarget:self andSelector:@selector(leftButtonAction:)];
  93. self.navigationItem.leftBarButtonItem = _menuButton;
  94. if (SYSTEM_RUNS_IOS7_OR_LATER)
  95. self.editButtonItem.tintColor = [UIColor whiteColor];
  96. else {
  97. [self.editButtonItem setBackgroundImage:[UIImage imageNamed:@"button"]
  98. forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
  99. [self.editButtonItem setBackgroundImage:[UIImage imageNamed:@"buttonHighlight"]
  100. forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
  101. }
  102. _emptyLibraryView.emptyLibraryLabel.text = NSLocalizedString(@"EMPTY_LIBRARY", @"");
  103. _emptyLibraryView.emptyLibraryLongDescriptionLabel.text = NSLocalizedString(@"EMPTY_LIBRARY_LONG", @"");
  104. [_emptyLibraryView.emptyLibraryLongDescriptionLabel sizeToFit];
  105. [self setToolbarItems:@[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil], [UIBarButtonItem themedDarkToolbarButtonWithTitle:NSLocalizedString(@"BUTTON_RENAME", @"") target:self andSelector:@selector(renameSelection)], [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil], [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(deleteSelection)]]];
  106. self.navigationController.toolbar.barStyle = UIBarStyleBlack;
  107. if (SYSTEM_RUNS_IOS7_OR_LATER) {
  108. self.navigationController.toolbar.tintColor = [UIColor whiteColor];
  109. [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
  110. } else
  111. [self.navigationController.toolbar setBackgroundImage:[UIImage imageNamed:@"bottomBlackBar"] forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
  112. }
  113. - (void)viewWillAppear:(BOOL)animated
  114. {
  115. [super viewWillAppear:animated];
  116. [self.collectionView.collectionViewLayout invalidateLayout];
  117. [self _displayEmptyLibraryViewIfNeeded];
  118. }
  119. - (void)viewDidAppear:(BOOL)animated
  120. {
  121. [super viewDidAppear:animated];
  122. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  123. if (![[defaults objectForKey:kDisplayedFirstSteps] boolValue]) {
  124. [self.emptyLibraryView performSelector:@selector(learnMore:) withObject:nil afterDelay:1.];
  125. [defaults setObject:[NSNumber numberWithBool:YES] forKey:kDisplayedFirstSteps];
  126. [defaults synchronize];
  127. }
  128. if ([[MLMediaLibrary sharedMediaLibrary] libraryNeedsUpgrade]) {
  129. self.navigationItem.rightBarButtonItem = nil;
  130. self.navigationItem.leftBarButtonItem = nil;
  131. self.title = @"";
  132. self.emptyLibraryView.emptyLibraryLabel.text = NSLocalizedString(@"UPGRADING_LIBRARY", @"");
  133. self.emptyLibraryView.emptyLibraryLongDescriptionLabel.hidden = YES;
  134. [self.emptyLibraryView.activityIndicator startAnimating];
  135. self.emptyLibraryView.frame = self.view.bounds;
  136. [self.view addSubview:self.emptyLibraryView];
  137. [[MLMediaLibrary sharedMediaLibrary] setDelegate: self];
  138. [[MLMediaLibrary sharedMediaLibrary] performSelectorInBackground:@selector(upgradeLibrary) withObject:nil];
  139. return;
  140. }
  141. if (_foundMedia.count < 1)
  142. [self updateViewContents];
  143. [[MLMediaLibrary sharedMediaLibrary] performSelector:@selector(libraryDidAppear) withObject:nil afterDelay:1.];
  144. }
  145. - (void)viewDidDisappear:(BOOL)animated
  146. {
  147. [super viewDidDisappear:animated];
  148. [[MLMediaLibrary sharedMediaLibrary] libraryDidDisappear];
  149. }
  150. - (BOOL)canBecomeFirstResponder
  151. {
  152. return YES;
  153. }
  154. - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
  155. {
  156. if (motion == UIEventSubtypeMotionShake)
  157. [[VLCBugreporter sharedInstance] handleBugreportRequest];
  158. }
  159. - (void)openMediaObject:(NSManagedObject *)mediaObject
  160. {
  161. if ([mediaObject isKindOfClass:[MLAlbum class]]) {
  162. _foundMedia = [NSMutableArray arrayWithArray:[(MLAlbum *)mediaObject sortedTracks]];
  163. self.navigationItem.leftBarButtonItem = [UIBarButtonItem themedBackButtonWithTarget:self andSelector:@selector(backToAllItems:)];
  164. if (_libraryMode == VLCLibraryModeAllFiles)
  165. self.navigationItem.leftBarButtonItem.title = NSLocalizedString(@"BUTTON_BACK", @"");
  166. else
  167. [self.navigationItem.leftBarButtonItem setTitle:NSLocalizedString(@"LIBRARY_MUSIC", @"")];
  168. self.title = [(MLAlbum*)mediaObject name];
  169. [self reloadViews];
  170. } else if ([mediaObject isKindOfClass:[MLShow class]]) {
  171. _foundMedia = [NSMutableArray arrayWithArray:[(MLShow *)mediaObject sortedEpisodes]];
  172. self.navigationItem.leftBarButtonItem = [UIBarButtonItem themedBackButtonWithTarget:self andSelector:@selector(backToAllItems:)];
  173. if (_libraryMode == VLCLibraryModeAllFiles)
  174. self.navigationItem.leftBarButtonItem.title = NSLocalizedString(@"BUTTON_BACK", @"");
  175. else
  176. [self.navigationItem.leftBarButtonItem setTitle:NSLocalizedString(@"LIBRARY_SERIES", @"")];
  177. self.title = [(MLShow*)mediaObject name];
  178. [self reloadViews];
  179. } else
  180. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate openMediaFromManagedObject:mediaObject];
  181. }
  182. - (void)removeMediaObject:(id)managedObject updateDatabase:(BOOL)updateDB
  183. {
  184. // delete all tracks from an album
  185. if ([managedObject isKindOfClass:[MLAlbum class]]) {
  186. MLAlbum *album = managedObject;
  187. NSSet *iterAlbumTrack = [NSSet setWithSet:album.tracks];
  188. for (MLAlbumTrack *track in iterAlbumTrack) {
  189. NSSet *iterFiles = [NSSet setWithSet:track.files];
  190. for (MLFile *file in iterFiles)
  191. [self _deleteMediaObject:file];
  192. }
  193. // delete all episodes from a show
  194. } else if ([managedObject isKindOfClass:[MLShow class]]) {
  195. MLShow *show = managedObject;
  196. NSSet *iterShowEpisodes = [NSSet setWithSet:show.episodes];
  197. for (MLShowEpisode *episode in iterShowEpisodes) {
  198. NSSet *iterFiles = [NSSet setWithSet:episode.files];
  199. for (MLFile *file in iterFiles)
  200. [self _deleteMediaObject:file];
  201. }
  202. // delete all files from an episode
  203. } else if ([managedObject isKindOfClass:[MLShowEpisode class]]) {
  204. MLShowEpisode *episode = managedObject;
  205. NSSet *iterFiles = [NSSet setWithSet:episode.files];
  206. for (MLFile *file in iterFiles)
  207. [self _deleteMediaObject:file];
  208. // delete all files from a track
  209. } else if ([managedObject isKindOfClass:[MLAlbumTrack class]]) {
  210. MLAlbumTrack *track = managedObject;
  211. NSSet *iterFiles = [NSSet setWithSet:track.files];
  212. for (MLFile *file in iterFiles)
  213. [self _deleteMediaObject:file];
  214. } else
  215. [self _deleteMediaObject:managedObject];
  216. if (updateDB) {
  217. [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
  218. [self updateViewContents];
  219. }
  220. }
  221. - (void)_deleteMediaObject:(MLFile *)mediaObject
  222. {
  223. NSFileManager *fileManager = [NSFileManager defaultManager];
  224. NSString *folderLocation = [[[NSURL URLWithString:mediaObject.url] path] stringByDeletingLastPathComponent];
  225. NSArray *allfiles = [fileManager contentsOfDirectoryAtPath:folderLocation error:nil];
  226. NSString *fileName = [[[[NSURL URLWithString:mediaObject.url] path] lastPathComponent] stringByDeletingPathExtension];
  227. NSIndexSet *indexSet = [allfiles indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
  228. return ([obj rangeOfString:fileName].location != NSNotFound);
  229. }];
  230. unsigned int count = indexSet.count;
  231. NSString *additionalFilePath;
  232. NSUInteger currentIndex = [indexSet firstIndex];
  233. for (unsigned int x = 0; x < count; x++) {
  234. additionalFilePath = allfiles[currentIndex];
  235. if ([additionalFilePath isSupportedSubtitleFormat])
  236. [fileManager removeItemAtPath:[folderLocation stringByAppendingPathComponent:additionalFilePath] error:nil];
  237. currentIndex = [indexSet indexGreaterThanIndex:currentIndex];
  238. }
  239. [fileManager removeItemAtPath:[[NSURL URLWithString:mediaObject.url] path] error:nil];
  240. }
  241. - (void)_displayEmptyLibraryViewIfNeeded
  242. {
  243. if (self.emptyLibraryView.superview)
  244. [self.emptyLibraryView removeFromSuperview];
  245. if (_foundMedia.count == 0) {
  246. self.emptyLibraryView.frame = self.view.bounds;
  247. [self.view addSubview:self.emptyLibraryView];
  248. self.navigationItem.rightBarButtonItem = nil;
  249. } else
  250. self.navigationItem.rightBarButtonItem = self.editButtonItem;
  251. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
  252. _tableView.separatorStyle = (_foundMedia.count > 0)? UITableViewCellSeparatorStyleSingleLine:
  253. UITableViewCellSeparatorStyleNone;
  254. } else
  255. [self.collectionView.collectionViewLayout invalidateLayout];
  256. }
  257. - (void)libraryUpgradeComplete
  258. {
  259. self.title = NSLocalizedString(@"LIBRARY_ALL_FILES", @"");
  260. self.navigationItem.leftBarButtonItem = _menuButton;
  261. self.emptyLibraryView.emptyLibraryLongDescriptionLabel.hidden = NO;
  262. self.emptyLibraryView.emptyLibraryLabel.text = NSLocalizedString(@"EMPTY_LIBRARY", @"");
  263. [self.emptyLibraryView.activityIndicator stopAnimating];
  264. [self.emptyLibraryView removeFromSuperview];
  265. [self updateViewContents];
  266. }
  267. - (void)libraryWasUpdated
  268. {
  269. [self updateViewContents];
  270. }
  271. - (void)updateViewContents
  272. {
  273. _foundMedia = [[NSMutableArray alloc] init];
  274. self.navigationItem.leftBarButtonItem = _menuButton;
  275. if (_libraryMode == VLCLibraryModeAllAlbums)
  276. self.title = NSLocalizedString(@"LIBRARY_MUSIC", @"");
  277. else if( _libraryMode == VLCLibraryModeAllSeries)
  278. self.title = NSLocalizedString(@"LIBRARY_SERIES", @"");
  279. else
  280. self.title = NSLocalizedString(@"LIBRARY_ALL_FILES", @"");
  281. /* add all albums */
  282. if (_libraryMode != VLCLibraryModeAllSeries) {
  283. NSArray *rawAlbums = [MLAlbum allAlbums];
  284. for (MLAlbum *album in rawAlbums) {
  285. if (album.name.length > 0 && album.tracks.count > 1)
  286. [_foundMedia addObject:album];
  287. }
  288. }
  289. if (_libraryMode == VLCLibraryModeAllAlbums) {
  290. [self reloadViews];
  291. return;
  292. }
  293. /* add all shows */
  294. NSArray *rawShows = [MLShow allShows];
  295. for (MLShow *show in rawShows) {
  296. if (show.name.length > 0 && show.episodes.count > 1)
  297. [_foundMedia addObject:show];
  298. }
  299. if (_libraryMode == VLCLibraryModeAllSeries) {
  300. [self reloadViews];
  301. return;
  302. }
  303. /* add all remaining files */
  304. NSArray *allFiles = [MLFile allFiles];
  305. for (MLFile *file in allFiles) {
  306. if (!file.isShowEpisode && !file.isAlbumTrack)
  307. [_foundMedia addObject:file];
  308. else if (file.isShowEpisode) {
  309. if (file.showEpisode.show.episodes.count < 2)
  310. [_foundMedia addObject:file];
  311. } else if (file.isAlbumTrack) {
  312. if (file.albumTrack.album.tracks.count < 2)
  313. [_foundMedia addObject:file];
  314. }
  315. }
  316. [self reloadViews];
  317. }
  318. - (void)reloadViews
  319. {
  320. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
  321. [self.tableView reloadData];
  322. else
  323. [self.collectionView reloadData];
  324. [self _displayEmptyLibraryViewIfNeeded];
  325. }
  326. #pragma mark - Table View
  327. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  328. {
  329. return 1;
  330. }
  331. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  332. {
  333. return _foundMedia.count;
  334. }
  335. // Customize the appearance of table view cells.
  336. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  337. {
  338. static NSString *CellIdentifier = @"PlaylistCell";
  339. VLCPlaylistTableViewCell *cell = (VLCPlaylistTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  340. if (cell == nil)
  341. cell = [VLCPlaylistTableViewCell cellWithReuseIdentifier:CellIdentifier];
  342. NSInteger row = indexPath.row;
  343. cell.mediaObject = _foundMedia[row];
  344. return cell;
  345. }
  346. - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  347. {
  348. cell.backgroundColor = (indexPath.row % 2 == 0)? [UIColor blackColor]: [UIColor colorWithWhite:.122 alpha:1.];
  349. cell.multipleSelectionBackgroundView.backgroundColor = cell.backgroundColor;
  350. }
  351. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  352. {
  353. return YES;
  354. }
  355. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  356. {
  357. if (editingStyle == UITableViewCellEditingStyleDelete)
  358. [self removeMediaObject: _foundMedia[indexPath.row] updateDatabase:YES];
  359. }
  360. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  361. {
  362. if (tableView.isEditing)
  363. return;
  364. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  365. NSManagedObject *selectedObject = _foundMedia[indexPath.row];
  366. [self openMediaObject:selectedObject];
  367. }
  368. #pragma mark - table view gestures
  369. - (void)tableViewLongTouchGestureAction:(UIGestureRecognizer *)recognizer
  370. {
  371. NSIndexPath *path = [(UITableView *)self.view indexPathForRowAtPoint:[recognizer locationInView:self.view]];
  372. UITableViewCell *cell = [(UITableView *)self.view cellForRowAtIndexPath:path];
  373. CGRect frame = cell.frame;
  374. if (frame.size.height > 90.)
  375. frame.size.height = 90.;
  376. else if (recognizer.state == UIGestureRecognizerStateBegan)
  377. frame.size.height = 180;
  378. void (^animationBlock)() = ^() {
  379. cell.frame = frame;
  380. };
  381. void (^completionBlock)(BOOL finished) = ^(BOOL finished) {
  382. cell.frame = frame;
  383. [self.tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionNone animated:YES];
  384. };
  385. NSTimeInterval animationDuration = .2;
  386. [UIView animateWithDuration:animationDuration animations:animationBlock completion:completionBlock];
  387. }
  388. #pragma mark - Collection View
  389. - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
  390. {
  391. return _foundMedia.count;
  392. }
  393. - (UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
  394. {
  395. VLCPlaylistCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PlaylistCell" forIndexPath:indexPath];
  396. cell.mediaObject = _foundMedia[indexPath.row];
  397. cell.collectionView = _collectionView;
  398. [cell setEditing:self.editing animated:NO];
  399. return cell;
  400. }
  401. - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
  402. {
  403. if (SYSTEM_RUNS_IOS7_OR_LATER) {
  404. if (UIDeviceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation))
  405. return CGSizeMake(341., 190.);
  406. else
  407. return CGSizeMake(384., 216.);
  408. }
  409. return CGSizeMake(298.0, 220.0);
  410. }
  411. - (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
  412. {
  413. if (SYSTEM_RUNS_IOS7_OR_LATER)
  414. return UIEdgeInsetsMake(0., 0., 0., 0.);
  415. return UIEdgeInsetsMake(0.0, 34.0, 0.0, 34.0);
  416. }
  417. - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
  418. {
  419. if (SYSTEM_RUNS_IOS7_OR_LATER)
  420. return 0.;
  421. return 10.0;
  422. }
  423. - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
  424. {
  425. if (SYSTEM_RUNS_IOS7_OR_LATER)
  426. return 0.;
  427. return 10.0;
  428. }
  429. - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
  430. {
  431. if (self.editing) {
  432. [(VLCPlaylistCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath] selectionUpdate];
  433. return;
  434. }
  435. NSManagedObject *selectedObject = _foundMedia[indexPath.row];
  436. [self openMediaObject:selectedObject];
  437. }
  438. - (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
  439. {
  440. [(VLCPlaylistCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath] selectionUpdate];
  441. }
  442. #pragma mark - UI implementation
  443. - (void)setEditing:(BOOL)editing animated:(BOOL)animated
  444. {
  445. [super setEditing:editing animated:animated];
  446. UIBarButtonItem *editButton = self.editButtonItem;
  447. NSString *editImage = editing? @"doneButton": @"button";
  448. NSString *editImageHighlight = editing? @"doneButtonHighlight": @"buttonHighlight";
  449. if (SYSTEM_RUNS_IOS7_OR_LATER)
  450. editButton.tintColor = [UIColor whiteColor];
  451. else {
  452. [editButton setBackgroundImage:[UIImage imageNamed:editImage] forState:UIControlStateNormal
  453. barMetrics:UIBarMetricsDefault];
  454. [editButton setBackgroundImage:[UIImage imageNamed:editImageHighlight]
  455. forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
  456. [editButton setTitleTextAttributes: editing ? @{UITextAttributeTextShadowColor : [UIColor whiteColor], UITextAttributeTextColor : [UIColor blackColor]} : @{UITextAttributeTextShadowColor : [UIColor colorWithWhite:0. alpha:.37], UITextAttributeTextColor : [UIColor whiteColor]} forState:UIControlStateNormal];
  457. }
  458. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  459. NSArray *visibleCells = self.collectionView.visibleCells;
  460. [visibleCells enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  461. VLCPlaylistCollectionViewCell *aCell = (VLCPlaylistCollectionViewCell*)obj;
  462. [aCell setEditing:editing animated:animated];
  463. }];
  464. self.collectionView.allowsMultipleSelection = editing;
  465. /* UIKit doesn't clear the selection automagically if we leave the editing mode
  466. * so we need to do so manually */
  467. if (!editing) {
  468. NSArray *selectedItems = [self.collectionView indexPathsForSelectedItems];
  469. NSUInteger count = selectedItems.count;
  470. for (NSUInteger x = 0; x < count; x++)
  471. [self.collectionView deselectItemAtIndexPath:selectedItems[x] animated:NO];
  472. }
  473. } else {
  474. self.tableView.allowsMultipleSelectionDuringEditing = editing;
  475. [self.tableView setEditing:editing animated:YES];
  476. [self.editButtonItem setTitle:editing ? NSLocalizedString(@"BUTTON_CANCEL",@"") : NSLocalizedString(@"BUTTON_EDIT", @"")];
  477. }
  478. self.navigationController.toolbarHidden = !editing;
  479. }
  480. - (UITableViewCellEditingStyle)tableView:(UITableView *)aTableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
  481. {
  482. return UITableViewCellEditingStyleDelete;
  483. }
  484. - (IBAction)leftButtonAction:(id)sender
  485. {
  486. [[(VLCAppDelegate*)[UIApplication sharedApplication].delegate revealController] toggleSidebar:![(VLCAppDelegate*)[UIApplication sharedApplication].delegate revealController].sidebarShowing duration:kGHRevealSidebarDefaultAnimationDuration];
  487. if (self.isEditing)
  488. [self setEditing:NO animated:YES];
  489. }
  490. - (IBAction)backToAllItems:(id)sender
  491. {
  492. [self setLibraryMode:_libraryMode];
  493. [self updateViewContents];
  494. }
  495. - (void)_endEditingWithHardReset:(BOOL)hardReset
  496. {
  497. [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
  498. if (hardReset)
  499. [self updateViewContents];
  500. else
  501. [self reloadViews];
  502. [self setEditing:NO animated:YES];
  503. }
  504. - (void)deleteSelection
  505. {
  506. NSArray *indexPaths;
  507. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  508. indexPaths = [self.collectionView indexPathsForSelectedItems];
  509. else
  510. indexPaths = [self.tableView indexPathsForSelectedRows];
  511. NSUInteger count = indexPaths.count;
  512. NSMutableArray *objects = [[NSMutableArray alloc] initWithCapacity:count];
  513. for (NSUInteger x = 0; x < count; x++)
  514. [objects addObject:_foundMedia[[indexPaths[x] row]]];
  515. for (NSUInteger x = 0; x < count; x++)
  516. [self removeMediaObject:objects[x] updateDatabase:NO];
  517. [self _endEditingWithHardReset:YES];
  518. }
  519. - (void)renameSelection
  520. {
  521. NSArray *indexPaths;
  522. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  523. indexPaths = [self.collectionView indexPathsForSelectedItems];
  524. else
  525. indexPaths = [self.tableView indexPathsForSelectedRows];
  526. if (indexPaths.count < 1) {
  527. [self _endEditingWithHardReset:NO];
  528. return;
  529. }
  530. NSString *itemName;
  531. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  532. itemName = [(VLCPlaylistCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPaths[0]] titleLabel].text;
  533. else
  534. itemName = [(VLCPlaylistTableViewCell *)[self.tableView cellForRowAtIndexPath:indexPaths[0]] titleLabel].text;
  535. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:NSLocalizedString(@"RENAME_MEDIA_TO", @""), itemName] message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", @"") otherButtonTitles:NSLocalizedString(@"BUTTON_RENAME", @""), nil];
  536. [alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
  537. [[alert textFieldAtIndex:0] setText:itemName];
  538. [alert show];
  539. }
  540. - (void)renameMediaObjectTo:(NSString*)newName
  541. {
  542. NSArray *indexPaths;
  543. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  544. indexPaths = [self.collectionView indexPathsForSelectedItems];
  545. else
  546. indexPaths = [self.tableView indexPathsForSelectedRows];
  547. id mediaObject = _foundMedia[[indexPaths[0] row]];
  548. if ([mediaObject isKindOfClass:[MLAlbum class]] || [mediaObject isKindOfClass:[MLShowEpisode class]] || [mediaObject isKindOfClass:[MLShow class]])
  549. [mediaObject setName:newName];
  550. else
  551. [mediaObject setTitle:newName];
  552. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  553. [self.collectionView deselectItemAtIndexPath:indexPaths[0] animated:YES];
  554. else
  555. [self.tableView deselectRowAtIndexPath:indexPaths[0] animated:YES];
  556. if (indexPaths.count > 1)
  557. [self renameSelection];
  558. else
  559. [self _endEditingWithHardReset:NO];
  560. }
  561. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  562. {
  563. if (buttonIndex == 1)
  564. [self renameMediaObjectTo:[alertView textFieldAtIndex:0].text];
  565. else
  566. [self _endEditingWithHardReset:NO];
  567. }
  568. #pragma mark - coin coin
  569. - (void)setLibraryMode:(VLCLibraryMode)mode
  570. {
  571. _libraryMode = mode;
  572. [self updateViewContents];
  573. }
  574. #pragma mark - autorotation
  575. // RootController is responsible for supporting interface orientation(iOS6.0+), i.e. navigation controller
  576. // so this will not work as intended without "voodoo magic"(UINavigationController category, subclassing, etc)
  577. /* introduced in iOS 6 */
  578. - (NSUInteger)supportedInterfaceOrientations {
  579. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  580. return UIInterfaceOrientationMaskAll;
  581. return (_foundMedia.count > 0)? UIInterfaceOrientationMaskAllButUpsideDown:
  582. UIInterfaceOrientationMaskPortrait;
  583. }
  584. /* introduced in iOS 6 */
  585. - (BOOL)shouldAutorotate {
  586. return (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) || (_foundMedia.count > 0);
  587. }
  588. - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
  589. [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
  590. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  591. [self.collectionView.collectionViewLayout invalidateLayout];
  592. }
  593. @end