VLCPlaylistViewController.m 67 KB

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