MediaCategoryViewController.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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. }
  162. }
  163. // MARK: - Search
  164. func updateSearchResults(for searchController: UISearchController) {
  165. searchDataSource.shouldReloadTable(forSearch: searchController.searchBar.text, searchableFiles: model.anyfiles)
  166. collectionView?.reloadData()
  167. }
  168. func didPresentSearchController(_ searchController: UISearchController) {
  169. collectionView?.dataSource = searchDataSource
  170. }
  171. func didDismissSearchController(_ searchController: UISearchController) {
  172. collectionView?.dataSource = self
  173. }
  174. func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo {
  175. return IndicatorInfo(title:model.indicatorName)
  176. }
  177. // MARK: - UICollectionViewDataSource
  178. override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  179. return model.anyfiles.count
  180. }
  181. override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  182. guard let mediaCell = collectionView.dequeueReusableCell(withReuseIdentifier:model.cellType.defaultReuseIdentifier, for: indexPath) as? BaseCollectionViewCell else {
  183. assertionFailure("you forgot to register the cell or the cell is not a subclass of BaseCollectionViewCell")
  184. return UICollectionViewCell()
  185. }
  186. let mediaObject = model.anyfiles[indexPath.row]
  187. if let media = mediaObject as? VLCMLMedia {
  188. assert(media.mainFile() != nil, "The mainfile is nil")
  189. mediaCell.media = media.mainFile() != nil ? media : nil
  190. } else {
  191. mediaCell.media = mediaObject
  192. }
  193. return mediaCell
  194. }
  195. // MARK: - UICollectionViewDelegate
  196. override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  197. if let media = model.anyfiles[indexPath.row] as? VLCMLMedia {
  198. play(media: media)
  199. createSpotlightItem(media: media)
  200. } else if let mediaCollection = model.anyfiles[indexPath.row] as? MediaCollectionModel {
  201. let collectionViewController = VLCCollectionCategoryViewController(services, mediaCollection: mediaCollection)
  202. navigationController?.pushViewController(collectionViewController, animated: true)
  203. }
  204. }
  205. func createSpotlightItem(media: VLCMLMedia) {
  206. if KeychainCoordinator.passcodeLockEnabled {
  207. return
  208. }
  209. userActivity = NSUserActivity(activityType: kVLCUserActivityPlaying)
  210. userActivity?.title = media.title
  211. userActivity?.contentAttributeSet = media.coreSpotlightAttributeSet()
  212. userActivity?.userInfo = ["playingmedia" : media.identifier()]
  213. userActivity?.isEligibleForSearch = true
  214. userActivity?.isEligibleForHandoff = true
  215. userActivity?.becomeCurrent()
  216. }
  217. }
  218. // MARK: - UICollectionViewDelegateFlowLayout
  219. extension VLCMediaCategoryViewController {
  220. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
  221. if cachedCellSize == .zero {
  222. if #available(iOS 11.0, *) {
  223. cachedCellSize = model.cellType.cellSizeForWidth(collectionView.safeAreaLayoutGuide.layoutFrame.width)
  224. } else {
  225. cachedCellSize = model.cellType.cellSizeForWidth(collectionView.frame.size.width)
  226. }
  227. }
  228. return cachedCellSize
  229. }
  230. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
  231. return UIEdgeInsets(top: model.cellType.edgePadding, left: model.cellType.edgePadding, bottom: model.cellType.edgePadding, right: model.cellType.edgePadding)
  232. }
  233. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
  234. return model.cellType.edgePadding
  235. }
  236. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
  237. return model.cellType.interItemPadding
  238. }
  239. override func handleSort() {
  240. present(sortActionSheet, animated: false, completion: nil)
  241. }
  242. }
  243. // MARK: VLCActionSheetDelegate
  244. extension VLCMediaCategoryViewController: ActionSheetDelegate {
  245. func headerViewTitle() -> String? {
  246. return NSLocalizedString("HEADER_TITLE_SORT", comment: "")
  247. }
  248. // This provide the item to send to the selection action
  249. func itemAtIndexPath(_ indexPath: IndexPath) -> Any? {
  250. let enabledSortCriteria = model.sortModel.sortingCriteria
  251. if indexPath.row < enabledSortCriteria.count {
  252. return enabledSortCriteria[indexPath.row]
  253. }
  254. assertionFailure("VLCMediaCategoryViewController: VLCActionSheetDelegate: IndexPath out of range")
  255. return nil
  256. }
  257. }
  258. // MARK: VLCActionSheetDataSource
  259. extension VLCMediaCategoryViewController: ActionSheetDataSource {
  260. func numberOfRows() -> Int {
  261. return model.sortModel.sortingCriteria.count
  262. }
  263. func actionSheet(collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  264. guard let cell = collectionView.dequeueReusableCell(
  265. withReuseIdentifier: ActionSheetCell.identifier, for: indexPath) as? ActionSheetCell else {
  266. assertionFailure("VLCMediaCategoryViewController: VLCActionSheetDataSource: Unable to dequeue reusable cell")
  267. return UICollectionViewCell()
  268. }
  269. let sortingCriterias = model.sortModel.sortingCriteria
  270. guard indexPath.row < sortingCriterias.count else {
  271. assertionFailure("VLCMediaCategoryViewController: VLCActionSheetDataSource: IndexPath out of range")
  272. return cell
  273. }
  274. cell.name.text = String(describing: sortingCriterias[indexPath.row])
  275. return cell
  276. }
  277. }
  278. extension VLCMediaCategoryViewController: VLCEditControllerDelegate {
  279. func editController(editController: VLCEditController, cellforItemAt indexPath: IndexPath) -> MediaEditCell? {
  280. return collectionView.cellForItem(at: indexPath) as? MediaEditCell
  281. }
  282. func editController(editController: VLCEditController,
  283. present viewController: UIViewController) {
  284. let newNavigationController = UINavigationController(rootViewController: viewController)
  285. navigationController?.present(newNavigationController, animated: true, completion: nil)
  286. }
  287. }
  288. private extension VLCMediaCategoryViewController {
  289. func setupCollectionView() {
  290. let cellNib = UINib(nibName: model.cellType.nibName, bundle: nil)
  291. collectionView?.register(cellNib, forCellWithReuseIdentifier: model.cellType.defaultReuseIdentifier)
  292. if let editCell = (model as? EditableMLModel)?.editCellType() {
  293. let editCellNib = UINib(nibName: editCell.nibName, bundle: nil)
  294. collectionView?.register(editCellNib, forCellWithReuseIdentifier: editCell.defaultReuseIdentifier)
  295. }
  296. collectionView?.backgroundColor = PresentationTheme.current.colors.background
  297. collectionView?.alwaysBounceVertical = true
  298. longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.handleLongGesture(gesture:)))
  299. collectionView?.addGestureRecognizer(longPressGesture)
  300. if #available(iOS 11.0, *) {
  301. collectionView?.contentInsetAdjustmentBehavior = .always
  302. // collectionView?.dragDelegate = dragAndDropManager
  303. // collectionView?.dropDelegate = dragAndDropManager
  304. }
  305. }
  306. func setupSearchController() {
  307. searchController = UISearchController(searchResultsController: nil)
  308. searchController?.searchResultsUpdater = self
  309. searchController?.dimsBackgroundDuringPresentation = false
  310. searchController?.delegate = self
  311. if let textfield = searchController?.searchBar.value(forKey: "searchField") as? UITextField {
  312. if let backgroundview = textfield.subviews.first {
  313. backgroundview.backgroundColor = UIColor.white
  314. backgroundview.layer.cornerRadius = 10
  315. backgroundview.clipsToBounds = true
  316. }
  317. }
  318. }
  319. @objc func handleLongGesture(gesture: UILongPressGestureRecognizer) {
  320. switch gesture.state {
  321. case .began:
  322. guard let selectedIndexPath = collectionView.indexPathForItem(at: gesture.location(in: collectionView)) else {
  323. break
  324. }
  325. collectionView.beginInteractiveMovementForItem(at: selectedIndexPath)
  326. case .changed:
  327. collectionView.updateInteractiveMovementTargetPosition(gesture.location(in: gesture.view!))
  328. case .ended:
  329. collectionView.endInteractiveMovement()
  330. default:
  331. collectionView.cancelInteractiveMovement()
  332. }
  333. }
  334. }
  335. // MARK: - Player
  336. extension VLCMediaCategoryViewController {
  337. func play(media: VLCMLMedia) {
  338. VLCPlaybackController.sharedInstance().fullscreenSessionRequested = media.subtype() != .albumTrack
  339. if let collectionModel = model as? CollectionModel, collectionModel.mediaCollection is VLCMLPlaylist || collectionModel.mediaCollection is VLCMLAlbum {
  340. guard let index = collectionModel.files.index(of: media) else {
  341. return
  342. }
  343. VLCPlaybackController.sharedInstance().playMedia(at: index, fromCollection: collectionModel.files)
  344. } else {
  345. VLCPlaybackController.sharedInstance().play(media)
  346. }
  347. }
  348. }
  349. // MARK: - MediaLibraryModelView
  350. extension VLCMediaCategoryViewController {
  351. func dataChanged() {
  352. reloadData()
  353. }
  354. }