MediaCategoryViewController.swift 25 KB

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