VLCPlaylistViewController.m 67 KB

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