MediaCategoryViewController.swift 28 KB

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