VLCPlaylistViewController.m 70 KB

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