VLCPlaylistViewController.m 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137
  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. * Carola Nitz <nitz.carola # gmail.com>
  12. *
  13. * Refer to the COPYING file of the official project for license.
  14. *****************************************************************************/
  15. #import "VLCPlaylistViewController.h"
  16. #import "VLCMovieViewController.h"
  17. #import "VLCPlaylistTableViewCell.h"
  18. #import "VLCPlaylistCollectionViewCell.h"
  19. #import "UINavigationController+Theme.h"
  20. #import "NSString+SupportedMedia.h"
  21. #import "VLCBugreporter.h"
  22. #import "VLCAppDelegate.h"
  23. #import "UIBarButtonItem+Theme.h"
  24. #import "VLCFirstStepsViewController.h"
  25. #import "VLCFolderCollectionViewFlowLayout.h"
  26. #import "LXReorderableCollectionViewFlowLayout.h"
  27. #import "VLCAlertView.h"
  28. /* prefs keys */
  29. static NSString *kDisplayedFirstSteps = @"Did we display the first steps tutorial?";
  30. @implementation EmptyLibraryView
  31. - (IBAction)learnMore:(id)sender
  32. {
  33. UIViewController *firstStepsVC = [[VLCFirstStepsViewController alloc] initWithNibName:nil bundle:nil];
  34. UINavigationController *navCon = [[UINavigationController alloc] initWithRootViewController:firstStepsVC];
  35. navCon.modalPresentationStyle = UIModalPresentationFormSheet;
  36. [navCon loadTheme];
  37. [self.window.rootViewController presentViewController:navCon animated:YES completion:nil];
  38. }
  39. @end
  40. @interface VLCPlaylistViewController () <VLCFolderCollectionViewDelegateFlowLayout, LXReorderableCollectionViewDataSource, LXReorderableCollectionViewDelegateFlowLayout, UITableViewDataSource, UITableViewDelegate, MLMediaLibrary, VLCMediaListDelegate> {
  41. NSMutableArray *_foundMedia;
  42. VLCLibraryMode _libraryMode;
  43. VLCLibraryMode _previousLibraryMode;
  44. UIBarButtonItem *_menuButton;
  45. NSMutableArray *_indexPaths;
  46. id _folderObject;
  47. VLCFolderCollectionViewFlowLayout *_folderLayout;
  48. LXReorderableCollectionViewFlowLayout *_reorderLayout;
  49. BOOL inFolder;
  50. UILongPressGestureRecognizer *_longPressGestureRecognizer;
  51. NSInteger _mediaToPlayIndex;
  52. VLCMediaList *_list;
  53. NSArray *_tracks;
  54. }
  55. @property (nonatomic, strong) UITableView *tableView;
  56. @property (nonatomic, strong) UICollectionView *collectionView;
  57. @property (nonatomic, strong) EmptyLibraryView *emptyLibraryView;
  58. @end
  59. @implementation VLCPlaylistViewController
  60. + (void)initialize
  61. {
  62. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  63. [defaults registerDefaults:@{kDisplayedFirstSteps : [NSNumber numberWithBool:NO]}];
  64. }
  65. - (void)loadView
  66. {
  67. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
  68. _tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
  69. _tableView.backgroundColor = [UIColor colorWithWhite:.122 alpha:1.];
  70. _tableView.rowHeight = [VLCPlaylistTableViewCell heightOfCell];
  71. _tableView.separatorColor = [UIColor colorWithWhite:.122 alpha:1.];
  72. _tableView.delegate = self;
  73. _tableView.dataSource = self;
  74. _tableView.opaque = YES;
  75. self.view = _tableView;
  76. } else {
  77. _folderLayout = [[VLCFolderCollectionViewFlowLayout alloc] init];
  78. _collectionView = [[UICollectionView alloc] initWithFrame:[UIScreen mainScreen].bounds collectionViewLayout:_folderLayout];
  79. _collectionView.alwaysBounceVertical = YES;
  80. _collectionView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
  81. _collectionView.delegate = self;
  82. _collectionView.dataSource = self;
  83. _collectionView.opaque = YES;
  84. _collectionView.backgroundColor = [UIColor colorWithWhite:.122 alpha:1.];
  85. self.view = _collectionView;
  86. _longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(_collectionViewHandleLongPressGesture:)];
  87. [_collectionView addGestureRecognizer:_longPressGestureRecognizer];
  88. if (SYSTEM_RUNS_IOS7_OR_LATER)
  89. [_collectionView registerNib:[UINib nibWithNibName:@"VLCFuturePlaylistCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"PlaylistCell"];
  90. else
  91. [_collectionView registerNib:[UINib nibWithNibName:@"VLCPlaylistCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"PlaylistCell"];
  92. self.view.backgroundColor = [UIColor colorWithWhite:.122 alpha:1.];
  93. }
  94. _libraryMode = VLCLibraryModeAllFiles;
  95. self.view.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
  96. self.emptyLibraryView = [[[NSBundle mainBundle] loadNibNamed:@"VLCEmptyLibraryView" owner:self options:nil] lastObject];
  97. _emptyLibraryView.emptyLibraryLongDescriptionLabel.lineBreakMode = NSLineBreakByWordWrapping;
  98. _emptyLibraryView.emptyLibraryLongDescriptionLabel.numberOfLines = 0;
  99. }
  100. #pragma mark -
  101. - (void)viewDidLoad
  102. {
  103. [super viewDidLoad];
  104. self.title = NSLocalizedString(@"LIBRARY_ALL_FILES", @"");
  105. _menuButton = [UIBarButtonItem themedRevealMenuButtonWithTarget:self andSelector:@selector(leftButtonAction:)];
  106. self.navigationItem.leftBarButtonItem = _menuButton;
  107. if (SYSTEM_RUNS_IOS7_OR_LATER)
  108. self.editButtonItem.tintColor = [UIColor whiteColor];
  109. else {
  110. [self.editButtonItem setBackgroundImage:[UIImage imageNamed:@"button"]
  111. forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
  112. [self.editButtonItem setBackgroundImage:[UIImage imageNamed:@"buttonHighlight"]
  113. forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
  114. }
  115. _emptyLibraryView.emptyLibraryLabel.text = NSLocalizedString(@"EMPTY_LIBRARY", @"");
  116. _emptyLibraryView.emptyLibraryLongDescriptionLabel.text = NSLocalizedString(@"EMPTY_LIBRARY_LONG", @"");
  117. [_emptyLibraryView.emptyLibraryLongDescriptionLabel sizeToFit];
  118. [_emptyLibraryView.learnMoreButton setTitle:NSLocalizedString(@"BUTTON_LEARN_MORE", @"") forState:UIControlStateNormal];
  119. UIBarButtonItem *createFolderItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemOrganize target:self action:@selector(createFolder)];
  120. [self setToolbarItems:@[createFolderItem, [[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)]]];
  121. self.navigationController.toolbar.barStyle = UIBarStyleBlack;
  122. if (SYSTEM_RUNS_IOS7_OR_LATER) {
  123. self.navigationController.toolbar.tintColor = [UIColor whiteColor];
  124. [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
  125. } else
  126. [self.navigationController.toolbar setBackgroundImage:[UIImage imageNamed:@"bottomBlackBar"] forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
  127. }
  128. - (void)viewWillAppear:(BOOL)animated
  129. {
  130. [super viewWillAppear:animated];
  131. [self.collectionView.collectionViewLayout invalidateLayout];
  132. [self _displayEmptyLibraryViewIfNeeded];
  133. }
  134. - (void)viewDidAppear:(BOOL)animated
  135. {
  136. [super viewDidAppear:animated];
  137. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  138. if (![[defaults objectForKey:kDisplayedFirstSteps] boolValue]) {
  139. [self.emptyLibraryView performSelector:@selector(learnMore:) withObject:nil afterDelay:1.];
  140. [defaults setObject:[NSNumber numberWithBool:YES] forKey:kDisplayedFirstSteps];
  141. [defaults synchronize];
  142. }
  143. if ([[MLMediaLibrary sharedMediaLibrary] libraryNeedsUpgrade]) {
  144. self.navigationItem.rightBarButtonItem = nil;
  145. self.navigationItem.leftBarButtonItem = nil;
  146. self.title = @"";
  147. self.emptyLibraryView.emptyLibraryLabel.text = NSLocalizedString(@"UPGRADING_LIBRARY", @"");
  148. self.emptyLibraryView.emptyLibraryLongDescriptionLabel.hidden = YES;
  149. [self.emptyLibraryView.activityIndicator startAnimating];
  150. self.emptyLibraryView.frame = self.view.bounds;
  151. [self.view addSubview:self.emptyLibraryView];
  152. [[MLMediaLibrary sharedMediaLibrary] setDelegate: self];
  153. [[MLMediaLibrary sharedMediaLibrary] performSelectorInBackground:@selector(upgradeLibrary) withObject:nil];
  154. return;
  155. }
  156. if (_foundMedia.count < 1)
  157. [self updateViewContents];
  158. [[MLMediaLibrary sharedMediaLibrary] performSelector:@selector(libraryDidAppear) withObject:nil afterDelay:1.];
  159. }
  160. - (void)viewDidDisappear:(BOOL)animated
  161. {
  162. [super viewDidDisappear:animated];
  163. [[MLMediaLibrary sharedMediaLibrary] libraryDidDisappear];
  164. }
  165. - (BOOL)canBecomeFirstResponder
  166. {
  167. return YES;
  168. }
  169. - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
  170. {
  171. if (motion == UIEventSubtypeMotionShake)
  172. [[VLCBugreporter sharedInstance] handleBugreportRequest];
  173. }
  174. - (void)openMediaObject:(NSManagedObject *)mediaObject
  175. {
  176. if ([mediaObject isKindOfClass:[MLAlbum class]]) {
  177. _foundMedia = [NSMutableArray arrayWithArray:[(MLAlbum *)mediaObject sortedTracks]];
  178. self.navigationItem.leftBarButtonItem = [UIBarButtonItem themedBackButtonWithTarget:self andSelector:@selector(backToAllItems:)];
  179. if (_libraryMode == VLCLibraryModeAllFiles)
  180. self.navigationItem.leftBarButtonItem.title = NSLocalizedString(@"BUTTON_BACK", @"");
  181. else
  182. [self.navigationItem.leftBarButtonItem setTitle:NSLocalizedString(@"LIBRARY_MUSIC", @"")];
  183. self.title = [(MLAlbum*)mediaObject name];
  184. [self reloadViews];
  185. } else if ([mediaObject isKindOfClass:[MLShow class]]) {
  186. _foundMedia = [NSMutableArray arrayWithArray:[(MLShow *)mediaObject sortedEpisodes]];
  187. self.navigationItem.leftBarButtonItem = [UIBarButtonItem themedBackButtonWithTarget:self andSelector:@selector(backToAllItems:)];
  188. if (_libraryMode == VLCLibraryModeAllFiles)
  189. self.navigationItem.leftBarButtonItem.title = NSLocalizedString(@"BUTTON_BACK", @"");
  190. else
  191. [self.navigationItem.leftBarButtonItem setTitle:NSLocalizedString(@"LIBRARY_SERIES", @"")];
  192. self.title = [(MLShow*)mediaObject name];
  193. [self reloadViews];
  194. } else if ([mediaObject isKindOfClass:[MLLabel class]]) {
  195. MLLabel *folder = (MLLabel*) mediaObject;
  196. inFolder = YES;
  197. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  198. if (![self.collectionView.collectionViewLayout isEqual:_reorderLayout]) {
  199. for (UIGestureRecognizer *recognizer in self.view.gestureRecognizers) {
  200. if (recognizer == _folderLayout.panGestureRecognizer || recognizer == _folderLayout.longPressGestureRecognizer || recognizer == _longPressGestureRecognizer)
  201. [self.collectionView removeGestureRecognizer:recognizer];
  202. }
  203. _reorderLayout = [[LXReorderableCollectionViewFlowLayout alloc] init];
  204. [self.collectionView setCollectionViewLayout:_reorderLayout animated:NO];
  205. }
  206. }
  207. _foundMedia = [NSMutableArray arrayWithArray:[folder sortedFolderItems]];
  208. self.navigationItem.leftBarButtonItem = [UIBarButtonItem themedBackButtonWithTarget:self andSelector:@selector(backToAllItems:)];
  209. self.navigationItem.leftBarButtonItem.title = NSLocalizedString(@"BUTTON_BACK", @"");
  210. self.title = [folder name];
  211. UIBarButtonItem *removeFromFolder = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemReply target:self action:@selector(removeFromFolder)];
  212. NSMutableArray *toolbarItems = [self.toolbarItems mutableCopy];
  213. toolbarItems[0] = removeFromFolder;
  214. self.toolbarItems = toolbarItems;
  215. [self reloadViews];
  216. return;
  217. } else
  218. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate openMediaFromManagedObject:mediaObject];
  219. }
  220. - (void)removeMediaObject:(id)managedObject updateDatabase:(BOOL)updateDB
  221. {
  222. // delete all tracks from an album
  223. if ([managedObject isKindOfClass:[MLAlbum class]]) {
  224. MLAlbum *album = managedObject;
  225. NSSet *iterAlbumTrack = [NSSet setWithSet:album.tracks];
  226. for (MLAlbumTrack *track in iterAlbumTrack) {
  227. NSSet *iterFiles = [NSSet setWithSet:track.files];
  228. for (MLFile *file in iterFiles)
  229. [self _deleteMediaObject:file];
  230. }
  231. // delete all episodes from a show
  232. } else if ([managedObject isKindOfClass:[MLShow class]]) {
  233. MLShow *show = managedObject;
  234. NSSet *iterShowEpisodes = [NSSet setWithSet:show.episodes];
  235. for (MLShowEpisode *episode in iterShowEpisodes) {
  236. NSSet *iterFiles = [NSSet setWithSet:episode.files];
  237. for (MLFile *file in iterFiles)
  238. [self _deleteMediaObject:file];
  239. }
  240. // delete all files from an episode
  241. } else if ([managedObject isKindOfClass:[MLShowEpisode class]]) {
  242. MLShowEpisode *episode = managedObject;
  243. NSSet *iterFiles = [NSSet setWithSet:episode.files];
  244. for (MLFile *file in iterFiles)
  245. [self _deleteMediaObject:file];
  246. // delete all files from a track
  247. } else if ([managedObject isKindOfClass:[MLAlbumTrack class]]) {
  248. MLAlbumTrack *track = managedObject;
  249. NSSet *iterFiles = [NSSet setWithSet:track.files];
  250. for (MLFile *file in iterFiles)
  251. [self _deleteMediaObject:file];
  252. } else if ([managedObject isKindOfClass:[MLLabel class]]) {
  253. MLLabel *folder = managedObject;
  254. NSSet *iterFiles = [NSSet setWithSet:folder.files];
  255. [folder removeFiles:folder.files];
  256. for (MLFile *file in iterFiles)
  257. [self _deleteMediaObject:file];
  258. [[MLMediaLibrary sharedMediaLibrary] removeObject:folder];
  259. }
  260. else
  261. [self _deleteMediaObject:managedObject];
  262. if (updateDB) {
  263. [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
  264. [self updateViewContents];
  265. }
  266. }
  267. - (void)_deleteMediaObject:(MLFile *)mediaObject
  268. {
  269. if (inFolder)
  270. [self rearrangeFolderTrackNumbersForRemovedItem:mediaObject];
  271. NSFileManager *fileManager = [NSFileManager defaultManager];
  272. NSString *folderLocation = [[[NSURL URLWithString:mediaObject.url] path] stringByDeletingLastPathComponent];
  273. NSArray *allfiles = [fileManager contentsOfDirectoryAtPath:folderLocation error:nil];
  274. NSString *fileName = [[[[NSURL URLWithString:mediaObject.url] path] lastPathComponent] stringByDeletingPathExtension];
  275. NSIndexSet *indexSet = [allfiles indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
  276. return ([obj rangeOfString:fileName].location != NSNotFound);
  277. }];
  278. NSUInteger count = indexSet.count;
  279. NSString *additionalFilePath;
  280. NSUInteger currentIndex = [indexSet firstIndex];
  281. for (unsigned int x = 0; x < count; x++) {
  282. additionalFilePath = allfiles[currentIndex];
  283. if ([additionalFilePath isSupportedSubtitleFormat])
  284. [fileManager removeItemAtPath:[folderLocation stringByAppendingPathComponent:additionalFilePath] error:nil];
  285. currentIndex = [indexSet indexGreaterThanIndex:currentIndex];
  286. }
  287. [fileManager removeItemAtPath:[[NSURL URLWithString:mediaObject.url] path] error:nil];
  288. }
  289. - (void)_displayEmptyLibraryViewIfNeeded
  290. {
  291. if (self.emptyLibraryView.superview)
  292. [self.emptyLibraryView removeFromSuperview];
  293. if (_foundMedia.count == 0) {
  294. self.emptyLibraryView.emptyLibraryLabel.text = inFolder ? NSLocalizedString(@"FOLDER_EMPTY", @"") : NSLocalizedString(@"EMPTY_LIBRARY", @"");
  295. self.emptyLibraryView.emptyLibraryLongDescriptionLabel.text = inFolder ? NSLocalizedString(@"FOLDER_EMPTY_LONG", @"") : NSLocalizedString(@"EMPTY_LIBRARY_LONG", @"");
  296. self.emptyLibraryView.learnMoreButton.hidden = inFolder;
  297. self.emptyLibraryView.frame = self.view.bounds;
  298. [self.view addSubview:self.emptyLibraryView];
  299. self.navigationItem.rightBarButtonItem = nil;
  300. } else
  301. self.navigationItem.rightBarButtonItem = self.editButtonItem;
  302. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
  303. _tableView.separatorStyle = (_foundMedia.count > 0)? UITableViewCellSeparatorStyleSingleLine:
  304. UITableViewCellSeparatorStyleNone;
  305. } else
  306. [self.collectionView.collectionViewLayout invalidateLayout];
  307. }
  308. - (void)libraryUpgradeComplete
  309. {
  310. self.title = NSLocalizedString(@"LIBRARY_ALL_FILES", @"");
  311. self.navigationItem.leftBarButtonItem = _menuButton;
  312. self.emptyLibraryView.emptyLibraryLongDescriptionLabel.hidden = NO;
  313. self.emptyLibraryView.emptyLibraryLabel.text = NSLocalizedString(@"EMPTY_LIBRARY", @"");
  314. [self.emptyLibraryView.activityIndicator stopAnimating];
  315. [self.emptyLibraryView removeFromSuperview];
  316. [self updateViewContents];
  317. }
  318. - (void)libraryWasUpdated
  319. {
  320. [self updateViewContents];
  321. }
  322. - (void)updateViewContents
  323. {
  324. _foundMedia = [[NSMutableArray alloc] init];
  325. self.navigationItem.leftBarButtonItem = _menuButton;
  326. if (_libraryMode == VLCLibraryModeAllAlbums)
  327. self.title = NSLocalizedString(@"LIBRARY_MUSIC", @"");
  328. else if( _libraryMode == VLCLibraryModeAllSeries)
  329. self.title = NSLocalizedString(@"LIBRARY_SERIES", @"");
  330. else
  331. self.title = NSLocalizedString(@"LIBRARY_ALL_FILES", @"");
  332. /* add all albums */
  333. if (_libraryMode != VLCLibraryModeAllSeries) {
  334. NSArray *rawAlbums = [MLAlbum allAlbums];
  335. for (MLAlbum *album in rawAlbums) {
  336. if (album.name.length > 0 && album.tracks.count > 1)
  337. [_foundMedia addObject:album];
  338. }
  339. }
  340. if (_libraryMode == VLCLibraryModeAllAlbums) {
  341. [self reloadViews];
  342. return;
  343. }
  344. /* add all shows */
  345. NSArray *rawShows = [MLShow allShows];
  346. for (MLShow *show in rawShows) {
  347. if (show.name.length > 0 && show.episodes.count > 1)
  348. [_foundMedia addObject:show];
  349. }
  350. if (_libraryMode == VLCLibraryModeAllSeries) {
  351. [self reloadViews];
  352. return;
  353. }
  354. /* add all folders*/
  355. NSArray *allFolders = [MLLabel allLabels];
  356. for (MLLabel *folder in allFolders)
  357. [_foundMedia addObject:folder];
  358. /* add all remaining files */
  359. NSArray *allFiles = [MLFile allFiles];
  360. for (MLFile *file in allFiles) {
  361. if (file.labels.count > 0) continue;
  362. if (!file.isShowEpisode && !file.isAlbumTrack)
  363. [_foundMedia addObject:file];
  364. else if (file.isShowEpisode) {
  365. if (file.showEpisode.show.episodes.count < 2)
  366. [_foundMedia addObject:file];
  367. /* older MediaLibraryKit versions don't send a show name in a popular
  368. * corner case. hence, we need to work-around here and force a reload
  369. * afterwards as this could lead to the 'all my shows are gone'
  370. * syndrome (see #10435, #10464, #10432 et al) */
  371. if (file.showEpisode.show.name.length == 0) {
  372. file.showEpisode.show.name = NSLocalizedString(@"UNTITLED_SHOW", @"");
  373. [self performSelector:@selector(updateViewContents) withObject:nil afterDelay:0.1];
  374. }
  375. } else if (file.isAlbumTrack) {
  376. if (file.albumTrack.album.tracks.count < 2)
  377. [_foundMedia addObject:file];
  378. }
  379. }
  380. [self reloadViews];
  381. }
  382. - (void)reloadViews
  383. {
  384. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
  385. [self.tableView reloadData];
  386. else
  387. [self.collectionView reloadData];
  388. [self _displayEmptyLibraryViewIfNeeded];
  389. }
  390. #pragma mark - Table View
  391. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  392. {
  393. return 1;
  394. }
  395. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  396. {
  397. return _foundMedia.count;
  398. }
  399. // Customize the appearance of table view cells.
  400. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  401. {
  402. static NSString *CellIdentifier = @"PlaylistCell";
  403. VLCPlaylistTableViewCell *cell = (VLCPlaylistTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  404. if (cell == nil)
  405. cell = [VLCPlaylistTableViewCell cellWithReuseIdentifier:CellIdentifier];
  406. UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRightGestureAction:)];
  407. [swipeRight setDirection:(UISwipeGestureRecognizerDirectionRight)];
  408. [cell addGestureRecognizer:swipeRight];
  409. NSInteger row = indexPath.row;
  410. cell.mediaObject = _foundMedia[row];
  411. return cell;
  412. }
  413. - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
  414. {
  415. MLFile* object = [_foundMedia objectAtIndex:fromIndexPath.item];
  416. [_foundMedia removeObjectAtIndex:fromIndexPath.item];
  417. [_foundMedia insertObject:object atIndex:toIndexPath.item];
  418. object.folderTrackNumber = @(toIndexPath.item - 1);
  419. object = [_foundMedia objectAtIndex:fromIndexPath.item];
  420. object.folderTrackNumber = @(fromIndexPath.item - 1);
  421. }
  422. - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
  423. {
  424. return inFolder;
  425. }
  426. - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  427. {
  428. cell.backgroundColor = (indexPath.row % 2 == 0)? [UIColor blackColor]: [UIColor colorWithWhite:.122 alpha:1.];
  429. cell.multipleSelectionBackgroundView.backgroundColor = cell.backgroundColor;
  430. }
  431. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  432. {
  433. return YES;
  434. }
  435. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  436. {
  437. if (editingStyle == UITableViewCellEditingStyleDelete)
  438. [self removeMediaObject: _foundMedia[indexPath.row] updateDatabase:YES];
  439. }
  440. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  441. {
  442. if (tableView.isEditing) {
  443. if (_libraryMode == VLCLibraryModeCreateFolder) {
  444. _folderObject = _foundMedia[indexPath.row];
  445. _libraryMode = _previousLibraryMode;
  446. [self updateViewContents];
  447. [self createFolderWithName:nil];
  448. }
  449. return;
  450. }
  451. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  452. NSManagedObject *selectedObject = _foundMedia[indexPath.row];
  453. if ([selectedObject isKindOfClass:[MLAlbumTrack class]]) {
  454. _tracks = [[(MLAlbumTrack*)selectedObject album] sortedTracks];
  455. NSUInteger count = _tracks.count;
  456. _list = [[VLCMediaList alloc] init];
  457. _list.delegate = self;
  458. MLFile *file;
  459. VLCMedia *media;
  460. for (NSInteger x = count - 1; x > -1; x--) {
  461. file = [(MLAlbumTrack*)_tracks[x] files].anyObject;
  462. media = [VLCMedia mediaWithURL: [NSURL URLWithString:file.url]];
  463. [media parse];
  464. [_list addMedia:media];
  465. }
  466. _mediaToPlayIndex = indexPath.row;
  467. } else if ([selectedObject isKindOfClass:[MLFile class]] && [((MLFile *)selectedObject).labels count] > 0) {
  468. MLLabel *folder = [((MLFile *)selectedObject).labels anyObject];
  469. _tracks = [folder sortedFolderItems];
  470. NSUInteger count = _tracks.count;
  471. _list = [[VLCMediaList alloc] init];
  472. _list.delegate = self;
  473. MLFile *file;
  474. for (NSInteger x = count - 1; x > -1; x--) {
  475. file = (MLFile *)_tracks[x];
  476. [_list addMedia:[VLCMedia mediaWithURL:[NSURL URLWithString:file.url]]];
  477. }
  478. _mediaToPlayIndex = indexPath.row;
  479. } else
  480. [self openMediaObject:selectedObject];
  481. }
  482. #pragma mark - VLCMedialistDelegate
  483. - (void)mediaList:(VLCMediaList *)aMediaList mediaAdded:(VLCMedia *)media atIndex:(NSInteger)index
  484. {
  485. if (index == _tracks.count - 1) {
  486. NSManagedObject *selectedObject = _foundMedia[_mediaToPlayIndex];
  487. [(VLCAppDelegate *)[UIApplication sharedApplication].delegate openMediaList:_list atIndex:(int)[_tracks indexOfObject:selectedObject]];
  488. }
  489. }
  490. #pragma mark - table view gestures
  491. - (void)swipeRightGestureAction:(UIGestureRecognizer *)recognizer
  492. {
  493. if ([[self.editButtonItem title] isEqualToString:NSLocalizedString(@"BUTTON_CANCEL",@"")])
  494. [self setEditing:NO animated:YES];
  495. else {
  496. [self setEditing:YES animated:YES];
  497. NSIndexPath *path = [(UITableView *)self.view indexPathForRowAtPoint:[recognizer locationInView:self.view]];
  498. [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:path.row inSection:path.section]
  499. animated:YES
  500. scrollPosition:UITableViewScrollPositionNone];
  501. }
  502. }
  503. #pragma mark - Collection View
  504. - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
  505. {
  506. return _foundMedia.count;
  507. }
  508. - (UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
  509. {
  510. VLCPlaylistCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PlaylistCell" forIndexPath:indexPath];
  511. cell.mediaObject = _foundMedia[indexPath.row];
  512. cell.collectionView = _collectionView;
  513. [cell setEditing:self.editing animated:NO];
  514. return cell;
  515. }
  516. - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
  517. {
  518. if (SYSTEM_RUNS_IOS7_OR_LATER) {
  519. if (UIDeviceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation))
  520. return CGSizeMake(341., 190.);
  521. else
  522. return CGSizeMake(384., 216.);
  523. }
  524. return CGSizeMake(298.0, 220.0);
  525. }
  526. - (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
  527. {
  528. if (SYSTEM_RUNS_IOS7_OR_LATER)
  529. return UIEdgeInsetsMake(0., 0., 0., 0.);
  530. return UIEdgeInsetsMake(0.0, 34.0, 0.0, 34.0);
  531. }
  532. - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
  533. {
  534. if (SYSTEM_RUNS_IOS7_OR_LATER)
  535. return 0.;
  536. return 10.0;
  537. }
  538. - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
  539. {
  540. if (SYSTEM_RUNS_IOS7_OR_LATER)
  541. return 0.;
  542. return 10.0;
  543. }
  544. - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
  545. {
  546. if (self.editing) {
  547. if (_libraryMode == VLCLibraryModeCreateFolder) {
  548. _folderObject = _foundMedia[indexPath.item];
  549. [self createFolderWithName:nil];
  550. _libraryMode = _previousLibraryMode;
  551. }
  552. [(VLCPlaylistCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath] selectionUpdate];
  553. return;
  554. }
  555. NSManagedObject *selectedObject = _foundMedia[indexPath.row];
  556. if ([selectedObject isKindOfClass:[MLAlbumTrack class]]) {
  557. VLCMediaList *list;
  558. NSArray *tracks = [[(MLAlbumTrack*)selectedObject album] sortedTracks];
  559. NSUInteger count = tracks.count;
  560. list = [[VLCMediaList alloc] init];
  561. MLFile *file;
  562. for (NSInteger x = count - 1; x > -1; x--) {
  563. file = [(MLAlbumTrack*)tracks[x] files].anyObject;
  564. [list addMedia:[VLCMedia mediaWithURL: [NSURL URLWithString:file.url]]];
  565. }
  566. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate openMediaList:list atIndex:(int)[tracks indexOfObject:selectedObject]];
  567. } else if ([selectedObject isKindOfClass:[MLFile class]] && [((MLFile *)selectedObject).labels count] > 0) {
  568. VLCMediaList *list;
  569. MLLabel *folder = [((MLFile *)selectedObject).labels anyObject];
  570. NSArray *folderTracks = [folder sortedFolderItems];
  571. NSUInteger count = folderTracks.count;
  572. list = [[VLCMediaList alloc] init];
  573. MLFile *file;
  574. for (NSInteger x = count - 1; x > -1; x--) {
  575. file = (MLFile *)folderTracks[x];
  576. [list addMedia:[VLCMedia mediaWithURL:[NSURL URLWithString:file.url]]];
  577. }
  578. [(VLCAppDelegate *)[UIApplication sharedApplication].delegate openMediaList:list atIndex:(int)[folderTracks indexOfObject:selectedObject]];
  579. } else
  580. [self openMediaObject:selectedObject];
  581. }
  582. - (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
  583. {
  584. [(VLCPlaylistCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath] selectionUpdate];
  585. }
  586. - (void)collectionView:(UICollectionView *)collectionView removeItemFromFolderAtIndexPathIfNeeded:(NSIndexPath *)indexPath
  587. {
  588. MLFile *mediaObject = (MLFile *)_foundMedia[indexPath.item];
  589. [self rearrangeFolderTrackNumbersForRemovedItem:mediaObject];
  590. mediaObject.labels = nil;
  591. mediaObject.folderTrackNumber = nil;
  592. [self backToAllItems:nil];
  593. }
  594. - (void)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)fromIndexPath willMoveToIndexPath:(NSIndexPath *)toIndexPath
  595. {
  596. MLFile* object = [_foundMedia objectAtIndex:fromIndexPath.item];
  597. [_foundMedia removeObjectAtIndex:fromIndexPath.item];
  598. [_foundMedia insertObject:object atIndex:toIndexPath.item];
  599. object.folderTrackNumber = @(toIndexPath.item - 1);
  600. object = [_foundMedia objectAtIndex:fromIndexPath.item];
  601. object.folderTrackNumber = @(fromIndexPath.item - 1);
  602. }
  603. - (void)collectionView:(UICollectionView *)collectionView requestToMoveItemAtIndexPath:(NSIndexPath *)itemPath intoFolderAtIndexPath:(NSIndexPath *)folderPath
  604. {
  605. BOOL validFileTypeAtFolderPath = ([_foundMedia[folderPath.item] isKindOfClass:[MLFile class]] || [_foundMedia[folderPath.item] isKindOfClass:[MLLabel class]]) && [_foundMedia[itemPath.item] isKindOfClass:[MLFile class]];
  606. if (!validFileTypeAtFolderPath) {
  607. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"FOLDER_INVALID_TYPE_TITLE", @"") message:NSLocalizedString(@"FOLDER_INVALID_TYPE_MESSAGE", @"") cancelButtonTitle:nil otherButtonTitles:@[NSLocalizedString(@"BUTTON_OK", @"")]];
  608. alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
  609. [self updateViewContents];
  610. };
  611. [alert show];
  612. return;
  613. }
  614. BOOL isFolder = [_foundMedia[folderPath.item] isKindOfClass:[MLLabel class]];
  615. if (isFolder){
  616. MLLabel *folder = _foundMedia[folderPath.item];
  617. MLFile *file = _foundMedia[itemPath.item];
  618. [file setLabels:[[NSSet alloc] initWithObjects:folder, nil]];
  619. file.folderTrackNumber = @([folder.files count] - 1);
  620. [_foundMedia removeObjectAtIndex:itemPath.item];
  621. [self updateViewContents];
  622. } else {
  623. _folderObject = _foundMedia[folderPath.item];
  624. _indexPaths = [NSMutableArray arrayWithArray:@[itemPath]];
  625. [self showCreateFolderAlert];
  626. }
  627. }
  628. #pragma mark - Folder implementation
  629. - (void)rearrangeFolderTrackNumbersForRemovedItem:(MLFile *) mediaObject
  630. {
  631. MLLabel *label = [mediaObject.labels anyObject];
  632. NSSet *allFiles = label.files;
  633. for (MLFile *file in allFiles) {
  634. if (file.folderTrackNumber > mediaObject.folderTrackNumber) {
  635. int value = [file.folderTrackNumber intValue];
  636. file.folderTrackNumber = [NSNumber numberWithInt:value - 1];
  637. }
  638. }
  639. }
  640. - (void)showCreateFolderAlert
  641. {
  642. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"FOLDER_CHOOSE_NAME_TITLE", @"") message:NSLocalizedString(@"FOLDER_CHOOSE_NAME_MESSAGE", @"") cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", @"") otherButtonTitles:@[NSLocalizedString(@"BUTTON_SAVE", @"")]];
  643. [alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
  644. [[alert textFieldAtIndex:0] setText:NSLocalizedString(@"FOLDER_NAME_PLACEHOLDER", @"")];
  645. [[alert textFieldAtIndex:0] setClearButtonMode:UITextFieldViewModeAlways];
  646. __weak VLCAlertView *weakAlert = alert;
  647. alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
  648. if (cancelled)
  649. [self updateViewContents];
  650. else
  651. [self createFolderWithName:[weakAlert textFieldAtIndex:0].text];
  652. };
  653. [alert show];
  654. }
  655. - (void)createFolder
  656. {
  657. if (_libraryMode == VLCLibraryModeCreateFolder) {
  658. _libraryMode = _previousLibraryMode;
  659. [self updateViewContents];
  660. [self showCreateFolderAlert];
  661. return;
  662. }
  663. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  664. _indexPaths = [NSMutableArray arrayWithArray:[self.collectionView indexPathsForSelectedItems]];
  665. else
  666. _indexPaths = [NSMutableArray arrayWithArray:[self.tableView indexPathsForSelectedRows]];
  667. for (NSInteger i = _indexPaths.count - 1; i >=0; i--) {
  668. NSIndexPath *path = _indexPaths[i];
  669. id mediaObject;
  670. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  671. mediaObject = _foundMedia[path.item];
  672. else
  673. mediaObject = _foundMedia[path.row];
  674. if ([mediaObject isKindOfClass:[MLLabel class]])
  675. [_indexPaths removeObject:path];
  676. }
  677. if ([_indexPaths count] != 0) {
  678. NSArray *folder = [MLLabel allLabels];
  679. //if we already have folders display them
  680. if ([folder count] > 0) {
  681. _foundMedia = [NSMutableArray arrayWithArray:folder];
  682. self.title = NSLocalizedString(@"SELECT_FOLDER", @"");
  683. _previousLibraryMode = _libraryMode;
  684. _libraryMode = VLCLibraryModeCreateFolder;
  685. [self reloadViews];
  686. return;
  687. }
  688. }
  689. //no selected items or no existing folder ask for foldername
  690. [self showCreateFolderAlert];
  691. }
  692. - (void)removeFromFolder
  693. {
  694. BOOL isPad = UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad;
  695. if (isPad)
  696. _indexPaths = [NSMutableArray arrayWithArray:[self.collectionView indexPathsForSelectedItems]];
  697. else
  698. _indexPaths = [NSMutableArray arrayWithArray:[self.tableView indexPathsForSelectedRows]];
  699. [_indexPaths sortUsingSelector:@selector(compare:)];
  700. for (NSInteger i = [_indexPaths count] - 1; i >= 0; i--) {
  701. NSIndexPath *path = _indexPaths[i];
  702. MLFile *file = (MLFile *)_foundMedia[isPad ? path.item : path.row];
  703. MLLabel *folder = [file.labels anyObject];
  704. [self rearrangeFolderTrackNumbersForRemovedItem:file];
  705. file.labels = nil;
  706. file.folderTrackNumber = nil;
  707. [_foundMedia removeObject:file];
  708. if ([folder.files count] == 0) {
  709. [self removeMediaObject:folder updateDatabase:YES];
  710. [self setEditing:NO];
  711. [self backToAllItems:nil];
  712. }
  713. }
  714. [self reloadViews];
  715. }
  716. - (void)createFolderWithName:(NSString *)folderName
  717. {
  718. NSArray *labels = [MLLabel allLabels];
  719. for (MLLabel *label in labels){
  720. if ([label.name isEqualToString:folderName]) {
  721. _folderObject = nil;
  722. _indexPaths = nil;
  723. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"FOLDER_NAME_DUPLICATE_TITLE", @"") message:NSLocalizedString(@"FOLDER_NAME_DUPLICATE_MESSAGE", @"") cancelButtonTitle:nil otherButtonTitles:@[NSLocalizedString(@"BUTTON_OK", @"")]];
  724. alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
  725. [self updateViewContents];
  726. };
  727. [alert show];
  728. return;
  729. }
  730. }
  731. if (_folderObject != nil) {
  732. NSUInteger folderIndex = [_foundMedia indexOfObject:_folderObject];
  733. //item got dragged onto item
  734. if ([_foundMedia[folderIndex] isKindOfClass:[MLFile class]]) {
  735. MLFile *file = _foundMedia[folderIndex];
  736. MLLabel *label = [[MLMediaLibrary sharedMediaLibrary] createObjectForEntity:@"Label"];
  737. label.name = folderName;
  738. file.labels = [NSSet setWithObjects:label,nil];
  739. NSNumber *folderTrackNumber = [NSNumber numberWithInt:(int)[label files].count - 1];
  740. file.folderTrackNumber = folderTrackNumber;
  741. [_foundMedia removeObjectAtIndex:folderIndex];
  742. [_foundMedia insertObject:label atIndex:folderIndex];
  743. MLFile *itemFile = _foundMedia[((NSIndexPath *)_indexPaths[0]).item];
  744. itemFile.labels = file.labels;
  745. [_foundMedia removeObjectAtIndex:((NSIndexPath *)_indexPaths[0]).item];
  746. itemFile.folderTrackNumber = @([label files].count - 1);
  747. } else {
  748. //item got dragged onto folder or items should be added to folder
  749. MLLabel *label = _foundMedia[folderIndex];
  750. [_indexPaths sortUsingSelector:@selector(compare:)];
  751. for (NSInteger i = [_indexPaths count] - 1; i >= 0; i--) {
  752. NSIndexPath *path = _indexPaths[i];
  753. if (_libraryMode != VLCLibraryModeCreateFolder && ![_foundMedia[path.row] isKindOfClass:[MLFile class]])
  754. continue;
  755. if (_libraryMode == VLCLibraryModeCreateFolder)
  756. [self updateViewContents];
  757. MLFile *file = _foundMedia[path.row];
  758. file.labels = [NSSet setWithObjects:label, nil];
  759. [_foundMedia removeObjectAtIndex:path.row];
  760. file.folderTrackNumber = @([label files].count - 1);
  761. }
  762. }
  763. _folderObject = nil;
  764. } else {
  765. //create new folder
  766. MLLabel *label = [[MLMediaLibrary sharedMediaLibrary] createObjectForEntity:@"Label"];
  767. label.name = folderName;
  768. //if items were selected
  769. if ([_indexPaths count] != 0) {
  770. [_indexPaths sortUsingSelector:@selector(compare:)];
  771. for (NSInteger i = [_indexPaths count] - 1; i >= 0; i--) {
  772. NSIndexPath *path = _indexPaths[i];
  773. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  774. MLFile *file = _foundMedia[path.item];
  775. file.labels = [NSSet setWithObjects:label, nil];
  776. file.folderTrackNumber = @([label files].count - 1);
  777. [_foundMedia removeObjectAtIndex:path.item];
  778. } else {
  779. MLFile *file = _foundMedia[path.row];
  780. file.labels = [NSSet setWithObjects:label, nil];
  781. file.folderTrackNumber = @([label files].count - 1);
  782. [_foundMedia removeObjectAtIndex:path.row];
  783. }
  784. }
  785. }
  786. }
  787. _indexPaths = nil;
  788. [self setEditing:NO];
  789. [self updateViewContents];
  790. }
  791. - (void)_collectionViewHandleLongPressGesture:(UIGestureRecognizer *) sender
  792. {
  793. [self setEditing:YES animated:YES];
  794. }
  795. #pragma mark - UI implementation
  796. - (void)setEditing:(BOOL)editing animated:(BOOL)animated
  797. {
  798. [super setEditing:editing animated:animated];
  799. UIBarButtonItem *editButton = self.editButtonItem;
  800. NSString *editImage = editing? @"doneButton": @"button";
  801. NSString *editImageHighlight = editing? @"doneButtonHighlight": @"buttonHighlight";
  802. if (SYSTEM_RUNS_IOS7_OR_LATER)
  803. editButton.tintColor = [UIColor whiteColor];
  804. else {
  805. [editButton setBackgroundImage:[UIImage imageNamed:editImage] forState:UIControlStateNormal
  806. barMetrics:UIBarMetricsDefault];
  807. [editButton setBackgroundImage:[UIImage imageNamed:editImageHighlight]
  808. forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
  809. [editButton setTitleTextAttributes: editing ? @{UITextAttributeTextShadowColor : [UIColor whiteColor], UITextAttributeTextColor : [UIColor blackColor]} : @{UITextAttributeTextShadowColor : [UIColor colorWithWhite:0. alpha:.37], UITextAttributeTextColor : [UIColor whiteColor]} forState:UIControlStateNormal];
  810. }
  811. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  812. NSArray *visibleCells = self.collectionView.visibleCells;
  813. [visibleCells enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  814. VLCPlaylistCollectionViewCell *aCell = (VLCPlaylistCollectionViewCell*)obj;
  815. [aCell setEditing:editing animated:animated];
  816. }];
  817. self.collectionView.allowsMultipleSelection = editing;
  818. /* UIKit doesn't clear the selection automagically if we leave the editing mode
  819. * so we need to do so manually */
  820. if (!editing) {
  821. [self.collectionView addGestureRecognizer:_longPressGestureRecognizer];
  822. NSArray *selectedItems = [self.collectionView indexPathsForSelectedItems];
  823. NSUInteger count = selectedItems.count;
  824. for (NSUInteger x = 0; x < count; x++)
  825. [self.collectionView deselectItemAtIndexPath:selectedItems[x] animated:NO];
  826. } else
  827. [self.collectionView removeGestureRecognizer:_longPressGestureRecognizer];
  828. } else {
  829. self.tableView.allowsMultipleSelectionDuringEditing = editing;
  830. [self.tableView setEditing:editing animated:YES];
  831. [self.editButtonItem setTitle:editing ? NSLocalizedString(@"BUTTON_CANCEL",@"") : NSLocalizedString(@"BUTTON_EDIT", @"")];
  832. }
  833. if (_libraryMode == VLCLibraryModeCreateFolder) {
  834. _libraryMode = _previousLibraryMode;
  835. _indexPaths = nil;
  836. [self updateViewContents];
  837. }
  838. self.navigationController.toolbarHidden = !editing;
  839. }
  840. - (UITableViewCellEditingStyle)tableView:(UITableView *)aTableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
  841. {
  842. return UITableViewCellEditingStyleDelete;
  843. }
  844. - (IBAction)leftButtonAction:(id)sender
  845. {
  846. [[(VLCAppDelegate*)[UIApplication sharedApplication].delegate revealController] toggleSidebar:![(VLCAppDelegate*)[UIApplication sharedApplication].delegate revealController].sidebarShowing duration:kGHRevealSidebarDefaultAnimationDuration];
  847. if (self.isEditing)
  848. [self setEditing:NO animated:YES];
  849. }
  850. - (IBAction)backToAllItems:(id)sender
  851. {
  852. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  853. if (![self.collectionView.collectionViewLayout isEqual:_folderLayout]) {
  854. //for some reason the Gesturerecognizer block themselves if not removed manually
  855. for (UIGestureRecognizer *recognizer in self.view.gestureRecognizers) {
  856. if (recognizer == _reorderLayout.panGestureRecognizer || recognizer == _reorderLayout.longPressGestureRecognizer)
  857. [self.collectionView removeGestureRecognizer:recognizer];
  858. }
  859. _folderLayout = [[VLCFolderCollectionViewFlowLayout alloc] init];
  860. [self.collectionView setCollectionViewLayout:_folderLayout animated:NO];
  861. [_collectionView addGestureRecognizer:_longPressGestureRecognizer];
  862. }
  863. }
  864. inFolder = NO;
  865. UIBarButtonItem *createFolderItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemOrganize target:self action:@selector(createFolder)];
  866. NSMutableArray *toolbarItems = [self.toolbarItems mutableCopy];
  867. toolbarItems[0] = createFolderItem;
  868. self.toolbarItems = toolbarItems;
  869. [self setLibraryMode:_libraryMode];
  870. [self updateViewContents];
  871. }
  872. - (void)_endEditingWithHardReset:(BOOL)hardReset
  873. {
  874. [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
  875. if (hardReset)
  876. [self updateViewContents];
  877. else
  878. [self reloadViews];
  879. [self setEditing:NO animated:YES];
  880. }
  881. - (void)deleteSelection
  882. {
  883. NSArray *indexPaths;
  884. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  885. indexPaths = [self.collectionView indexPathsForSelectedItems];
  886. else
  887. indexPaths = [self.tableView indexPathsForSelectedRows];
  888. NSUInteger count = indexPaths.count;
  889. NSMutableArray *objects = [[NSMutableArray alloc] initWithCapacity:count];
  890. for (NSUInteger x = 0; x < count; x++)
  891. [objects addObject:_foundMedia[[indexPaths[x] row]]];
  892. for (NSUInteger x = 0; x < count; x++)
  893. [self removeMediaObject:objects[x] updateDatabase:NO];
  894. [self _endEditingWithHardReset:YES];
  895. }
  896. - (void)renameSelection
  897. {
  898. NSArray *indexPaths;
  899. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  900. indexPaths = [self.collectionView indexPathsForSelectedItems];
  901. else
  902. indexPaths = [self.tableView indexPathsForSelectedRows];
  903. if (indexPaths.count < 1) {
  904. [self _endEditingWithHardReset:NO];
  905. return;
  906. }
  907. NSString *itemName;
  908. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  909. itemName = [(VLCPlaylistCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPaths[0]] titleLabel].text;
  910. else
  911. itemName = [(VLCPlaylistTableViewCell *)[self.tableView cellForRowAtIndexPath:indexPaths[0]] titleLabel].text;
  912. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:[NSString stringWithFormat:NSLocalizedString(@"RENAME_MEDIA_TO", @""), itemName] message:nil cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", @"") otherButtonTitles:@[NSLocalizedString(@"BUTTON_RENAME", @"")]];
  913. [alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
  914. [[alert textFieldAtIndex:0] setText:itemName];
  915. [[alert textFieldAtIndex:0] setClearButtonMode:UITextFieldViewModeAlways];
  916. __weak VLCAlertView *weakAlert = alert;
  917. alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
  918. if (cancelled)
  919. [self _endEditingWithHardReset:NO];
  920. else
  921. [self renameMediaObjectTo:[weakAlert textFieldAtIndex:0].text];
  922. };
  923. [alert show];
  924. }
  925. - (void)renameMediaObjectTo:(NSString*)newName
  926. {
  927. NSArray *indexPaths;
  928. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  929. indexPaths = [self.collectionView indexPathsForSelectedItems];
  930. else
  931. indexPaths = [self.tableView indexPathsForSelectedRows];
  932. if (indexPaths.count < 1)
  933. return;
  934. id mediaObject = _foundMedia[[indexPaths[0] row]];
  935. if ([mediaObject isKindOfClass:[MLAlbum class]] || [mediaObject isKindOfClass:[MLShowEpisode class]] || [mediaObject isKindOfClass:[MLShow class]] || [mediaObject isKindOfClass:[MLLabel class]] )
  936. [mediaObject setName:newName];
  937. else
  938. [mediaObject setTitle:newName];
  939. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  940. [self.collectionView deselectItemAtIndexPath:indexPaths[0] animated:YES];
  941. else
  942. [self.tableView deselectRowAtIndexPath:indexPaths[0] animated:YES];
  943. if (indexPaths.count > 1)
  944. [self renameSelection];
  945. else
  946. [self _endEditingWithHardReset:NO];
  947. }
  948. #pragma mark - coin coin
  949. - (void)setLibraryMode:(VLCLibraryMode)mode
  950. {
  951. _libraryMode = mode;
  952. [self updateViewContents];
  953. }
  954. #pragma mark - autorotation
  955. // RootController is responsible for supporting interface orientation(iOS6.0+), i.e. navigation controller
  956. // so this will not work as intended without "voodoo magic"(UINavigationController category, subclassing, etc)
  957. /* introduced in iOS 6 */
  958. - (NSUInteger)supportedInterfaceOrientations
  959. {
  960. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  961. return UIInterfaceOrientationMaskAll;
  962. return (_foundMedia.count > 0)? UIInterfaceOrientationMaskAllButUpsideDown:
  963. UIInterfaceOrientationMaskPortrait;
  964. }
  965. /* introduced in iOS 6 */
  966. - (BOOL)shouldAutorotate
  967. {
  968. return (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) || (_foundMedia.count > 0);
  969. }
  970. - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
  971. {
  972. [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
  973. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  974. [self.collectionView.collectionViewLayout invalidateLayout];
  975. }
  976. @end