VLCPlaylistViewController.m 72 KB

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