MediaCategoryViewController.swift 21 KB

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