MediaCategoryViewController.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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. let cellPadding: CGFloat = 5.0
  16. private var services: Services
  17. private var searchController: UISearchController?
  18. private let searchDataSource = VLCLibrarySearchDisplayDataSource()
  19. var category: MediaLibraryBaseModel
  20. private lazy var editController = VLCEditController(collectionView: self.collectionView!, category: self.category)
  21. // @available(iOS 11.0, *)
  22. // lazy var dragAndDropManager: VLCDragAndDropManager = { () -> VLCDragAndDropManager<T> in
  23. // VLCDragAndDropManager<T>(subcategory: VLCMediaSubcategories<>)
  24. // }()
  25. lazy var emptyView: VLCEmptyLibraryView = {
  26. let name = String(describing: VLCEmptyLibraryView.self)
  27. let nib = Bundle.main.loadNibNamed(name, owner: self, options: nil)
  28. guard let emptyView = nib?.first as? VLCEmptyLibraryView else { fatalError("Can't find nib for \(name)") }
  29. return emptyView
  30. }()
  31. let editCollectionViewLayout: UICollectionViewFlowLayout = {
  32. let editCollectionViewLayout = UICollectionViewFlowLayout()
  33. editCollectionViewLayout.minimumLineSpacing = 1
  34. editCollectionViewLayout.minimumInteritemSpacing = 0
  35. return editCollectionViewLayout
  36. }()
  37. @available(*, unavailable)
  38. init() {
  39. fatalError()
  40. }
  41. init(services: Services, category: MediaLibraryBaseModel) {
  42. self.services = services
  43. self.category = category
  44. super.init(collectionViewLayout: UICollectionViewFlowLayout())
  45. NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .VLCThemeDidChangeNotification, object: nil)
  46. }
  47. override var preferredStatusBarStyle: UIStatusBarStyle {
  48. return PresentationTheme.current.colors.statusBarStyle
  49. }
  50. @objc func reloadData() {
  51. DispatchQueue.main.async {
  52. [weak self] in
  53. self?.collectionView?.reloadData()
  54. self?.updateUIForContent()
  55. }
  56. }
  57. @available(*, unavailable)
  58. required init?(coder aDecoder: NSCoder) {
  59. fatalError("init(coder: ) has not been implemented")
  60. }
  61. override func viewDidLoad() {
  62. super.viewDidLoad()
  63. setupCollectionView()
  64. setupSearchController()
  65. _ = (MLMediaLibrary.sharedMediaLibrary() as! MLMediaLibrary).libraryDidAppear()
  66. }
  67. override func viewWillAppear(_ animated: Bool) {
  68. super.viewWillAppear(animated)
  69. let manager = services.rendererDiscovererManager
  70. if manager.discoverers.isEmpty {
  71. // Either didn't start or stopped before
  72. manager.start()
  73. }
  74. manager.presentingViewController = self
  75. }
  76. @objc func themeDidChange() {
  77. collectionView?.backgroundColor = PresentationTheme.current.colors.background
  78. setNeedsStatusBarAppearanceUpdate()
  79. }
  80. func setupCollectionView() {
  81. let cellNib = UINib(nibName: category.cellType.nibName, bundle: nil)
  82. collectionView?.register(cellNib, forCellWithReuseIdentifier: category.cellType.defaultReuseIdentifier)
  83. collectionView?.register(VLCMediaViewEditCell.self, forCellWithReuseIdentifier: VLCMediaViewEditCell.identifier)
  84. collectionView?.backgroundColor = PresentationTheme.current.colors.background
  85. collectionView?.alwaysBounceVertical = true
  86. if #available(iOS 11.0, *) {
  87. // collectionView?.dragDelegate = dragAndDropManager
  88. // collectionView?.dropDelegate = dragAndDropManager
  89. }
  90. }
  91. override func viewDidAppear(_ animated: Bool) {
  92. super.viewDidAppear(animated)
  93. reloadData()
  94. }
  95. func setupSearchController() {
  96. searchController = UISearchController(searchResultsController: nil)
  97. searchController?.searchResultsUpdater = self
  98. searchController?.dimsBackgroundDuringPresentation = false
  99. searchController?.delegate = self
  100. if let textfield = searchController?.searchBar.value(forKey: "searchField") as? UITextField {
  101. if let backgroundview = textfield.subviews.first {
  102. backgroundview.backgroundColor = UIColor.white
  103. backgroundview.layer.cornerRadius = 10
  104. backgroundview.clipsToBounds = true
  105. }
  106. }
  107. }
  108. func updateUIForContent() {
  109. let isEmpty = collectionView?.numberOfItems(inSection: 0) == 0
  110. if isEmpty {
  111. collectionView?.setContentOffset(.zero, animated: false)
  112. }
  113. collectionView?.backgroundView = isEmpty ? emptyView : nil
  114. if #available(iOS 11.0, *) {
  115. navigationItem.searchController = isEmpty ? nil : searchController
  116. } else {
  117. navigationItem.titleView = isEmpty ? nil : searchController?.searchBar
  118. }
  119. }
  120. // MARK: Renderer
  121. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  122. collectionView?.collectionViewLayout.invalidateLayout()
  123. }
  124. // MARK: - Edit
  125. override func setEditing(_ editing: Bool, animated: Bool) {
  126. super.setEditing(editing, animated: animated)
  127. // might have an issue if the old datasource was search
  128. // Most of the edit logic is handled inside editController
  129. collectionView?.dataSource = editing ? editController : self
  130. collectionView?.delegate = editing ? editController : self
  131. editController.toolbarNeedsUpdate(editing: editing)
  132. let layoutToBe = editing ? editCollectionViewLayout : UICollectionViewFlowLayout()
  133. collectionView?.setCollectionViewLayout(layoutToBe, animated: false, completion: {
  134. [weak self] finished in
  135. guard finished else {
  136. assertionFailure("VLCMediaSubcategoryViewController: Edit layout transition failed.")
  137. return
  138. }
  139. self?.reloadData()
  140. })
  141. }
  142. // MARK: - Search
  143. func updateSearchResults(for searchController: UISearchController) {
  144. searchDataSource.shouldReloadTable(forSearch: searchController.searchBar.text, searchableFiles: category.anyfiles)
  145. collectionView?.reloadData()
  146. }
  147. func didPresentSearchController(_ searchController: UISearchController) {
  148. collectionView?.dataSource = searchDataSource
  149. }
  150. func didDismissSearchController(_ searchController: UISearchController) {
  151. collectionView?.dataSource = self
  152. }
  153. func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo {
  154. return IndicatorInfo(title:category.indicatorName)
  155. }
  156. // MARK: - UICollectionViewDataSource
  157. override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  158. return category.anyfiles.count
  159. }
  160. override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  161. guard let mediaCell = collectionView.dequeueReusableCell(withReuseIdentifier:category.cellType.defaultReuseIdentifier, for: indexPath) as? BaseCollectionViewCell else {
  162. assertionFailure("you forgot to register the cell or the cell is not a subclass of BaseCollectionViewCell")
  163. return UICollectionViewCell()
  164. }
  165. guard let media = category.anyfiles[indexPath.row] as? VLCMLMedia else {
  166. assertionFailure("The contained file in the category doesn't conform to VLCMLMedia")
  167. return mediaCell
  168. }
  169. assert(media.mainFile() != nil, "The mainfile is nil")
  170. mediaCell.media = media.mainFile() != nil ? media : nil
  171. return mediaCell
  172. }
  173. // MARK: - UICollectionViewDelegate
  174. override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  175. if let media = category.anyfiles[indexPath.row] as? VLCMLMedia {
  176. play(media: media)
  177. }
  178. }
  179. // MARK: - UICollectionViewDelegateFlowLayout
  180. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
  181. let numberOfCells: CGFloat = round(collectionView.frame.size.width / 250)
  182. let aspectRatio: CGFloat = 10.0 / 16.0
  183. // We have the number of cells and we always have numberofCells + 1 padding spaces. -pad-[Cell]-pad-[Cell]-pad-
  184. // we then have the entire padding, we divide the entire padding by the number of Cells to know how much needs to be substracted from ech cell
  185. // since this might be an uneven number we ceil
  186. var cellWidth = collectionView.bounds.size.width / numberOfCells
  187. cellWidth = cellWidth - ceil(((numberOfCells + 1) * cellPadding) / numberOfCells)
  188. // 3*20 for the labels + 24 for 3*8 which is the padding
  189. return CGSize(width: cellWidth, height: cellWidth * aspectRatio + 3*20+24)
  190. }
  191. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
  192. return UIEdgeInsets(top: cellPadding, left: cellPadding, bottom: cellPadding, right: cellPadding)
  193. }
  194. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
  195. return cellPadding
  196. }
  197. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
  198. return cellPadding
  199. }
  200. }
  201. // MARK: - Sort
  202. extension VLCMediaCategoryViewController {
  203. // FIXME: Need to add a button for ascending/descending result
  204. func sortByFileName() {
  205. // The issue is that for audio we show title which is quite confusing if we use filename
  206. category.sort(by: .alpha)
  207. }
  208. func sortByDate() {
  209. category.sort(by: .insertionDate)
  210. }
  211. func sortBySize() {
  212. category.sort(by: .fileSize)
  213. }
  214. }
  215. // MARK: - Player
  216. extension VLCMediaCategoryViewController {
  217. func play(mediaObject: NSManagedObject) {
  218. VLCPlaybackController.sharedInstance().playMediaLibraryObject(mediaObject)
  219. }
  220. func play(media: VLCMLMedia) {
  221. VLCPlaybackController.sharedInstance().fullscreenSessionRequested = media.subtype() != .albumTrack
  222. VLCPlaybackController.sharedInstance().play(media)
  223. }
  224. }
  225. // MARK: - MediaLibraryModelView
  226. extension VLCMediaCategoryViewController {
  227. func dataChanged() {
  228. reloadData()
  229. }
  230. }