VLCPlaylistViewController.m 31 KB

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