VLCPlaylistViewController.m 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124
  1. /*****************************************************************************
  2. * VLCPlaylistViewController.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2013-2014 VideoLAN. All rights reserved.
  6. * $Id$
  7. *
  8. * Authors: Felix Paul Kühne <fkuehne # videolan.org>
  9. * Gleb Pinigin <gpinigin # gmail.com>
  10. * Tamas Timar <ttimar.vlc # gmail.com>
  11. * Carola Nitz <nitz.carola # gmail.com>
  12. *
  13. * Refer to the COPYING file of the official project for license.
  14. *****************************************************************************/
  15. #import "VLCPlaylistViewController.h"
  16. #import "VLCMovieViewController.h"
  17. #import "VLCPlaylistTableViewCell.h"
  18. #import "VLCPlaylistCollectionViewCell.h"
  19. #import "UINavigationController+Theme.h"
  20. #import "NSString+SupportedMedia.h"
  21. #import "VLCBugreporter.h"
  22. #import "VLCAppDelegate.h"
  23. #import "UIBarButtonItem+Theme.h"
  24. #import "VLCFirstStepsViewController.h"
  25. #import "VLCFolderCollectionViewFlowLayout.h"
  26. #import "LXReorderableCollectionViewFlowLayout.h"
  27. #import "VLCAlertView.h"
  28. /* prefs keys */
  29. static NSString *kDisplayedFirstSteps = @"Did we display the first steps tutorial?";
  30. @implementation EmptyLibraryView
  31. - (IBAction)learnMore:(id)sender
  32. {
  33. UIViewController *firstStepsVC = [[VLCFirstStepsViewController alloc] initWithNibName:nil bundle:nil];
  34. UINavigationController *navCon = [[UINavigationController alloc] initWithRootViewController:firstStepsVC];
  35. navCon.modalPresentationStyle = UIModalPresentationFormSheet;
  36. [navCon loadTheme];
  37. [self.window.rootViewController presentViewController:navCon animated:YES completion:nil];
  38. }
  39. @end
  40. @interface VLCPlaylistViewController () <VLCFolderCollectionViewDelegateFlowLayout, LXReorderableCollectionViewDataSource, LXReorderableCollectionViewDelegateFlowLayout, UITableViewDataSource, UITableViewDelegate, MLMediaLibrary> {
  41. NSMutableArray *_foundMedia;
  42. VLCLibraryMode _libraryMode;
  43. VLCLibraryMode _previousLibraryMode;
  44. UIBarButtonItem *_menuButton;
  45. NSMutableArray *_indexPaths;
  46. id _folderObject;
  47. VLCFolderCollectionViewFlowLayout *_folderLayout;
  48. LXReorderableCollectionViewFlowLayout *_reorderLayout;
  49. BOOL inFolder;
  50. UILongPressGestureRecognizer *_longPressGestureRecognizer;
  51. }
  52. @property (nonatomic, strong) UITableView *tableView;
  53. @property (nonatomic, strong) UICollectionView *collectionView;
  54. @property (nonatomic, strong) EmptyLibraryView *emptyLibraryView;
  55. @end
  56. @implementation VLCPlaylistViewController
  57. + (void)initialize
  58. {
  59. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  60. [defaults registerDefaults:@{kDisplayedFirstSteps : [NSNumber numberWithBool:NO]}];
  61. }
  62. - (void)loadView
  63. {
  64. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
  65. _tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
  66. _tableView.backgroundColor = [UIColor colorWithWhite:.122 alpha:1.];
  67. _tableView.rowHeight = [VLCPlaylistTableViewCell heightOfCell];
  68. _tableView.separatorColor = [UIColor colorWithWhite:.122 alpha:1.];
  69. _tableView.delegate = self;
  70. _tableView.dataSource = self;
  71. _tableView.opaque = YES;
  72. self.view = _tableView;
  73. } else {
  74. _folderLayout = [[VLCFolderCollectionViewFlowLayout alloc] init];
  75. _collectionView = [[UICollectionView alloc] initWithFrame:[UIScreen mainScreen].bounds collectionViewLayout:_folderLayout];
  76. _collectionView.alwaysBounceVertical = YES;
  77. _collectionView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
  78. _collectionView.delegate = self;
  79. _collectionView.dataSource = self;
  80. _collectionView.opaque = YES;
  81. _collectionView.backgroundColor = [UIColor colorWithWhite:.122 alpha:1.];
  82. self.view = _collectionView;
  83. _longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(_collectionViewHandleLongPressGesture:)];
  84. [_collectionView addGestureRecognizer:_longPressGestureRecognizer];
  85. if (SYSTEM_RUNS_IOS7_OR_LATER)
  86. [_collectionView registerNib:[UINib nibWithNibName:@"VLCFuturePlaylistCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"PlaylistCell"];
  87. else
  88. [_collectionView registerNib:[UINib nibWithNibName:@"VLCPlaylistCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"PlaylistCell"];
  89. self.view.backgroundColor = [UIColor colorWithWhite:.122 alpha:1.];
  90. }
  91. _libraryMode = VLCLibraryModeAllFiles;
  92. self.view.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
  93. self.emptyLibraryView = [[[NSBundle mainBundle] loadNibNamed:@"VLCEmptyLibraryView" owner:self options:nil] lastObject];
  94. _emptyLibraryView.emptyLibraryLongDescriptionLabel.lineBreakMode = NSLineBreakByWordWrapping;
  95. _emptyLibraryView.emptyLibraryLongDescriptionLabel.numberOfLines = 0;
  96. }
  97. #pragma mark -
  98. - (void)viewDidLoad
  99. {
  100. [super viewDidLoad];
  101. self.title = NSLocalizedString(@"LIBRARY_ALL_FILES", @"");
  102. _menuButton = [UIBarButtonItem themedRevealMenuButtonWithTarget:self andSelector:@selector(leftButtonAction:)];
  103. self.navigationItem.leftBarButtonItem = _menuButton;
  104. if (SYSTEM_RUNS_IOS7_OR_LATER)
  105. self.editButtonItem.tintColor = [UIColor whiteColor];
  106. else {
  107. [self.editButtonItem setBackgroundImage:[UIImage imageNamed:@"button"]
  108. forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
  109. [self.editButtonItem setBackgroundImage:[UIImage imageNamed:@"buttonHighlight"]
  110. forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
  111. }
  112. _emptyLibraryView.emptyLibraryLabel.text = NSLocalizedString(@"EMPTY_LIBRARY", @"");
  113. _emptyLibraryView.emptyLibraryLongDescriptionLabel.text = NSLocalizedString(@"EMPTY_LIBRARY_LONG", @"");
  114. [_emptyLibraryView.emptyLibraryLongDescriptionLabel sizeToFit];
  115. [_emptyLibraryView.learnMoreButton setTitle:NSLocalizedString(@"BUTTON_LEARN_MORE", @"") forState:UIControlStateNormal];
  116. UIBarButtonItem *createFolderItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemOrganize target:self action:@selector(createFolder)];
  117. [self setToolbarItems:@[createFolderItem, [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil], [UIBarButtonItem themedDarkToolbarButtonWithTitle:NSLocalizedString(@"BUTTON_RENAME", @"") target:self andSelector:@selector(renameSelection)], [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil], [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(deleteSelection)]]];
  118. self.navigationController.toolbar.barStyle = UIBarStyleBlack;
  119. if (SYSTEM_RUNS_IOS7_OR_LATER) {
  120. self.navigationController.toolbar.tintColor = [UIColor whiteColor];
  121. [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
  122. } else
  123. [self.navigationController.toolbar setBackgroundImage:[UIImage imageNamed:@"bottomBlackBar"] forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
  124. }
  125. - (void)viewWillAppear:(BOOL)animated
  126. {
  127. [super viewWillAppear:animated];
  128. [self.collectionView.collectionViewLayout invalidateLayout];
  129. [self _displayEmptyLibraryViewIfNeeded];
  130. }
  131. - (void)viewDidAppear:(BOOL)animated
  132. {
  133. [super viewDidAppear:animated];
  134. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  135. if (![[defaults objectForKey:kDisplayedFirstSteps] boolValue]) {
  136. [self.emptyLibraryView performSelector:@selector(learnMore:) withObject:nil afterDelay:1.];
  137. [defaults setObject:[NSNumber numberWithBool:YES] forKey:kDisplayedFirstSteps];
  138. [defaults synchronize];
  139. }
  140. if ([[MLMediaLibrary sharedMediaLibrary] libraryNeedsUpgrade]) {
  141. self.navigationItem.rightBarButtonItem = nil;
  142. self.navigationItem.leftBarButtonItem = nil;
  143. self.title = @"";
  144. self.emptyLibraryView.emptyLibraryLabel.text = NSLocalizedString(@"UPGRADING_LIBRARY", @"");
  145. self.emptyLibraryView.emptyLibraryLongDescriptionLabel.hidden = YES;
  146. [self.emptyLibraryView.activityIndicator startAnimating];
  147. self.emptyLibraryView.frame = self.view.bounds;
  148. [self.view addSubview:self.emptyLibraryView];
  149. [[MLMediaLibrary sharedMediaLibrary] setDelegate: self];
  150. [[MLMediaLibrary sharedMediaLibrary] performSelectorInBackground:@selector(upgradeLibrary) withObject:nil];
  151. return;
  152. }
  153. if (_foundMedia.count < 1)
  154. [self updateViewContents];
  155. [[MLMediaLibrary sharedMediaLibrary] performSelector:@selector(libraryDidAppear) withObject:nil afterDelay:1.];
  156. }
  157. - (void)viewDidDisappear:(BOOL)animated
  158. {
  159. [super viewDidDisappear:animated];
  160. [[MLMediaLibrary sharedMediaLibrary] libraryDidDisappear];
  161. }
  162. - (BOOL)canBecomeFirstResponder
  163. {
  164. return YES;
  165. }
  166. - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
  167. {
  168. if (motion == UIEventSubtypeMotionShake)
  169. [[VLCBugreporter sharedInstance] handleBugreportRequest];
  170. }
  171. - (void)openMediaObject:(NSManagedObject *)mediaObject
  172. {
  173. if ([mediaObject isKindOfClass:[MLAlbum class]]) {
  174. _foundMedia = [NSMutableArray arrayWithArray:[(MLAlbum *)mediaObject sortedTracks]];
  175. self.navigationItem.leftBarButtonItem = [UIBarButtonItem themedBackButtonWithTarget:self andSelector:@selector(backToAllItems:)];
  176. if (_libraryMode == VLCLibraryModeAllFiles)
  177. self.navigationItem.leftBarButtonItem.title = NSLocalizedString(@"BUTTON_BACK", @"");
  178. else
  179. [self.navigationItem.leftBarButtonItem setTitle:NSLocalizedString(@"LIBRARY_MUSIC", @"")];
  180. self.title = [(MLAlbum*)mediaObject name];
  181. [self reloadViews];
  182. } else if ([mediaObject isKindOfClass:[MLShow class]]) {
  183. _foundMedia = [NSMutableArray arrayWithArray:[(MLShow *)mediaObject sortedEpisodes]];
  184. self.navigationItem.leftBarButtonItem = [UIBarButtonItem themedBackButtonWithTarget:self andSelector:@selector(backToAllItems:)];
  185. if (_libraryMode == VLCLibraryModeAllFiles)
  186. self.navigationItem.leftBarButtonItem.title = NSLocalizedString(@"BUTTON_BACK", @"");
  187. else
  188. [self.navigationItem.leftBarButtonItem setTitle:NSLocalizedString(@"LIBRARY_SERIES", @"")];
  189. self.title = [(MLShow*)mediaObject name];
  190. [self reloadViews];
  191. } else if ([mediaObject isKindOfClass:[MLLabel class]]) {
  192. MLLabel *folder = (MLLabel*) mediaObject;
  193. inFolder = YES;
  194. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  195. if (![self.collectionView.collectionViewLayout isEqual:_reorderLayout]) {
  196. for (UIGestureRecognizer *recognizer in self.view.gestureRecognizers) {
  197. if (recognizer == _folderLayout.panGestureRecognizer || recognizer == _folderLayout.longPressGestureRecognizer || recognizer == _longPressGestureRecognizer)
  198. [self.collectionView removeGestureRecognizer:recognizer];
  199. }
  200. _reorderLayout = [[LXReorderableCollectionViewFlowLayout alloc] init];
  201. [self.collectionView setCollectionViewLayout:_reorderLayout animated:NO];
  202. _folderLayout = nil;
  203. }
  204. }
  205. _foundMedia = [NSMutableArray arrayWithArray:[folder sortedFolderItems]];
  206. self.navigationItem.leftBarButtonItem = [UIBarButtonItem themedBackButtonWithTarget:self andSelector:@selector(backToAllItems:)];
  207. self.navigationItem.leftBarButtonItem.title = NSLocalizedString(@"BUTTON_BACK", @"");
  208. self.title = [folder name];
  209. UIBarButtonItem *removeFromFolder = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemReply target:self action:@selector(removeFromFolder)];
  210. NSMutableArray *toolbarItems = [self.toolbarItems mutableCopy];
  211. toolbarItems[0] = removeFromFolder;
  212. self.toolbarItems = toolbarItems;
  213. [self reloadViews];
  214. return;
  215. } else
  216. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate openMediaFromManagedObject:mediaObject];
  217. }
  218. - (void)removeMediaObject:(id)managedObject updateDatabase:(BOOL)updateDB
  219. {
  220. // delete all tracks from an album
  221. if ([managedObject isKindOfClass:[MLAlbum class]]) {
  222. MLAlbum *album = managedObject;
  223. NSSet *iterAlbumTrack = [NSSet setWithSet:album.tracks];
  224. for (MLAlbumTrack *track in iterAlbumTrack) {
  225. NSSet *iterFiles = [NSSet setWithSet:track.files];
  226. for (MLFile *file in iterFiles)
  227. [self _deleteMediaObject:file];
  228. }
  229. // delete all episodes from a show
  230. } else if ([managedObject isKindOfClass:[MLShow class]]) {
  231. MLShow *show = managedObject;
  232. NSSet *iterShowEpisodes = [NSSet setWithSet:show.episodes];
  233. for (MLShowEpisode *episode in iterShowEpisodes) {
  234. NSSet *iterFiles = [NSSet setWithSet:episode.files];
  235. for (MLFile *file in iterFiles)
  236. [self _deleteMediaObject:file];
  237. }
  238. // delete all files from an episode
  239. } else if ([managedObject isKindOfClass:[MLShowEpisode class]]) {
  240. MLShowEpisode *episode = managedObject;
  241. NSSet *iterFiles = [NSSet setWithSet:episode.files];
  242. for (MLFile *file in iterFiles)
  243. [self _deleteMediaObject:file];
  244. // delete all files from a track
  245. } else if ([managedObject isKindOfClass:[MLAlbumTrack class]]) {
  246. MLAlbumTrack *track = managedObject;
  247. NSSet *iterFiles = [NSSet setWithSet:track.files];
  248. for (MLFile *file in iterFiles)
  249. [self _deleteMediaObject:file];
  250. } else if ([managedObject isKindOfClass:[MLLabel class]]) {
  251. MLLabel *folder = managedObject;
  252. NSSet *iterFiles = [NSSet setWithSet:folder.files];
  253. [folder removeFiles:folder.files];
  254. for (MLFile *file in iterFiles)
  255. [self _deleteMediaObject:file];
  256. [[MLMediaLibrary sharedMediaLibrary] removeObject:folder];
  257. }
  258. else
  259. [self _deleteMediaObject:managedObject];
  260. if (updateDB) {
  261. [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
  262. [self updateViewContents];
  263. }
  264. }
  265. - (void)_deleteMediaObject:(MLFile *)mediaObject
  266. {
  267. if (inFolder)
  268. [self rearrangeFolderTrackNumbersForRemovedItem:mediaObject];
  269. NSFileManager *fileManager = [NSFileManager defaultManager];
  270. NSString *folderLocation = [[[NSURL URLWithString:mediaObject.url] path] stringByDeletingLastPathComponent];
  271. NSArray *allfiles = [fileManager contentsOfDirectoryAtPath:folderLocation error:nil];
  272. NSString *fileName = [[[[NSURL URLWithString:mediaObject.url] path] lastPathComponent] stringByDeletingPathExtension];
  273. NSIndexSet *indexSet = [allfiles indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
  274. return ([obj rangeOfString:fileName].location != NSNotFound);
  275. }];
  276. NSUInteger count = indexSet.count;
  277. NSString *additionalFilePath;
  278. NSUInteger currentIndex = [indexSet firstIndex];
  279. for (unsigned int x = 0; x < count; x++) {
  280. additionalFilePath = allfiles[currentIndex];
  281. if ([additionalFilePath isSupportedSubtitleFormat])
  282. [fileManager removeItemAtPath:[folderLocation stringByAppendingPathComponent:additionalFilePath] error:nil];
  283. currentIndex = [indexSet indexGreaterThanIndex:currentIndex];
  284. }
  285. [fileManager removeItemAtPath:[[NSURL URLWithString:mediaObject.url] path] error:nil];
  286. }
  287. - (void)_displayEmptyLibraryViewIfNeeded
  288. {
  289. if (self.emptyLibraryView.superview)
  290. [self.emptyLibraryView removeFromSuperview];
  291. if (_foundMedia.count == 0) {
  292. self.emptyLibraryView.emptyLibraryLabel.text = inFolder ? NSLocalizedString(@"FOLDER_EMPTY", @"") : NSLocalizedString(@"EMPTY_LIBRARY", @"");
  293. self.emptyLibraryView.emptyLibraryLongDescriptionLabel.text = inFolder ? NSLocalizedString(@"FOLDER_EMPTY_LONG", @"") : NSLocalizedString(@"EMPTY_LIBRARY_LONG", @"");
  294. self.emptyLibraryView.learnMoreButton.hidden = inFolder;
  295. self.emptyLibraryView.frame = self.view.bounds;
  296. [self.view addSubview:self.emptyLibraryView];
  297. self.navigationItem.rightBarButtonItem = nil;
  298. } else
  299. self.navigationItem.rightBarButtonItem = self.editButtonItem;
  300. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
  301. _tableView.separatorStyle = (_foundMedia.count > 0)? UITableViewCellSeparatorStyleSingleLine:
  302. UITableViewCellSeparatorStyleNone;
  303. } else
  304. [self.collectionView.collectionViewLayout invalidateLayout];
  305. }
  306. - (void)libraryUpgradeComplete
  307. {
  308. self.title = NSLocalizedString(@"LIBRARY_ALL_FILES", @"");
  309. self.navigationItem.leftBarButtonItem = _menuButton;
  310. self.emptyLibraryView.emptyLibraryLongDescriptionLabel.hidden = NO;
  311. self.emptyLibraryView.emptyLibraryLabel.text = NSLocalizedString(@"EMPTY_LIBRARY", @"");
  312. [self.emptyLibraryView.activityIndicator stopAnimating];
  313. [self.emptyLibraryView removeFromSuperview];
  314. [self updateViewContents];
  315. }
  316. - (void)libraryWasUpdated
  317. {
  318. [self updateViewContents];
  319. }
  320. - (void)updateViewContents
  321. {
  322. _foundMedia = [[NSMutableArray alloc] init];
  323. self.navigationItem.leftBarButtonItem = _menuButton;
  324. if (_libraryMode == VLCLibraryModeAllAlbums)
  325. self.title = NSLocalizedString(@"LIBRARY_MUSIC", @"");
  326. else if( _libraryMode == VLCLibraryModeAllSeries)
  327. self.title = NSLocalizedString(@"LIBRARY_SERIES", @"");
  328. else
  329. self.title = NSLocalizedString(@"LIBRARY_ALL_FILES", @"");
  330. /* add all albums */
  331. if (_libraryMode != VLCLibraryModeAllSeries) {
  332. NSArray *rawAlbums = [MLAlbum allAlbums];
  333. for (MLAlbum *album in rawAlbums) {
  334. if (album.name.length > 0 && album.tracks.count > 1)
  335. [_foundMedia addObject:album];
  336. }
  337. }
  338. if (_libraryMode == VLCLibraryModeAllAlbums) {
  339. [self reloadViews];
  340. return;
  341. }
  342. /* add all shows */
  343. NSArray *rawShows = [MLShow allShows];
  344. for (MLShow *show in rawShows) {
  345. if (show.name.length > 0 && show.episodes.count > 1)
  346. [_foundMedia addObject:show];
  347. }
  348. if (_libraryMode == VLCLibraryModeAllSeries) {
  349. [self reloadViews];
  350. return;
  351. }
  352. /* add all folders*/
  353. NSArray *allFolders = [MLLabel allLabels];
  354. for (MLLabel *folder in allFolders)
  355. [_foundMedia addObject:folder];
  356. /* add all remaining files */
  357. NSArray *allFiles = [MLFile allFiles];
  358. for (MLFile *file in allFiles) {
  359. if (file.labels.count > 0) continue;
  360. if (!file.isShowEpisode && !file.isAlbumTrack)
  361. [_foundMedia addObject:file];
  362. else if (file.isShowEpisode) {
  363. if (file.showEpisode.show.episodes.count < 2)
  364. [_foundMedia addObject:file];
  365. /* older MediaLibraryKit versions don't send a show name in a popular
  366. * corner case. hence, we need to work-around here and force a reload
  367. * afterwards as this could lead to the 'all my shows are gone'
  368. * syndrome (see #10435, #10464, #10432 et al) */
  369. if (file.showEpisode.show.name.length == 0) {
  370. file.showEpisode.show.name = NSLocalizedString(@"UNTITLED_SHOW", @"");
  371. [self performSelector:@selector(updateViewContents) withObject:nil afterDelay:0.1];
  372. }
  373. } else if (file.isAlbumTrack) {
  374. if (file.albumTrack.album.tracks.count < 2)
  375. [_foundMedia addObject:file];
  376. }
  377. }
  378. [self reloadViews];
  379. }
  380. - (void)reloadViews
  381. {
  382. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
  383. [self.tableView reloadData];
  384. else
  385. [self.collectionView reloadData];
  386. [self _displayEmptyLibraryViewIfNeeded];
  387. }
  388. #pragma mark - Table View
  389. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  390. {
  391. return 1;
  392. }
  393. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  394. {
  395. return _foundMedia.count;
  396. }
  397. // Customize the appearance of table view cells.
  398. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  399. {
  400. static NSString *CellIdentifier = @"PlaylistCell";
  401. VLCPlaylistTableViewCell *cell = (VLCPlaylistTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  402. if (cell == nil)
  403. cell = [VLCPlaylistTableViewCell cellWithReuseIdentifier:CellIdentifier];
  404. UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRightGestureAction:)];
  405. [swipeRight setDirection:(UISwipeGestureRecognizerDirectionRight)];
  406. [cell addGestureRecognizer:swipeRight];
  407. NSInteger row = indexPath.row;
  408. cell.mediaObject = _foundMedia[row];
  409. return cell;
  410. }
  411. - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
  412. {
  413. MLFile* object = [_foundMedia objectAtIndex:fromIndexPath.item];
  414. [_foundMedia removeObjectAtIndex:fromIndexPath.item];
  415. [_foundMedia insertObject:object atIndex:toIndexPath.item];
  416. object.folderTrackNumber = @(toIndexPath.item - 1);
  417. object = [_foundMedia objectAtIndex:fromIndexPath.item];
  418. object.folderTrackNumber = @(fromIndexPath.item - 1);
  419. }
  420. - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
  421. {
  422. return inFolder;
  423. }
  424. - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  425. {
  426. cell.backgroundColor = (indexPath.row % 2 == 0)? [UIColor blackColor]: [UIColor colorWithWhite:.122 alpha:1.];
  427. cell.multipleSelectionBackgroundView.backgroundColor = cell.backgroundColor;
  428. }
  429. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  430. {
  431. return YES;
  432. }
  433. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  434. {
  435. if (editingStyle == UITableViewCellEditingStyleDelete)
  436. [self removeMediaObject: _foundMedia[indexPath.row] updateDatabase:YES];
  437. }
  438. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  439. {
  440. if (tableView.isEditing) {
  441. if (_libraryMode == VLCLibraryModeCreateFolder) {
  442. _folderObject = _foundMedia[indexPath.row];
  443. _libraryMode = _previousLibraryMode;
  444. [self updateViewContents];
  445. [self createFolderWithName:nil];
  446. }
  447. return;
  448. }
  449. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  450. NSManagedObject *selectedObject = _foundMedia[indexPath.row];
  451. if ([selectedObject isKindOfClass:[MLAlbumTrack class]]) {
  452. VLCMediaList *list;
  453. NSArray *tracks = [[(MLAlbumTrack*)selectedObject album] sortedTracks];
  454. NSUInteger count = tracks.count;
  455. list = [[VLCMediaList alloc] init];
  456. MLFile *file;
  457. VLCMedia *media;
  458. for (NSInteger x = count - 1; x > -1; x--) {
  459. file = [(MLAlbumTrack*)tracks[x] files].anyObject;
  460. media = [VLCMedia mediaWithURL: [NSURL URLWithString:file.url]];
  461. [media parse];
  462. [list addMedia:media];
  463. }
  464. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate openMediaList:list atIndex:(int)[tracks indexOfObject:selectedObject]];
  465. } else if ([selectedObject isKindOfClass:[MLFile class]] && [((MLFile *)selectedObject).labels count] > 0) {
  466. VLCMediaList *list;
  467. MLLabel *folder = [((MLFile *)selectedObject).labels anyObject];
  468. NSArray *folderTracks = [folder sortedFolderItems];
  469. NSUInteger count = folderTracks.count;
  470. list = [[VLCMediaList alloc] init];
  471. MLFile *file;
  472. for (NSInteger x = count - 1; x > -1; x--) {
  473. file = (MLFile *)folderTracks[x];
  474. [list addMedia:[VLCMedia mediaWithURL:[NSURL URLWithString:file.url]]];
  475. }
  476. [(VLCAppDelegate *)[UIApplication sharedApplication].delegate openMediaList:list atIndex:(int)[folderTracks indexOfObject:selectedObject]];
  477. } else
  478. [self openMediaObject:selectedObject];
  479. }
  480. #pragma mark - table view gestures
  481. - (void)swipeRightGestureAction:(UIGestureRecognizer *)recognizer
  482. {
  483. if ([[self.editButtonItem title] isEqualToString:NSLocalizedString(@"BUTTON_CANCEL",@"")])
  484. [self setEditing:NO animated:YES];
  485. else {
  486. [self setEditing:YES animated:YES];
  487. NSIndexPath *path = [(UITableView *)self.view indexPathForRowAtPoint:[recognizer locationInView:self.view]];
  488. [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:path.row inSection:path.section]
  489. animated:YES
  490. scrollPosition:UITableViewScrollPositionNone];
  491. }
  492. }
  493. #pragma mark - Collection View
  494. - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
  495. {
  496. return _foundMedia.count;
  497. }
  498. - (UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
  499. {
  500. VLCPlaylistCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PlaylistCell" forIndexPath:indexPath];
  501. cell.mediaObject = _foundMedia[indexPath.row];
  502. cell.collectionView = _collectionView;
  503. [cell setEditing:self.editing animated:NO];
  504. return cell;
  505. }
  506. - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
  507. {
  508. if (SYSTEM_RUNS_IOS7_OR_LATER) {
  509. if (UIDeviceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation))
  510. return CGSizeMake(341., 190.);
  511. else
  512. return CGSizeMake(384., 216.);
  513. }
  514. return CGSizeMake(298.0, 220.0);
  515. }
  516. - (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
  517. {
  518. if (SYSTEM_RUNS_IOS7_OR_LATER)
  519. return UIEdgeInsetsMake(0., 0., 0., 0.);
  520. return UIEdgeInsetsMake(0.0, 34.0, 0.0, 34.0);
  521. }
  522. - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
  523. {
  524. if (SYSTEM_RUNS_IOS7_OR_LATER)
  525. return 0.;
  526. return 10.0;
  527. }
  528. - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
  529. {
  530. if (SYSTEM_RUNS_IOS7_OR_LATER)
  531. return 0.;
  532. return 10.0;
  533. }
  534. - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
  535. {
  536. if (self.editing) {
  537. if (_libraryMode == VLCLibraryModeCreateFolder) {
  538. _folderObject = _foundMedia[indexPath.item];
  539. _libraryMode = _previousLibraryMode;
  540. [self createFolderWithName:nil];
  541. }
  542. [(VLCPlaylistCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath] selectionUpdate];
  543. return;
  544. }
  545. NSManagedObject *selectedObject = _foundMedia[indexPath.row];
  546. if ([selectedObject isKindOfClass:[MLAlbumTrack class]]) {
  547. VLCMediaList *list;
  548. NSArray *tracks = [[(MLAlbumTrack*)selectedObject album] sortedTracks];
  549. NSUInteger count = tracks.count;
  550. list = [[VLCMediaList alloc] init];
  551. MLFile *file;
  552. for (NSInteger x = count - 1; x > -1; x--) {
  553. file = [(MLAlbumTrack*)tracks[x] files].anyObject;
  554. [list addMedia:[VLCMedia mediaWithURL: [NSURL URLWithString:file.url]]];
  555. }
  556. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate openMediaList:list atIndex:(int)[tracks indexOfObject:selectedObject]];
  557. } else if ([selectedObject isKindOfClass:[MLFile class]] && [((MLFile *)selectedObject).labels count] > 0) {
  558. VLCMediaList *list;
  559. MLLabel *folder = [((MLFile *)selectedObject).labels anyObject];
  560. NSArray *folderTracks = [folder sortedFolderItems];
  561. NSUInteger count = folderTracks.count;
  562. list = [[VLCMediaList alloc] init];
  563. MLFile *file;
  564. for (NSInteger x = count - 1; x > -1; x--) {
  565. file = (MLFile *)folderTracks[x];
  566. [list addMedia:[VLCMedia mediaWithURL:[NSURL URLWithString:file.url]]];
  567. }
  568. [(VLCAppDelegate *)[UIApplication sharedApplication].delegate openMediaList:list atIndex:(int)[folderTracks indexOfObject:selectedObject]];
  569. } else
  570. [self openMediaObject:selectedObject];
  571. }
  572. - (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
  573. {
  574. [(VLCPlaylistCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath] selectionUpdate];
  575. }
  576. - (void)collectionView:(UICollectionView *)collectionView removeItemFromFolderAtIndexPathIfNeeded:(NSIndexPath *)indexPath
  577. {
  578. MLFile *mediaObject = (MLFile *)_foundMedia[indexPath.item];
  579. [self rearrangeFolderTrackNumbersForRemovedItem:mediaObject];
  580. mediaObject.labels = nil;
  581. mediaObject.folderTrackNumber = nil;
  582. [self backToAllItems:nil];
  583. }
  584. - (void)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)fromIndexPath willMoveToIndexPath:(NSIndexPath *)toIndexPath
  585. {
  586. MLFile* object = [_foundMedia objectAtIndex:fromIndexPath.item];
  587. [_foundMedia removeObjectAtIndex:fromIndexPath.item];
  588. [_foundMedia insertObject:object atIndex:toIndexPath.item];
  589. object.folderTrackNumber = @(toIndexPath.item - 1);
  590. object = [_foundMedia objectAtIndex:fromIndexPath.item];
  591. object.folderTrackNumber = @(fromIndexPath.item - 1);
  592. }
  593. - (void)collectionView:(UICollectionView *)collectionView requestToMoveItemAtIndexPath:(NSIndexPath *)itemPath intoFolderAtIndexPath:(NSIndexPath *)folderPath
  594. {
  595. BOOL validFileTypeAtFolderPath = ([_foundMedia[folderPath.item] isKindOfClass:[MLFile class]] || [_foundMedia[folderPath.item] isKindOfClass:[MLLabel class]]) && [_foundMedia[itemPath.item] isKindOfClass:[MLFile class]];
  596. if (!validFileTypeAtFolderPath) {
  597. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"FOLDER_INVALID_TYPE_TITLE", @"") message:NSLocalizedString(@"FOLDER_INVALID_TYPE_MESSAGE", @"") cancelButtonTitle:nil otherButtonTitles:@[NSLocalizedString(@"BUTTON_OK", @"")]];
  598. alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
  599. [self updateViewContents];
  600. };
  601. [alert show];
  602. return;
  603. }
  604. BOOL isFolder = [_foundMedia[folderPath.item] isKindOfClass:[MLLabel class]];
  605. if (isFolder){
  606. MLLabel *folder = _foundMedia[folderPath.item];
  607. MLFile *file = _foundMedia[itemPath.item];
  608. [file setLabels:[[NSSet alloc] initWithObjects:folder, nil]];
  609. file.folderTrackNumber = @([folder.files count] - 1);
  610. [_foundMedia removeObjectAtIndex:itemPath.item];
  611. [self updateViewContents];
  612. } else {
  613. _folderObject = _foundMedia[folderPath.item];
  614. _indexPaths = [NSMutableArray arrayWithArray:@[itemPath]];
  615. [self showCreateFolderAlert];
  616. }
  617. }
  618. #pragma mark - Folder implementation
  619. - (void)rearrangeFolderTrackNumbersForRemovedItem:(MLFile *) mediaObject
  620. {
  621. MLLabel *label = [mediaObject.labels anyObject];
  622. NSSet *allFiles = label.files;
  623. for (MLFile *file in allFiles) {
  624. if (file.folderTrackNumber > mediaObject.folderTrackNumber) {
  625. int value = [file.folderTrackNumber intValue];
  626. file.folderTrackNumber = [NSNumber numberWithInt:value - 1];
  627. }
  628. }
  629. }
  630. - (void)showCreateFolderAlert
  631. {
  632. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"FOLDER_CHOOSE_NAME_TITLE", @"") message:NSLocalizedString(@"FOLDER_CHOOSE_NAME_MESSAGE", @"") cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", @"") otherButtonTitles:@[NSLocalizedString(@"BUTTON_SAVE", @"")]];
  633. [alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
  634. [[alert textFieldAtIndex:0] setText:NSLocalizedString(@"FOLDER_NAME_PLACEHOLDER", @"")];
  635. [[alert textFieldAtIndex:0] setClearButtonMode:UITextFieldViewModeAlways];
  636. __weak VLCAlertView *weakAlert = alert;
  637. alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
  638. if (cancelled)
  639. [self updateViewContents];
  640. else
  641. [self createFolderWithName:[weakAlert textFieldAtIndex:0].text];
  642. };
  643. [alert show];
  644. }
  645. - (void)createFolder
  646. {
  647. if (_libraryMode == VLCLibraryModeCreateFolder) {
  648. _libraryMode = _previousLibraryMode;
  649. [self updateViewContents];
  650. [self showCreateFolderAlert];
  651. return;
  652. }
  653. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  654. _indexPaths = [NSMutableArray arrayWithArray:[self.collectionView indexPathsForSelectedItems]];
  655. else
  656. _indexPaths = [NSMutableArray arrayWithArray:[self.tableView indexPathsForSelectedRows]];
  657. for (NSIndexPath *path in _indexPaths) {
  658. id mediaObject;
  659. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  660. mediaObject = _foundMedia[path.item];
  661. else
  662. mediaObject = _foundMedia[path.row];
  663. if ([mediaObject isKindOfClass:[MLLabel class]])
  664. [_indexPaths removeObject:path];
  665. }
  666. if ([_indexPaths count] != 0) {
  667. NSArray *folder = [MLLabel allLabels];
  668. //if we already have folders display them
  669. if ([folder count] > 0) {
  670. _foundMedia = [NSMutableArray arrayWithArray:folder];
  671. self.title = NSLocalizedString(@"SELECT_FOLDER", @"");
  672. _previousLibraryMode = _libraryMode;
  673. _libraryMode = VLCLibraryModeCreateFolder;
  674. [self reloadViews];
  675. return;
  676. }
  677. }
  678. //no selected items or no existing folder ask for foldername
  679. [self showCreateFolderAlert];
  680. }
  681. - (void)removeFromFolder
  682. {
  683. BOOL isPad = UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad;
  684. if (isPad)
  685. _indexPaths = [NSMutableArray arrayWithArray:[self.collectionView indexPathsForSelectedItems]];
  686. else
  687. _indexPaths = [NSMutableArray arrayWithArray:[self.tableView indexPathsForSelectedRows]];
  688. [_indexPaths sortUsingSelector:@selector(compare:)];
  689. for (NSInteger i = [_indexPaths count] - 1; i >= 0; i--) {
  690. NSIndexPath *path = _indexPaths[i];
  691. MLFile *file = (MLFile *)_foundMedia[isPad ? path.item : path.row];
  692. MLLabel *folder = [file.labels anyObject];
  693. [self rearrangeFolderTrackNumbersForRemovedItem:file];
  694. file.labels = nil;
  695. file.folderTrackNumber = nil;
  696. [_foundMedia removeObject:file];
  697. if ([folder.files count] == 0) {
  698. [self removeMediaObject:folder updateDatabase:YES];
  699. [self backToAllItems:nil];
  700. }
  701. }
  702. [self reloadViews];
  703. }
  704. - (void)createFolderWithName:(NSString *)folderName
  705. {
  706. NSArray *labels = [MLLabel allLabels];
  707. for (MLLabel *label in labels){
  708. if ([label.name isEqualToString:folderName]) {
  709. _folderObject = nil;
  710. _indexPaths = nil;
  711. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"FOLDER_NAME_DUPLICATE_TITLE", @"") message:NSLocalizedString(@"FOLDER_NAME_DUPLICATE_MESSAGE", @"") cancelButtonTitle:nil otherButtonTitles:@[NSLocalizedString(@"BUTTON_OK", @"")]];
  712. alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
  713. [self updateViewContents];
  714. };
  715. [alert show];
  716. return;
  717. }
  718. }
  719. if (_folderObject != nil) {
  720. NSUInteger folderIndex = [_foundMedia indexOfObject:_folderObject];
  721. //item got dragged onto item
  722. if ([_foundMedia[folderIndex] isKindOfClass:[MLFile class]]) {
  723. MLFile *file = _foundMedia[folderIndex];
  724. MLLabel *label = [[MLMediaLibrary sharedMediaLibrary] createObjectForEntity:@"Label"];
  725. label.name = folderName;
  726. file.labels = [NSSet setWithObjects:label,nil];
  727. NSNumber *folderTrackNumber = [NSNumber numberWithInt:(int)[label files].count - 1];
  728. file.folderTrackNumber = folderTrackNumber;
  729. [_foundMedia removeObjectAtIndex:folderIndex];
  730. [_foundMedia insertObject:label atIndex:folderIndex];
  731. MLFile *itemFile = _foundMedia[((NSIndexPath *)_indexPaths[0]).item];
  732. itemFile.labels = file.labels;
  733. [_foundMedia removeObjectAtIndex:((NSIndexPath *)_indexPaths[0]).item];
  734. itemFile.folderTrackNumber = @([label files].count - 1);
  735. } else {
  736. //item got dragged onto folder or items should be added to folder
  737. MLLabel *label = _foundMedia[folderIndex];
  738. [_indexPaths sortUsingSelector:@selector(compare:)];
  739. for (NSInteger i = [_indexPaths count] - 1; i >= 0; i--) {
  740. NSIndexPath *path = _indexPaths[i];
  741. if (![_foundMedia[path.row] isKindOfClass:[MLFile class]])
  742. continue;
  743. MLFile *file = _foundMedia[path.row];
  744. file.labels = [NSSet setWithObjects:label, nil];
  745. [_foundMedia removeObjectAtIndex:path.row];
  746. file.folderTrackNumber = @([label files].count - 1);
  747. }
  748. }
  749. _folderObject = nil;
  750. } else {
  751. //create new folder
  752. MLLabel *label = [[MLMediaLibrary sharedMediaLibrary] createObjectForEntity:@"Label"];
  753. label.name = folderName;
  754. //if items were selected
  755. if ([_indexPaths count] != 0) {
  756. [_indexPaths sortUsingSelector:@selector(compare:)];
  757. for (NSInteger i = [_indexPaths count] - 1; i >= 0; i--) {
  758. NSIndexPath *path = _indexPaths[i];
  759. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  760. MLFile *file = _foundMedia[path.item];
  761. file.labels = [NSSet setWithObjects:label, nil];
  762. file.folderTrackNumber = @([label files].count - 1);
  763. [_foundMedia removeObjectAtIndex:path.item];
  764. } else {
  765. MLFile *file = _foundMedia[path.row];
  766. file.labels = [NSSet setWithObjects:label, nil];
  767. file.folderTrackNumber = @([label files].count - 1);
  768. [_foundMedia removeObjectAtIndex:path.row];
  769. }
  770. }
  771. }
  772. }
  773. _indexPaths = nil;
  774. [self setEditing:NO];
  775. [self updateViewContents];
  776. }
  777. - (void)_collectionViewHandleLongPressGesture:(UIGestureRecognizer *) sender
  778. {
  779. [self setEditing:YES animated:YES];
  780. }
  781. #pragma mark - UI implementation
  782. - (void)setEditing:(BOOL)editing animated:(BOOL)animated
  783. {
  784. [super setEditing:editing animated:animated];
  785. UIBarButtonItem *editButton = self.editButtonItem;
  786. NSString *editImage = editing? @"doneButton": @"button";
  787. NSString *editImageHighlight = editing? @"doneButtonHighlight": @"buttonHighlight";
  788. if (SYSTEM_RUNS_IOS7_OR_LATER)
  789. editButton.tintColor = [UIColor whiteColor];
  790. else {
  791. [editButton setBackgroundImage:[UIImage imageNamed:editImage] forState:UIControlStateNormal
  792. barMetrics:UIBarMetricsDefault];
  793. [editButton setBackgroundImage:[UIImage imageNamed:editImageHighlight]
  794. forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
  795. [editButton setTitleTextAttributes: editing ? @{UITextAttributeTextShadowColor : [UIColor whiteColor], UITextAttributeTextColor : [UIColor blackColor]} : @{UITextAttributeTextShadowColor : [UIColor colorWithWhite:0. alpha:.37], UITextAttributeTextColor : [UIColor whiteColor]} forState:UIControlStateNormal];
  796. }
  797. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  798. NSArray *visibleCells = self.collectionView.visibleCells;
  799. [visibleCells enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  800. VLCPlaylistCollectionViewCell *aCell = (VLCPlaylistCollectionViewCell*)obj;
  801. [aCell setEditing:editing animated:animated];
  802. }];
  803. self.collectionView.allowsMultipleSelection = editing;
  804. /* UIKit doesn't clear the selection automagically if we leave the editing mode
  805. * so we need to do so manually */
  806. if (!editing) {
  807. [self.collectionView addGestureRecognizer:_longPressGestureRecognizer];
  808. NSArray *selectedItems = [self.collectionView indexPathsForSelectedItems];
  809. NSUInteger count = selectedItems.count;
  810. for (NSUInteger x = 0; x < count; x++)
  811. [self.collectionView deselectItemAtIndexPath:selectedItems[x] animated:NO];
  812. } else
  813. [self.collectionView removeGestureRecognizer:_longPressGestureRecognizer];
  814. } else {
  815. self.tableView.allowsMultipleSelectionDuringEditing = editing;
  816. [self.tableView setEditing:editing animated:YES];
  817. [self.editButtonItem setTitle:editing ? NSLocalizedString(@"BUTTON_CANCEL",@"") : NSLocalizedString(@"BUTTON_EDIT", @"")];
  818. }
  819. if (_libraryMode == VLCLibraryModeCreateFolder) {
  820. _libraryMode = _previousLibraryMode;
  821. _indexPaths = nil;
  822. [self updateViewContents];
  823. }
  824. self.navigationController.toolbarHidden = !editing;
  825. }
  826. - (UITableViewCellEditingStyle)tableView:(UITableView *)aTableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
  827. {
  828. return UITableViewCellEditingStyleDelete;
  829. }
  830. - (IBAction)leftButtonAction:(id)sender
  831. {
  832. [[(VLCAppDelegate*)[UIApplication sharedApplication].delegate revealController] toggleSidebar:![(VLCAppDelegate*)[UIApplication sharedApplication].delegate revealController].sidebarShowing duration:kGHRevealSidebarDefaultAnimationDuration];
  833. if (self.isEditing)
  834. [self setEditing:NO animated:YES];
  835. }
  836. - (IBAction)backToAllItems:(id)sender
  837. {
  838. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  839. if (![self.collectionView.collectionViewLayout isEqual:_folderLayout]) {
  840. //for some reason the Gesturerecognizer block themselves if not removed manually
  841. for (UIGestureRecognizer *recognizer in self.view.gestureRecognizers) {
  842. if (recognizer == _reorderLayout.panGestureRecognizer || recognizer == _reorderLayout.longPressGestureRecognizer)
  843. [self.collectionView removeGestureRecognizer:recognizer];
  844. }
  845. _folderLayout = [[VLCFolderCollectionViewFlowLayout alloc] init];
  846. [self.collectionView setCollectionViewLayout:_folderLayout animated:NO];
  847. _reorderLayout = nil;
  848. [_collectionView addGestureRecognizer:_longPressGestureRecognizer];
  849. }
  850. }
  851. inFolder = NO;
  852. UIBarButtonItem *createFolderItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemOrganize target:self action:@selector(createFolder)];
  853. NSMutableArray *toolbarItems = [self.toolbarItems mutableCopy];
  854. toolbarItems[0] = createFolderItem;
  855. self.toolbarItems = toolbarItems;
  856. [self setLibraryMode:_libraryMode];
  857. [self updateViewContents];
  858. }
  859. - (void)_endEditingWithHardReset:(BOOL)hardReset
  860. {
  861. [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
  862. if (hardReset)
  863. [self updateViewContents];
  864. else
  865. [self reloadViews];
  866. [self setEditing:NO animated:YES];
  867. }
  868. - (void)deleteSelection
  869. {
  870. NSArray *indexPaths;
  871. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  872. indexPaths = [self.collectionView indexPathsForSelectedItems];
  873. else
  874. indexPaths = [self.tableView indexPathsForSelectedRows];
  875. NSUInteger count = indexPaths.count;
  876. NSMutableArray *objects = [[NSMutableArray alloc] initWithCapacity:count];
  877. for (NSUInteger x = 0; x < count; x++)
  878. [objects addObject:_foundMedia[[indexPaths[x] row]]];
  879. for (NSUInteger x = 0; x < count; x++)
  880. [self removeMediaObject:objects[x] updateDatabase:NO];
  881. [self _endEditingWithHardReset:YES];
  882. }
  883. - (void)renameSelection
  884. {
  885. NSArray *indexPaths;
  886. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  887. indexPaths = [self.collectionView indexPathsForSelectedItems];
  888. else
  889. indexPaths = [self.tableView indexPathsForSelectedRows];
  890. if (indexPaths.count < 1) {
  891. [self _endEditingWithHardReset:NO];
  892. return;
  893. }
  894. NSString *itemName;
  895. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  896. itemName = [(VLCPlaylistCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPaths[0]] titleLabel].text;
  897. else
  898. itemName = [(VLCPlaylistTableViewCell *)[self.tableView cellForRowAtIndexPath:indexPaths[0]] titleLabel].text;
  899. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:[NSString stringWithFormat:NSLocalizedString(@"RENAME_MEDIA_TO", @""), itemName] message:nil cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", @"") otherButtonTitles:@[NSLocalizedString(@"BUTTON_RENAME", @"")]];
  900. [alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
  901. [[alert textFieldAtIndex:0] setText:itemName];
  902. [[alert textFieldAtIndex:0] setClearButtonMode:UITextFieldViewModeAlways];
  903. __weak VLCAlertView *weakAlert = alert;
  904. alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
  905. if (cancelled)
  906. [self _endEditingWithHardReset:NO];
  907. else
  908. [self renameMediaObjectTo:[weakAlert textFieldAtIndex:0].text];
  909. };
  910. [alert show];
  911. }
  912. - (void)renameMediaObjectTo:(NSString*)newName
  913. {
  914. NSArray *indexPaths;
  915. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  916. indexPaths = [self.collectionView indexPathsForSelectedItems];
  917. else
  918. indexPaths = [self.tableView indexPathsForSelectedRows];
  919. if (indexPaths.count < 1)
  920. return;
  921. id mediaObject = _foundMedia[[indexPaths[0] row]];
  922. if ([mediaObject isKindOfClass:[MLAlbum class]] || [mediaObject isKindOfClass:[MLShowEpisode class]] || [mediaObject isKindOfClass:[MLShow class]] || [mediaObject isKindOfClass:[MLLabel class]] )
  923. [mediaObject setName:newName];
  924. else
  925. [mediaObject setTitle:newName];
  926. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  927. [self.collectionView deselectItemAtIndexPath:indexPaths[0] animated:YES];
  928. else
  929. [self.tableView deselectRowAtIndexPath:indexPaths[0] animated:YES];
  930. if (indexPaths.count > 1)
  931. [self renameSelection];
  932. else
  933. [self _endEditingWithHardReset:NO];
  934. }
  935. #pragma mark - coin coin
  936. - (void)setLibraryMode:(VLCLibraryMode)mode
  937. {
  938. _libraryMode = mode;
  939. [self updateViewContents];
  940. }
  941. #pragma mark - autorotation
  942. // RootController is responsible for supporting interface orientation(iOS6.0+), i.e. navigation controller
  943. // so this will not work as intended without "voodoo magic"(UINavigationController category, subclassing, etc)
  944. /* introduced in iOS 6 */
  945. - (NSUInteger)supportedInterfaceOrientations
  946. {
  947. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  948. return UIInterfaceOrientationMaskAll;
  949. return (_foundMedia.count > 0)? UIInterfaceOrientationMaskAllButUpsideDown:
  950. UIInterfaceOrientationMaskPortrait;
  951. }
  952. /* introduced in iOS 6 */
  953. - (BOOL)shouldAutorotate
  954. {
  955. return (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) || (_foundMedia.count > 0);
  956. }
  957. - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
  958. {
  959. [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
  960. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  961. [self.collectionView.collectionViewLayout invalidateLayout];
  962. }
  963. @end