VLCPlaylistViewController.m 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448
  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. #import "VLCOpenInActivity.h"
  29. #import <AssetsLibrary/AssetsLibrary.h>
  30. /* prefs keys */
  31. static NSString *kDisplayedFirstSteps = @"Did we display the first steps tutorial?";
  32. @implementation EmptyLibraryView
  33. - (IBAction)learnMore:(id)sender
  34. {
  35. UIViewController *firstStepsVC = [[VLCFirstStepsViewController alloc] initWithNibName:nil bundle:nil];
  36. UINavigationController *navCon = [[UINavigationController alloc] initWithRootViewController:firstStepsVC];
  37. navCon.modalPresentationStyle = UIModalPresentationFormSheet;
  38. [navCon loadTheme];
  39. [self.window.rootViewController presentViewController:navCon animated:YES completion:nil];
  40. }
  41. @end
  42. @interface VLCPlaylistViewController () <VLCFolderCollectionViewDelegateFlowLayout, LXReorderableCollectionViewDataSource, LXReorderableCollectionViewDelegateFlowLayout, UITableViewDataSource, UITableViewDelegate, MLMediaLibrary, VLCMediaListDelegate, UISearchBarDelegate, UISearchDisplayDelegate> {
  43. NSMutableArray *_foundMedia;
  44. VLCLibraryMode _libraryMode;
  45. VLCLibraryMode _previousLibraryMode;
  46. UIBarButtonItem *_menuButton;
  47. NSMutableArray *_indexPaths;
  48. id _folderObject;
  49. VLCFolderCollectionViewFlowLayout *_folderLayout;
  50. LXReorderableCollectionViewFlowLayout *_reorderLayout;
  51. BOOL inFolder;
  52. UILongPressGestureRecognizer *_longPressGestureRecognizer;
  53. NSInteger _mediaToPlayIndex;
  54. VLCMediaList *_list;
  55. NSArray *_tracks;
  56. NSMutableArray *_searchData;
  57. UISearchBar *_searchBar;
  58. UISearchDisplayController *_searchDisplayController;
  59. BOOL _usingTableViewToShowData;
  60. UIBarButtonItem *_actionBarButtonItem;
  61. VLCOpenInActivity *_openInActivity;
  62. }
  63. @property (nonatomic, strong) UITableView *tableView;
  64. @property (nonatomic, strong) UICollectionView *collectionView;
  65. @property (nonatomic, strong) EmptyLibraryView *emptyLibraryView;
  66. @end
  67. @implementation VLCPlaylistViewController
  68. + (void)initialize
  69. {
  70. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  71. [defaults registerDefaults:@{kDisplayedFirstSteps : [NSNumber numberWithBool:NO]}];
  72. }
  73. - (void)loadView
  74. {
  75. _usingTableViewToShowData = UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone;
  76. if (_usingTableViewToShowData) {
  77. _tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
  78. _tableView.backgroundColor = [UIColor VLCDarkBackgroundColor];
  79. _tableView.rowHeight = [VLCPlaylistTableViewCell heightOfCell];
  80. _tableView.separatorColor = [UIColor VLCDarkBackgroundColor];
  81. _tableView.delegate = self;
  82. _tableView.dataSource = self;
  83. _tableView.opaque = YES;
  84. self.view = _tableView;
  85. } else {
  86. _folderLayout = [[VLCFolderCollectionViewFlowLayout alloc] init];
  87. _collectionView = [[UICollectionView alloc] initWithFrame:[UIScreen mainScreen].bounds collectionViewLayout:_folderLayout];
  88. _collectionView.alwaysBounceVertical = YES;
  89. _collectionView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
  90. _collectionView.delegate = self;
  91. _collectionView.dataSource = self;
  92. _collectionView.opaque = YES;
  93. _collectionView.backgroundColor = [UIColor VLCDarkBackgroundColor];
  94. self.view = _collectionView;
  95. _longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(_collectionViewHandleLongPressGesture:)];
  96. [_collectionView addGestureRecognizer:_longPressGestureRecognizer];
  97. if (SYSTEM_RUNS_IOS7_OR_LATER)
  98. [_collectionView registerNib:[UINib nibWithNibName:@"VLCFuturePlaylistCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"PlaylistCell"];
  99. else
  100. [_collectionView registerNib:[UINib nibWithNibName:@"VLCPlaylistCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"PlaylistCell"];
  101. self.view.backgroundColor = [UIColor VLCDarkBackgroundColor];
  102. }
  103. _libraryMode = VLCLibraryModeAllFiles;
  104. self.view.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
  105. self.emptyLibraryView = [[[NSBundle mainBundle] loadNibNamed:@"VLCEmptyLibraryView" owner:self options:nil] lastObject];
  106. _emptyLibraryView.emptyLibraryLongDescriptionLabel.lineBreakMode = NSLineBreakByWordWrapping;
  107. _emptyLibraryView.emptyLibraryLongDescriptionLabel.numberOfLines = 0;
  108. }
  109. #pragma mark -
  110. - (void)viewDidLoad
  111. {
  112. [super viewDidLoad];
  113. self.title = NSLocalizedString(@"LIBRARY_ALL_FILES", @"");
  114. _menuButton = [UIBarButtonItem themedRevealMenuButtonWithTarget:self andSelector:@selector(leftButtonAction:)];
  115. self.navigationItem.leftBarButtonItem = _menuButton;
  116. if (SYSTEM_RUNS_IOS7_OR_LATER)
  117. self.editButtonItem.tintColor = [UIColor whiteColor];
  118. else {
  119. [self.editButtonItem setBackgroundImage:[UIImage imageNamed:@"button"]
  120. forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
  121. [self.editButtonItem setBackgroundImage:[UIImage imageNamed:@"buttonHighlight"]
  122. forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
  123. }
  124. _emptyLibraryView.emptyLibraryLabel.text = NSLocalizedString(@"EMPTY_LIBRARY", @"");
  125. _emptyLibraryView.emptyLibraryLongDescriptionLabel.text = NSLocalizedString(@"EMPTY_LIBRARY_LONG", @"");
  126. [_emptyLibraryView.emptyLibraryLongDescriptionLabel sizeToFit];
  127. [_emptyLibraryView.learnMoreButton setTitle:NSLocalizedString(@"BUTTON_LEARN_MORE", @"") forState:UIControlStateNormal];
  128. UIBarButtonItem *createFolderItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemOrganize target:self action:@selector(createFolder)];
  129. // Better visual alignment with the action button
  130. UIEdgeInsets insets = UIEdgeInsetsMake(4, 0, 0, 0);
  131. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
  132. insets.top += 1;
  133. }
  134. createFolderItem.imageInsets = insets;
  135. _actionBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(actOnSelection:)];
  136. _actionBarButtonItem.enabled = NO;
  137. // If you find strange issues with multiple Edit/Cancel actions causing UIToolbar spacing corruption, use a flexible space instead of a fixed space.
  138. UIBarButtonItem *fixedSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
  139. fixedSpace.width = 20;
  140. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  141. fixedSpace.width *= 2;
  142. }
  143. [self setToolbarItems:@[_actionBarButtonItem, fixedSpace, 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)]]];
  144. self.navigationController.toolbar.barStyle = UIBarStyleBlack;
  145. if (SYSTEM_RUNS_IOS7_OR_LATER) {
  146. self.navigationController.toolbar.tintColor = [UIColor whiteColor];
  147. [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
  148. } else
  149. [self.navigationController.toolbar setBackgroundImage:[UIImage imageNamed:@"bottomBlackBar"] forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
  150. if (_usingTableViewToShowData) {
  151. _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
  152. UINavigationBar *navBar = self.navigationController.navigationBar;
  153. if (SYSTEM_RUNS_IOS7_OR_LATER) {
  154. _searchBar.barTintColor = navBar.barTintColor;
  155. }
  156. _searchBar.tintColor = navBar.tintColor;
  157. _searchBar.translucent = navBar.translucent;
  158. _searchBar.opaque = navBar.opaque;
  159. _searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:_searchBar contentsController:self];
  160. _searchDisplayController.delegate = self;
  161. _searchDisplayController.searchResultsDataSource = self;
  162. _searchDisplayController.searchResultsDelegate = self;
  163. _searchBar.delegate = self;
  164. UITapGestureRecognizer *tapTwiceGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTwiceGestureAction:)];
  165. [tapTwiceGesture setNumberOfTapsRequired:2];
  166. [self.navigationController.navigationBar addGestureRecognizer:tapTwiceGesture];
  167. }
  168. _searchData = [[NSMutableArray alloc] init];
  169. }
  170. - (void)viewWillAppear:(BOOL)animated
  171. {
  172. [super viewWillAppear:animated];
  173. [self.collectionView.collectionViewLayout invalidateLayout];
  174. [self _displayEmptyLibraryViewIfNeeded];
  175. }
  176. - (void)viewDidAppear:(BOOL)animated
  177. {
  178. [super viewDidAppear:animated];
  179. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  180. if (![[defaults objectForKey:kDisplayedFirstSteps] boolValue]) {
  181. [self.emptyLibraryView performSelector:@selector(learnMore:) withObject:nil afterDelay:1.];
  182. [defaults setObject:[NSNumber numberWithBool:YES] forKey:kDisplayedFirstSteps];
  183. [defaults synchronize];
  184. }
  185. if ([[MLMediaLibrary sharedMediaLibrary] libraryNeedsUpgrade]) {
  186. self.navigationItem.rightBarButtonItem = nil;
  187. self.navigationItem.leftBarButtonItem = nil;
  188. self.title = @"";
  189. self.emptyLibraryView.emptyLibraryLabel.text = NSLocalizedString(@"UPGRADING_LIBRARY", @"");
  190. self.emptyLibraryView.emptyLibraryLongDescriptionLabel.hidden = YES;
  191. [self.emptyLibraryView.activityIndicator startAnimating];
  192. self.emptyLibraryView.frame = self.view.bounds;
  193. [self.view addSubview:self.emptyLibraryView];
  194. [[MLMediaLibrary sharedMediaLibrary] setDelegate: self];
  195. [[MLMediaLibrary sharedMediaLibrary] performSelectorInBackground:@selector(upgradeLibrary) withObject:nil];
  196. return;
  197. }
  198. if (_foundMedia.count < 1)
  199. [self updateViewContents];
  200. [[MLMediaLibrary sharedMediaLibrary] performSelector:@selector(libraryDidAppear) withObject:nil afterDelay:1.];
  201. }
  202. - (void)viewDidDisappear:(BOOL)animated
  203. {
  204. [super viewDidDisappear:animated];
  205. [[MLMediaLibrary sharedMediaLibrary] libraryDidDisappear];
  206. }
  207. - (BOOL)canBecomeFirstResponder
  208. {
  209. return YES;
  210. }
  211. - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
  212. {
  213. if (motion == UIEventSubtypeMotionShake)
  214. [[VLCBugreporter sharedInstance] handleBugreportRequest];
  215. }
  216. - (void)openMediaObject:(NSManagedObject *)mediaObject
  217. {
  218. if ([mediaObject isKindOfClass:[MLAlbum class]]) {
  219. _foundMedia = [NSMutableArray arrayWithArray:[(MLAlbum *)mediaObject sortedTracks]];
  220. self.navigationItem.leftBarButtonItem = [UIBarButtonItem themedBackButtonWithTarget:self andSelector:@selector(backToAllItems:)];
  221. if (_libraryMode == VLCLibraryModeAllFiles)
  222. self.navigationItem.leftBarButtonItem.title = NSLocalizedString(@"BUTTON_BACK", @"");
  223. else
  224. [self.navigationItem.leftBarButtonItem setTitle:NSLocalizedString(@"LIBRARY_MUSIC", @"")];
  225. self.title = [(MLAlbum*)mediaObject name];
  226. [self reloadViews];
  227. } else if ([mediaObject isKindOfClass:[MLShow class]]) {
  228. _foundMedia = [NSMutableArray arrayWithArray:[(MLShow *)mediaObject sortedEpisodes]];
  229. self.navigationItem.leftBarButtonItem = [UIBarButtonItem themedBackButtonWithTarget:self andSelector:@selector(backToAllItems:)];
  230. if (_libraryMode == VLCLibraryModeAllFiles)
  231. self.navigationItem.leftBarButtonItem.title = NSLocalizedString(@"BUTTON_BACK", @"");
  232. else
  233. [self.navigationItem.leftBarButtonItem setTitle:NSLocalizedString(@"LIBRARY_SERIES", @"")];
  234. self.title = [(MLShow*)mediaObject name];
  235. [self reloadViews];
  236. } else if ([mediaObject isKindOfClass:[MLLabel class]]) {
  237. MLLabel *folder = (MLLabel*) mediaObject;
  238. inFolder = YES;
  239. if (!_usingTableViewToShowData) {
  240. if (![self.collectionView.collectionViewLayout isEqual:_reorderLayout]) {
  241. for (UIGestureRecognizer *recognizer in self.view.gestureRecognizers) {
  242. if (recognizer == _folderLayout.panGestureRecognizer || recognizer == _folderLayout.longPressGestureRecognizer || recognizer == _longPressGestureRecognizer)
  243. [self.collectionView removeGestureRecognizer:recognizer];
  244. }
  245. _reorderLayout = [[LXReorderableCollectionViewFlowLayout alloc] init];
  246. [self.collectionView setCollectionViewLayout:_reorderLayout animated:NO];
  247. }
  248. }
  249. _foundMedia = [NSMutableArray arrayWithArray:[folder sortedFolderItems]];
  250. self.navigationItem.leftBarButtonItem = [UIBarButtonItem themedBackButtonWithTarget:self andSelector:@selector(backToAllItems:)];
  251. self.navigationItem.leftBarButtonItem.title = NSLocalizedString(@"BUTTON_BACK", @"");
  252. self.title = [folder name];
  253. UIBarButtonItem *removeFromFolder = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemReply target:self action:@selector(removeFromFolder)];
  254. NSMutableArray *toolbarItems = [self.toolbarItems mutableCopy];
  255. toolbarItems[2] = removeFromFolder;
  256. self.toolbarItems = toolbarItems;
  257. [self reloadViews];
  258. return;
  259. } else
  260. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate openMediaFromManagedObject:mediaObject];
  261. }
  262. - (void)removeMediaObject:(id)managedObject updateDatabase:(BOOL)updateDB
  263. {
  264. // delete all tracks from an album
  265. if ([managedObject isKindOfClass:[MLAlbum class]]) {
  266. MLAlbum *album = managedObject;
  267. NSSet *iterAlbumTrack = [NSSet setWithSet:album.tracks];
  268. for (MLAlbumTrack *track in iterAlbumTrack) {
  269. NSSet *iterFiles = [NSSet setWithSet:track.files];
  270. for (MLFile *file in iterFiles)
  271. [self _deleteMediaObject:file];
  272. }
  273. // delete all episodes from a show
  274. } else if ([managedObject isKindOfClass:[MLShow class]]) {
  275. MLShow *show = managedObject;
  276. NSSet *iterShowEpisodes = [NSSet setWithSet:show.episodes];
  277. for (MLShowEpisode *episode in iterShowEpisodes) {
  278. NSSet *iterFiles = [NSSet setWithSet:episode.files];
  279. for (MLFile *file in iterFiles)
  280. [self _deleteMediaObject:file];
  281. }
  282. // delete all files from an episode
  283. } else if ([managedObject isKindOfClass:[MLShowEpisode class]]) {
  284. MLShowEpisode *episode = managedObject;
  285. NSSet *iterFiles = [NSSet setWithSet:episode.files];
  286. for (MLFile *file in iterFiles)
  287. [self _deleteMediaObject:file];
  288. // delete all files from a track
  289. } else if ([managedObject isKindOfClass:[MLAlbumTrack class]]) {
  290. MLAlbumTrack *track = managedObject;
  291. NSSet *iterFiles = [NSSet setWithSet:track.files];
  292. for (MLFile *file in iterFiles)
  293. [self _deleteMediaObject:file];
  294. } else if ([managedObject isKindOfClass:[MLLabel class]]) {
  295. MLLabel *folder = managedObject;
  296. NSSet *iterFiles = [NSSet setWithSet:folder.files];
  297. [folder removeFiles:folder.files];
  298. for (MLFile *file in iterFiles)
  299. [self _deleteMediaObject:file];
  300. [[MLMediaLibrary sharedMediaLibrary] removeObject:folder];
  301. }
  302. else
  303. [self _deleteMediaObject:managedObject];
  304. if (updateDB) {
  305. [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
  306. [self updateViewContents];
  307. }
  308. }
  309. - (void)_deleteMediaObject:(MLFile *)mediaObject
  310. {
  311. if (inFolder)
  312. [self rearrangeFolderTrackNumbersForRemovedItem:mediaObject];
  313. NSFileManager *fileManager = [NSFileManager defaultManager];
  314. NSString *folderLocation = [[[NSURL URLWithString:mediaObject.url] path] stringByDeletingLastPathComponent];
  315. NSArray *allfiles = [fileManager contentsOfDirectoryAtPath:folderLocation error:nil];
  316. NSString *fileName = [[[[NSURL URLWithString:mediaObject.url] path] lastPathComponent] stringByDeletingPathExtension];
  317. NSIndexSet *indexSet = [allfiles indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
  318. return ([obj rangeOfString:fileName].location != NSNotFound);
  319. }];
  320. NSUInteger count = indexSet.count;
  321. NSString *additionalFilePath;
  322. NSUInteger currentIndex = [indexSet firstIndex];
  323. for (unsigned int x = 0; x < count; x++) {
  324. additionalFilePath = allfiles[currentIndex];
  325. if ([additionalFilePath isSupportedSubtitleFormat])
  326. [fileManager removeItemAtPath:[folderLocation stringByAppendingPathComponent:additionalFilePath] error:nil];
  327. currentIndex = [indexSet indexGreaterThanIndex:currentIndex];
  328. }
  329. [fileManager removeItemAtPath:[[NSURL URLWithString:mediaObject.url] path] error:nil];
  330. }
  331. - (void)_displayEmptyLibraryViewIfNeeded
  332. {
  333. if (self.emptyLibraryView.superview)
  334. [self.emptyLibraryView removeFromSuperview];
  335. if (_foundMedia.count == 0) {
  336. self.emptyLibraryView.emptyLibraryLabel.text = inFolder ? NSLocalizedString(@"FOLDER_EMPTY", @"") : NSLocalizedString(@"EMPTY_LIBRARY", @"");
  337. self.emptyLibraryView.emptyLibraryLongDescriptionLabel.text = inFolder ? NSLocalizedString(@"FOLDER_EMPTY_LONG", @"") : NSLocalizedString(@"EMPTY_LIBRARY_LONG", @"");
  338. self.emptyLibraryView.learnMoreButton.hidden = inFolder;
  339. self.emptyLibraryView.frame = self.view.bounds;
  340. [self.view addSubview:self.emptyLibraryView];
  341. self.navigationItem.rightBarButtonItem = nil;
  342. } else
  343. self.navigationItem.rightBarButtonItem = self.editButtonItem;
  344. if (_usingTableViewToShowData)
  345. _tableView.separatorStyle = (_foundMedia.count > 0)? UITableViewCellSeparatorStyleSingleLine:
  346. UITableViewCellSeparatorStyleNone;
  347. else
  348. [self.collectionView.collectionViewLayout invalidateLayout];
  349. }
  350. - (void)libraryUpgradeComplete
  351. {
  352. self.title = NSLocalizedString(@"LIBRARY_ALL_FILES", @"");
  353. self.navigationItem.leftBarButtonItem = _menuButton;
  354. self.emptyLibraryView.emptyLibraryLongDescriptionLabel.hidden = NO;
  355. self.emptyLibraryView.emptyLibraryLabel.text = NSLocalizedString(@"EMPTY_LIBRARY", @"");
  356. [self.emptyLibraryView.activityIndicator stopAnimating];
  357. [self.emptyLibraryView removeFromSuperview];
  358. [self updateViewContents];
  359. }
  360. - (void)libraryWasUpdated
  361. {
  362. [self updateViewContents];
  363. }
  364. - (void)updateViewContents
  365. {
  366. _foundMedia = [[NSMutableArray alloc] init];
  367. self.navigationItem.leftBarButtonItem = _menuButton;
  368. if (_libraryMode == VLCLibraryModeAllAlbums)
  369. self.title = NSLocalizedString(@"LIBRARY_MUSIC", @"");
  370. else if( _libraryMode == VLCLibraryModeAllSeries)
  371. self.title = NSLocalizedString(@"LIBRARY_SERIES", @"");
  372. else
  373. self.title = NSLocalizedString(@"LIBRARY_ALL_FILES", @"");
  374. /* add all albums */
  375. if (_libraryMode != VLCLibraryModeAllSeries) {
  376. NSArray *rawAlbums = [MLAlbum allAlbums];
  377. for (MLAlbum *album in rawAlbums) {
  378. if (album.name.length > 0 && album.tracks.count > 1)
  379. [_foundMedia addObject:album];
  380. }
  381. }
  382. if (_libraryMode == VLCLibraryModeAllAlbums) {
  383. [self reloadViews];
  384. return;
  385. }
  386. /* add all shows */
  387. NSArray *rawShows = [MLShow allShows];
  388. for (MLShow *show in rawShows) {
  389. if (show.name.length > 0 && show.episodes.count > 1)
  390. [_foundMedia addObject:show];
  391. }
  392. if (_libraryMode == VLCLibraryModeAllSeries) {
  393. [self reloadViews];
  394. return;
  395. }
  396. /* add all folders*/
  397. NSArray *allFolders = [MLLabel allLabels];
  398. for (MLLabel *folder in allFolders)
  399. [_foundMedia addObject:folder];
  400. /* add all remaining files */
  401. NSArray *allFiles = [MLFile allFiles];
  402. for (MLFile *file in allFiles) {
  403. if (file.labels.count > 0) continue;
  404. if (!file.isShowEpisode && !file.isAlbumTrack)
  405. [_foundMedia addObject:file];
  406. else if (file.isShowEpisode) {
  407. if (file.showEpisode.show.episodes.count < 2)
  408. [_foundMedia addObject:file];
  409. /* older MediaLibraryKit versions don't send a show name in a popular
  410. * corner case. hence, we need to work-around here and force a reload
  411. * afterwards as this could lead to the 'all my shows are gone'
  412. * syndrome (see #10435, #10464, #10432 et al) */
  413. if (file.showEpisode.show.name.length == 0) {
  414. file.showEpisode.show.name = NSLocalizedString(@"UNTITLED_SHOW", @"");
  415. [self performSelector:@selector(updateViewContents) withObject:nil afterDelay:0.1];
  416. }
  417. } else if (file.isAlbumTrack) {
  418. if (file.albumTrack.album.tracks.count < 2)
  419. [_foundMedia addObject:file];
  420. }
  421. }
  422. [self reloadViews];
  423. }
  424. - (void)reloadViews
  425. {
  426. // Since this gets can get called at any point and wipe away the selections, we update the actionBarButtonItem here because this can happen if you tap "Save Video" in the UIActivityController and a media access alert view takes away focus (the corresponding 'became active' notification of UIApplication will call this). Or simply try bringing down the notification center to trigger this. Any existing UIActivityViewController session should be safe as it would have copies of the selected file references.
  427. if (_usingTableViewToShowData) {
  428. [self.tableView reloadData];
  429. [self updateActionBarButtonItemStateWithSelectedIndexPaths:[self.tableView indexPathsForSelectedRows]];
  430. } else {
  431. [self.collectionView reloadData];
  432. [self updateActionBarButtonItemStateWithSelectedIndexPaths:[self.collectionView indexPathsForSelectedItems]];
  433. }
  434. [self _displayEmptyLibraryViewIfNeeded];
  435. }
  436. #pragma mark - Table View
  437. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  438. {
  439. return 1;
  440. }
  441. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  442. {
  443. if (tableView == self.searchDisplayController.searchResultsTableView)
  444. return _searchData.count;
  445. return _foundMedia.count;
  446. }
  447. // Customize the appearance of table view cells.
  448. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  449. {
  450. static NSString *CellIdentifier = @"PlaylistCell";
  451. VLCPlaylistTableViewCell *cell = (VLCPlaylistTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  452. if (cell == nil)
  453. cell = [VLCPlaylistTableViewCell cellWithReuseIdentifier:CellIdentifier];
  454. UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRightGestureAction:)];
  455. [swipeRight setDirection:(UISwipeGestureRecognizerDirectionRight)];
  456. [cell addGestureRecognizer:swipeRight];
  457. NSInteger row = indexPath.row;
  458. if (tableView == self.searchDisplayController.searchResultsTableView)
  459. cell.mediaObject = _searchData[row];
  460. else
  461. cell.mediaObject = _foundMedia[row];
  462. return cell;
  463. }
  464. - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
  465. {
  466. MLFile* object = [_foundMedia objectAtIndex:fromIndexPath.item];
  467. [_foundMedia removeObjectAtIndex:fromIndexPath.item];
  468. [_foundMedia insertObject:object atIndex:toIndexPath.item];
  469. object.folderTrackNumber = @(toIndexPath.item - 1);
  470. object = [_foundMedia objectAtIndex:fromIndexPath.item];
  471. object.folderTrackNumber = @(fromIndexPath.item - 1);
  472. }
  473. - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
  474. {
  475. return inFolder;
  476. }
  477. - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  478. {
  479. cell.backgroundColor = (indexPath.row % 2 == 0)? [UIColor blackColor]: [UIColor VLCDarkBackgroundColor];
  480. cell.multipleSelectionBackgroundView.backgroundColor = cell.backgroundColor;
  481. }
  482. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  483. {
  484. return YES;
  485. }
  486. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  487. {
  488. if (editingStyle == UITableViewCellEditingStyleDelete)
  489. [self removeMediaObject: _foundMedia[indexPath.row] updateDatabase:YES];
  490. }
  491. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
  492. {
  493. if (tableView.isEditing) {
  494. [self updateActionBarButtonItemStateWithSelectedIndexPaths:[tableView indexPathsForSelectedRows]];
  495. }
  496. }
  497. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  498. {
  499. if (tableView.isEditing) {
  500. if (_libraryMode == VLCLibraryModeCreateFolder) {
  501. _folderObject = _foundMedia[indexPath.row];
  502. _libraryMode = _previousLibraryMode;
  503. [self updateViewContents];
  504. [self createFolderWithName:nil];
  505. } else {
  506. [self updateActionBarButtonItemStateWithSelectedIndexPaths:[tableView indexPathsForSelectedRows]];
  507. }
  508. return;
  509. }
  510. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  511. NSManagedObject *selectedObject;
  512. if (tableView == self.searchDisplayController.searchResultsTableView)
  513. selectedObject = _searchData[indexPath.row];
  514. else
  515. selectedObject = _foundMedia[indexPath.row];
  516. if ([selectedObject isKindOfClass:[MLAlbumTrack class]]) {
  517. _tracks = [[(MLAlbumTrack*)selectedObject album] sortedTracks];
  518. NSUInteger count = _tracks.count;
  519. _list = [[VLCMediaList alloc] init];
  520. _list.delegate = self;
  521. MLFile *file;
  522. VLCMedia *media;
  523. for (NSInteger x = count - 1; x > -1; x--) {
  524. file = [(MLAlbumTrack*)_tracks[x] files].anyObject;
  525. media = [VLCMedia mediaWithURL: [NSURL URLWithString:file.url]];
  526. [media parse];
  527. [_list addMedia:media];
  528. }
  529. _mediaToPlayIndex = indexPath.row;
  530. } else if ([selectedObject isKindOfClass:[MLFile class]] && [((MLFile *)selectedObject).labels count] > 0) {
  531. MLLabel *folder = [((MLFile *)selectedObject).labels anyObject];
  532. _tracks = [folder sortedFolderItems];
  533. NSUInteger count = _tracks.count;
  534. _list = [[VLCMediaList alloc] init];
  535. _list.delegate = self;
  536. MLFile *file;
  537. for (NSInteger x = count - 1; x > -1; x--) {
  538. file = (MLFile *)_tracks[x];
  539. [_list addMedia:[VLCMedia mediaWithURL:[NSURL URLWithString:file.url]]];
  540. }
  541. _mediaToPlayIndex = indexPath.row;
  542. }
  543. if (_searchDisplayController.active == YES)
  544. [_searchDisplayController setActive:NO animated:YES];
  545. [self openMediaObject:selectedObject];
  546. }
  547. #pragma mark - VLCMedialistDelegate
  548. - (void)mediaList:(VLCMediaList *)aMediaList mediaAdded:(VLCMedia *)media atIndex:(NSInteger)index
  549. {
  550. if (index == _tracks.count - 1) {
  551. NSManagedObject *selectedObject = _foundMedia[_mediaToPlayIndex];
  552. [(VLCAppDelegate *)[UIApplication sharedApplication].delegate openMediaList:_list atIndex:(int)[_tracks indexOfObject:selectedObject]];
  553. }
  554. }
  555. #pragma mark - Gesture Action
  556. - (void)swipeRightGestureAction:(UIGestureRecognizer *)recognizer
  557. {
  558. if ([[self.editButtonItem title] isEqualToString:NSLocalizedString(@"BUTTON_CANCEL",@"")])
  559. [self setEditing:NO animated:YES];
  560. else {
  561. [self setEditing:YES animated:YES];
  562. NSIndexPath *path = [(UITableView *)self.view indexPathForRowAtPoint:[recognizer locationInView:self.view]];
  563. [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:path.row inSection:path.section]
  564. animated:YES
  565. scrollPosition:UITableViewScrollPositionNone];
  566. }
  567. }
  568. - (void)tapTwiceGestureAction:(UIGestureRecognizer *)recognizer
  569. {
  570. _searchBar.hidden = !_searchBar.hidden;
  571. if (_searchBar.hidden)
  572. self.tableView.tableHeaderView = nil;
  573. else
  574. self.tableView.tableHeaderView = _searchBar;
  575. }
  576. #pragma mark - Collection View
  577. - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
  578. {
  579. return _foundMedia.count;
  580. }
  581. - (UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
  582. {
  583. VLCPlaylistCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PlaylistCell" forIndexPath:indexPath];
  584. cell.mediaObject = _foundMedia[indexPath.row];
  585. cell.collectionView = _collectionView;
  586. [cell setEditing:self.editing animated:NO];
  587. return cell;
  588. }
  589. - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
  590. {
  591. if (SYSTEM_RUNS_IOS7_OR_LATER) {
  592. if (UIDeviceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation))
  593. return CGSizeMake(341., 190.);
  594. else
  595. return CGSizeMake(384., 216.);
  596. }
  597. return CGSizeMake(298.0, 220.0);
  598. }
  599. - (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
  600. {
  601. if (SYSTEM_RUNS_IOS7_OR_LATER)
  602. return UIEdgeInsetsZero;
  603. return UIEdgeInsetsMake(0.0, 34.0, 0.0, 34.0);
  604. }
  605. - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
  606. {
  607. if (SYSTEM_RUNS_IOS7_OR_LATER)
  608. return 0.;
  609. return 10.0;
  610. }
  611. - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
  612. {
  613. if (SYSTEM_RUNS_IOS7_OR_LATER)
  614. return 0.;
  615. return 10.0;
  616. }
  617. - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
  618. {
  619. if (self.editing) {
  620. if (_libraryMode == VLCLibraryModeCreateFolder) {
  621. _folderObject = _foundMedia[indexPath.item];
  622. [self createFolderWithName:nil];
  623. _libraryMode = _previousLibraryMode;
  624. } else {
  625. [self updateActionBarButtonItemStateWithSelectedIndexPaths:[collectionView indexPathsForSelectedItems]];
  626. }
  627. [(VLCPlaylistCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath] selectionUpdate];
  628. return;
  629. }
  630. NSManagedObject *selectedObject = _foundMedia[indexPath.row];
  631. if ([selectedObject isKindOfClass:[MLAlbumTrack class]]) {
  632. VLCMediaList *list;
  633. NSArray *tracks = [[(MLAlbumTrack*)selectedObject album] sortedTracks];
  634. NSUInteger count = tracks.count;
  635. list = [[VLCMediaList alloc] init];
  636. MLFile *file;
  637. for (NSInteger x = count - 1; x > -1; x--) {
  638. file = [(MLAlbumTrack*)tracks[x] files].anyObject;
  639. [list addMedia:[VLCMedia mediaWithURL: [NSURL URLWithString:file.url]]];
  640. }
  641. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate openMediaList:list atIndex:(int)[tracks indexOfObject:selectedObject]];
  642. } else if ([selectedObject isKindOfClass:[MLFile class]] && [((MLFile *)selectedObject).labels count] > 0) {
  643. VLCMediaList *list;
  644. MLLabel *folder = [((MLFile *)selectedObject).labels anyObject];
  645. NSArray *folderTracks = [folder sortedFolderItems];
  646. NSUInteger count = folderTracks.count;
  647. list = [[VLCMediaList alloc] init];
  648. MLFile *file;
  649. for (NSInteger x = count - 1; x > -1; x--) {
  650. file = (MLFile *)folderTracks[x];
  651. [list addMedia:[VLCMedia mediaWithURL:[NSURL URLWithString:file.url]]];
  652. }
  653. [(VLCAppDelegate *)[UIApplication sharedApplication].delegate openMediaList:list atIndex:(int)[folderTracks indexOfObject:selectedObject]];
  654. } else
  655. [self openMediaObject:selectedObject];
  656. }
  657. - (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
  658. {
  659. if (self.editing) {
  660. [self updateActionBarButtonItemStateWithSelectedIndexPaths:[collectionView indexPathsForSelectedItems]];
  661. }
  662. [(VLCPlaylistCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath] selectionUpdate];
  663. }
  664. - (void)collectionView:(UICollectionView *)collectionView removeItemFromFolderAtIndexPathIfNeeded:(NSIndexPath *)indexPath
  665. {
  666. MLFile *mediaObject = (MLFile *)_foundMedia[indexPath.item];
  667. [self rearrangeFolderTrackNumbersForRemovedItem:mediaObject];
  668. mediaObject.labels = nil;
  669. mediaObject.folderTrackNumber = nil;
  670. [self backToAllItems:nil];
  671. }
  672. - (void)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)fromIndexPath willMoveToIndexPath:(NSIndexPath *)toIndexPath
  673. {
  674. MLFile* object = [_foundMedia objectAtIndex:fromIndexPath.item];
  675. [_foundMedia removeObjectAtIndex:fromIndexPath.item];
  676. [_foundMedia insertObject:object atIndex:toIndexPath.item];
  677. object.folderTrackNumber = @(toIndexPath.item - 1);
  678. object = [_foundMedia objectAtIndex:fromIndexPath.item];
  679. object.folderTrackNumber = @(fromIndexPath.item - 1);
  680. }
  681. - (void)collectionView:(UICollectionView *)collectionView requestToMoveItemAtIndexPath:(NSIndexPath *)itemPath intoFolderAtIndexPath:(NSIndexPath *)folderPath
  682. {
  683. BOOL validFileTypeAtFolderPath = ([_foundMedia[folderPath.item] isKindOfClass:[MLFile class]] || [_foundMedia[folderPath.item] isKindOfClass:[MLLabel class]]) && [_foundMedia[itemPath.item] isKindOfClass:[MLFile class]];
  684. if (!validFileTypeAtFolderPath) {
  685. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"FOLDER_INVALID_TYPE_TITLE", @"") message:NSLocalizedString(@"FOLDER_INVALID_TYPE_MESSAGE", @"") cancelButtonTitle:nil otherButtonTitles:@[NSLocalizedString(@"BUTTON_OK", @"")]];
  686. alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
  687. [self updateViewContents];
  688. };
  689. [alert show];
  690. return;
  691. }
  692. BOOL isFolder = [_foundMedia[folderPath.item] isKindOfClass:[MLLabel class]];
  693. if (isFolder){
  694. MLLabel *folder = _foundMedia[folderPath.item];
  695. MLFile *file = _foundMedia[itemPath.item];
  696. [file setLabels:[[NSSet alloc] initWithObjects:folder, nil]];
  697. file.folderTrackNumber = @([folder.files count] - 1);
  698. [_foundMedia removeObjectAtIndex:itemPath.item];
  699. [self updateViewContents];
  700. } else {
  701. _folderObject = _foundMedia[folderPath.item];
  702. _indexPaths = [NSMutableArray arrayWithArray:@[itemPath]];
  703. [self showCreateFolderAlert];
  704. }
  705. }
  706. #pragma mark - Folder implementation
  707. - (void)rearrangeFolderTrackNumbersForRemovedItem:(MLFile *) mediaObject
  708. {
  709. MLLabel *label = [mediaObject.labels anyObject];
  710. NSSet *allFiles = label.files;
  711. for (MLFile *file in allFiles) {
  712. if (file.folderTrackNumber > mediaObject.folderTrackNumber) {
  713. int value = [file.folderTrackNumber intValue];
  714. file.folderTrackNumber = [NSNumber numberWithInt:value - 1];
  715. }
  716. }
  717. }
  718. - (void)showCreateFolderAlert
  719. {
  720. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"FOLDER_CHOOSE_NAME_TITLE", @"") message:NSLocalizedString(@"FOLDER_CHOOSE_NAME_MESSAGE", @"") cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", @"") otherButtonTitles:@[NSLocalizedString(@"BUTTON_SAVE", @"")]];
  721. [alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
  722. [[alert textFieldAtIndex:0] setText:NSLocalizedString(@"FOLDER_NAME_PLACEHOLDER", @"")];
  723. [[alert textFieldAtIndex:0] setClearButtonMode:UITextFieldViewModeAlways];
  724. __weak VLCAlertView *weakAlert = alert;
  725. alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
  726. if (cancelled)
  727. [self updateViewContents];
  728. else
  729. [self createFolderWithName:[weakAlert textFieldAtIndex:0].text];
  730. };
  731. [alert show];
  732. }
  733. - (void)createFolder
  734. {
  735. if (_libraryMode == VLCLibraryModeCreateFolder) {
  736. _libraryMode = _previousLibraryMode;
  737. [self updateViewContents];
  738. [self showCreateFolderAlert];
  739. return;
  740. }
  741. if (!_usingTableViewToShowData)
  742. _indexPaths = [NSMutableArray arrayWithArray:[self.collectionView indexPathsForSelectedItems]];
  743. else
  744. _indexPaths = [NSMutableArray arrayWithArray:[self.tableView indexPathsForSelectedRows]];
  745. for (NSInteger i = _indexPaths.count - 1; i >=0; i--) {
  746. NSIndexPath *path = _indexPaths[i];
  747. id mediaObject;
  748. if (!_usingTableViewToShowData)
  749. mediaObject = _foundMedia[path.item];
  750. else
  751. mediaObject = _foundMedia[path.row];
  752. if ([mediaObject isKindOfClass:[MLLabel class]])
  753. [_indexPaths removeObject:path];
  754. }
  755. if ([_indexPaths count] != 0) {
  756. NSArray *folder = [MLLabel allLabels];
  757. //if we already have folders display them
  758. if ([folder count] > 0) {
  759. _foundMedia = [NSMutableArray arrayWithArray:folder];
  760. self.title = NSLocalizedString(@"SELECT_FOLDER", @"");
  761. _previousLibraryMode = _libraryMode;
  762. _libraryMode = VLCLibraryModeCreateFolder;
  763. [self reloadViews];
  764. return;
  765. }
  766. }
  767. //no selected items or no existing folder ask for foldername
  768. [self showCreateFolderAlert];
  769. }
  770. - (void)removeFromFolder
  771. {
  772. if (!_usingTableViewToShowData)
  773. _indexPaths = [NSMutableArray arrayWithArray:[self.collectionView indexPathsForSelectedItems]];
  774. else
  775. _indexPaths = [NSMutableArray arrayWithArray:[self.tableView indexPathsForSelectedRows]];
  776. [_indexPaths sortUsingSelector:@selector(compare:)];
  777. for (NSInteger i = [_indexPaths count] - 1; i >= 0; i--) {
  778. NSIndexPath *path = _indexPaths[i];
  779. MLFile *file = (MLFile *)_foundMedia[_usingTableViewToShowData ? path.row : path.item];
  780. MLLabel *folder = [file.labels anyObject];
  781. [self rearrangeFolderTrackNumbersForRemovedItem:file];
  782. file.labels = nil;
  783. file.folderTrackNumber = nil;
  784. [_foundMedia removeObject:file];
  785. if ([folder.files count] == 0) {
  786. [self removeMediaObject:folder updateDatabase:YES];
  787. [self setEditing:NO];
  788. [self backToAllItems:nil];
  789. }
  790. }
  791. [self reloadViews];
  792. }
  793. - (void)createFolderWithName:(NSString *)folderName
  794. {
  795. NSArray *labels = [MLLabel allLabels];
  796. for (MLLabel *label in labels){
  797. if ([label.name isEqualToString:folderName]) {
  798. _folderObject = nil;
  799. _indexPaths = nil;
  800. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"FOLDER_NAME_DUPLICATE_TITLE", @"") message:NSLocalizedString(@"FOLDER_NAME_DUPLICATE_MESSAGE", @"") cancelButtonTitle:nil otherButtonTitles:@[NSLocalizedString(@"BUTTON_OK", @"")]];
  801. alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
  802. [self updateViewContents];
  803. };
  804. [alert show];
  805. return;
  806. }
  807. }
  808. if (_folderObject != nil) {
  809. NSUInteger folderIndex = [_foundMedia indexOfObject:_folderObject];
  810. //item got dragged onto item
  811. if ([_foundMedia[folderIndex] isKindOfClass:[MLFile class]]) {
  812. MLFile *file = _foundMedia[folderIndex];
  813. MLLabel *label = [[MLMediaLibrary sharedMediaLibrary] createObjectForEntity:@"Label"];
  814. label.name = folderName;
  815. file.labels = [NSSet setWithObjects:label,nil];
  816. NSNumber *folderTrackNumber = [NSNumber numberWithInt:(int)[label files].count - 1];
  817. file.folderTrackNumber = folderTrackNumber;
  818. [_foundMedia removeObjectAtIndex:folderIndex];
  819. [_foundMedia insertObject:label atIndex:folderIndex];
  820. MLFile *itemFile = _foundMedia[((NSIndexPath *)_indexPaths[0]).item];
  821. itemFile.labels = file.labels;
  822. [_foundMedia removeObjectAtIndex:((NSIndexPath *)_indexPaths[0]).item];
  823. itemFile.folderTrackNumber = @([label files].count - 1);
  824. } else {
  825. //item got dragged onto folder or items should be added to folder
  826. MLLabel *label = _foundMedia[folderIndex];
  827. [_indexPaths sortUsingSelector:@selector(compare:)];
  828. for (NSInteger i = [_indexPaths count] - 1; i >= 0; i--) {
  829. NSIndexPath *path = _indexPaths[i];
  830. if (_libraryMode != VLCLibraryModeCreateFolder && ![_foundMedia[path.row] isKindOfClass:[MLFile class]])
  831. continue;
  832. if (_libraryMode == VLCLibraryModeCreateFolder)
  833. [self updateViewContents];
  834. MLFile *file = _foundMedia[path.row];
  835. file.labels = [NSSet setWithObjects:label, nil];
  836. [_foundMedia removeObjectAtIndex:path.row];
  837. file.folderTrackNumber = @([label files].count - 1);
  838. }
  839. }
  840. _folderObject = nil;
  841. } else {
  842. //create new folder
  843. MLLabel *label = [[MLMediaLibrary sharedMediaLibrary] createObjectForEntity:@"Label"];
  844. label.name = folderName;
  845. //if items were selected
  846. if ([_indexPaths count] != 0) {
  847. [_indexPaths sortUsingSelector:@selector(compare:)];
  848. for (NSInteger i = [_indexPaths count] - 1; i >= 0; i--) {
  849. NSIndexPath *path = _indexPaths[i];
  850. if (!_usingTableViewToShowData) {
  851. MLFile *file = _foundMedia[path.item];
  852. file.labels = [NSSet setWithObjects:label, nil];
  853. file.folderTrackNumber = @([label files].count - 1);
  854. [_foundMedia removeObjectAtIndex:path.item];
  855. } else {
  856. MLFile *file = _foundMedia[path.row];
  857. file.labels = [NSSet setWithObjects:label, nil];
  858. file.folderTrackNumber = @([label files].count - 1);
  859. [_foundMedia removeObjectAtIndex:path.row];
  860. }
  861. }
  862. }
  863. }
  864. _indexPaths = nil;
  865. [self setEditing:NO];
  866. [self updateViewContents];
  867. }
  868. - (void)_collectionViewHandleLongPressGesture:(UIGestureRecognizer *) sender
  869. {
  870. [self setEditing:YES animated:YES];
  871. }
  872. #pragma mark - UI implementation
  873. - (void)setEditing:(BOOL)editing animated:(BOOL)animated
  874. {
  875. [super setEditing:editing animated:animated];
  876. UIBarButtonItem *editButton = self.editButtonItem;
  877. NSString *editImage = editing? @"doneButton": @"button";
  878. NSString *editImageHighlight = editing? @"doneButtonHighlight": @"buttonHighlight";
  879. if (SYSTEM_RUNS_IOS7_OR_LATER)
  880. editButton.tintColor = [UIColor whiteColor];
  881. else {
  882. [editButton setBackgroundImage:[UIImage imageNamed:editImage] forState:UIControlStateNormal
  883. barMetrics:UIBarMetricsDefault];
  884. [editButton setBackgroundImage:[UIImage imageNamed:editImageHighlight]
  885. forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
  886. [editButton setTitleTextAttributes: editing ? @{UITextAttributeTextShadowColor : [UIColor whiteColor], UITextAttributeTextColor : [UIColor blackColor]} : @{UITextAttributeTextShadowColor : [UIColor VLCDarkTextShadowColor], UITextAttributeTextColor : [UIColor whiteColor]} forState:UIControlStateNormal];
  887. }
  888. if (!_usingTableViewToShowData) {
  889. NSArray *visibleCells = self.collectionView.visibleCells;
  890. [visibleCells enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  891. VLCPlaylistCollectionViewCell *aCell = (VLCPlaylistCollectionViewCell*)obj;
  892. [aCell setEditing:editing animated:animated];
  893. }];
  894. self.collectionView.allowsMultipleSelection = editing;
  895. /* UIKit doesn't clear the selection automagically if we leave the editing mode
  896. * so we need to do so manually */
  897. if (!editing) {
  898. [self.collectionView addGestureRecognizer:_longPressGestureRecognizer];
  899. NSArray *selectedItems = [self.collectionView indexPathsForSelectedItems];
  900. NSUInteger count = selectedItems.count;
  901. for (NSUInteger x = 0; x < count; x++)
  902. [self.collectionView deselectItemAtIndexPath:selectedItems[x] animated:NO];
  903. } else
  904. [self.collectionView removeGestureRecognizer:_longPressGestureRecognizer];
  905. } else {
  906. self.tableView.allowsMultipleSelectionDuringEditing = editing;
  907. [self.tableView setEditing:editing animated:YES];
  908. [self.editButtonItem setTitle:editing ? NSLocalizedString(@"BUTTON_CANCEL",@"") : NSLocalizedString(@"BUTTON_EDIT", @"")];
  909. }
  910. if (_libraryMode == VLCLibraryModeCreateFolder) {
  911. _libraryMode = _previousLibraryMode;
  912. _indexPaths = nil;
  913. [self updateViewContents];
  914. }
  915. self.navigationController.toolbarHidden = !editing;
  916. }
  917. - (UITableViewCellEditingStyle)tableView:(UITableView *)aTableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
  918. {
  919. return UITableViewCellEditingStyleDelete;
  920. }
  921. - (IBAction)leftButtonAction:(id)sender
  922. {
  923. [[(VLCAppDelegate*)[UIApplication sharedApplication].delegate revealController] toggleSidebar:![(VLCAppDelegate*)[UIApplication sharedApplication].delegate revealController].sidebarShowing duration:kGHRevealSidebarDefaultAnimationDuration];
  924. if (self.isEditing)
  925. [self setEditing:NO animated:YES];
  926. }
  927. - (IBAction)backToAllItems:(id)sender
  928. {
  929. if (!_usingTableViewToShowData) {
  930. if (![self.collectionView.collectionViewLayout isEqual:_folderLayout]) {
  931. //for some reason the Gesturerecognizer block themselves if not removed manually
  932. for (UIGestureRecognizer *recognizer in self.view.gestureRecognizers) {
  933. if (recognizer == _reorderLayout.panGestureRecognizer || recognizer == _reorderLayout.longPressGestureRecognizer)
  934. [self.collectionView removeGestureRecognizer:recognizer];
  935. }
  936. _folderLayout = [[VLCFolderCollectionViewFlowLayout alloc] init];
  937. [self.collectionView setCollectionViewLayout:_folderLayout animated:NO];
  938. [_collectionView addGestureRecognizer:_longPressGestureRecognizer];
  939. }
  940. }
  941. inFolder = NO;
  942. UIBarButtonItem *createFolderItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemOrganize target:self action:@selector(createFolder)];
  943. NSMutableArray *toolbarItems = [self.toolbarItems mutableCopy];
  944. toolbarItems[2] = createFolderItem;
  945. self.toolbarItems = toolbarItems;
  946. [self setLibraryMode:_libraryMode];
  947. [self updateViewContents];
  948. }
  949. - (void)_endEditingWithHardReset:(BOOL)hardReset
  950. {
  951. [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
  952. if (hardReset)
  953. [self updateViewContents];
  954. else
  955. [self reloadViews];
  956. [self setEditing:NO animated:YES];
  957. }
  958. - (void)deleteSelection
  959. {
  960. NSArray *indexPaths;
  961. if (!_usingTableViewToShowData)
  962. indexPaths = [self.collectionView indexPathsForSelectedItems];
  963. else
  964. indexPaths = [self.tableView indexPathsForSelectedRows];
  965. NSUInteger count = indexPaths.count;
  966. NSMutableArray *objects = [[NSMutableArray alloc] initWithCapacity:count];
  967. for (NSUInteger x = 0; x < count; x++)
  968. [objects addObject:_foundMedia[[indexPaths[x] row]]];
  969. for (NSUInteger x = 0; x < count; x++)
  970. [self removeMediaObject:objects[x] updateDatabase:NO];
  971. [self _endEditingWithHardReset:YES];
  972. }
  973. - (void)renameSelection
  974. {
  975. NSArray *indexPaths;
  976. if (!_usingTableViewToShowData)
  977. indexPaths = [self.collectionView indexPathsForSelectedItems];
  978. else
  979. indexPaths = [self.tableView indexPathsForSelectedRows];
  980. if (indexPaths.count < 1) {
  981. [self _endEditingWithHardReset:NO];
  982. return;
  983. }
  984. NSString *itemName;
  985. if (!_usingTableViewToShowData)
  986. itemName = [(VLCPlaylistCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPaths[0]] titleLabel].text;
  987. else
  988. itemName = [(VLCPlaylistTableViewCell *)[self.tableView cellForRowAtIndexPath:indexPaths[0]] titleLabel].text;
  989. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:[NSString stringWithFormat:NSLocalizedString(@"RENAME_MEDIA_TO", @""), itemName] message:nil cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", @"") otherButtonTitles:@[NSLocalizedString(@"BUTTON_RENAME", @"")]];
  990. [alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
  991. [[alert textFieldAtIndex:0] setText:itemName];
  992. [[alert textFieldAtIndex:0] setClearButtonMode:UITextFieldViewModeAlways];
  993. __weak VLCAlertView *weakAlert = alert;
  994. alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
  995. if (cancelled)
  996. [self _endEditingWithHardReset:NO];
  997. else
  998. [self renameMediaObjectTo:[weakAlert textFieldAtIndex:0].text];
  999. };
  1000. [alert show];
  1001. }
  1002. - (void)renameMediaObjectTo:(NSString*)newName
  1003. {
  1004. NSArray *indexPaths;
  1005. if (!_usingTableViewToShowData)
  1006. indexPaths = [self.collectionView indexPathsForSelectedItems];
  1007. else
  1008. indexPaths = [self.tableView indexPathsForSelectedRows];
  1009. if (indexPaths.count < 1)
  1010. return;
  1011. id mediaObject = _foundMedia[[indexPaths[0] row]];
  1012. if ([mediaObject isKindOfClass:[MLAlbum class]] || [mediaObject isKindOfClass:[MLShowEpisode class]] || [mediaObject isKindOfClass:[MLShow class]] || [mediaObject isKindOfClass:[MLLabel class]] )
  1013. [mediaObject setName:newName];
  1014. else
  1015. [mediaObject setTitle:newName];
  1016. if (!_usingTableViewToShowData)
  1017. [self.collectionView deselectItemAtIndexPath:indexPaths[0] animated:YES];
  1018. else
  1019. [self.tableView deselectRowAtIndexPath:indexPaths[0] animated:YES];
  1020. if (indexPaths.count > 1)
  1021. [self renameSelection];
  1022. else
  1023. [self _endEditingWithHardReset:NO];
  1024. }
  1025. #pragma mark - Sharing
  1026. // We take the array of index paths (instead of a count) to actually examine if the content is shareable. Selecting a single folder should not enable the share button.
  1027. - (void)updateActionBarButtonItemStateWithSelectedIndexPaths:(NSArray *)indexPaths
  1028. {
  1029. NSUInteger count = [indexPaths count];
  1030. if (!indexPaths || count == 0) {
  1031. _actionBarButtonItem.enabled = NO;
  1032. } else {
  1033. // Look for at least one MLFile
  1034. for (NSUInteger x = 0; x < count; x++) {
  1035. MLFile *file = _foundMedia[[indexPaths[x] row]];
  1036. if ([file isKindOfClass:[MLFile class]]) {
  1037. _actionBarButtonItem.enabled = YES;
  1038. return;
  1039. }
  1040. }
  1041. }
  1042. }
  1043. - (void)actOnSelection:(UIBarButtonItem *)barButtonItem
  1044. {
  1045. NSParameterAssert(barButtonItem);
  1046. if (!barButtonItem) {
  1047. APLog(@"Missing a UIBarButtonItem to present from");
  1048. return;
  1049. }
  1050. NSArray *indexPaths;
  1051. if (!_usingTableViewToShowData)
  1052. indexPaths = [self.collectionView indexPathsForSelectedItems];
  1053. else
  1054. indexPaths = [self.tableView indexPathsForSelectedRows];
  1055. NSUInteger count = indexPaths.count;
  1056. if (count) {
  1057. NSMutableArray /* NSURL */ *fileURLobjects = [[NSMutableArray alloc] initWithCapacity:count];
  1058. for (NSUInteger x = 0; x < count; x++) {
  1059. MLFile *file = _foundMedia[[indexPaths[x] row]];
  1060. if ([file isKindOfClass:[MLFile class]]) {
  1061. NSURL *fileURL = [NSURL URLWithString:[file url]];
  1062. if ([fileURL isFileURL]) {
  1063. [fileURLobjects addObject:fileURL];
  1064. }
  1065. }
  1066. }
  1067. if ([fileURLobjects count]) {
  1068. // Provide some basic user feedback as UIActivityController lags in presentation sometimes (blocking the main thread).
  1069. // iOS 6 has trouble re-enabling all the icons, so only disable the sharing one. Usage of the toolbar will be disabled by UIApplication in this case anyhow.
  1070. if (SYSTEM_RUNS_IOS7_OR_LATER) {
  1071. [self.navigationController.toolbar.items makeObjectsPerformSelector:@selector(setEnabled:) withObject:@(NO)];
  1072. } else {
  1073. _actionBarButtonItem.enabled = YES;
  1074. }
  1075. // Just in case, since we are facing a possible delay from code we do not control (UIActivityViewController), disable any possible changes to selection (or exit from this screen)
  1076. [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
  1077. // The reason we do a dispatch_async to the main queue here even though we are already on the main queue is because UIActivityViewController blocks the main thread at some point (either during creation or presentation), which won't let UIKit draw our call to disable the toolbar items in time. On an actual device (where the lag can be seen when UIActivityViewController is presented for the first time during an applications lifetime) this makes for a much better user experience. If you have more items to share the lag may be greater.
  1078. dispatch_async(dispatch_get_main_queue(), ^{
  1079. _openInActivity = [[VLCOpenInActivity alloc] init];
  1080. _openInActivity.presentingViewController = self;
  1081. _openInActivity.presentingBarButtonItem = barButtonItem;
  1082. dispatch_block_t enableInteractionBlock = ^{
  1083. if (SYSTEM_RUNS_IOS7_OR_LATER) {
  1084. // Strangely makeObjectsPerformSelector:withObject has trouble here (when called from presentViewController:animated:completion:)
  1085. // [self.navigationController.toolbar.items makeObjectsPerformSelector:@selector(setEnabled:) withObject:@(YES)];
  1086. for (UIBarButtonItem *item in self.navigationController.toolbar.items) {
  1087. item.enabled = YES;
  1088. }
  1089. } else {
  1090. _actionBarButtonItem.enabled = YES;
  1091. }
  1092. if ([[UIApplication sharedApplication] isIgnoringInteractionEvents]) {
  1093. [[UIApplication sharedApplication] endIgnoringInteractionEvents];
  1094. }
  1095. };
  1096. UIActivityViewController *controller = [[UIActivityViewController alloc] initWithActivityItems:fileURLobjects applicationActivities:@[_openInActivity]];
  1097. controller.completionHandler = ^(NSString *activityType, BOOL completed) {
  1098. APLog(@"UIActivityViewController finished with activity type: %@, completed: %i", activityType, completed);
  1099. // Provide some feedback if saving media to the Camera Roll. Note that this could caus a false positive if the user chooses "Don't Allow" in the permissions dialog, and UIActivityViewController does not inform us of that, so check the authorization status.
  1100. // By the time this is called, the user has not had time to choose whether to allow access to the Photos library, so only display the message if we are truly sure we got authorization. The first time the user saves to the camera roll he won't see the confirmation because of this timing issue. This is better than showing a success message when the user had denied access. A timing workaround could be developed if needed through UIApplicationDidBecomeActiveNotification (to know when the security alert view was dismissed) or through other ALAssets APIs.
  1101. if (completed && [activityType isEqualToString:UIActivityTypeSaveToCameraRoll] && [ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  1102. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"SHARING_SUCCESS_CAMERA_ROLL", nil)
  1103. message:nil
  1104. delegate:nil
  1105. cancelButtonTitle:NSLocalizedString(@"BUTTON_OK", nil)
  1106. otherButtonTitles:nil];
  1107. [alertView show];
  1108. }
  1109. _openInActivity = nil;
  1110. // Just in case, we could call enableInteractionBlock here. Since we are disabling touch interaction for the entire UI, to be safe that we return to the proper state: re-enable everything (if presentViewController:animated:completion: failed for some reason). But UIApplication gives us a warning even if we check isIgnoringInteractionEvents, so do not call it for now.
  1111. // enableInteractionBlock();
  1112. };
  1113. [self.navigationController presentViewController:controller animated:YES completion:enableInteractionBlock];
  1114. });
  1115. return;
  1116. }
  1117. }
  1118. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"SHARING_ERROR_NO_FILES", nil)
  1119. message:nil
  1120. delegate:nil
  1121. cancelButtonTitle:NSLocalizedString(@"BUTTON_OK", nil)
  1122. otherButtonTitles:nil];
  1123. [alertView show];
  1124. }
  1125. #pragma mark - coin coin
  1126. - (void)setLibraryMode:(VLCLibraryMode)mode
  1127. {
  1128. _libraryMode = mode;
  1129. [self updateViewContents];
  1130. }
  1131. #pragma mark - autorotation
  1132. // RootController is responsible for supporting interface orientation(iOS6.0+), i.e. navigation controller
  1133. // so this will not work as intended without "voodoo magic"(UINavigationController category, subclassing, etc)
  1134. /* introduced in iOS 6 */
  1135. - (NSUInteger)supportedInterfaceOrientations
  1136. {
  1137. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1138. return UIInterfaceOrientationMaskAll;
  1139. return (_foundMedia.count > 0)? UIInterfaceOrientationMaskAllButUpsideDown:
  1140. UIInterfaceOrientationMaskPortrait;
  1141. }
  1142. /* introduced in iOS 6 */
  1143. - (BOOL)shouldAutorotate
  1144. {
  1145. return (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) || (_foundMedia.count > 0);
  1146. }
  1147. - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
  1148. {
  1149. [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
  1150. if (!_usingTableViewToShowData)
  1151. [self.collectionView.collectionViewLayout invalidateLayout];
  1152. }
  1153. #pragma mark - Search Display Controller Delegate
  1154. - (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
  1155. {
  1156. NSInteger listCount = _foundMedia.count;
  1157. [_searchData removeAllObjects];
  1158. NSManagedObject *item;
  1159. NSRange nameRange;
  1160. for (int i = 0; i < listCount; i++) {
  1161. item = _foundMedia[i];
  1162. if ([item isKindOfClass:[MLAlbum class]]) {
  1163. nameRange = [[(MLAlbum*)item name] rangeOfString:searchString options:NSCaseInsensitiveSearch];
  1164. if (nameRange.location == NSNotFound) {
  1165. NSString *releaseYear = [(MLAlbum *)item releaseYear];
  1166. if (releaseYear)
  1167. nameRange = [releaseYear rangeOfString:searchString options:NSCaseInsensitiveSearch];
  1168. /* user didn't search for our album name or year, let's do a deeper search */
  1169. if (nameRange.location == NSNotFound) {
  1170. NSArray *tracks = [(MLAlbum*)item sortedTracks];
  1171. NSUInteger trackCount = tracks.count;
  1172. for (NSUInteger x = 0; x < trackCount; x++) {
  1173. nameRange = [self _processItem:tracks[x] withString:searchString];
  1174. if (nameRange.location != NSNotFound)
  1175. break;
  1176. }
  1177. }
  1178. }
  1179. } else if ([item isKindOfClass:[MLShow class]]) {
  1180. nameRange = [[(MLShow*)item name] rangeOfString:searchString options:NSCaseInsensitiveSearch];
  1181. /* user didn't search for our show name, let's do a deeper search */
  1182. if (nameRange.location == NSNotFound) {
  1183. NSArray *episodes = [(MLShow*)item sortedEpisodes];
  1184. NSUInteger episodeCount = episodes.count;
  1185. NSString *name;
  1186. for (NSUInteger x = 0; x < episodeCount; x++) {
  1187. name = [(MLShowEpisode*)episodes[x] name];
  1188. if (name)
  1189. nameRange = [name rangeOfString:searchString options:NSCaseInsensitiveSearch];
  1190. if (nameRange.location != NSNotFound) {
  1191. break;
  1192. }
  1193. }
  1194. }
  1195. } else if ([item isKindOfClass:[MLLabel class]]) {
  1196. nameRange = [[(MLLabel*)item name] rangeOfString:searchString options:NSCaseInsensitiveSearch];
  1197. /* user didn't search for our label name, let's do a deeper search */
  1198. if (nameRange.location == NSNotFound) {
  1199. NSArray *files = [(MLLabel*)item sortedFolderItems];
  1200. NSUInteger fileCount = files.count;
  1201. for (NSUInteger x = 0; x < fileCount; x++) {
  1202. nameRange = [self _processItem:files[x] withString:searchString];
  1203. if (nameRange.location != NSNotFound)
  1204. break;
  1205. }
  1206. }
  1207. } else // simple file
  1208. nameRange = [self _processItem:(MLFile*)item withString:searchString];
  1209. if (nameRange.location != NSNotFound)
  1210. [_searchData addObject:item];
  1211. }
  1212. return YES;
  1213. }
  1214. - (NSRange)_processItem:(NSManagedObject *)file withString:(NSString *)searchString
  1215. {
  1216. NSRange nameRange;
  1217. nameRange = [[(MLFile *)file title] rangeOfString:searchString options:NSCaseInsensitiveSearch];
  1218. if (nameRange.location == NSNotFound) {
  1219. NSString *artist = [(MLFile *)file artist];
  1220. if (artist)
  1221. nameRange = [artist rangeOfString:searchString options:NSCaseInsensitiveSearch];
  1222. if (nameRange.location == NSNotFound && ![file isKindOfClass:[MLAlbumTrack class]]) {
  1223. NSString *releaseYear = [(MLFile *)file releaseYear];
  1224. if (releaseYear)
  1225. nameRange = [releaseYear rangeOfString:searchString options:NSCaseInsensitiveSearch];
  1226. }
  1227. }
  1228. return nameRange;
  1229. }
  1230. - (void)searchDisplayController:(UISearchDisplayController *)controller didLoadSearchResultsTableView:(UITableView *)tableView
  1231. {
  1232. tableView.rowHeight = 90.;
  1233. tableView.backgroundColor = [UIColor blackColor];
  1234. }
  1235. @end