MediaCategoryViewController.swift 14 KB

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