MediaCategoryViewController.swift 20 KB

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