VLCPlaylistViewController.m 65 KB

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