VLCPlaylistViewController.m 63 KB

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