MediaCategoryViewController.swift 13 KB

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