MediaCategoryViewController.swift 30 KB

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