VLCPlaylistViewController.m 68 KB

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