MediaCategoryViewController.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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. // MARK: - UICollectionViewDelegateFlowLayout
  183. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
  184. if cachedCellSize == .zero {
  185. cachedCellSize = model.cellType.cellSizeForWidth(collectionView.frame.size.width)
  186. }
  187. return cachedCellSize
  188. }
  189. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
  190. return UIEdgeInsets(top: model.cellType.cellPadding, left: model.cellType.cellPadding, bottom: model.cellType.cellPadding, right: model.cellType.cellPadding)
  191. }
  192. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
  193. return model.cellType.cellPadding
  194. }
  195. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
  196. return model.cellType.cellPadding
  197. }
  198. }
  199. private extension VLCMediaCategoryViewController {
  200. func setupCollectionView() {
  201. let cellNib = UINib(nibName: model.cellType.nibName, bundle: nil)
  202. collectionView?.register(cellNib, forCellWithReuseIdentifier: model.cellType.defaultReuseIdentifier)
  203. if let editCell = (model as? EditableMLModel)?.editCellType() {
  204. let editCellNib = UINib(nibName: editCell.nibName, bundle: nil)
  205. collectionView?.register(editCellNib, forCellWithReuseIdentifier: editCell.defaultReuseIdentifier)
  206. }
  207. collectionView?.backgroundColor = PresentationTheme.current.colors.background
  208. collectionView?.alwaysBounceVertical = true
  209. if #available(iOS 11.0, *) {
  210. collectionView?.contentInsetAdjustmentBehavior = .always
  211. // collectionView?.dragDelegate = dragAndDropManager
  212. // collectionView?.dropDelegate = dragAndDropManager
  213. }
  214. }
  215. func setupSearchController() {
  216. searchController = UISearchController(searchResultsController: nil)
  217. searchController?.searchResultsUpdater = self
  218. searchController?.dimsBackgroundDuringPresentation = false
  219. searchController?.delegate = self
  220. if let textfield = searchController?.searchBar.value(forKey: "searchField") as? UITextField {
  221. if let backgroundview = textfield.subviews.first {
  222. backgroundview.backgroundColor = UIColor.white
  223. backgroundview.layer.cornerRadius = 10
  224. backgroundview.clipsToBounds = true
  225. }
  226. }
  227. }
  228. }
  229. // MARK: - Sort
  230. extension VLCMediaCategoryViewController {
  231. // FIXME: Need to add a button for ascending/descending result
  232. func sortByFileName() {
  233. // The issue is that for audio we show title which is quite confusing if we use filename
  234. model.sort(by: .alpha)
  235. }
  236. func sortByDate() {
  237. model.sort(by: .insertionDate)
  238. }
  239. func sortBySize() {
  240. model.sort(by: .fileSize)
  241. }
  242. }
  243. // MARK: - Player
  244. extension VLCMediaCategoryViewController {
  245. func play(mediaObject: NSManagedObject) {
  246. VLCPlaybackController.sharedInstance().playMediaLibraryObject(mediaObject)
  247. }
  248. func play(media: VLCMLMedia) {
  249. VLCPlaybackController.sharedInstance().fullscreenSessionRequested = media.subtype() != .albumTrack
  250. VLCPlaybackController.sharedInstance().play(media)
  251. }
  252. }
  253. // MARK: - MediaLibraryModelView
  254. extension VLCMediaCategoryViewController {
  255. func dataChanged() {
  256. reloadData()
  257. }
  258. }