MediaCategoryViewController.swift 19 KB

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