VLCPlaylistViewController.m 28 KB

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