VLCPlaylistViewController.m 67 KB

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