VLCPlaylistViewController.m 67 KB

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