MediaCategoryViewController.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. /*****************************************************************************
  2. * MediaCateogoryViewController.swift
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2018 VideoLAN. All rights reserved.
  6. * $Id$
  7. *
  8. * Authors: Carola Nitz <nitz.carola # gmail.com>
  9. * Mike JS. Choi <mkchoi212 # icloud.com>
  10. *
  11. * Refer to the COPYING file of the official project for license.
  12. *****************************************************************************/
  13. import Foundation
  14. protocol MediaCategoryViewControllerDelegate: NSObjectProtocol {
  15. func needsToUpdateNavigationbarIfNeeded(_ viewController: VLCMediaCategoryViewController)
  16. }
  17. class VLCMediaCategoryViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, UISearchBarDelegate, IndicatorInfoProvider {
  18. var model: MediaLibraryBaseModel
  19. private var services: Services
  20. var searchBar = UISearchBar(frame: .zero)
  21. var isSearching: Bool = false
  22. private var searchBarConstraint: NSLayoutConstraint?
  23. private let searchDataSource: LibrarySearchDataSource
  24. private let searchBarSize: CGFloat = 50.0
  25. private var rendererButton: UIButton
  26. private lazy var editController: EditController = {
  27. let editController = EditController(mediaLibraryService:services.medialibraryService, model: model)
  28. editController.delegate = self
  29. return editController
  30. }()
  31. private var editToolbarConstraint: NSLayoutConstraint?
  32. private var cachedCellSize = CGSize.zero
  33. private var toSize = CGSize.zero
  34. private var longPressGesture: UILongPressGestureRecognizer!
  35. weak var delegate: MediaCategoryViewControllerDelegate?
  36. // @available(iOS 11.0, *)
  37. // lazy var dragAndDropManager: VLCDragAndDropManager = { () -> VLCDragAndDropManager<T> in
  38. // VLCDragAndDropManager<T>(subcategory: VLCMediaSubcategories<>)
  39. // }()
  40. @objc private lazy var sortActionSheet: ActionSheet = {
  41. let header = ActionSheetSortSectionHeader(model: model.sortModel)
  42. let actionSheet = ActionSheet(header: header)
  43. header.delegate = self
  44. actionSheet.delegate = self
  45. actionSheet.dataSource = self
  46. actionSheet.modalPresentationStyle = .custom
  47. actionSheet.setAction { [weak self] item in
  48. guard let sortingCriteria = item as? VLCMLSortingCriteria else {
  49. return
  50. }
  51. self?.model.sort(by: sortingCriteria, desc: header.actionSwitch.isOn)
  52. self?.sortActionSheet.removeActionSheet()
  53. }
  54. return actionSheet
  55. }()
  56. lazy var emptyView: VLCEmptyLibraryView = {
  57. let name = String(describing: VLCEmptyLibraryView.self)
  58. let nib = Bundle.main.loadNibNamed(name, owner: self, options: nil)
  59. guard let emptyView = nib?.first as? VLCEmptyLibraryView else { fatalError("Can't find nib for \(name)") }
  60. return emptyView
  61. }()
  62. let editCollectionViewLayout: UICollectionViewFlowLayout = {
  63. let editCollectionViewLayout = UICollectionViewFlowLayout()
  64. editCollectionViewLayout.minimumLineSpacing = 1
  65. editCollectionViewLayout.minimumInteritemSpacing = 0
  66. return editCollectionViewLayout
  67. }()
  68. @available(*, unavailable)
  69. init() {
  70. fatalError()
  71. }
  72. init(services: Services, model: MediaLibraryBaseModel) {
  73. self.services = services
  74. self.model = model
  75. self.rendererButton = services.rendererDiscovererManager.setupRendererButton()
  76. self.searchDataSource = LibrarySearchDataSource(model: model)
  77. super.init(collectionViewLayout: UICollectionViewFlowLayout())
  78. if let collection = model as? CollectionModel {
  79. title = collection.mediaCollection.title()
  80. }
  81. NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .VLCThemeDidChangeNotification, object: nil)
  82. navigationItem.rightBarButtonItems = [editButtonItem, UIBarButtonItem(customView: rendererButton)]
  83. }
  84. func setupSearchBar() {
  85. searchBar.delegate = self
  86. searchBar.searchBarStyle = .minimal
  87. searchBar.translatesAutoresizingMaskIntoConstraints = false
  88. searchBar.placeholder = NSLocalizedString("SEARCH", comment: "")
  89. if #available(iOS 11.0, *) {
  90. navigationItem.largeTitleDisplayMode = .never
  91. }
  92. if let textfield = searchBar.value(forKey: "searchField") as? UITextField {
  93. if let backgroundview = textfield.subviews.first {
  94. backgroundview.backgroundColor = UIColor.white
  95. backgroundview.layer.cornerRadius = 10
  96. backgroundview.clipsToBounds = true
  97. }
  98. }
  99. searchBarConstraint = searchBar.topAnchor.constraint(equalTo: view.topAnchor, constant: -searchBarSize)
  100. view.addSubview(searchBar)
  101. NSLayoutConstraint.activate([
  102. searchBarConstraint!,
  103. searchBar.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10),
  104. searchBar.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10),
  105. searchBar.heightAnchor.constraint(equalToConstant: searchBarSize)
  106. ])
  107. }
  108. override var preferredStatusBarStyle: UIStatusBarStyle {
  109. return PresentationTheme.current.colors.statusBarStyle
  110. }
  111. @objc func reloadData() {
  112. DispatchQueue.main.async {
  113. [weak self] in
  114. guard let self = self else {
  115. return
  116. }
  117. self.delegate?.needsToUpdateNavigationbarIfNeeded(self)
  118. self.collectionView?.reloadData()
  119. self.updateUIForContent()
  120. }
  121. }
  122. @available(*, unavailable)
  123. required init?(coder aDecoder: NSCoder) {
  124. fatalError("init(coder: ) has not been implemented")
  125. }
  126. override func viewDidLoad() {
  127. super.viewDidLoad()
  128. setupCollectionView()
  129. setupSearchBar()
  130. setupEditToolbar()
  131. _ = (MLMediaLibrary.sharedMediaLibrary() as! MLMediaLibrary).libraryDidAppear()
  132. }
  133. override func viewWillAppear(_ animated: Bool) {
  134. super.viewWillAppear(animated)
  135. let manager = services.rendererDiscovererManager
  136. if manager.discoverers.isEmpty {
  137. // Either didn't start or stopped before
  138. manager.start()
  139. }
  140. manager.presentingViewController = self
  141. cachedCellSize = .zero
  142. collectionView.collectionViewLayout.invalidateLayout()
  143. }
  144. @objc func themeDidChange() {
  145. collectionView?.backgroundColor = PresentationTheme.current.colors.background
  146. editController.view.backgroundColor = PresentationTheme.current.colors.background
  147. setNeedsStatusBarAppearanceUpdate()
  148. }
  149. func setupEditToolbar() {
  150. editController.view.translatesAutoresizingMaskIntoConstraints = false
  151. view.addSubview(editController.view)
  152. var guide: LayoutAnchorContainer = view
  153. if #available(iOS 11.0, *) {
  154. guide = view.safeAreaLayoutGuide
  155. }
  156. editToolbarConstraint = editController.view.bottomAnchor.constraint(equalTo: guide.bottomAnchor, constant: EditToolbar.height)
  157. NSLayoutConstraint.activate([
  158. editToolbarConstraint!,
  159. editController.view.leadingAnchor.constraint(equalTo: guide.leadingAnchor),
  160. editController.view.trailingAnchor.constraint(equalTo: guide.trailingAnchor),
  161. editController.view.heightAnchor.constraint(equalToConstant: 50)
  162. ])
  163. }
  164. override func viewDidAppear(_ animated: Bool) {
  165. super.viewDidAppear(animated)
  166. reloadData()
  167. }
  168. func isEmptyCollectionView() -> Bool {
  169. return collectionView?.numberOfItems(inSection: 0) == 0
  170. }
  171. func updateUIForContent() {
  172. let isEmpty = isEmptyCollectionView()
  173. if isEmpty {
  174. collectionView?.setContentOffset(.zero, animated: false)
  175. }
  176. searchBar.isHidden = isEmpty || isEditing
  177. collectionView?.backgroundView = isEmpty ? emptyView : nil
  178. }
  179. // MARK: Renderer
  180. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  181. super.viewWillTransition(to: size, with: coordinator)
  182. cachedCellSize = .zero
  183. toSize = size
  184. collectionView?.collectionViewLayout.invalidateLayout()
  185. }
  186. // MARK: - Edit
  187. override func scrollViewDidScroll(_ scrollView: UIScrollView) {
  188. searchBarConstraint?.constant = -min(scrollView.contentOffset.y, searchBarSize) - searchBarSize
  189. if scrollView.contentOffset.y < -searchBarSize && scrollView.contentInset.top != searchBarSize {
  190. collectionView.contentInset = UIEdgeInsets(top: searchBarSize, left: 0, bottom: 0, right: 0)
  191. }
  192. if scrollView.contentOffset.y >= 0 && scrollView.contentInset.top != 0 {
  193. collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
  194. }
  195. }
  196. override func setEditing(_ editing: Bool, animated: Bool) {
  197. super.setEditing(editing, animated: animated)
  198. // might have an issue if the old datasource was search
  199. // Most of the edit logic is handled inside editController
  200. collectionView?.dataSource = editing ? editController : self
  201. collectionView?.delegate = editing ? editController : self
  202. editController.resetSelections()
  203. displayEditToolbar()
  204. let layoutToBe = editing ? editCollectionViewLayout : UICollectionViewFlowLayout()
  205. collectionView?.setCollectionViewLayout(layoutToBe, animated: false, completion: {
  206. [unowned self] finished in
  207. guard finished else {
  208. assertionFailure("VLCMediaSubcategoryViewController: Edit layout transition failed.")
  209. return
  210. }
  211. self.searchBarConstraint?.constant = -self.searchBarSize
  212. self.reloadData()
  213. })
  214. }
  215. private func displayEditToolbar() {
  216. UIView.animate(withDuration: 0.3) { [weak self] in
  217. self?.editToolbarConstraint?.constant = self?.isEditing == true ? 0 : EditToolbar.height
  218. self?.view.layoutIfNeeded()
  219. self?.collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: self?.isEditing == true ? EditToolbar.height : 0, right: 0)
  220. }
  221. }
  222. func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo {
  223. let uiTestAccessibilityIdentifier = model is TrackModel ? VLCAccessibilityIdentifier.songs : nil
  224. return IndicatorInfo(title: model.indicatorName, accessibilityIdentifier: uiTestAccessibilityIdentifier)
  225. }
  226. // MARK: - UICollectionViewDataSource
  227. override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  228. return isSearching ? searchDataSource.searchData.count : model.anyfiles.count
  229. }
  230. override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  231. guard let mediaCell = collectionView.dequeueReusableCell(withReuseIdentifier:model.cellType.defaultReuseIdentifier, for: indexPath) as? BaseCollectionViewCell else {
  232. assertionFailure("you forgot to register the cell or the cell is not a subclass of BaseCollectionViewCell")
  233. return UICollectionViewCell()
  234. }
  235. let mediaObject = isSearching ? searchDataSource.objectAtIndex(index: indexPath.row) : model.anyfiles[indexPath.row]
  236. if let media = mediaObject as? VLCMLMedia {
  237. assert(media.mainFile() != nil, "The mainfile is nil")
  238. mediaCell.media = media.mainFile() != nil ? media : nil
  239. } else {
  240. mediaCell.media = mediaObject
  241. }
  242. mediaCell.isAccessibilityElement = true
  243. return mediaCell
  244. }
  245. // MARK: - UICollectionViewDelegate
  246. override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  247. let modelContent = isSearching ? searchDataSource.objectAtIndex(index: indexPath.row) : model.anyfiles[indexPath.row]
  248. if let media = modelContent as? VLCMLMedia {
  249. play(media: media, at: indexPath)
  250. createSpotlightItem(media: media)
  251. } else if let mediaCollection = modelContent as? MediaCollectionModel {
  252. let collectionViewController = VLCCollectionCategoryViewController(services, mediaCollection: mediaCollection)
  253. navigationController?.pushViewController(collectionViewController, animated: true)
  254. }
  255. }
  256. func createSpotlightItem(media: VLCMLMedia) {
  257. if KeychainCoordinator.passcodeLockEnabled {
  258. return
  259. }
  260. userActivity = NSUserActivity(activityType: kVLCUserActivityPlaying)
  261. userActivity?.title = media.title
  262. userActivity?.contentAttributeSet = media.coreSpotlightAttributeSet()
  263. userActivity?.userInfo = ["playingmedia" : media.identifier()]
  264. userActivity?.isEligibleForSearch = true
  265. userActivity?.isEligibleForHandoff = true
  266. userActivity?.becomeCurrent()
  267. }
  268. }
  269. // MARK: - UISearchBarDelegate
  270. extension VLCMediaCategoryViewController {
  271. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  272. reloadData()
  273. isSearching = true
  274. searchBar.setShowsCancelButton(true, animated: true)
  275. }
  276. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  277. searchBar.resignFirstResponder()
  278. // Empty the text field and reset the research
  279. searchBar.text = ""
  280. searchDataSource.shouldReloadFor(searchString: "")
  281. searchBar.setShowsCancelButton(false, animated: true)
  282. isSearching = false
  283. reloadData()
  284. }
  285. func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
  286. searchBar.resignFirstResponder()
  287. }
  288. func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
  289. searchDataSource.shouldReloadFor(searchString: searchText)
  290. reloadData()
  291. if searchText.isEmpty {
  292. self.searchBar.resignFirstResponder
  293. }
  294. }
  295. }
  296. // MARK: - UICollectionViewDelegateFlowLayout
  297. extension VLCMediaCategoryViewController {
  298. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
  299. if cachedCellSize == .zero {
  300. //For iOS 10 when rotating we take the value from willTransition to size, for the first layout pass that value is 0 though,
  301. //so we need the frame.size width. For rotation on iOS 11 this approach doesn't work because at the time when this is called
  302. //we don't have yet the updated safeare layout frame. This is addressed by relayouting from viewSafeAreaInsetsDidChange
  303. var toWidth = toSize.width != 0 ? toSize.width : collectionView.frame.size.width
  304. if #available(iOS 11.0, *) {
  305. toWidth = collectionView.safeAreaLayoutGuide.layoutFrame.width
  306. }
  307. cachedCellSize = model.cellType.cellSizeForWidth(toWidth)
  308. }
  309. return cachedCellSize
  310. }
  311. override func viewSafeAreaInsetsDidChange() {
  312. cachedCellSize = .zero
  313. collectionView?.collectionViewLayout.invalidateLayout()
  314. }
  315. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
  316. return UIEdgeInsets(top: model.cellType.edgePadding, left: model.cellType.edgePadding, bottom: model.cellType.edgePadding, right: model.cellType.edgePadding)
  317. }
  318. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
  319. return model.cellType.edgePadding
  320. }
  321. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
  322. return model.cellType.interItemPadding
  323. }
  324. func handleSort() {
  325. var currentSortIndex: Int = 0
  326. for (index, criteria) in
  327. model.sortModel.sortingCriteria.enumerated()
  328. where criteria == model.sortModel.currentSort {
  329. currentSortIndex = index
  330. break
  331. }
  332. present(sortActionSheet, animated: false) {
  333. [sortActionSheet, currentSortIndex] in
  334. sortActionSheet.collectionView.selectItem(at:
  335. IndexPath(row: currentSortIndex, section: 0), animated: false,
  336. scrollPosition: .centeredVertically)
  337. }
  338. }
  339. func handleSortShortcut() {
  340. model.sort(by: model.sortModel.currentSort, desc: !model.sortModel.desc)
  341. }
  342. }
  343. // MARK: VLCActionSheetDelegate
  344. extension VLCMediaCategoryViewController: ActionSheetDelegate {
  345. func headerViewTitle() -> String? {
  346. return NSLocalizedString("HEADER_TITLE_SORT", comment: "")
  347. }
  348. // This provide the item to send to the selection action
  349. func itemAtIndexPath(_ indexPath: IndexPath) -> Any? {
  350. let enabledSortCriteria = model.sortModel.sortingCriteria
  351. if indexPath.row < enabledSortCriteria.count {
  352. return enabledSortCriteria[indexPath.row]
  353. }
  354. assertionFailure("VLCMediaCategoryViewController: VLCActionSheetDelegate: IndexPath out of range")
  355. return nil
  356. }
  357. }
  358. // MARK: VLCActionSheetDataSource
  359. extension VLCMediaCategoryViewController: ActionSheetDataSource {
  360. func numberOfRows() -> Int {
  361. return model.sortModel.sortingCriteria.count
  362. }
  363. func actionSheet(collectionView: UICollectionView,
  364. cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  365. guard let cell = collectionView.dequeueReusableCell(
  366. withReuseIdentifier: ActionSheetCell.identifier,
  367. for: indexPath) as? ActionSheetCell else {
  368. assertionFailure("VLCMediaCategoryViewController: VLCActionSheetDataSource: Unable to dequeue reusable cell")
  369. return UICollectionViewCell()
  370. }
  371. let sortingCriterias = model.sortModel.sortingCriteria
  372. guard indexPath.row < sortingCriterias.count else {
  373. assertionFailure("VLCMediaCategoryViewController: VLCActionSheetDataSource: IndexPath out of range")
  374. return cell
  375. }
  376. cell.name.text = String(describing: sortingCriterias[indexPath.row])
  377. return cell
  378. }
  379. }
  380. // MARK: - ActionSheetSortSectionHeaderDelegate
  381. extension VLCMediaCategoryViewController: ActionSheetSortSectionHeaderDelegate {
  382. func actionSheetSortSectionHeader(_ header: ActionSheetSortSectionHeader,
  383. onSwitchIsOnChange: Bool) {
  384. model.sort(by: model.sortModel.currentSort, desc: onSwitchIsOnChange)
  385. }
  386. }
  387. // MARK: - EditControllerDelegate
  388. extension VLCMediaCategoryViewController: EditControllerDelegate {
  389. func editController(editController: EditController, cellforItemAt indexPath: IndexPath) -> MediaEditCell? {
  390. return collectionView.cellForItem(at: indexPath) as? MediaEditCell
  391. }
  392. func editController(editController: EditController,
  393. present viewController: UIViewController) {
  394. let newNavigationController = UINavigationController(rootViewController: viewController)
  395. navigationController?.present(newNavigationController, animated: true, completion: nil)
  396. }
  397. }
  398. private extension VLCMediaCategoryViewController {
  399. func setupCollectionView() {
  400. let cellNib = UINib(nibName: model.cellType.nibName, bundle: nil)
  401. collectionView?.register(cellNib, forCellWithReuseIdentifier: model.cellType.defaultReuseIdentifier)
  402. if let editCell = (model as? EditableMLModel)?.editCellType() {
  403. let editCellNib = UINib(nibName: editCell.nibName, bundle: nil)
  404. collectionView?.register(editCellNib, forCellWithReuseIdentifier: editCell.defaultReuseIdentifier)
  405. }
  406. collectionView?.backgroundColor = PresentationTheme.current.colors.background
  407. collectionView?.alwaysBounceVertical = true
  408. longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.handleLongGesture(gesture:)))
  409. collectionView?.addGestureRecognizer(longPressGesture)
  410. if #available(iOS 11.0, *) {
  411. collectionView?.contentInsetAdjustmentBehavior = .always
  412. // collectionView?.dragDelegate = dragAndDropManager
  413. // collectionView?.dropDelegate = dragAndDropManager
  414. }
  415. }
  416. @objc func handleLongGesture(gesture: UILongPressGestureRecognizer) {
  417. switch gesture.state {
  418. case .began:
  419. guard let selectedIndexPath = collectionView.indexPathForItem(at: gesture.location(in: collectionView)) else {
  420. break
  421. }
  422. collectionView.beginInteractiveMovementForItem(at: selectedIndexPath)
  423. case .changed:
  424. collectionView.updateInteractiveMovementTargetPosition(gesture.location(in: gesture.view!))
  425. case .ended:
  426. collectionView.endInteractiveMovement()
  427. default:
  428. collectionView.cancelInteractiveMovement()
  429. }
  430. }
  431. }
  432. // MARK: - Player
  433. extension VLCMediaCategoryViewController {
  434. func play(media: VLCMLMedia, at indexPath: IndexPath) {
  435. let playbackController = VLCPlaybackController.sharedInstance()
  436. let autoPlayNextItem = UserDefaults.standard.bool(forKey: kVLCAutomaticallyPlayNextItem)
  437. playbackController.fullscreenSessionRequested = media.type() != .audio
  438. if !autoPlayNextItem {
  439. playbackController.play(media)
  440. return
  441. }
  442. var tracks = [VLCMLMedia]()
  443. if let model = model as? MediaCollectionModel {
  444. tracks = model.files() ?? []
  445. } else {
  446. tracks = (isSearching ? searchDataSource.searchData : model.anyfiles) as? [VLCMLMedia] ?? []
  447. }
  448. playbackController.playMedia(at: indexPath.row, fromCollection: tracks)
  449. }
  450. }
  451. // MARK: - MediaLibraryModelView
  452. extension VLCMediaCategoryViewController {
  453. func dataChanged() {
  454. reloadData()
  455. }
  456. }