VLCLibraryViewController.m 74 KB

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