VLCPlaylistViewController.m 47 KB

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