MediaCategoryViewController.swift 22 KB

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