MediaCategoryViewController.swift 27 KB

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