VLCPlaylistViewController.m 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123
  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 (NSInteger i = _indexPaths.count - 1; i >=0; i--) {
  657. NSIndexPath *path = _indexPaths[i];
  658. id mediaObject;
  659. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  660. mediaObject = _foundMedia[path.item];
  661. else
  662. mediaObject = _foundMedia[path.row];
  663. if ([mediaObject isKindOfClass:[MLLabel class]])
  664. [_indexPaths removeObject:path];
  665. }
  666. if ([_indexPaths count] != 0) {
  667. NSArray *folder = [MLLabel allLabels];
  668. //if we already have folders display them
  669. if ([folder count] > 0) {
  670. _foundMedia = [NSMutableArray arrayWithArray:folder];
  671. self.title = NSLocalizedString(@"SELECT_FOLDER", @"");
  672. _previousLibraryMode = _libraryMode;
  673. _libraryMode = VLCLibraryModeCreateFolder;
  674. [self reloadViews];
  675. return;
  676. }
  677. }
  678. //no selected items or no existing folder ask for foldername
  679. [self showCreateFolderAlert];
  680. }
  681. - (void)removeFromFolder
  682. {
  683. BOOL isPad = UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad;
  684. if (isPad)
  685. _indexPaths = [NSMutableArray arrayWithArray:[self.collectionView indexPathsForSelectedItems]];
  686. else
  687. _indexPaths = [NSMutableArray arrayWithArray:[self.tableView indexPathsForSelectedRows]];
  688. [_indexPaths sortUsingSelector:@selector(compare:)];
  689. for (NSInteger i = [_indexPaths count] - 1; i >= 0; i--) {
  690. NSIndexPath *path = _indexPaths[i];
  691. MLFile *file = (MLFile *)_foundMedia[isPad ? path.item : path.row];
  692. MLLabel *folder = [file.labels anyObject];
  693. [self rearrangeFolderTrackNumbersForRemovedItem:file];
  694. file.labels = nil;
  695. file.folderTrackNumber = nil;
  696. [_foundMedia removeObject:file];
  697. if ([folder.files count] == 0) {
  698. [self removeMediaObject:folder updateDatabase:YES];
  699. [self backToAllItems:nil];
  700. }
  701. }
  702. [self reloadViews];
  703. }
  704. - (void)createFolderWithName:(NSString *)folderName
  705. {
  706. NSArray *labels = [MLLabel allLabels];
  707. for (MLLabel *label in labels){
  708. if ([label.name isEqualToString:folderName]) {
  709. _folderObject = nil;
  710. _indexPaths = nil;
  711. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"FOLDER_NAME_DUPLICATE_TITLE", @"") message:NSLocalizedString(@"FOLDER_NAME_DUPLICATE_MESSAGE", @"") cancelButtonTitle:nil otherButtonTitles:@[NSLocalizedString(@"BUTTON_OK", @"")]];
  712. alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
  713. [self updateViewContents];
  714. };
  715. [alert show];
  716. return;
  717. }
  718. }
  719. if (_folderObject != nil) {
  720. NSUInteger folderIndex = [_foundMedia indexOfObject:_folderObject];
  721. //item got dragged onto item
  722. if ([_foundMedia[folderIndex] isKindOfClass:[MLFile class]]) {
  723. MLFile *file = _foundMedia[folderIndex];
  724. MLLabel *label = [[MLMediaLibrary sharedMediaLibrary] createObjectForEntity:@"Label"];
  725. label.name = folderName;
  726. file.labels = [NSSet setWithObjects:label,nil];
  727. NSNumber *folderTrackNumber = [NSNumber numberWithInt:(int)[label files].count - 1];
  728. file.folderTrackNumber = folderTrackNumber;
  729. [_foundMedia removeObjectAtIndex:folderIndex];
  730. [_foundMedia insertObject:label atIndex:folderIndex];
  731. MLFile *itemFile = _foundMedia[((NSIndexPath *)_indexPaths[0]).item];
  732. itemFile.labels = file.labels;
  733. [_foundMedia removeObjectAtIndex:((NSIndexPath *)_indexPaths[0]).item];
  734. itemFile.folderTrackNumber = @([label files].count - 1);
  735. } else {
  736. //item got dragged onto folder or items should be added to folder
  737. MLLabel *label = _foundMedia[folderIndex];
  738. [_indexPaths sortUsingSelector:@selector(compare:)];
  739. for (NSInteger i = [_indexPaths count] - 1; i >= 0; i--) {
  740. NSIndexPath *path = _indexPaths[i];
  741. if (![_foundMedia[path.row] isKindOfClass:[MLFile class]])
  742. continue;
  743. MLFile *file = _foundMedia[path.row];
  744. file.labels = [NSSet setWithObjects:label, nil];
  745. [_foundMedia removeObjectAtIndex:path.row];
  746. file.folderTrackNumber = @([label files].count - 1);
  747. }
  748. }
  749. _folderObject = nil;
  750. } else {
  751. //create new folder
  752. MLLabel *label = [[MLMediaLibrary sharedMediaLibrary] createObjectForEntity:@"Label"];
  753. label.name = folderName;
  754. //if items were selected
  755. if ([_indexPaths count] != 0) {
  756. [_indexPaths sortUsingSelector:@selector(compare:)];
  757. for (NSInteger i = [_indexPaths count] - 1; i >= 0; i--) {
  758. NSIndexPath *path = _indexPaths[i];
  759. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  760. MLFile *file = _foundMedia[path.item];
  761. file.labels = [NSSet setWithObjects:label, nil];
  762. file.folderTrackNumber = @([label files].count - 1);
  763. [_foundMedia removeObjectAtIndex:path.item];
  764. } else {
  765. MLFile *file = _foundMedia[path.row];
  766. file.labels = [NSSet setWithObjects:label, nil];
  767. file.folderTrackNumber = @([label files].count - 1);
  768. [_foundMedia removeObjectAtIndex:path.row];
  769. }
  770. }
  771. }
  772. }
  773. _indexPaths = nil;
  774. [self setEditing:NO];
  775. [self updateViewContents];
  776. }
  777. - (void)_collectionViewHandleLongPressGesture:(UIGestureRecognizer *) sender
  778. {
  779. [self setEditing:YES animated:YES];
  780. }
  781. #pragma mark - UI implementation
  782. - (void)setEditing:(BOOL)editing animated:(BOOL)animated
  783. {
  784. [super setEditing:editing animated:animated];
  785. UIBarButtonItem *editButton = self.editButtonItem;
  786. NSString *editImage = editing? @"doneButton": @"button";
  787. NSString *editImageHighlight = editing? @"doneButtonHighlight": @"buttonHighlight";
  788. if (SYSTEM_RUNS_IOS7_OR_LATER)
  789. editButton.tintColor = [UIColor whiteColor];
  790. else {
  791. [editButton setBackgroundImage:[UIImage imageNamed:editImage] forState:UIControlStateNormal
  792. barMetrics:UIBarMetricsDefault];
  793. [editButton setBackgroundImage:[UIImage imageNamed:editImageHighlight]
  794. forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
  795. [editButton setTitleTextAttributes: editing ? @{UITextAttributeTextShadowColor : [UIColor whiteColor], UITextAttributeTextColor : [UIColor blackColor]} : @{UITextAttributeTextShadowColor : [UIColor colorWithWhite:0. alpha:.37], UITextAttributeTextColor : [UIColor whiteColor]} forState:UIControlStateNormal];
  796. }
  797. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  798. NSArray *visibleCells = self.collectionView.visibleCells;
  799. [visibleCells enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  800. VLCPlaylistCollectionViewCell *aCell = (VLCPlaylistCollectionViewCell*)obj;
  801. [aCell setEditing:editing animated:animated];
  802. }];
  803. self.collectionView.allowsMultipleSelection = editing;
  804. /* UIKit doesn't clear the selection automagically if we leave the editing mode
  805. * so we need to do so manually */
  806. if (!editing) {
  807. [self.collectionView addGestureRecognizer:_longPressGestureRecognizer];
  808. NSArray *selectedItems = [self.collectionView indexPathsForSelectedItems];
  809. NSUInteger count = selectedItems.count;
  810. for (NSUInteger x = 0; x < count; x++)
  811. [self.collectionView deselectItemAtIndexPath:selectedItems[x] animated:NO];
  812. } else
  813. [self.collectionView removeGestureRecognizer:_longPressGestureRecognizer];
  814. } else {
  815. self.tableView.allowsMultipleSelectionDuringEditing = editing;
  816. [self.tableView setEditing:editing animated:YES];
  817. [self.editButtonItem setTitle:editing ? NSLocalizedString(@"BUTTON_CANCEL",@"") : NSLocalizedString(@"BUTTON_EDIT", @"")];
  818. }
  819. if (_libraryMode == VLCLibraryModeCreateFolder) {
  820. _libraryMode = _previousLibraryMode;
  821. _indexPaths = nil;
  822. [self updateViewContents];
  823. }
  824. self.navigationController.toolbarHidden = !editing;
  825. }
  826. - (UITableViewCellEditingStyle)tableView:(UITableView *)aTableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
  827. {
  828. return UITableViewCellEditingStyleDelete;
  829. }
  830. - (IBAction)leftButtonAction:(id)sender
  831. {
  832. [[(VLCAppDelegate*)[UIApplication sharedApplication].delegate revealController] toggleSidebar:![(VLCAppDelegate*)[UIApplication sharedApplication].delegate revealController].sidebarShowing duration:kGHRevealSidebarDefaultAnimationDuration];
  833. if (self.isEditing)
  834. [self setEditing:NO animated:YES];
  835. }
  836. - (IBAction)backToAllItems:(id)sender
  837. {
  838. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  839. if (![self.collectionView.collectionViewLayout isEqual:_folderLayout]) {
  840. //for some reason the Gesturerecognizer block themselves if not removed manually
  841. for (UIGestureRecognizer *recognizer in self.view.gestureRecognizers) {
  842. if (recognizer == _reorderLayout.panGestureRecognizer || recognizer == _reorderLayout.longPressGestureRecognizer)
  843. [self.collectionView removeGestureRecognizer:recognizer];
  844. }
  845. _folderLayout = [[VLCFolderCollectionViewFlowLayout alloc] init];
  846. [self.collectionView setCollectionViewLayout:_folderLayout animated:NO];
  847. [_collectionView addGestureRecognizer:_longPressGestureRecognizer];
  848. }
  849. }
  850. inFolder = NO;
  851. UIBarButtonItem *createFolderItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemOrganize target:self action:@selector(createFolder)];
  852. NSMutableArray *toolbarItems = [self.toolbarItems mutableCopy];
  853. toolbarItems[0] = createFolderItem;
  854. self.toolbarItems = toolbarItems;
  855. [self setLibraryMode:_libraryMode];
  856. [self updateViewContents];
  857. }
  858. - (void)_endEditingWithHardReset:(BOOL)hardReset
  859. {
  860. [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
  861. if (hardReset)
  862. [self updateViewContents];
  863. else
  864. [self reloadViews];
  865. [self setEditing:NO animated:YES];
  866. }
  867. - (void)deleteSelection
  868. {
  869. NSArray *indexPaths;
  870. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  871. indexPaths = [self.collectionView indexPathsForSelectedItems];
  872. else
  873. indexPaths = [self.tableView indexPathsForSelectedRows];
  874. NSUInteger count = indexPaths.count;
  875. NSMutableArray *objects = [[NSMutableArray alloc] initWithCapacity:count];
  876. for (NSUInteger x = 0; x < count; x++)
  877. [objects addObject:_foundMedia[[indexPaths[x] row]]];
  878. for (NSUInteger x = 0; x < count; x++)
  879. [self removeMediaObject:objects[x] updateDatabase:NO];
  880. [self _endEditingWithHardReset:YES];
  881. }
  882. - (void)renameSelection
  883. {
  884. NSArray *indexPaths;
  885. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  886. indexPaths = [self.collectionView indexPathsForSelectedItems];
  887. else
  888. indexPaths = [self.tableView indexPathsForSelectedRows];
  889. if (indexPaths.count < 1) {
  890. [self _endEditingWithHardReset:NO];
  891. return;
  892. }
  893. NSString *itemName;
  894. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  895. itemName = [(VLCPlaylistCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPaths[0]] titleLabel].text;
  896. else
  897. itemName = [(VLCPlaylistTableViewCell *)[self.tableView cellForRowAtIndexPath:indexPaths[0]] titleLabel].text;
  898. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:[NSString stringWithFormat:NSLocalizedString(@"RENAME_MEDIA_TO", @""), itemName] message:nil cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", @"") otherButtonTitles:@[NSLocalizedString(@"BUTTON_RENAME", @"")]];
  899. [alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
  900. [[alert textFieldAtIndex:0] setText:itemName];
  901. [[alert textFieldAtIndex:0] setClearButtonMode:UITextFieldViewModeAlways];
  902. __weak VLCAlertView *weakAlert = alert;
  903. alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
  904. if (cancelled)
  905. [self _endEditingWithHardReset:NO];
  906. else
  907. [self renameMediaObjectTo:[weakAlert textFieldAtIndex:0].text];
  908. };
  909. [alert show];
  910. }
  911. - (void)renameMediaObjectTo:(NSString*)newName
  912. {
  913. NSArray *indexPaths;
  914. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  915. indexPaths = [self.collectionView indexPathsForSelectedItems];
  916. else
  917. indexPaths = [self.tableView indexPathsForSelectedRows];
  918. if (indexPaths.count < 1)
  919. return;
  920. id mediaObject = _foundMedia[[indexPaths[0] row]];
  921. if ([mediaObject isKindOfClass:[MLAlbum class]] || [mediaObject isKindOfClass:[MLShowEpisode class]] || [mediaObject isKindOfClass:[MLShow class]] || [mediaObject isKindOfClass:[MLLabel class]] )
  922. [mediaObject setName:newName];
  923. else
  924. [mediaObject setTitle:newName];
  925. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  926. [self.collectionView deselectItemAtIndexPath:indexPaths[0] animated:YES];
  927. else
  928. [self.tableView deselectRowAtIndexPath:indexPaths[0] animated:YES];
  929. if (indexPaths.count > 1)
  930. [self renameSelection];
  931. else
  932. [self _endEditingWithHardReset:NO];
  933. }
  934. #pragma mark - coin coin
  935. - (void)setLibraryMode:(VLCLibraryMode)mode
  936. {
  937. _libraryMode = mode;
  938. [self updateViewContents];
  939. }
  940. #pragma mark - autorotation
  941. // RootController is responsible for supporting interface orientation(iOS6.0+), i.e. navigation controller
  942. // so this will not work as intended without "voodoo magic"(UINavigationController category, subclassing, etc)
  943. /* introduced in iOS 6 */
  944. - (NSUInteger)supportedInterfaceOrientations
  945. {
  946. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  947. return UIInterfaceOrientationMaskAll;
  948. return (_foundMedia.count > 0)? UIInterfaceOrientationMaskAllButUpsideDown:
  949. UIInterfaceOrientationMaskPortrait;
  950. }
  951. /* introduced in iOS 6 */
  952. - (BOOL)shouldAutorotate
  953. {
  954. return (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) || (_foundMedia.count > 0);
  955. }
  956. - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
  957. {
  958. [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
  959. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  960. [self.collectionView.collectionViewLayout invalidateLayout];
  961. }
  962. @end