MediaCategoryViewController.swift 27 KB

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