VLCPlaylistViewController.m 30 KB

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