VLCPlaylistViewController.m 47 KB

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