VLCPlaylistViewController.m 73 KB

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