VLCPlaylistViewController.m 67 KB

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