MediaCategoryViewController.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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. class VLCMediaCategoryViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, UISearchResultsUpdating, UISearchControllerDelegate, IndicatorInfoProvider {
  15. var model: MediaLibraryBaseModel
  16. private var services: Services
  17. private var searchController: UISearchController?
  18. private let searchDataSource = VLCLibrarySearchDisplayDataSource()
  19. private var rendererButton: UIButton
  20. private lazy var editController: VLCEditController = {
  21. let editController = VLCEditController(mediaLibraryService:services.medialibraryService, model: model)
  22. editController.delegate = self
  23. return editController
  24. }()
  25. private var editToolbarConstraint: NSLayoutConstraint?
  26. private var cachedCellSize = CGSize.zero
  27. private var longPressGesture: UILongPressGestureRecognizer!
  28. // @available(iOS 11.0, *)
  29. // lazy var dragAndDropManager: VLCDragAndDropManager = { () -> VLCDragAndDropManager<T> in
  30. // VLCDragAndDropManager<T>(subcategory: VLCMediaSubcategories<>)
  31. // }()
  32. @objc private lazy var sortActionSheet: ActionSheet = {
  33. let actionSheet = ActionSheet()
  34. actionSheet.delegate = self
  35. actionSheet.dataSource = self
  36. actionSheet.modalPresentationStyle = .custom
  37. actionSheet.setAction { [weak self] item in
  38. guard let sortingCriteria = item as? VLCMLSortingCriteria else {
  39. return
  40. }
  41. self?.model.sort(by: sortingCriteria)
  42. self?.sortActionSheet.removeActionSheet()
  43. }
  44. return actionSheet
  45. }()
  46. lazy var emptyView: VLCEmptyLibraryView = {
  47. let name = String(describing: VLCEmptyLibraryView.self)
  48. let nib = Bundle.main.loadNibNamed(name, owner: self, options: nil)
  49. guard let emptyView = nib?.first as? VLCEmptyLibraryView else { fatalError("Can't find nib for \(name)") }
  50. return emptyView
  51. }()
  52. let editCollectionViewLayout: UICollectionViewFlowLayout = {
  53. let editCollectionViewLayout = UICollectionViewFlowLayout()
  54. editCollectionViewLayout.minimumLineSpacing = 1
  55. editCollectionViewLayout.minimumInteritemSpacing = 0
  56. return editCollectionViewLayout
  57. }()
  58. @available(*, unavailable)
  59. init() {
  60. fatalError()
  61. }
  62. init(services: Services, model: MediaLibraryBaseModel) {
  63. self.services = services
  64. self.model = model
  65. self.rendererButton = services.rendererDiscovererManager.setupRendererButton()
  66. super.init(collectionViewLayout: UICollectionViewFlowLayout())
  67. NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .VLCThemeDidChangeNotification, object: nil)
  68. navigationItem.rightBarButtonItems = [editButtonItem, UIBarButtonItem(customView: rendererButton)]
  69. }
  70. override var preferredStatusBarStyle: UIStatusBarStyle {
  71. return PresentationTheme.current.colors.statusBarStyle
  72. }
  73. @objc func reloadData() {
  74. DispatchQueue.main.async {
  75. [weak self] in
  76. self?.collectionView?.reloadData()
  77. self?.updateUIForContent()
  78. }
  79. }
  80. @available(*, unavailable)
  81. required init?(coder aDecoder: NSCoder) {
  82. fatalError("init(coder: ) has not been implemented")
  83. }
  84. override func viewDidLoad() {
  85. super.viewDidLoad()
  86. setupCollectionView()
  87. setupSearchController()
  88. setupEditToolbar()
  89. _ = (MLMediaLibrary.sharedMediaLibrary() as! MLMediaLibrary).libraryDidAppear()
  90. }
  91. override func viewWillAppear(_ animated: Bool) {
  92. super.viewWillAppear(animated)
  93. let manager = services.rendererDiscovererManager
  94. if manager.discoverers.isEmpty {
  95. // Either didn't start or stopped before
  96. manager.start()
  97. }
  98. manager.presentingViewController = self
  99. }
  100. @objc func themeDidChange() {
  101. collectionView?.backgroundColor = PresentationTheme.current.colors.background
  102. editController.view.backgroundColor = PresentationTheme.current.colors.background
  103. setNeedsStatusBarAppearanceUpdate()
  104. }
  105. func setupEditToolbar() {
  106. editController.view.translatesAutoresizingMaskIntoConstraints = false
  107. view.addSubview(editController.view)
  108. editToolbarConstraint = editController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: VLCEditToolbar.height)
  109. NSLayoutConstraint.activate([
  110. editToolbarConstraint!,
  111. editController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
  112. editController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
  113. editController.view.heightAnchor.constraint(equalToConstant: 50)
  114. ])
  115. }
  116. override func viewDidAppear(_ animated: Bool) {
  117. super.viewDidAppear(animated)
  118. reloadData()
  119. }
  120. func updateUIForContent() {
  121. let isEmpty = collectionView?.numberOfItems(inSection: 0) == 0
  122. if isEmpty {
  123. collectionView?.setContentOffset(.zero, animated: false)
  124. }
  125. collectionView?.backgroundView = isEmpty ? emptyView : nil
  126. if #available(iOS 11.0, *) {
  127. navigationItem.searchController = isEmpty ? nil : searchController
  128. } else {
  129. navigationItem.titleView = isEmpty ? nil : searchController?.searchBar
  130. }
  131. }
  132. // MARK: Renderer
  133. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  134. super.viewWillTransition(to: size, with: coordinator)
  135. collectionView?.collectionViewLayout.invalidateLayout()
  136. cachedCellSize = .zero
  137. }
  138. // MARK: - Edit
  139. override func setEditing(_ editing: Bool, animated: Bool) {
  140. super.setEditing(editing, animated: animated)
  141. // might have an issue if the old datasource was search
  142. // Most of the edit logic is handled inside editController
  143. collectionView?.dataSource = editing ? editController : self
  144. collectionView?.delegate = editing ? editController : self
  145. editController.resetSelections()
  146. displayEditToolbar()
  147. let layoutToBe = editing ? editCollectionViewLayout : UICollectionViewFlowLayout()
  148. collectionView?.setCollectionViewLayout(layoutToBe, animated: false, completion: {
  149. [weak self] finished in
  150. guard finished else {
  151. assertionFailure("VLCMediaSubcategoryViewController: Edit layout transition failed.")
  152. return
  153. }
  154. self?.reloadData()
  155. })
  156. }
  157. private func displayEditToolbar() {
  158. UIView.animate(withDuration: 0.3) { [weak self] in
  159. self?.editToolbarConstraint?.constant = self?.isEditing == true ? 0 : VLCEditToolbar.height
  160. self?.view.layoutIfNeeded()
  161. self?.collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: self?.isEditing == true ? VLCEditToolbar.height : 0, right: 0)
  162. }
  163. }
  164. // MARK: - Search
  165. func updateSearchResults(for searchController: UISearchController) {
  166. searchDataSource.shouldReloadTable(forSearch: searchController.searchBar.text, searchableFiles: model.anyfiles)
  167. collectionView?.reloadData()
  168. }
  169. func didPresentSearchController(_ searchController: UISearchController) {
  170. collectionView?.dataSource = searchDataSource
  171. }
  172. func didDismissSearchController(_ searchController: UISearchController) {
  173. collectionView?.dataSource = self
  174. }
  175. func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo {
  176. return IndicatorInfo(title:model.indicatorName)
  177. }
  178. // MARK: - UICollectionViewDataSource
  179. override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  180. return model.anyfiles.count
  181. }
  182. override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  183. guard let mediaCell = collectionView.dequeueReusableCell(withReuseIdentifier:model.cellType.defaultReuseIdentifier, for: indexPath) as? BaseCollectionViewCell else {
  184. assertionFailure("you forgot to register the cell or the cell is not a subclass of BaseCollectionViewCell")
  185. return UICollectionViewCell()
  186. }
  187. let mediaObject = model.anyfiles[indexPath.row]
  188. if let media = mediaObject as? VLCMLMedia {
  189. assert(media.mainFile() != nil, "The mainfile is nil")
  190. mediaCell.media = media.mainFile() != nil ? media : nil
  191. } else {
  192. mediaCell.media = mediaObject
  193. }
  194. return mediaCell
  195. }
  196. // MARK: - UICollectionViewDelegate
  197. override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  198. if let media = model.anyfiles[indexPath.row] as? VLCMLMedia {
  199. play(media: media)
  200. createSpotlightItem(media: media)
  201. } else if let mediaCollection = model.anyfiles[indexPath.row] as? MediaCollectionModel {
  202. let collectionViewController = VLCCollectionCategoryViewController(services, mediaCollection: mediaCollection)
  203. navigationController?.pushViewController(collectionViewController, animated: true)
  204. }
  205. }
  206. func createSpotlightItem(media: VLCMLMedia) {
  207. if KeychainCoordinator.passcodeLockEnabled {
  208. return
  209. }
  210. userActivity = NSUserActivity(activityType: kVLCUserActivityPlaying)
  211. userActivity?.title = media.title
  212. userActivity?.contentAttributeSet = media.coreSpotlightAttributeSet()
  213. userActivity?.userInfo = ["playingmedia" : media.identifier()]
  214. userActivity?.isEligibleForSearch = true
  215. userActivity?.isEligibleForHandoff = true
  216. userActivity?.becomeCurrent()
  217. }
  218. }
  219. // MARK: - UICollectionViewDelegateFlowLayout
  220. extension VLCMediaCategoryViewController {
  221. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
  222. if cachedCellSize == .zero {
  223. if #available(iOS 11.0, *) {
  224. cachedCellSize = model.cellType.cellSizeForWidth(collectionView.safeAreaLayoutGuide.layoutFrame.width)
  225. } else {
  226. cachedCellSize = model.cellType.cellSizeForWidth(collectionView.frame.size.width)
  227. }
  228. }
  229. return cachedCellSize
  230. }
  231. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
  232. return UIEdgeInsets(top: model.cellType.edgePadding, left: model.cellType.edgePadding, bottom: model.cellType.edgePadding, right: model.cellType.edgePadding)
  233. }
  234. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
  235. return model.cellType.edgePadding
  236. }
  237. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
  238. return model.cellType.interItemPadding
  239. }
  240. func handleSort() {
  241. present(sortActionSheet, animated: false, completion: nil)
  242. }
  243. }
  244. // MARK: VLCActionSheetDelegate
  245. extension VLCMediaCategoryViewController: ActionSheetDelegate {
  246. func headerViewTitle() -> String? {
  247. return NSLocalizedString("HEADER_TITLE_SORT", comment: "")
  248. }
  249. // This provide the item to send to the selection action
  250. func itemAtIndexPath(_ indexPath: IndexPath) -> Any? {
  251. let enabledSortCriteria = model.sortModel.sortingCriteria
  252. if indexPath.row < enabledSortCriteria.count {
  253. return enabledSortCriteria[indexPath.row]
  254. }
  255. assertionFailure("VLCMediaCategoryViewController: VLCActionSheetDelegate: IndexPath out of range")
  256. return nil
  257. }
  258. }
  259. // MARK: VLCActionSheetDataSource
  260. extension VLCMediaCategoryViewController: ActionSheetDataSource {
  261. func numberOfRows() -> Int {
  262. return model.sortModel.sortingCriteria.count
  263. }
  264. func actionSheet(collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  265. guard let cell = collectionView.dequeueReusableCell(
  266. withReuseIdentifier: ActionSheetCell.identifier, for: indexPath) as? ActionSheetCell else {
  267. assertionFailure("VLCMediaCategoryViewController: VLCActionSheetDataSource: Unable to dequeue reusable cell")
  268. return UICollectionViewCell()
  269. }
  270. let sortingCriterias = model.sortModel.sortingCriteria
  271. guard indexPath.row < sortingCriterias.count else {
  272. assertionFailure("VLCMediaCategoryViewController: VLCActionSheetDataSource: IndexPath out of range")
  273. return cell
  274. }
  275. cell.name.text = String(describing: sortingCriterias[indexPath.row])
  276. return cell
  277. }
  278. }
  279. extension VLCMediaCategoryViewController: VLCEditControllerDelegate {
  280. func editController(editController: VLCEditController, cellforItemAt indexPath: IndexPath) -> MediaEditCell? {
  281. return collectionView.cellForItem(at: indexPath) as? MediaEditCell
  282. }
  283. func editController(editController: VLCEditController,
  284. present viewController: UIViewController) {
  285. let newNavigationController = UINavigationController(rootViewController: viewController)
  286. navigationController?.present(newNavigationController, animated: true, completion: nil)
  287. }
  288. }
  289. private extension VLCMediaCategoryViewController {
  290. func setupCollectionView() {
  291. let cellNib = UINib(nibName: model.cellType.nibName, bundle: nil)
  292. collectionView?.register(cellNib, forCellWithReuseIdentifier: model.cellType.defaultReuseIdentifier)
  293. if let editCell = (model as? EditableMLModel)?.editCellType() {
  294. let editCellNib = UINib(nibName: editCell.nibName, bundle: nil)
  295. collectionView?.register(editCellNib, forCellWithReuseIdentifier: editCell.defaultReuseIdentifier)
  296. }
  297. collectionView?.backgroundColor = PresentationTheme.current.colors.background
  298. collectionView?.alwaysBounceVertical = true
  299. longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.handleLongGesture(gesture:)))
  300. collectionView?.addGestureRecognizer(longPressGesture)
  301. if #available(iOS 11.0, *) {
  302. collectionView?.contentInsetAdjustmentBehavior = .always
  303. // collectionView?.dragDelegate = dragAndDropManager
  304. // collectionView?.dropDelegate = dragAndDropManager
  305. }
  306. }
  307. func setupSearchController() {
  308. searchController = UISearchController(searchResultsController: nil)
  309. searchController?.searchResultsUpdater = self
  310. searchController?.dimsBackgroundDuringPresentation = false
  311. searchController?.delegate = self
  312. if let textfield = searchController?.searchBar.value(forKey: "searchField") as? UITextField {
  313. if let backgroundview = textfield.subviews.first {
  314. backgroundview.backgroundColor = UIColor.white
  315. backgroundview.layer.cornerRadius = 10
  316. backgroundview.clipsToBounds = true
  317. }
  318. }
  319. }
  320. @objc func handleLongGesture(gesture: UILongPressGestureRecognizer) {
  321. switch gesture.state {
  322. case .began:
  323. guard let selectedIndexPath = collectionView.indexPathForItem(at: gesture.location(in: collectionView)) else {
  324. break
  325. }
  326. collectionView.beginInteractiveMovementForItem(at: selectedIndexPath)
  327. case .changed:
  328. collectionView.updateInteractiveMovementTargetPosition(gesture.location(in: gesture.view!))
  329. case .ended:
  330. collectionView.endInteractiveMovement()
  331. default:
  332. collectionView.cancelInteractiveMovement()
  333. }
  334. }
  335. }
  336. // MARK: - Player
  337. extension VLCMediaCategoryViewController {
  338. func play(media: VLCMLMedia) {
  339. VLCPlaybackController.sharedInstance().fullscreenSessionRequested = media.subtype() != .albumTrack
  340. if let collectionModel = model as? CollectionModel, collectionModel.mediaCollection is VLCMLPlaylist || collectionModel.mediaCollection is VLCMLAlbum {
  341. guard let index = collectionModel.files.index(of: media) else {
  342. return
  343. }
  344. VLCPlaybackController.sharedInstance().playMedia(at: index, fromCollection: collectionModel.files)
  345. } else {
  346. VLCPlaybackController.sharedInstance().play(media)
  347. }
  348. }
  349. }
  350. // MARK: - MediaLibraryModelView
  351. extension VLCMediaCategoryViewController {
  352. func dataChanged() {
  353. reloadData()
  354. }
  355. }