VLCPlaylistViewController.m 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. /*****************************************************************************
  2. * VLCPlaylistViewController.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2013-2014 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. [_emptyLibraryView.learnMoreButton setTitle:NSLocalizedString(@"BUTTON_LEARN_MORE", @"") forState:UIControlStateNormal];
  106. [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)]]];
  107. self.navigationController.toolbar.barStyle = UIBarStyleBlack;
  108. if (SYSTEM_RUNS_IOS7_OR_LATER) {
  109. self.navigationController.toolbar.tintColor = [UIColor whiteColor];
  110. [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
  111. } else
  112. [self.navigationController.toolbar setBackgroundImage:[UIImage imageNamed:@"bottomBlackBar"] forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
  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. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  124. if (![[defaults objectForKey:kDisplayedFirstSteps] boolValue]) {
  125. [self.emptyLibraryView performSelector:@selector(learnMore:) withObject:nil afterDelay:1.];
  126. [defaults setObject:[NSNumber numberWithBool:YES] forKey:kDisplayedFirstSteps];
  127. [defaults synchronize];
  128. }
  129. if ([[MLMediaLibrary sharedMediaLibrary] libraryNeedsUpgrade]) {
  130. self.navigationItem.rightBarButtonItem = nil;
  131. self.navigationItem.leftBarButtonItem = nil;
  132. self.title = @"";
  133. self.emptyLibraryView.emptyLibraryLabel.text = NSLocalizedString(@"UPGRADING_LIBRARY", @"");
  134. self.emptyLibraryView.emptyLibraryLongDescriptionLabel.hidden = YES;
  135. [self.emptyLibraryView.activityIndicator startAnimating];
  136. self.emptyLibraryView.frame = self.view.bounds;
  137. [self.view addSubview:self.emptyLibraryView];
  138. [[MLMediaLibrary sharedMediaLibrary] setDelegate: self];
  139. [[MLMediaLibrary sharedMediaLibrary] performSelectorInBackground:@selector(upgradeLibrary) withObject:nil];
  140. return;
  141. }
  142. if (_foundMedia.count < 1)
  143. [self updateViewContents];
  144. [[MLMediaLibrary sharedMediaLibrary] performSelector:@selector(libraryDidAppear) withObject:nil afterDelay:1.];
  145. }
  146. - (void)viewDidDisappear:(BOOL)animated
  147. {
  148. [super viewDidDisappear:animated];
  149. [[MLMediaLibrary sharedMediaLibrary] libraryDidDisappear];
  150. }
  151. - (BOOL)canBecomeFirstResponder
  152. {
  153. return YES;
  154. }
  155. - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
  156. {
  157. if (motion == UIEventSubtypeMotionShake)
  158. [[VLCBugreporter sharedInstance] handleBugreportRequest];
  159. }
  160. - (void)openMediaObject:(NSManagedObject *)mediaObject
  161. {
  162. if ([mediaObject isKindOfClass:[MLAlbum class]]) {
  163. _foundMedia = [NSMutableArray arrayWithArray:[(MLAlbum *)mediaObject sortedTracks]];
  164. self.navigationItem.leftBarButtonItem = [UIBarButtonItem themedBackButtonWithTarget:self andSelector:@selector(backToAllItems:)];
  165. if (_libraryMode == VLCLibraryModeAllFiles)
  166. self.navigationItem.leftBarButtonItem.title = NSLocalizedString(@"BUTTON_BACK", @"");
  167. else
  168. [self.navigationItem.leftBarButtonItem setTitle:NSLocalizedString(@"LIBRARY_MUSIC", @"")];
  169. self.title = [(MLAlbum*)mediaObject name];
  170. [self reloadViews];
  171. } else if ([mediaObject isKindOfClass:[MLShow class]]) {
  172. _foundMedia = [NSMutableArray arrayWithArray:[(MLShow *)mediaObject sortedEpisodes]];
  173. self.navigationItem.leftBarButtonItem = [UIBarButtonItem themedBackButtonWithTarget:self andSelector:@selector(backToAllItems:)];
  174. if (_libraryMode == VLCLibraryModeAllFiles)
  175. self.navigationItem.leftBarButtonItem.title = NSLocalizedString(@"BUTTON_BACK", @"");
  176. else
  177. [self.navigationItem.leftBarButtonItem setTitle:NSLocalizedString(@"LIBRARY_SERIES", @"")];
  178. self.title = [(MLShow*)mediaObject name];
  179. [self reloadViews];
  180. } else
  181. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate openMediaFromManagedObject:mediaObject];
  182. }
  183. - (void)removeMediaObject:(id)managedObject updateDatabase:(BOOL)updateDB
  184. {
  185. // delete all tracks from an album
  186. if ([managedObject isKindOfClass:[MLAlbum class]]) {
  187. MLAlbum *album = managedObject;
  188. NSSet *iterAlbumTrack = [NSSet setWithSet:album.tracks];
  189. for (MLAlbumTrack *track in iterAlbumTrack) {
  190. NSSet *iterFiles = [NSSet setWithSet:track.files];
  191. for (MLFile *file in iterFiles)
  192. [self _deleteMediaObject:file];
  193. }
  194. // delete all episodes from a show
  195. } else if ([managedObject isKindOfClass:[MLShow class]]) {
  196. MLShow *show = managedObject;
  197. NSSet *iterShowEpisodes = [NSSet setWithSet:show.episodes];
  198. for (MLShowEpisode *episode in iterShowEpisodes) {
  199. NSSet *iterFiles = [NSSet setWithSet:episode.files];
  200. for (MLFile *file in iterFiles)
  201. [self _deleteMediaObject:file];
  202. }
  203. // delete all files from an episode
  204. } else if ([managedObject isKindOfClass:[MLShowEpisode class]]) {
  205. MLShowEpisode *episode = managedObject;
  206. NSSet *iterFiles = [NSSet setWithSet:episode.files];
  207. for (MLFile *file in iterFiles)
  208. [self _deleteMediaObject:file];
  209. // delete all files from a track
  210. } else if ([managedObject isKindOfClass:[MLAlbumTrack class]]) {
  211. MLAlbumTrack *track = managedObject;
  212. NSSet *iterFiles = [NSSet setWithSet:track.files];
  213. for (MLFile *file in iterFiles)
  214. [self _deleteMediaObject:file];
  215. } else
  216. [self _deleteMediaObject:managedObject];
  217. if (updateDB) {
  218. [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
  219. [self updateViewContents];
  220. }
  221. }
  222. - (void)_deleteMediaObject:(MLFile *)mediaObject
  223. {
  224. NSFileManager *fileManager = [NSFileManager defaultManager];
  225. NSString *folderLocation = [[[NSURL URLWithString:mediaObject.url] path] stringByDeletingLastPathComponent];
  226. NSArray *allfiles = [fileManager contentsOfDirectoryAtPath:folderLocation error:nil];
  227. NSString *fileName = [[[[NSURL URLWithString:mediaObject.url] path] lastPathComponent] stringByDeletingPathExtension];
  228. NSIndexSet *indexSet = [allfiles indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
  229. return ([obj rangeOfString:fileName].location != NSNotFound);
  230. }];
  231. NSUInteger count = indexSet.count;
  232. NSString *additionalFilePath;
  233. NSUInteger currentIndex = [indexSet firstIndex];
  234. for (unsigned int x = 0; x < count; x++) {
  235. additionalFilePath = allfiles[currentIndex];
  236. if ([additionalFilePath isSupportedSubtitleFormat])
  237. [fileManager removeItemAtPath:[folderLocation stringByAppendingPathComponent:additionalFilePath] error:nil];
  238. currentIndex = [indexSet indexGreaterThanIndex:currentIndex];
  239. }
  240. [fileManager removeItemAtPath:[[NSURL URLWithString:mediaObject.url] path] error:nil];
  241. }
  242. - (void)_displayEmptyLibraryViewIfNeeded
  243. {
  244. if (self.emptyLibraryView.superview)
  245. [self.emptyLibraryView removeFromSuperview];
  246. if (_foundMedia.count == 0) {
  247. self.emptyLibraryView.frame = self.view.bounds;
  248. [self.view addSubview:self.emptyLibraryView];
  249. self.navigationItem.rightBarButtonItem = nil;
  250. } else
  251. self.navigationItem.rightBarButtonItem = self.editButtonItem;
  252. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
  253. _tableView.separatorStyle = (_foundMedia.count > 0)? UITableViewCellSeparatorStyleSingleLine:
  254. UITableViewCellSeparatorStyleNone;
  255. } else
  256. [self.collectionView.collectionViewLayout invalidateLayout];
  257. }
  258. - (void)libraryUpgradeComplete
  259. {
  260. self.title = NSLocalizedString(@"LIBRARY_ALL_FILES", @"");
  261. self.navigationItem.leftBarButtonItem = _menuButton;
  262. self.emptyLibraryView.emptyLibraryLongDescriptionLabel.hidden = NO;
  263. self.emptyLibraryView.emptyLibraryLabel.text = NSLocalizedString(@"EMPTY_LIBRARY", @"");
  264. [self.emptyLibraryView.activityIndicator stopAnimating];
  265. [self.emptyLibraryView removeFromSuperview];
  266. [self updateViewContents];
  267. }
  268. - (void)libraryWasUpdated
  269. {
  270. [self updateViewContents];
  271. }
  272. - (void)updateViewContents
  273. {
  274. _foundMedia = [[NSMutableArray alloc] init];
  275. self.navigationItem.leftBarButtonItem = _menuButton;
  276. if (_libraryMode == VLCLibraryModeAllAlbums)
  277. self.title = NSLocalizedString(@"LIBRARY_MUSIC", @"");
  278. else if( _libraryMode == VLCLibraryModeAllSeries)
  279. self.title = NSLocalizedString(@"LIBRARY_SERIES", @"");
  280. else
  281. self.title = NSLocalizedString(@"LIBRARY_ALL_FILES", @"");
  282. /* add all albums */
  283. if (_libraryMode != VLCLibraryModeAllSeries) {
  284. NSArray *rawAlbums = [MLAlbum allAlbums];
  285. for (MLAlbum *album in rawAlbums) {
  286. if (album.name.length > 0 && album.tracks.count > 1)
  287. [_foundMedia addObject:album];
  288. }
  289. }
  290. if (_libraryMode == VLCLibraryModeAllAlbums) {
  291. [self reloadViews];
  292. return;
  293. }
  294. /* add all shows */
  295. NSArray *rawShows = [MLShow allShows];
  296. for (MLShow *show in rawShows) {
  297. if (show.name.length > 0 && show.episodes.count > 1)
  298. [_foundMedia addObject:show];
  299. }
  300. if (_libraryMode == VLCLibraryModeAllSeries) {
  301. [self reloadViews];
  302. return;
  303. }
  304. /* add all remaining files */
  305. NSArray *allFiles = [MLFile allFiles];
  306. for (MLFile *file in allFiles) {
  307. if (!file.isShowEpisode && !file.isAlbumTrack)
  308. [_foundMedia addObject:file];
  309. else if (file.isShowEpisode) {
  310. if (file.showEpisode.show.episodes.count < 2)
  311. [_foundMedia addObject:file];
  312. } else if (file.isAlbumTrack) {
  313. if (file.albumTrack.album.tracks.count < 2)
  314. [_foundMedia addObject:file];
  315. }
  316. }
  317. [self reloadViews];
  318. }
  319. - (void)reloadViews
  320. {
  321. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
  322. [self.tableView reloadData];
  323. else
  324. [self.collectionView reloadData];
  325. [self _displayEmptyLibraryViewIfNeeded];
  326. }
  327. #pragma mark - Table View
  328. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  329. {
  330. return 1;
  331. }
  332. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  333. {
  334. return _foundMedia.count;
  335. }
  336. // Customize the appearance of table view cells.
  337. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  338. {
  339. static NSString *CellIdentifier = @"PlaylistCell";
  340. VLCPlaylistTableViewCell *cell = (VLCPlaylistTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  341. if (cell == nil)
  342. cell = [VLCPlaylistTableViewCell cellWithReuseIdentifier:CellIdentifier];
  343. UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRightGestureAction:)];
  344. [swipeRight setDirection:(UISwipeGestureRecognizerDirectionRight)];
  345. [cell addGestureRecognizer:swipeRight];
  346. NSInteger row = indexPath.row;
  347. cell.mediaObject = _foundMedia[row];
  348. return cell;
  349. }
  350. - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  351. {
  352. cell.backgroundColor = (indexPath.row % 2 == 0)? [UIColor blackColor]: [UIColor colorWithWhite:.122 alpha:1.];
  353. cell.multipleSelectionBackgroundView.backgroundColor = cell.backgroundColor;
  354. }
  355. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  356. {
  357. return YES;
  358. }
  359. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  360. {
  361. if (editingStyle == UITableViewCellEditingStyleDelete)
  362. [self removeMediaObject: _foundMedia[indexPath.row] updateDatabase:YES];
  363. }
  364. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  365. {
  366. if (tableView.isEditing)
  367. return;
  368. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  369. NSManagedObject *selectedObject = _foundMedia[indexPath.row];
  370. if ([selectedObject isKindOfClass:[MLAlbumTrack class]]) {
  371. VLCMediaList *list;
  372. NSArray *tracks = [[(MLAlbumTrack*)selectedObject album] sortedTracks];
  373. NSUInteger count = tracks.count;
  374. list = [[VLCMediaList alloc] init];
  375. MLFile *file;
  376. VLCMedia *media;
  377. for (NSInteger x = count - 1; x > -1; x--) {
  378. file = [(MLAlbumTrack*)tracks[x] files].anyObject;
  379. media = [VLCMedia mediaWithURL: [NSURL URLWithString:file.url]];
  380. [media parse];
  381. [list addMedia:media];
  382. }
  383. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate openMediaList:list atIndex:(int)[tracks indexOfObject:selectedObject]];
  384. } else
  385. [self openMediaObject:selectedObject];
  386. }
  387. #pragma mark - table view gestures
  388. - (void)tableViewLongTouchGestureAction:(UIGestureRecognizer *)recognizer
  389. {
  390. NSIndexPath *path = [(UITableView *)self.view indexPathForRowAtPoint:[recognizer locationInView:self.view]];
  391. UITableViewCell *cell = [(UITableView *)self.view cellForRowAtIndexPath:path];
  392. CGRect frame = cell.frame;
  393. if (frame.size.height > 90.)
  394. frame.size.height = 90.;
  395. else if (recognizer.state == UIGestureRecognizerStateBegan)
  396. frame.size.height = 180;
  397. void (^animationBlock)() = ^() {
  398. cell.frame = frame;
  399. };
  400. void (^completionBlock)(BOOL finished) = ^(BOOL finished) {
  401. cell.frame = frame;
  402. [self.tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionNone animated:YES];
  403. };
  404. NSTimeInterval animationDuration = .2;
  405. [UIView animateWithDuration:animationDuration animations:animationBlock completion:completionBlock];
  406. }
  407. - (void)swipeRightGestureAction:(UIGestureRecognizer *)recognizer
  408. {
  409. if ([[self.editButtonItem title] isEqualToString:NSLocalizedString(@"BUTTON_CANCEL",@"")])
  410. [self setEditing:NO animated:YES];
  411. else {
  412. [self setEditing:YES animated:YES];
  413. NSIndexPath *path = [(UITableView *)self.view indexPathForRowAtPoint:[recognizer locationInView:self.view]];
  414. [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:path.row inSection:path.section]
  415. animated:YES
  416. scrollPosition:UITableViewScrollPositionNone];
  417. }
  418. }
  419. #pragma mark - Collection View
  420. - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
  421. {
  422. return _foundMedia.count;
  423. }
  424. - (UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
  425. {
  426. VLCPlaylistCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PlaylistCell" forIndexPath:indexPath];
  427. cell.mediaObject = _foundMedia[indexPath.row];
  428. cell.collectionView = _collectionView;
  429. [cell setEditing:self.editing animated:NO];
  430. return cell;
  431. }
  432. - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
  433. {
  434. if (SYSTEM_RUNS_IOS7_OR_LATER) {
  435. if (UIDeviceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation))
  436. return CGSizeMake(341., 190.);
  437. else
  438. return CGSizeMake(384., 216.);
  439. }
  440. return CGSizeMake(298.0, 220.0);
  441. }
  442. - (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
  443. {
  444. if (SYSTEM_RUNS_IOS7_OR_LATER)
  445. return UIEdgeInsetsMake(0., 0., 0., 0.);
  446. return UIEdgeInsetsMake(0.0, 34.0, 0.0, 34.0);
  447. }
  448. - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
  449. {
  450. if (SYSTEM_RUNS_IOS7_OR_LATER)
  451. return 0.;
  452. return 10.0;
  453. }
  454. - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
  455. {
  456. if (SYSTEM_RUNS_IOS7_OR_LATER)
  457. return 0.;
  458. return 10.0;
  459. }
  460. - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
  461. {
  462. if (self.editing) {
  463. [(VLCPlaylistCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath] selectionUpdate];
  464. return;
  465. }
  466. NSManagedObject *selectedObject = _foundMedia[indexPath.row];
  467. if ([selectedObject isKindOfClass:[MLAlbumTrack class]]) {
  468. VLCMediaList *list;
  469. NSArray *tracks = [[(MLAlbumTrack*)selectedObject album] sortedTracks];
  470. NSUInteger count = tracks.count;
  471. list = [[VLCMediaList alloc] init];
  472. MLFile *file;
  473. for (NSInteger x = count - 1; x > -1; x--) {
  474. file = [(MLAlbumTrack*)tracks[x] files].anyObject;
  475. [list addMedia:[VLCMedia mediaWithURL: [NSURL URLWithString:file.url]]];
  476. }
  477. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate openMediaList:list atIndex:(int)[tracks indexOfObject:selectedObject]];
  478. } else
  479. [self openMediaObject:selectedObject];
  480. }
  481. - (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
  482. {
  483. [(VLCPlaylistCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath] selectionUpdate];
  484. }
  485. #pragma mark - UI implementation
  486. - (void)setEditing:(BOOL)editing animated:(BOOL)animated
  487. {
  488. [super setEditing:editing animated:animated];
  489. UIBarButtonItem *editButton = self.editButtonItem;
  490. NSString *editImage = editing? @"doneButton": @"button";
  491. NSString *editImageHighlight = editing? @"doneButtonHighlight": @"buttonHighlight";
  492. if (SYSTEM_RUNS_IOS7_OR_LATER)
  493. editButton.tintColor = [UIColor whiteColor];
  494. else {
  495. [editButton setBackgroundImage:[UIImage imageNamed:editImage] forState:UIControlStateNormal
  496. barMetrics:UIBarMetricsDefault];
  497. [editButton setBackgroundImage:[UIImage imageNamed:editImageHighlight]
  498. forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
  499. [editButton setTitleTextAttributes: editing ? @{UITextAttributeTextShadowColor : [UIColor whiteColor], UITextAttributeTextColor : [UIColor blackColor]} : @{UITextAttributeTextShadowColor : [UIColor colorWithWhite:0. alpha:.37], UITextAttributeTextColor : [UIColor whiteColor]} forState:UIControlStateNormal];
  500. }
  501. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  502. NSArray *visibleCells = self.collectionView.visibleCells;
  503. [visibleCells enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  504. VLCPlaylistCollectionViewCell *aCell = (VLCPlaylistCollectionViewCell*)obj;
  505. [aCell setEditing:editing animated:animated];
  506. }];
  507. self.collectionView.allowsMultipleSelection = editing;
  508. /* UIKit doesn't clear the selection automagically if we leave the editing mode
  509. * so we need to do so manually */
  510. if (!editing) {
  511. NSArray *selectedItems = [self.collectionView indexPathsForSelectedItems];
  512. NSUInteger count = selectedItems.count;
  513. for (NSUInteger x = 0; x < count; x++)
  514. [self.collectionView deselectItemAtIndexPath:selectedItems[x] animated:NO];
  515. }
  516. } else {
  517. self.tableView.allowsMultipleSelectionDuringEditing = editing;
  518. [self.tableView setEditing:editing animated:YES];
  519. [self.editButtonItem setTitle:editing ? NSLocalizedString(@"BUTTON_CANCEL",@"") : NSLocalizedString(@"BUTTON_EDIT", @"")];
  520. }
  521. self.navigationController.toolbarHidden = !editing;
  522. }
  523. - (UITableViewCellEditingStyle)tableView:(UITableView *)aTableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
  524. {
  525. return UITableViewCellEditingStyleDelete;
  526. }
  527. - (IBAction)leftButtonAction:(id)sender
  528. {
  529. [[(VLCAppDelegate*)[UIApplication sharedApplication].delegate revealController] toggleSidebar:![(VLCAppDelegate*)[UIApplication sharedApplication].delegate revealController].sidebarShowing duration:kGHRevealSidebarDefaultAnimationDuration];
  530. if (self.isEditing)
  531. [self setEditing:NO animated:YES];
  532. }
  533. - (IBAction)backToAllItems:(id)sender
  534. {
  535. [self setLibraryMode:_libraryMode];
  536. [self updateViewContents];
  537. }
  538. - (void)_endEditingWithHardReset:(BOOL)hardReset
  539. {
  540. [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
  541. if (hardReset)
  542. [self updateViewContents];
  543. else
  544. [self reloadViews];
  545. [self setEditing:NO animated:YES];
  546. }
  547. - (void)deleteSelection
  548. {
  549. NSArray *indexPaths;
  550. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  551. indexPaths = [self.collectionView indexPathsForSelectedItems];
  552. else
  553. indexPaths = [self.tableView indexPathsForSelectedRows];
  554. NSUInteger count = indexPaths.count;
  555. NSMutableArray *objects = [[NSMutableArray alloc] initWithCapacity:count];
  556. for (NSUInteger x = 0; x < count; x++)
  557. [objects addObject:_foundMedia[[indexPaths[x] row]]];
  558. for (NSUInteger x = 0; x < count; x++)
  559. [self removeMediaObject:objects[x] updateDatabase:NO];
  560. [self _endEditingWithHardReset:YES];
  561. }
  562. - (void)renameSelection
  563. {
  564. NSArray *indexPaths;
  565. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  566. indexPaths = [self.collectionView indexPathsForSelectedItems];
  567. else
  568. indexPaths = [self.tableView indexPathsForSelectedRows];
  569. if (indexPaths.count < 1) {
  570. [self _endEditingWithHardReset:NO];
  571. return;
  572. }
  573. NSString *itemName;
  574. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  575. itemName = [(VLCPlaylistCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPaths[0]] titleLabel].text;
  576. else
  577. itemName = [(VLCPlaylistTableViewCell *)[self.tableView cellForRowAtIndexPath:indexPaths[0]] titleLabel].text;
  578. 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];
  579. [alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
  580. [[alert textFieldAtIndex:0] setText:itemName];
  581. [alert show];
  582. }
  583. - (void)renameMediaObjectTo:(NSString*)newName
  584. {
  585. NSArray *indexPaths;
  586. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  587. indexPaths = [self.collectionView indexPathsForSelectedItems];
  588. else
  589. indexPaths = [self.tableView indexPathsForSelectedRows];
  590. id mediaObject = _foundMedia[[indexPaths[0] row]];
  591. if ([mediaObject isKindOfClass:[MLAlbum class]] || [mediaObject isKindOfClass:[MLShowEpisode class]] || [mediaObject isKindOfClass:[MLShow class]])
  592. [mediaObject setName:newName];
  593. else
  594. [mediaObject setTitle:newName];
  595. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  596. [self.collectionView deselectItemAtIndexPath:indexPaths[0] animated:YES];
  597. else
  598. [self.tableView deselectRowAtIndexPath:indexPaths[0] animated:YES];
  599. if (indexPaths.count > 1)
  600. [self renameSelection];
  601. else
  602. [self _endEditingWithHardReset:NO];
  603. }
  604. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  605. {
  606. if (buttonIndex == 1)
  607. [self renameMediaObjectTo:[alertView textFieldAtIndex:0].text];
  608. else
  609. [self _endEditingWithHardReset:NO];
  610. }
  611. #pragma mark - coin coin
  612. - (void)setLibraryMode:(VLCLibraryMode)mode
  613. {
  614. _libraryMode = mode;
  615. [self updateViewContents];
  616. }
  617. #pragma mark - autorotation
  618. // RootController is responsible for supporting interface orientation(iOS6.0+), i.e. navigation controller
  619. // so this will not work as intended without "voodoo magic"(UINavigationController category, subclassing, etc)
  620. /* introduced in iOS 6 */
  621. - (NSUInteger)supportedInterfaceOrientations {
  622. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  623. return UIInterfaceOrientationMaskAll;
  624. return (_foundMedia.count > 0)? UIInterfaceOrientationMaskAllButUpsideDown:
  625. UIInterfaceOrientationMaskPortrait;
  626. }
  627. /* introduced in iOS 6 */
  628. - (BOOL)shouldAutorotate {
  629. return (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) || (_foundMedia.count > 0);
  630. }
  631. - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
  632. [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
  633. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  634. [self.collectionView.collectionViewLayout invalidateLayout];
  635. }
  636. @end