MediaCategoryViewController.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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 cancelSearchButton = UIButton(type: .custom)
  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: VLCEditController = {
  27. let editController = VLCEditController(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 actionSheet = ActionSheet()
  42. actionSheet.delegate = self
  43. actionSheet.dataSource = self
  44. actionSheet.modalPresentationStyle = .custom
  45. actionSheet.setAction { [weak self] item in
  46. guard let sortingCriteria = item as? VLCMLSortingCriteria else {
  47. return
  48. }
  49. self?.model.sort(by: sortingCriteria)
  50. self?.sortActionSheet.removeActionSheet()
  51. }
  52. return actionSheet
  53. }()
  54. lazy var emptyView: VLCEmptyLibraryView = {
  55. let name = String(describing: VLCEmptyLibraryView.self)
  56. let nib = Bundle.main.loadNibNamed(name, owner: self, options: nil)
  57. guard let emptyView = nib?.first as? VLCEmptyLibraryView else { fatalError("Can't find nib for \(name)") }
  58. return emptyView
  59. }()
  60. let editCollectionViewLayout: UICollectionViewFlowLayout = {
  61. let editCollectionViewLayout = UICollectionViewFlowLayout()
  62. editCollectionViewLayout.minimumLineSpacing = 1
  63. editCollectionViewLayout.minimumInteritemSpacing = 0
  64. return editCollectionViewLayout
  65. }()
  66. @available(*, unavailable)
  67. init() {
  68. fatalError()
  69. }
  70. init(services: Services, model: MediaLibraryBaseModel) {
  71. self.services = services
  72. self.model = model
  73. self.rendererButton = services.rendererDiscovererManager.setupRendererButton()
  74. self.searchDataSource = LibrarySearchDataSource(model: model)
  75. super.init(collectionViewLayout: UICollectionViewFlowLayout())
  76. setupSearchBar()
  77. if let collection = model as? CollectionModel {
  78. title = collection.mediaCollection.title()
  79. }
  80. NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .VLCThemeDidChangeNotification, object: nil)
  81. navigationItem.rightBarButtonItems = [editButtonItem, UIBarButtonItem(customView: rendererButton)]
  82. }
  83. func setupSearchBar() {
  84. cancelSearchButton.setTitle(NSLocalizedString("BUTTON_CANCEL", comment: ""), for: .normal)
  85. cancelSearchButton.addTarget(self, action: #selector(cancelSearch), for: .touchUpInside)
  86. cancelSearchButton.setTitleColor(.vlcOrangeTint, for: .normal)
  87. cancelSearchButton.translatesAutoresizingMaskIntoConstraints = false
  88. cancelSearchButton.isHidden = true
  89. let searchBarStackView = UIStackView(arrangedSubviews: [searchBar, cancelSearchButton])
  90. searchBarStackView.translatesAutoresizingMaskIntoConstraints = false
  91. view.addSubview(searchBarStackView)
  92. searchBarConstraint = searchBarStackView.topAnchor.constraint(equalTo: view.topAnchor, constant: -searchBarSize)
  93. NSLayoutConstraint.activate([
  94. searchBarConstraint!,
  95. searchBarStackView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10),
  96. searchBarStackView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10),
  97. searchBarStackView.heightAnchor.constraint(equalToConstant: searchBarSize)
  98. ])
  99. }
  100. override var preferredStatusBarStyle: UIStatusBarStyle {
  101. return PresentationTheme.current.colors.statusBarStyle
  102. }
  103. @objc func reloadData() {
  104. DispatchQueue.main.async {
  105. [weak self] in
  106. guard let self = self else {
  107. return
  108. }
  109. self.delegate?.needsToUpdateNavigationbarIfNeeded(self)
  110. self.collectionView?.reloadData()
  111. self.updateUIForContent()
  112. }
  113. }
  114. @available(*, unavailable)
  115. required init?(coder aDecoder: NSCoder) {
  116. fatalError("init(coder: ) has not been implemented")
  117. }
  118. override func viewDidLoad() {
  119. super.viewDidLoad()
  120. setupCollectionView()
  121. setupSearchController()
  122. setupEditToolbar()
  123. _ = (MLMediaLibrary.sharedMediaLibrary() as! MLMediaLibrary).libraryDidAppear()
  124. }
  125. override func viewWillAppear(_ animated: Bool) {
  126. super.viewWillAppear(animated)
  127. let manager = services.rendererDiscovererManager
  128. if manager.discoverers.isEmpty {
  129. // Either didn't start or stopped before
  130. manager.start()
  131. }
  132. manager.presentingViewController = self
  133. }
  134. @objc func themeDidChange() {
  135. collectionView?.backgroundColor = PresentationTheme.current.colors.background
  136. editController.view.backgroundColor = PresentationTheme.current.colors.background
  137. setNeedsStatusBarAppearanceUpdate()
  138. }
  139. func setupEditToolbar() {
  140. editController.view.translatesAutoresizingMaskIntoConstraints = false
  141. view.addSubview(editController.view)
  142. var guide: LayoutAnchorContainer = view
  143. if #available(iOS 11.0, *) {
  144. guide = view.safeAreaLayoutGuide
  145. }
  146. editToolbarConstraint = editController.view.bottomAnchor.constraint(equalTo: guide.bottomAnchor, constant: EditToolbar.height)
  147. NSLayoutConstraint.activate([
  148. editToolbarConstraint!,
  149. editController.view.leadingAnchor.constraint(equalTo: guide.leadingAnchor),
  150. editController.view.trailingAnchor.constraint(equalTo: guide.trailingAnchor),
  151. editController.view.heightAnchor.constraint(equalToConstant: 50)
  152. ])
  153. }
  154. override func viewDidAppear(_ animated: Bool) {
  155. super.viewDidAppear(animated)
  156. reloadData()
  157. }
  158. func isEmptyCollectionView() -> Bool {
  159. return collectionView?.numberOfItems(inSection: 0) == 0
  160. }
  161. func updateUIForContent() {
  162. let isEmpty = isEmptyCollectionView() && !searchBar.isFirstResponder
  163. if isEmpty {
  164. collectionView?.setContentOffset(.zero, animated: false)
  165. }
  166. searchBar.isHidden = isEmpty
  167. collectionView?.backgroundView = isEmpty ? emptyView : nil
  168. }
  169. // MARK: Renderer
  170. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  171. super.viewWillTransition(to: size, with: coordinator)
  172. cachedCellSize = .zero
  173. toSize = size
  174. collectionView?.collectionViewLayout.invalidateLayout()
  175. }
  176. // MARK: - Edit
  177. override func scrollViewDidScroll(_ scrollView: UIScrollView) {
  178. searchBarConstraint?.constant = -min(scrollView.contentOffset.y, searchBarSize) - searchBarSize
  179. if scrollView.contentOffset.y < -searchBarSize && scrollView.contentInset.top != searchBarSize {
  180. collectionView.contentInset = UIEdgeInsets(top: searchBarSize, left: 0, bottom: 0, right: 0)
  181. }
  182. if scrollView.contentOffset.y >= 0 && scrollView.contentInset.top != 0 {
  183. collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
  184. }
  185. }
  186. override func setEditing(_ editing: Bool, animated: Bool) {
  187. super.setEditing(editing, animated: animated)
  188. // might have an issue if the old datasource was search
  189. // Most of the edit logic is handled inside editController
  190. collectionView?.dataSource = editing ? editController : self
  191. collectionView?.delegate = editing ? editController : self
  192. editController.resetSelections()
  193. displayEditToolbar()
  194. let layoutToBe = editing ? editCollectionViewLayout : UICollectionViewFlowLayout()
  195. collectionView?.setCollectionViewLayout(layoutToBe, animated: false, completion: {
  196. [weak self] finished in
  197. guard finished else {
  198. assertionFailure("VLCMediaSubcategoryViewController: Edit layout transition failed.")
  199. return
  200. }
  201. self?.reloadData()
  202. })
  203. }
  204. private func displayEditToolbar() {
  205. UIView.animate(withDuration: 0.3) { [weak self] in
  206. self?.editToolbarConstraint?.constant = self?.isEditing == true ? 0 : EditToolbar.height
  207. self?.view.layoutIfNeeded()
  208. self?.collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: self?.isEditing == true ? EditToolbar.height : 0, right: 0)
  209. }
  210. }
  211. // MARK: - Search
  212. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  213. reloadData()
  214. UIView.animate(withDuration: 0.3) { [weak self] in
  215. self?.cancelSearchButton.alpha = 1
  216. self?.cancelSearchButton.isHidden = false
  217. }
  218. }
  219. @objc func cancelSearch() {
  220. searchBar.resignFirstResponder()
  221. UIView.animate(withDuration: 0.3) { [weak self] in
  222. self?.cancelSearchButton.alpha = 0
  223. self?.cancelSearchButton.isHidden = true
  224. }
  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. func setupSearchController() {
  388. searchBar.delegate = self
  389. searchBar.searchBarStyle = .minimal
  390. if #available(iOS 11.0, *) {
  391. navigationItem.largeTitleDisplayMode = .never
  392. }
  393. if let textfield = searchBar.value(forKey: "searchField") as? UITextField {
  394. if let backgroundview = textfield.subviews.first {
  395. backgroundview.backgroundColor = UIColor.white
  396. backgroundview.layer.cornerRadius = 10
  397. backgroundview.clipsToBounds = true
  398. }
  399. }
  400. }
  401. @objc func handleLongGesture(gesture: UILongPressGestureRecognizer) {
  402. switch gesture.state {
  403. case .began:
  404. guard let selectedIndexPath = collectionView.indexPathForItem(at: gesture.location(in: collectionView)) else {
  405. break
  406. }
  407. collectionView.beginInteractiveMovementForItem(at: selectedIndexPath)
  408. case .changed:
  409. collectionView.updateInteractiveMovementTargetPosition(gesture.location(in: gesture.view!))
  410. case .ended:
  411. collectionView.endInteractiveMovement()
  412. default:
  413. collectionView.cancelInteractiveMovement()
  414. }
  415. }
  416. }
  417. // MARK: - Player
  418. extension VLCMediaCategoryViewController {
  419. func play(media: VLCMLMedia, at indexPath: IndexPath) {
  420. let playbackController = VLCPlaybackController.sharedInstance()
  421. let autoPlayNextItem = UserDefaults.standard.bool(forKey: kVLCAutomaticallyPlayNextItem)
  422. playbackController.fullscreenSessionRequested = media.type() != .audio
  423. if !autoPlayNextItem {
  424. playbackController.play(media)
  425. return
  426. }
  427. var tracks = [VLCMLMedia]()
  428. if let model = model as? MediaCollectionModel {
  429. tracks = model.files() ?? []
  430. } else {
  431. tracks = model.anyfiles as? [VLCMLMedia] ?? []
  432. }
  433. playbackController.playMedia(at: indexPath.row, fromCollection: tracks)
  434. }
  435. }
  436. // MARK: - MediaLibraryModelView
  437. extension VLCMediaCategoryViewController {
  438. func dataChanged() {
  439. reloadData()
  440. }
  441. }