MediaCategoryViewController.swift 31 KB

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