MediaCategoryViewController.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  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 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. _ = (MLMediaLibrary.sharedMediaLibrary() as! MLMediaLibrary).libraryDidAppear()
  162. }
  163. override func viewWillAppear(_ animated: Bool) {
  164. super.viewWillAppear(animated)
  165. let manager = services.rendererDiscovererManager
  166. if manager.discoverers.isEmpty {
  167. // Either didn't start or stopped before
  168. manager.start()
  169. }
  170. PlaybackService.sharedInstance().setPlayerHidden(isEditing)
  171. manager.presentingViewController = self
  172. cachedCellSize = .zero
  173. collectionView.collectionViewLayout.invalidateLayout()
  174. updateVideoGroups()
  175. reloadData()
  176. }
  177. @objc func themeDidChange() {
  178. collectionView?.backgroundColor = PresentationTheme.current.colors.background
  179. searchBar.backgroundColor = PresentationTheme.current.colors.background
  180. if #available(iOS 13.0, *) {
  181. navigationController?.navigationBar.standardAppearance = AppearanceManager.navigationbarAppearance()
  182. navigationController?.navigationBar.scrollEdgeAppearance = AppearanceManager.navigationbarAppearance()
  183. }
  184. setNeedsStatusBarAppearanceUpdate()
  185. }
  186. func isEmptyCollectionView() -> Bool {
  187. return collectionView?.numberOfItems(inSection: 0) == 0
  188. }
  189. func updateUIForContent() {
  190. if isSearching {
  191. return
  192. }
  193. let isEmpty = isEmptyCollectionView()
  194. if isEmpty {
  195. collectionView?.setContentOffset(.zero, animated: false)
  196. }
  197. searchBar.isHidden = isEmpty || isEditing
  198. collectionView?.backgroundView = isEmpty ? emptyView : nil
  199. }
  200. // MARK: Renderer
  201. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  202. super.viewWillTransition(to: size, with: coordinator)
  203. cachedCellSize = .zero
  204. toSize = size
  205. collectionView?.collectionViewLayout.invalidateLayout()
  206. }
  207. // MARK: - Edit
  208. override func scrollViewDidScroll(_ scrollView: UIScrollView) {
  209. // This ensures that the search bar is always visible like a sticky while searching
  210. if isSearching {
  211. searchBar.endEditing(true)
  212. delegate?.enableCategorySwitching(for: self, enable: true)
  213. // End search if scrolled and the textfield is empty
  214. if let searchBarText = searchBar.text, searchBarText.isEmpty {
  215. searchBarCancelButtonClicked(searchBar)
  216. }
  217. return
  218. }
  219. searchBarConstraint?.constant = -min(scrollView.contentOffset.y, searchBarSize) - searchBarSize
  220. if scrollView.contentOffset.y < -searchBarSize && scrollView.contentInset.top != searchBarSize {
  221. collectionView.contentInset = UIEdgeInsets(top: searchBarSize, left: 0, bottom: 0, right: 0)
  222. }
  223. if scrollView.contentOffset.y >= 0 && scrollView.contentInset.top != 0 {
  224. collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
  225. }
  226. }
  227. override func setEditing(_ editing: Bool, animated: Bool) {
  228. guard editing != isEditing else {
  229. // Guard in case where setEditing is called twice with the same state
  230. return
  231. }
  232. super.setEditing(editing, animated: animated)
  233. // might have an issue if the old datasource was search
  234. // Most of the edit logic is handled inside editController
  235. collectionView?.dataSource = editing ? editController : self
  236. collectionView?.delegate = editing ? editController : self
  237. editController.resetSelections(resetUI: true)
  238. displayEditToolbar()
  239. PlaybackService.sharedInstance().setPlayerHidden(editing)
  240. searchBarConstraint?.constant = -self.searchBarSize
  241. reloadData()
  242. }
  243. private func displayEditToolbar() {
  244. if isEditing {
  245. tabBarController?.editToolBar()?.delegate = editController
  246. tabBarController?.displayEditToolbar(with: model)
  247. } else {
  248. tabBarController?.hideEditToolbar()
  249. }
  250. }
  251. func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo {
  252. let uiTestAccessibilityIdentifier = model is TrackModel ? VLCAccessibilityIdentifier.songs : nil
  253. return IndicatorInfo(title: model.indicatorName, accessibilityIdentifier: uiTestAccessibilityIdentifier)
  254. }
  255. // MARK: - UICollectionViewDataSource
  256. override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  257. return isSearching ? searchDataSource.searchData.count : model.anyfiles.count
  258. }
  259. override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  260. guard let mediaCell = collectionView.dequeueReusableCell(withReuseIdentifier:model.cellType.defaultReuseIdentifier, for: indexPath) as? BaseCollectionViewCell else {
  261. assertionFailure("you forgot to register the cell or the cell is not a subclass of BaseCollectionViewCell")
  262. return UICollectionViewCell()
  263. }
  264. let mediaObject = isSearching ? searchDataSource.objectAtIndex(index: indexPath.row) : model.anyfiles[indexPath.row]
  265. if let media = mediaObject as? VLCMLMedia {
  266. // FIXME: This should be done in the VModel, workaround for the release.
  267. if media.type() == .video {
  268. services.medialibraryService.requestThumbnail(for: media)
  269. }
  270. assert(media.mainFile() != nil, "The mainfile is nil")
  271. mediaCell.media = media.mainFile() != nil ? media : nil
  272. } else {
  273. mediaCell.media = mediaObject
  274. }
  275. mediaCell.isAccessibilityElement = true
  276. return mediaCell
  277. }
  278. // MARK: - UICollectionViewDelegate
  279. override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  280. let modelContent = isSearching ? searchDataSource.objectAtIndex(index: indexPath.row) : model.anyfiles[indexPath.row]
  281. if let media = modelContent as? VLCMLMedia {
  282. play(media: media, at: indexPath)
  283. createSpotlightItem(media: media)
  284. } else if let mediaCollection = modelContent as? MediaCollectionModel {
  285. let collectionViewController = CollectionCategoryViewController(services,
  286. mediaCollection: mediaCollection)
  287. collectionViewController.navigationItem.rightBarButtonItems = collectionViewController.rightBarButtonItems()
  288. navigationController?.pushViewController(collectionViewController, animated: true)
  289. }
  290. }
  291. func objects(from modelContent: VLCMLObject) -> [VLCMLObject] {
  292. if let media = modelContent as? VLCMLMedia {
  293. return [media]
  294. } else if let mediaCollection = modelContent as? MediaCollectionModel {
  295. return mediaCollection.files() ?? [VLCMLObject]()
  296. }
  297. return [VLCMLObject]()
  298. }
  299. @available(iOS 13.0, *)
  300. override func collectionView(_ collectionView: UICollectionView,
  301. contextMenuConfigurationForItemAt indexPath: IndexPath,
  302. point: CGPoint) -> UIContextMenuConfiguration? {
  303. let cell = collectionView.cellForItem(at: indexPath)
  304. var thumbnail: UIImage? = nil
  305. if let cell = cell as? MovieCollectionViewCell {
  306. thumbnail = cell.thumbnailView.image
  307. } else if let cell = cell as? MediaCollectionViewCell {
  308. thumbnail = cell.thumbnailView.image
  309. }
  310. let configuration = UIContextMenuConfiguration(identifier: nil, previewProvider: {
  311. if let thumbnail = thumbnail {
  312. return CollectionViewCellPreviewController(thumbnail: thumbnail)
  313. } else {
  314. return nil
  315. }
  316. }) {
  317. [weak self] action in
  318. let modelContent = self?.isSearching ?? false ? self?.searchDataSource.objectAtIndex(index: indexPath.row) : self?.model.anyfiles[indexPath.row]
  319. let actionList = EditButtonsFactory.buttonList(for: self?.model.anyfiles.first)
  320. let actions = EditButtonsFactory.generate(buttons: actionList)
  321. return UIMenu(title: "", image: nil, identifier: nil, children: actions.map {
  322. switch $0.identifier {
  323. case .addToPlaylist:
  324. return $0.action({
  325. [weak self] _ in
  326. if let modelContent = modelContent {
  327. self?.editController.editActions.objects = self?.objects(from: modelContent) ?? []
  328. self?.editController.editActions.addToPlaylist()
  329. }
  330. })
  331. case .rename:
  332. return $0.action({
  333. [weak self] _ in
  334. if let modelContent = modelContent {
  335. self?.editController.editActions.objects = [modelContent]
  336. self?.editController.editActions.rename()
  337. }
  338. })
  339. case .delete:
  340. return $0.action({
  341. [weak self] _ in
  342. if let modelContent = modelContent {
  343. self?.editController.editActions.objects = [modelContent]
  344. self?.editController.editActions.delete()
  345. }
  346. })
  347. case .share:
  348. return $0.action({
  349. [weak self] _ in
  350. if let modelContent = modelContent {
  351. self?.editController.editActions.objects = self?.objects(from: modelContent) ?? []
  352. self?.editController.editActions.share()
  353. }
  354. })
  355. }
  356. })
  357. }
  358. return configuration
  359. }
  360. func createSpotlightItem(media: VLCMLMedia) {
  361. if KeychainCoordinator.passcodeLockEnabled {
  362. return
  363. }
  364. userActivity = NSUserActivity(activityType: kVLCUserActivityPlaying)
  365. userActivity?.title = media.title
  366. userActivity?.contentAttributeSet = media.coreSpotlightAttributeSet()
  367. userActivity?.userInfo = ["playingmedia" : media.identifier()]
  368. userActivity?.isEligibleForSearch = true
  369. userActivity?.isEligibleForHandoff = true
  370. userActivity?.becomeCurrent()
  371. }
  372. }
  373. // MARK: - NavigationItem
  374. extension MediaCategoryViewController {
  375. private func setupEditBarButton() -> UIBarButtonItem {
  376. let editButton = UIBarButtonItem(image: UIImage(named: "edit"),
  377. style: .plain, target: self,
  378. action: #selector(handleEditing))
  379. editButton.tintColor = PresentationTheme.current.colors.orangeUI
  380. editButton.accessibilityLabel = NSLocalizedString("BUTTON_EDIT", comment: "")
  381. editButton.accessibilityHint = NSLocalizedString("BUTTON_EDIT_HINT", comment: "")
  382. return editButton
  383. }
  384. private func setupSortButton() -> UIButton {
  385. // Fetch sortButton configuration from MediaVC
  386. let sortButton = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
  387. sortButton.setImage(UIImage(named: "sort"), for: .normal)
  388. sortButton.addTarget(self,
  389. action: #selector(handleSort),
  390. for: .touchUpInside)
  391. sortButton
  392. .addGestureRecognizer(UILongPressGestureRecognizer(target: self,
  393. action: #selector(handleSortLongPress(sender:))))
  394. sortButton.tintColor = PresentationTheme.current.colors.orangeUI
  395. sortButton.accessibilityLabel = NSLocalizedString("BUTTON_SORT", comment: "")
  396. sortButton.accessibilityHint = NSLocalizedString("BUTTON_SORT_HINT", comment: "")
  397. return sortButton
  398. }
  399. private func rightBarButtonItems() -> [UIBarButtonItem] {
  400. var rightBarButtonItems = [UIBarButtonItem]()
  401. rightBarButtonItems.append(editBarButton)
  402. // Sort is not available for Playlists
  403. if let model = model as? CollectionModel, !(model.mediaCollection is VLCMLPlaylist) {
  404. rightBarButtonItems.append(sortBarButton)
  405. }
  406. rightBarButtonItems.append(rendererBarButton)
  407. return rightBarButtonItems
  408. }
  409. @objc func handleSort() {
  410. var currentSortIndex: Int = 0
  411. for (index, criteria) in
  412. model.sortModel.sortingCriteria.enumerated()
  413. where criteria == model.sortModel.currentSort {
  414. currentSortIndex = index
  415. break
  416. }
  417. present(sortActionSheet, animated: false) {
  418. [sortActionSheet, currentSortIndex] in
  419. sortActionSheet.collectionView.selectItem(at:
  420. IndexPath(row: currentSortIndex, section: 0), animated: false,
  421. scrollPosition: .centeredVertically)
  422. }
  423. }
  424. @objc func handleSortLongPress(sender: UILongPressGestureRecognizer) {
  425. if sender.state == .began {
  426. if #available(iOS 10.0, *) {
  427. UIImpactFeedbackGenerator(style: .medium).impactOccurred()
  428. }
  429. handleSortShortcut()
  430. }
  431. }
  432. @objc func handleSortShortcut() {
  433. model.sort(by: model.sortModel.currentSort, desc: !model.sortModel.desc)
  434. }
  435. @objc func handleEditing() {
  436. isEditing = !isEditing
  437. navigationItem.rightBarButtonItems = isEditing ? [UIBarButtonItem(barButtonSystemItem: .done,
  438. target: self,
  439. action: #selector(handleEditing))]
  440. : rightBarButtonItems()
  441. navigationItem.setHidesBackButton(isEditing, animated: true)
  442. }
  443. }
  444. // MARK: - UISearchBarDelegate
  445. extension MediaCategoryViewController {
  446. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  447. reloadData()
  448. isSearching = true
  449. delegate?.enableCategorySwitching(for: self, enable: false)
  450. searchBar.setShowsCancelButton(true, animated: true)
  451. }
  452. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  453. searchBar.resignFirstResponder()
  454. // Empty the text field and reset the research
  455. searchBar.text = ""
  456. searchDataSource.shouldReloadFor(searchString: "")
  457. searchBar.setShowsCancelButton(false, animated: true)
  458. isSearching = false
  459. delegate?.enableCategorySwitching(for: self, enable: true)
  460. reloadData()
  461. }
  462. func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
  463. searchBar.resignFirstResponder()
  464. delegate?.enableCategorySwitching(for: self, enable: true)
  465. }
  466. func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
  467. searchDataSource.shouldReloadFor(searchString: searchText)
  468. reloadData()
  469. if searchText.isEmpty {
  470. self.searchBar.resignFirstResponder()
  471. }
  472. }
  473. }
  474. // MARK: - UICollectionViewDelegateFlowLayout
  475. extension MediaCategoryViewController: UICollectionViewDelegateFlowLayout {
  476. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
  477. if cachedCellSize == .zero {
  478. //For iOS 10 when rotating we take the value from willTransition to size, for the first layout pass that value is 0 though,
  479. //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
  480. //we don't have yet the updated safeare layout frame. This is addressed by relayouting from viewSafeAreaInsetsDidChange
  481. var toWidth = toSize.width != 0 ? toSize.width : collectionView.frame.size.width
  482. if #available(iOS 11.0, *) {
  483. toWidth = collectionView.safeAreaLayoutGuide.layoutFrame.width
  484. }
  485. cachedCellSize = model.cellType.cellSizeForWidth(toWidth)
  486. }
  487. return cachedCellSize
  488. }
  489. override func viewSafeAreaInsetsDidChange() {
  490. cachedCellSize = .zero
  491. collectionView?.collectionViewLayout.invalidateLayout()
  492. }
  493. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
  494. return UIEdgeInsets(top: model.cellType.edgePadding, left: model.cellType.edgePadding, bottom: model.cellType.edgePadding, right: model.cellType.edgePadding)
  495. }
  496. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
  497. return model.cellType.edgePadding
  498. }
  499. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
  500. return model.cellType.interItemPadding
  501. }
  502. }
  503. // MARK: VLCActionSheetDelegate
  504. extension MediaCategoryViewController: ActionSheetDelegate {
  505. func headerViewTitle() -> String? {
  506. return NSLocalizedString("HEADER_TITLE_SORT", comment: "")
  507. }
  508. // This provide the item to send to the selection action
  509. func itemAtIndexPath(_ indexPath: IndexPath) -> Any? {
  510. let enabledSortCriteria = model.sortModel.sortingCriteria
  511. if indexPath.row < enabledSortCriteria.count {
  512. return enabledSortCriteria[indexPath.row]
  513. }
  514. assertionFailure("VLCMediaCategoryViewController: VLCActionSheetDelegate: IndexPath out of range")
  515. return nil
  516. }
  517. }
  518. // MARK: VLCActionSheetDataSource
  519. extension MediaCategoryViewController: ActionSheetDataSource {
  520. func numberOfRows() -> Int {
  521. return model.sortModel.sortingCriteria.count
  522. }
  523. func actionSheet(collectionView: UICollectionView,
  524. cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  525. guard let cell = collectionView.dequeueReusableCell(
  526. withReuseIdentifier: ActionSheetCell.identifier,
  527. for: indexPath) as? ActionSheetCell else {
  528. assertionFailure("VLCMediaCategoryViewController: VLCActionSheetDataSource: Unable to dequeue reusable cell")
  529. return UICollectionViewCell()
  530. }
  531. let sortingCriterias = model.sortModel.sortingCriteria
  532. guard indexPath.row < sortingCriterias.count else {
  533. assertionFailure("VLCMediaCategoryViewController: VLCActionSheetDataSource: IndexPath out of range")
  534. return cell
  535. }
  536. cell.name.text = String(describing: sortingCriterias[indexPath.row])
  537. return cell
  538. }
  539. }
  540. // MARK: - ActionSheetSortSectionHeaderDelegate
  541. extension MediaCategoryViewController: ActionSheetSortSectionHeaderDelegate {
  542. func actionSheetSortSectionHeader(_ header: ActionSheetSortSectionHeader,
  543. onSwitchIsOnChange: Bool) {
  544. model.sort(by: model.sortModel.currentSort, desc: onSwitchIsOnChange)
  545. }
  546. }
  547. // MARK: - EditControllerDelegate
  548. extension MediaCategoryViewController: EditControllerDelegate {
  549. func editController(editController: EditController, cellforItemAt indexPath: IndexPath) -> BaseCollectionViewCell? {
  550. return collectionView.cellForItem(at: indexPath) as? BaseCollectionViewCell
  551. }
  552. func editController(editController: EditController,
  553. present viewController: UIViewController) {
  554. let newNavigationController = UINavigationController(rootViewController: viewController)
  555. navigationController?.present(newNavigationController, animated: true, completion: nil)
  556. }
  557. func editControllerDidFinishEditing(editController: EditController?) {
  558. // NavigationItems for Collections are create from the parent, there is no need to propagate the information.
  559. if self is CollectionCategoryViewController {
  560. handleEditing()
  561. } else {
  562. delegate?.setEditingStateChanged(for: self, editing: false)
  563. }
  564. }
  565. }
  566. private extension MediaCategoryViewController {
  567. func setupCollectionView() {
  568. let cellNib = UINib(nibName: model.cellType.nibName, bundle: nil)
  569. collectionView?.register(cellNib, forCellWithReuseIdentifier: model.cellType.defaultReuseIdentifier)
  570. collectionView.allowsMultipleSelection = true
  571. collectionView?.backgroundColor = PresentationTheme.current.colors.background
  572. collectionView?.alwaysBounceVertical = true
  573. longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.handleLongGesture(gesture:)))
  574. longPressGesture.minimumPressDuration = 0.2
  575. collectionView?.addGestureRecognizer(longPressGesture)
  576. if #available(iOS 11.0, *) {
  577. collectionView?.contentInsetAdjustmentBehavior = .always
  578. // collectionView?.dragDelegate = dragAndDropManager
  579. // collectionView?.dropDelegate = dragAndDropManager
  580. }
  581. }
  582. func constrainOnX(_ location: CGPoint, for width: CGFloat) -> CGPoint {
  583. var constrainedLocation = location
  584. if model.cellType.numberOfColumns(for: width) == 1 {
  585. constrainedLocation.x = width / 2
  586. }
  587. return constrainedLocation
  588. }
  589. @objc func handleLongGesture(gesture: UILongPressGestureRecognizer) {
  590. switch gesture.state {
  591. case .began:
  592. guard let selectedIndexPath = collectionView.indexPathForItem(at: gesture.location(in: collectionView)) else {
  593. break
  594. }
  595. collectionView.beginInteractiveMovementForItem(at: selectedIndexPath)
  596. case .changed:
  597. let location = constrainOnX(gesture.location(in: gesture.view!),
  598. for: collectionView.frame.width)
  599. collectionView.updateInteractiveMovementTargetPosition(location)
  600. case .ended:
  601. collectionView.endInteractiveMovement()
  602. default:
  603. collectionView.cancelInteractiveMovement()
  604. }
  605. }
  606. }
  607. // MARK: - Player
  608. extension MediaCategoryViewController {
  609. func play(media: VLCMLMedia, at indexPath: IndexPath) {
  610. let playbackController = PlaybackService.sharedInstance()
  611. let autoPlayNextItem = UserDefaults.standard.bool(forKey: kVLCAutomaticallyPlayNextItem)
  612. playbackController.fullscreenSessionRequested = media.type() != .audio
  613. if !autoPlayNextItem {
  614. playbackController.play(media)
  615. return
  616. }
  617. var tracks = [VLCMLMedia]()
  618. if let model = model as? MediaCollectionModel {
  619. tracks = model.files() ?? []
  620. } else {
  621. tracks = (isSearching ? searchDataSource.searchData : model.anyfiles) as? [VLCMLMedia] ?? []
  622. }
  623. playbackController.playMedia(at: indexPath.row, fromCollection: tracks)
  624. }
  625. }