MediaCategoryViewController.swift 15 KB

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