MediaCategoryViewController.swift 24 KB

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