MediaCategoryViewController.swift 19 KB

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