MediaCategoryViewController.swift 28 KB

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