VLCPlaylistViewController.m 68 KB

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