MediaCategoryViewController.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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 setupCollectionView() {
  89. let cellNib = UINib(nibName: model.cellType.nibName, bundle: nil)
  90. collectionView?.register(cellNib, forCellWithReuseIdentifier: model.cellType.defaultReuseIdentifier)
  91. if let editCell = (model as? EditableMLModel)?.editCellType() {
  92. let editCellNib = UINib(nibName: editCell.nibName, bundle: nil)
  93. collectionView?.register(editCellNib, forCellWithReuseIdentifier: editCell.defaultReuseIdentifier)
  94. }
  95. collectionView?.backgroundColor = PresentationTheme.current.colors.background
  96. collectionView?.alwaysBounceVertical = true
  97. if #available(iOS 11.0, *) {
  98. collectionView?.contentInsetAdjustmentBehavior = .always
  99. // collectionView?.dragDelegate = dragAndDropManager
  100. // collectionView?.dropDelegate = dragAndDropManager
  101. }
  102. }
  103. func setupEditToolbar() {
  104. editToolbar.translatesAutoresizingMaskIntoConstraints = false
  105. view.addSubview(editToolbar)
  106. editToolbarConstraint = editToolbar.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 50)
  107. NSLayoutConstraint.activate([
  108. editToolbarConstraint!,
  109. editToolbar.leadingAnchor.constraint(equalTo: view.leadingAnchor),
  110. editToolbar.trailingAnchor.constraint(equalTo: view.trailingAnchor),
  111. editToolbar.heightAnchor.constraint(equalToConstant: 50)
  112. ])
  113. }
  114. override func viewDidAppear(_ animated: Bool) {
  115. super.viewDidAppear(animated)
  116. reloadData()
  117. }
  118. func setupSearchController() {
  119. searchController = UISearchController(searchResultsController: nil)
  120. searchController?.searchResultsUpdater = self
  121. searchController?.dimsBackgroundDuringPresentation = false
  122. searchController?.delegate = self
  123. if let textfield = searchController?.searchBar.value(forKey: "searchField") as? UITextField {
  124. if let backgroundview = textfield.subviews.first {
  125. backgroundview.backgroundColor = UIColor.white
  126. backgroundview.layer.cornerRadius = 10
  127. backgroundview.clipsToBounds = true
  128. }
  129. }
  130. }
  131. func updateUIForContent() {
  132. let isEmpty = collectionView?.numberOfItems(inSection: 0) == 0
  133. if isEmpty {
  134. collectionView?.setContentOffset(.zero, animated: false)
  135. }
  136. collectionView?.backgroundView = isEmpty ? emptyView : nil
  137. if #available(iOS 11.0, *) {
  138. navigationItem.searchController = isEmpty ? nil : searchController
  139. } else {
  140. navigationItem.titleView = isEmpty ? nil : searchController?.searchBar
  141. }
  142. }
  143. // MARK: Renderer
  144. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  145. collectionView?.collectionViewLayout.invalidateLayout()
  146. }
  147. // MARK: - Edit
  148. override func setEditing(_ editing: Bool, animated: Bool) {
  149. super.setEditing(editing, animated: animated)
  150. // might have an issue if the old datasource was search
  151. // Most of the edit logic is handled inside editController
  152. collectionView?.dataSource = editing ? editController : self
  153. collectionView?.delegate = editing ? editController : self
  154. editController.resetSelections()
  155. displayEditToolbar()
  156. let layoutToBe = editing ? editCollectionViewLayout : UICollectionViewFlowLayout()
  157. collectionView?.setCollectionViewLayout(layoutToBe, animated: false, completion: {
  158. [weak self] finished in
  159. guard finished else {
  160. assertionFailure("VLCMediaSubcategoryViewController: Edit layout transition failed.")
  161. return
  162. }
  163. self?.reloadData()
  164. })
  165. }
  166. private func displayEditToolbar() {
  167. UIView.animate(withDuration: 0.3) { [weak self] in
  168. self?.editToolbarConstraint?.constant = self?.isEditing == true ? 0 : 50
  169. self?.view.layoutIfNeeded()
  170. }
  171. }
  172. // MARK: - Search
  173. func updateSearchResults(for searchController: UISearchController) {
  174. searchDataSource.shouldReloadTable(forSearch: searchController.searchBar.text, searchableFiles: model.anyfiles)
  175. collectionView?.reloadData()
  176. }
  177. func didPresentSearchController(_ searchController: UISearchController) {
  178. collectionView?.dataSource = searchDataSource
  179. }
  180. func didDismissSearchController(_ searchController: UISearchController) {
  181. collectionView?.dataSource = self
  182. }
  183. func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo {
  184. return IndicatorInfo(title:model.indicatorName)
  185. }
  186. // MARK: - UICollectionViewDataSource
  187. override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  188. return model.anyfiles.count
  189. }
  190. override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  191. guard let mediaCell = collectionView.dequeueReusableCell(withReuseIdentifier:model.cellType.defaultReuseIdentifier, for: indexPath) as? BaseCollectionViewCell else {
  192. assertionFailure("you forgot to register the cell or the cell is not a subclass of BaseCollectionViewCell")
  193. return UICollectionViewCell()
  194. }
  195. let mediaObject = model.anyfiles[indexPath.row]
  196. if let media = mediaObject as? VLCMLMedia {
  197. assert(media.mainFile() != nil, "The mainfile is nil")
  198. mediaCell.media = media.mainFile() != nil ? media : nil
  199. } else {
  200. mediaCell.media = mediaObject
  201. }
  202. return mediaCell
  203. }
  204. // MARK: - UICollectionViewDelegate
  205. override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  206. if let media = model.anyfiles[indexPath.row] as? VLCMLMedia {
  207. play(media: media)
  208. }
  209. }
  210. // MARK: - UICollectionViewDelegateFlowLayout
  211. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
  212. if cachedCellSize == .zero {
  213. cachedCellSize = model.cellType.cellSizeForWidth(collectionView.frame.size.width)
  214. }
  215. return cachedCellSize
  216. }
  217. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
  218. return UIEdgeInsets(top: model.cellType.cellPadding, left: model.cellType.cellPadding, bottom: model.cellType.cellPadding, right: model.cellType.cellPadding)
  219. }
  220. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
  221. return model.cellType.cellPadding
  222. }
  223. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
  224. return model.cellType.cellPadding
  225. }
  226. }
  227. // MARK: - Sort
  228. extension VLCMediaCategoryViewController {
  229. // FIXME: Need to add a button for ascending/descending result
  230. func sortByFileName() {
  231. // The issue is that for audio we show title which is quite confusing if we use filename
  232. model.sort(by: .alpha)
  233. }
  234. func sortByDate() {
  235. model.sort(by: .insertionDate)
  236. }
  237. func sortBySize() {
  238. model.sort(by: .fileSize)
  239. }
  240. }
  241. // MARK: - Player
  242. extension VLCMediaCategoryViewController {
  243. func play(mediaObject: NSManagedObject) {
  244. VLCPlaybackController.sharedInstance().playMediaLibraryObject(mediaObject)
  245. }
  246. func play(media: VLCMLMedia) {
  247. VLCPlaybackController.sharedInstance().fullscreenSessionRequested = media.subtype() != .albumTrack
  248. VLCPlaybackController.sharedInstance().play(media)
  249. }
  250. }
  251. // MARK: - MediaLibraryModelView
  252. extension VLCMediaCategoryViewController {
  253. func dataChanged() {
  254. reloadData()
  255. }
  256. }