MediaCategoryViewController.swift 24 KB

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