MediaCategoryViewController.swift 30 KB

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