VLCPlaylistViewController.m 72 KB

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