VLCPlaylistViewController.m 53 KB

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