MediaCategoryViewController.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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. // MARK: - Search
  217. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  218. reloadData()
  219. searchBar.setShowsCancelButton(true, animated: true)
  220. }
  221. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  222. searchBar.resignFirstResponder()
  223. searchBar.text = ""
  224. searchBar.setShowsCancelButton(false, animated: true)
  225. reloadData()
  226. }
  227. func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
  228. searchDataSource.shouldReloadFor(searchString: searchText)
  229. reloadData()
  230. if searchText.isEmpty {
  231. self.searchBar.resignFirstResponder
  232. }
  233. }
  234. func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo {
  235. return IndicatorInfo(title:model.indicatorName)
  236. }
  237. // MARK: - UICollectionViewDataSource
  238. override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  239. return searchBar.isFirstResponder ? searchDataSource.searchData.count : model.anyfiles.count
  240. }
  241. override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  242. guard let mediaCell = collectionView.dequeueReusableCell(withReuseIdentifier:model.cellType.defaultReuseIdentifier, for: indexPath) as? BaseCollectionViewCell else {
  243. assertionFailure("you forgot to register the cell or the cell is not a subclass of BaseCollectionViewCell")
  244. return UICollectionViewCell()
  245. }
  246. let mediaObject = searchBar.isFirstResponder ? searchDataSource.objectAtIndex(index: indexPath.row) : model.anyfiles[indexPath.row]
  247. if let media = mediaObject as? VLCMLMedia {
  248. assert(media.mainFile() != nil, "The mainfile is nil")
  249. mediaCell.media = media.mainFile() != nil ? media : nil
  250. } else {
  251. mediaCell.media = mediaObject
  252. }
  253. return mediaCell
  254. }
  255. // MARK: - UICollectionViewDelegate
  256. override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  257. if let media = model.anyfiles[indexPath.row] as? VLCMLMedia {
  258. play(media: media, at: indexPath)
  259. createSpotlightItem(media: media)
  260. } else if let mediaCollection = model.anyfiles[indexPath.row] as? MediaCollectionModel {
  261. let collectionViewController = VLCCollectionCategoryViewController(services, mediaCollection: mediaCollection)
  262. navigationController?.pushViewController(collectionViewController, animated: true)
  263. }
  264. }
  265. func createSpotlightItem(media: VLCMLMedia) {
  266. if KeychainCoordinator.passcodeLockEnabled {
  267. return
  268. }
  269. userActivity = NSUserActivity(activityType: kVLCUserActivityPlaying)
  270. userActivity?.title = media.title
  271. userActivity?.contentAttributeSet = media.coreSpotlightAttributeSet()
  272. userActivity?.userInfo = ["playingmedia" : media.identifier()]
  273. userActivity?.isEligibleForSearch = true
  274. userActivity?.isEligibleForHandoff = true
  275. userActivity?.becomeCurrent()
  276. }
  277. }
  278. // MARK: - UICollectionViewDelegateFlowLayout
  279. extension VLCMediaCategoryViewController {
  280. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
  281. if cachedCellSize == .zero {
  282. //For iOS 10 when rotating we take the value from willTransition to size, for the first layout pass that value is 0 though,
  283. //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
  284. //we don't have yet the updated safeare layout frame. This is addressed by relayouting from viewSafeAreaInsetsDidChange
  285. var toWidth = toSize.width != 0 ? toSize.width : collectionView.frame.size.width
  286. if #available(iOS 11.0, *) {
  287. toWidth = collectionView.safeAreaLayoutGuide.layoutFrame.width
  288. }
  289. cachedCellSize = model.cellType.cellSizeForWidth(toWidth)
  290. }
  291. return cachedCellSize
  292. }
  293. override func viewSafeAreaInsetsDidChange() {
  294. cachedCellSize = .zero
  295. collectionView?.collectionViewLayout.invalidateLayout()
  296. }
  297. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
  298. return UIEdgeInsets(top: model.cellType.edgePadding, left: model.cellType.edgePadding, bottom: model.cellType.edgePadding, right: model.cellType.edgePadding)
  299. }
  300. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
  301. return model.cellType.edgePadding
  302. }
  303. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
  304. return model.cellType.interItemPadding
  305. }
  306. func handleSort() {
  307. var currentSortIndex: Int = 0
  308. for (index, criteria) in
  309. model.sortModel.sortingCriteria.enumerated()
  310. where criteria == model.sortModel.currentSort {
  311. currentSortIndex = index
  312. break
  313. }
  314. present(sortActionSheet, animated: false) {
  315. [sortActionSheet, currentSortIndex] in
  316. sortActionSheet.collectionView.selectItem(at:
  317. IndexPath(row: currentSortIndex, section: 0), animated: false,
  318. scrollPosition: .centeredVertically)
  319. }
  320. }
  321. }
  322. // MARK: VLCActionSheetDelegate
  323. extension VLCMediaCategoryViewController: ActionSheetDelegate {
  324. func headerViewTitle() -> String? {
  325. return NSLocalizedString("HEADER_TITLE_SORT", comment: "")
  326. }
  327. // This provide the item to send to the selection action
  328. func itemAtIndexPath(_ indexPath: IndexPath) -> Any? {
  329. let enabledSortCriteria = model.sortModel.sortingCriteria
  330. if indexPath.row < enabledSortCriteria.count {
  331. return enabledSortCriteria[indexPath.row]
  332. }
  333. assertionFailure("VLCMediaCategoryViewController: VLCActionSheetDelegate: IndexPath out of range")
  334. return nil
  335. }
  336. }
  337. // MARK: VLCActionSheetDataSource
  338. extension VLCMediaCategoryViewController: ActionSheetDataSource {
  339. func numberOfRows() -> Int {
  340. return model.sortModel.sortingCriteria.count
  341. }
  342. func actionSheet(collectionView: UICollectionView,
  343. cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  344. guard let cell = collectionView.dequeueReusableCell(
  345. withReuseIdentifier: ActionSheetCell.identifier,
  346. for: indexPath) as? ActionSheetCell else {
  347. assertionFailure("VLCMediaCategoryViewController: VLCActionSheetDataSource: Unable to dequeue reusable cell")
  348. return UICollectionViewCell()
  349. }
  350. let sortingCriterias = model.sortModel.sortingCriteria
  351. guard indexPath.row < sortingCriterias.count else {
  352. assertionFailure("VLCMediaCategoryViewController: VLCActionSheetDataSource: IndexPath out of range")
  353. return cell
  354. }
  355. cell.name.text = String(describing: sortingCriterias[indexPath.row])
  356. return cell
  357. }
  358. }
  359. extension VLCMediaCategoryViewController: VLCEditControllerDelegate {
  360. func editController(editController: VLCEditController, cellforItemAt indexPath: IndexPath) -> MediaEditCell? {
  361. return collectionView.cellForItem(at: indexPath) as? MediaEditCell
  362. }
  363. func editController(editController: VLCEditController,
  364. present viewController: UIViewController) {
  365. let newNavigationController = UINavigationController(rootViewController: viewController)
  366. navigationController?.present(newNavigationController, animated: true, completion: nil)
  367. }
  368. }
  369. private extension VLCMediaCategoryViewController {
  370. func setupCollectionView() {
  371. let cellNib = UINib(nibName: model.cellType.nibName, bundle: nil)
  372. collectionView?.register(cellNib, forCellWithReuseIdentifier: model.cellType.defaultReuseIdentifier)
  373. if let editCell = (model as? EditableMLModel)?.editCellType() {
  374. let editCellNib = UINib(nibName: editCell.nibName, bundle: nil)
  375. collectionView?.register(editCellNib, forCellWithReuseIdentifier: editCell.defaultReuseIdentifier)
  376. }
  377. collectionView?.backgroundColor = PresentationTheme.current.colors.background
  378. collectionView?.alwaysBounceVertical = true
  379. longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.handleLongGesture(gesture:)))
  380. collectionView?.addGestureRecognizer(longPressGesture)
  381. if #available(iOS 11.0, *) {
  382. collectionView?.contentInsetAdjustmentBehavior = .always
  383. // collectionView?.dragDelegate = dragAndDropManager
  384. // collectionView?.dropDelegate = dragAndDropManager
  385. }
  386. }
  387. @objc func handleLongGesture(gesture: UILongPressGestureRecognizer) {
  388. switch gesture.state {
  389. case .began:
  390. guard let selectedIndexPath = collectionView.indexPathForItem(at: gesture.location(in: collectionView)) else {
  391. break
  392. }
  393. collectionView.beginInteractiveMovementForItem(at: selectedIndexPath)
  394. case .changed:
  395. collectionView.updateInteractiveMovementTargetPosition(gesture.location(in: gesture.view!))
  396. case .ended:
  397. collectionView.endInteractiveMovement()
  398. default:
  399. collectionView.cancelInteractiveMovement()
  400. }
  401. }
  402. }
  403. // MARK: - Player
  404. extension VLCMediaCategoryViewController {
  405. func play(media: VLCMLMedia, at indexPath: IndexPath) {
  406. let playbackController = VLCPlaybackController.sharedInstance()
  407. let autoPlayNextItem = UserDefaults.standard.bool(forKey: kVLCAutomaticallyPlayNextItem)
  408. playbackController.fullscreenSessionRequested = media.type() != .audio
  409. if !autoPlayNextItem {
  410. playbackController.play(media)
  411. return
  412. }
  413. var tracks = [VLCMLMedia]()
  414. if let model = model as? MediaCollectionModel {
  415. tracks = model.files() ?? []
  416. } else {
  417. tracks = model.anyfiles as? [VLCMLMedia] ?? []
  418. }
  419. playbackController.playMedia(at: indexPath.row, fromCollection: tracks)
  420. }
  421. }
  422. // MARK: - MediaLibraryModelView
  423. extension VLCMediaCategoryViewController {
  424. func dataChanged() {
  425. reloadData()
  426. }
  427. }