MediaCategoryViewController.swift 17 KB

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