MediaCategoryViewController.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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 var rendererButton: UIButton
  20. private lazy var editController: VLCEditController = {
  21. let editController = VLCEditController(mediaLibraryService:services.medialibraryService, model: model)
  22. editController.delegate = self
  23. return editController
  24. }()
  25. private var editToolbarConstraint: NSLayoutConstraint?
  26. private var cachedCellSize = CGSize.zero
  27. private var toSize = CGSize.zero
  28. private var longPressGesture: UILongPressGestureRecognizer!
  29. // @available(iOS 11.0, *)
  30. // lazy var dragAndDropManager: VLCDragAndDropManager = { () -> VLCDragAndDropManager<T> in
  31. // VLCDragAndDropManager<T>(subcategory: VLCMediaSubcategories<>)
  32. // }()
  33. @objc private lazy var sortActionSheet: ActionSheet = {
  34. let actionSheet = ActionSheet()
  35. actionSheet.delegate = self
  36. actionSheet.dataSource = self
  37. actionSheet.modalPresentationStyle = .custom
  38. actionSheet.setAction { [weak self] item in
  39. guard let sortingCriteria = item as? VLCMLSortingCriteria else {
  40. return
  41. }
  42. self?.model.sort(by: sortingCriteria)
  43. self?.sortActionSheet.removeActionSheet()
  44. }
  45. return actionSheet
  46. }()
  47. lazy var emptyView: VLCEmptyLibraryView = {
  48. let name = String(describing: VLCEmptyLibraryView.self)
  49. let nib = Bundle.main.loadNibNamed(name, owner: self, options: nil)
  50. guard let emptyView = nib?.first as? VLCEmptyLibraryView else { fatalError("Can't find nib for \(name)") }
  51. return emptyView
  52. }()
  53. let editCollectionViewLayout: UICollectionViewFlowLayout = {
  54. let editCollectionViewLayout = UICollectionViewFlowLayout()
  55. editCollectionViewLayout.minimumLineSpacing = 1
  56. editCollectionViewLayout.minimumInteritemSpacing = 0
  57. return editCollectionViewLayout
  58. }()
  59. @available(*, unavailable)
  60. init() {
  61. fatalError()
  62. }
  63. init(services: Services, model: MediaLibraryBaseModel) {
  64. self.services = services
  65. self.model = model
  66. self.rendererButton = services.rendererDiscovererManager.setupRendererButton()
  67. super.init(collectionViewLayout: UICollectionViewFlowLayout())
  68. if let collection = model as? CollectionModel {
  69. title = collection.mediaCollection.title()
  70. }
  71. NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .VLCThemeDidChangeNotification, object: nil)
  72. navigationItem.rightBarButtonItems = [editButtonItem, UIBarButtonItem(customView: rendererButton)]
  73. }
  74. override var preferredStatusBarStyle: UIStatusBarStyle {
  75. return PresentationTheme.current.colors.statusBarStyle
  76. }
  77. @objc func reloadData() {
  78. DispatchQueue.main.async {
  79. [weak self] in
  80. self?.collectionView?.reloadData()
  81. self?.updateUIForContent()
  82. }
  83. }
  84. @available(*, unavailable)
  85. required init?(coder aDecoder: NSCoder) {
  86. fatalError("init(coder: ) has not been implemented")
  87. }
  88. override func viewDidLoad() {
  89. super.viewDidLoad()
  90. setupCollectionView()
  91. setupSearchController()
  92. setupEditToolbar()
  93. _ = (MLMediaLibrary.sharedMediaLibrary() as! MLMediaLibrary).libraryDidAppear()
  94. }
  95. override func viewWillAppear(_ animated: Bool) {
  96. super.viewWillAppear(animated)
  97. let manager = services.rendererDiscovererManager
  98. if manager.discoverers.isEmpty {
  99. // Either didn't start or stopped before
  100. manager.start()
  101. }
  102. manager.presentingViewController = self
  103. }
  104. @objc func themeDidChange() {
  105. collectionView?.backgroundColor = PresentationTheme.current.colors.background
  106. editController.view.backgroundColor = PresentationTheme.current.colors.background
  107. setNeedsStatusBarAppearanceUpdate()
  108. }
  109. func setupEditToolbar() {
  110. editController.view.translatesAutoresizingMaskIntoConstraints = false
  111. view.addSubview(editController.view)
  112. var guide: LayoutAnchorContainer = view
  113. if #available(iOS 11.0, *) {
  114. guide = view.safeAreaLayoutGuide
  115. }
  116. editToolbarConstraint = editController.view.bottomAnchor.constraint(equalTo: guide.bottomAnchor, constant: EditToolbar.height)
  117. NSLayoutConstraint.activate([
  118. editToolbarConstraint!,
  119. editController.view.leadingAnchor.constraint(equalTo: guide.leadingAnchor),
  120. editController.view.trailingAnchor.constraint(equalTo: guide.trailingAnchor),
  121. editController.view.heightAnchor.constraint(equalToConstant: 50)
  122. ])
  123. }
  124. override func viewDidAppear(_ animated: Bool) {
  125. super.viewDidAppear(animated)
  126. reloadData()
  127. }
  128. func isEmptyCollectionView() -> Bool {
  129. return collectionView?.numberOfItems(inSection: 0) == 0
  130. }
  131. func updateUIForContent() {
  132. let isEmpty = isEmptyCollectionView()
  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. super.viewWillTransition(to: size, with: coordinator)
  146. cachedCellSize = .zero
  147. toSize = size
  148. collectionView?.collectionViewLayout.invalidateLayout()
  149. }
  150. // MARK: - Edit
  151. override func setEditing(_ editing: Bool, animated: Bool) {
  152. super.setEditing(editing, animated: animated)
  153. // might have an issue if the old datasource was search
  154. // Most of the edit logic is handled inside editController
  155. collectionView?.dataSource = editing ? editController : self
  156. collectionView?.delegate = editing ? editController : self
  157. editController.resetSelections()
  158. displayEditToolbar()
  159. let layoutToBe = editing ? editCollectionViewLayout : UICollectionViewFlowLayout()
  160. collectionView?.setCollectionViewLayout(layoutToBe, animated: false, completion: {
  161. [weak self] finished in
  162. guard finished else {
  163. assertionFailure("VLCMediaSubcategoryViewController: Edit layout transition failed.")
  164. return
  165. }
  166. self?.reloadData()
  167. })
  168. }
  169. private func displayEditToolbar() {
  170. UIView.animate(withDuration: 0.3) { [weak self] in
  171. self?.editToolbarConstraint?.constant = self?.isEditing == true ? 0 : EditToolbar.height
  172. self?.view.layoutIfNeeded()
  173. self?.collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: self?.isEditing == true ? EditToolbar.height : 0, right: 0)
  174. }
  175. }
  176. // MARK: - Search
  177. func updateSearchResults(for searchController: UISearchController) {
  178. searchDataSource.shouldReloadTable(forSearch: searchController.searchBar.text, searchableFiles: model.anyfiles)
  179. collectionView?.reloadData()
  180. }
  181. func didPresentSearchController(_ searchController: UISearchController) {
  182. collectionView?.dataSource = searchDataSource
  183. }
  184. func didDismissSearchController(_ searchController: UISearchController) {
  185. collectionView?.dataSource = self
  186. }
  187. func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo {
  188. return IndicatorInfo(title:model.indicatorName)
  189. }
  190. // MARK: - UICollectionViewDataSource
  191. override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  192. return model.anyfiles.count
  193. }
  194. override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  195. guard let mediaCell = collectionView.dequeueReusableCell(withReuseIdentifier:model.cellType.defaultReuseIdentifier, for: indexPath) as? BaseCollectionViewCell else {
  196. assertionFailure("you forgot to register the cell or the cell is not a subclass of BaseCollectionViewCell")
  197. return UICollectionViewCell()
  198. }
  199. let mediaObject = model.anyfiles[indexPath.row]
  200. if let media = mediaObject as? VLCMLMedia {
  201. assert(media.mainFile() != nil, "The mainfile is nil")
  202. mediaCell.media = media.mainFile() != nil ? media : nil
  203. } else {
  204. mediaCell.media = mediaObject
  205. }
  206. return mediaCell
  207. }
  208. // MARK: - UICollectionViewDelegate
  209. override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  210. if let media = model.anyfiles[indexPath.row] as? VLCMLMedia {
  211. play(media: media)
  212. createSpotlightItem(media: media)
  213. } else if let mediaCollection = model.anyfiles[indexPath.row] as? MediaCollectionModel {
  214. let collectionViewController = VLCCollectionCategoryViewController(services, mediaCollection: mediaCollection)
  215. navigationController?.pushViewController(collectionViewController, animated: true)
  216. }
  217. }
  218. func createSpotlightItem(media: VLCMLMedia) {
  219. if KeychainCoordinator.passcodeLockEnabled {
  220. return
  221. }
  222. userActivity = NSUserActivity(activityType: kVLCUserActivityPlaying)
  223. userActivity?.title = media.title
  224. userActivity?.contentAttributeSet = media.coreSpotlightAttributeSet()
  225. userActivity?.userInfo = ["playingmedia" : media.identifier()]
  226. userActivity?.isEligibleForSearch = true
  227. userActivity?.isEligibleForHandoff = true
  228. userActivity?.becomeCurrent()
  229. }
  230. }
  231. // MARK: - UICollectionViewDelegateFlowLayout
  232. extension VLCMediaCategoryViewController {
  233. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
  234. if cachedCellSize == .zero {
  235. //For iOS 10 when rotating we take the value from willTransition to size, for the first layout pass that value is 0 though,
  236. //so we need the frame.size width. For rotation on iOS 11 this approach doesn't work because at the time when this is called
  237. //we don't have yet the updated safeare layout frame. This is addressed by relayouting from viewSafeAreaInsetsDidChange
  238. var toWidth = toSize.width != 0 ? toSize.width : collectionView.frame.size.width
  239. if #available(iOS 11.0, *) {
  240. toWidth = collectionView.safeAreaLayoutGuide.layoutFrame.width
  241. }
  242. cachedCellSize = model.cellType.cellSizeForWidth(toWidth)
  243. }
  244. return cachedCellSize
  245. }
  246. override func viewSafeAreaInsetsDidChange() {
  247. cachedCellSize = .zero
  248. collectionView?.collectionViewLayout.invalidateLayout()
  249. }
  250. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
  251. return UIEdgeInsets(top: model.cellType.edgePadding, left: model.cellType.edgePadding, bottom: model.cellType.edgePadding, right: model.cellType.edgePadding)
  252. }
  253. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
  254. return model.cellType.edgePadding
  255. }
  256. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
  257. return model.cellType.interItemPadding
  258. }
  259. func handleSort() {
  260. var currentSortIndex: Int = 0
  261. for (index, criteria) in
  262. model.sortModel.sortingCriteria.enumerated()
  263. where criteria == model.sortModel.currentSort {
  264. currentSortIndex = index
  265. break
  266. }
  267. present(sortActionSheet, animated: false) {
  268. [sortActionSheet, currentSortIndex] in
  269. sortActionSheet.collectionView.selectItem(at:
  270. IndexPath(row: currentSortIndex, section: 0), animated: false,
  271. scrollPosition: .centeredVertically)
  272. }
  273. }
  274. }
  275. // MARK: VLCActionSheetDelegate
  276. extension VLCMediaCategoryViewController: ActionSheetDelegate {
  277. func headerViewTitle() -> String? {
  278. return NSLocalizedString("HEADER_TITLE_SORT", comment: "")
  279. }
  280. // This provide the item to send to the selection action
  281. func itemAtIndexPath(_ indexPath: IndexPath) -> Any? {
  282. let enabledSortCriteria = model.sortModel.sortingCriteria
  283. if indexPath.row < enabledSortCriteria.count {
  284. return enabledSortCriteria[indexPath.row]
  285. }
  286. assertionFailure("VLCMediaCategoryViewController: VLCActionSheetDelegate: IndexPath out of range")
  287. return nil
  288. }
  289. }
  290. // MARK: VLCActionSheetDataSource
  291. extension VLCMediaCategoryViewController: ActionSheetDataSource {
  292. func numberOfRows() -> Int {
  293. return model.sortModel.sortingCriteria.count
  294. }
  295. func actionSheet(collectionView: UICollectionView,
  296. cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  297. guard let cell = collectionView.dequeueReusableCell(
  298. withReuseIdentifier: ActionSheetCell.identifier,
  299. for: indexPath) as? ActionSheetCell else {
  300. assertionFailure("VLCMediaCategoryViewController: VLCActionSheetDataSource: Unable to dequeue reusable cell")
  301. return UICollectionViewCell()
  302. }
  303. let sortingCriterias = model.sortModel.sortingCriteria
  304. guard indexPath.row < sortingCriterias.count else {
  305. assertionFailure("VLCMediaCategoryViewController: VLCActionSheetDataSource: IndexPath out of range")
  306. return cell
  307. }
  308. cell.name.text = String(describing: sortingCriterias[indexPath.row])
  309. return cell
  310. }
  311. }
  312. extension VLCMediaCategoryViewController: VLCEditControllerDelegate {
  313. func editController(editController: VLCEditController, cellforItemAt indexPath: IndexPath) -> MediaEditCell? {
  314. return collectionView.cellForItem(at: indexPath) as? MediaEditCell
  315. }
  316. func editController(editController: VLCEditController,
  317. present viewController: UIViewController) {
  318. let newNavigationController = UINavigationController(rootViewController: viewController)
  319. navigationController?.present(newNavigationController, animated: true, completion: nil)
  320. }
  321. }
  322. private extension VLCMediaCategoryViewController {
  323. func setupCollectionView() {
  324. let cellNib = UINib(nibName: model.cellType.nibName, bundle: nil)
  325. collectionView?.register(cellNib, forCellWithReuseIdentifier: model.cellType.defaultReuseIdentifier)
  326. if let editCell = (model as? EditableMLModel)?.editCellType() {
  327. let editCellNib = UINib(nibName: editCell.nibName, bundle: nil)
  328. collectionView?.register(editCellNib, forCellWithReuseIdentifier: editCell.defaultReuseIdentifier)
  329. }
  330. collectionView?.backgroundColor = PresentationTheme.current.colors.background
  331. collectionView?.alwaysBounceVertical = true
  332. longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.handleLongGesture(gesture:)))
  333. collectionView?.addGestureRecognizer(longPressGesture)
  334. if #available(iOS 11.0, *) {
  335. collectionView?.contentInsetAdjustmentBehavior = .always
  336. // collectionView?.dragDelegate = dragAndDropManager
  337. // collectionView?.dropDelegate = dragAndDropManager
  338. }
  339. }
  340. func setupSearchController() {
  341. searchController = UISearchController(searchResultsController: nil)
  342. searchController?.searchResultsUpdater = self
  343. searchController?.dimsBackgroundDuringPresentation = false
  344. searchController?.delegate = self
  345. if let textfield = searchController?.searchBar.value(forKey: "searchField") as? UITextField {
  346. if let backgroundview = textfield.subviews.first {
  347. backgroundview.backgroundColor = UIColor.white
  348. backgroundview.layer.cornerRadius = 10
  349. backgroundview.clipsToBounds = true
  350. }
  351. }
  352. }
  353. @objc func handleLongGesture(gesture: UILongPressGestureRecognizer) {
  354. switch gesture.state {
  355. case .began:
  356. guard let selectedIndexPath = collectionView.indexPathForItem(at: gesture.location(in: collectionView)) else {
  357. break
  358. }
  359. collectionView.beginInteractiveMovementForItem(at: selectedIndexPath)
  360. case .changed:
  361. collectionView.updateInteractiveMovementTargetPosition(gesture.location(in: gesture.view!))
  362. case .ended:
  363. collectionView.endInteractiveMovement()
  364. default:
  365. collectionView.cancelInteractiveMovement()
  366. }
  367. }
  368. }
  369. // MARK: - Player
  370. extension VLCMediaCategoryViewController {
  371. func play(media: VLCMLMedia) {
  372. VLCPlaybackController.sharedInstance().fullscreenSessionRequested = media.subtype() != .albumTrack
  373. if let collectionModel = model as? CollectionModel, collectionModel.mediaCollection is VLCMLPlaylist || collectionModel.mediaCollection is VLCMLAlbum {
  374. guard let index = collectionModel.files.firstIndex(of: media) else {
  375. return
  376. }
  377. VLCPlaybackController.sharedInstance().playMedia(at: index, fromCollection: collectionModel.files)
  378. } else {
  379. VLCPlaybackController.sharedInstance().play(media)
  380. }
  381. }
  382. }
  383. // MARK: - MediaLibraryModelView
  384. extension VLCMediaCategoryViewController {
  385. func dataChanged() {
  386. reloadData()
  387. }
  388. }