MediaCategoryViewController.swift 30 KB

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