MediaCategoryViewController.swift 17 KB

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