VLCEditController.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. /*****************************************************************************
  2. * VLCEditController.swift
  3. *
  4. * Copyright © 2018 VLC authors and VideoLAN
  5. * Copyright © 2018 Videolabs
  6. *
  7. * Authors: Soomin Lee <bubu@mikan.io>
  8. *
  9. * Refer to the COPYING file of the official project for license.
  10. *****************************************************************************/
  11. protocol VLCEditControllerDelegate: class {
  12. func editController(editController: VLCEditController, cellforItemAt indexPath: IndexPath) -> MediaEditCell?
  13. func editController(editController: VLCEditController, present viewController: UIViewController)
  14. }
  15. class VLCEditController: UIViewController {
  16. private var selectedCellIndexPaths = Set<IndexPath>()
  17. private let model: MediaLibraryBaseModel
  18. private let mediaLibraryService: MediaLibraryService
  19. private lazy var addToPlaylistViewController: AddToPlaylistViewController = {
  20. var addToPlaylistViewController = AddToPlaylistViewController(playlists: mediaLibraryService.playlists())
  21. addToPlaylistViewController.delegate = self
  22. return addToPlaylistViewController
  23. }()
  24. weak var delegate: VLCEditControllerDelegate?
  25. override func loadView() {
  26. let editToolbar = EditToolbar(category: model)
  27. editToolbar.delegate = self
  28. self.view = editToolbar
  29. }
  30. init(mediaLibraryService: MediaLibraryService, model: MediaLibraryBaseModel) {
  31. self.mediaLibraryService = mediaLibraryService
  32. self.model = model
  33. super.init(nibName: nil, bundle: nil)
  34. }
  35. required init?(coder aDecoder: NSCoder) {
  36. fatalError("init(coder:) has not been implemented")
  37. }
  38. func resetSelections() {
  39. selectedCellIndexPaths.removeAll(keepingCapacity: false)
  40. }
  41. }
  42. // MARK: - Helpers
  43. private extension VLCEditController {
  44. private struct TextFieldAlertInfo {
  45. var alertTitle: String
  46. var alertDescription: String
  47. var placeHolder: String
  48. var confirmActionTitle: String
  49. init(alertTitle: String = "",
  50. alertDescription: String = "",
  51. placeHolder: String = "",
  52. confirmActionTitle: String = NSLocalizedString("BUTTON_DONE", comment: "")) {
  53. self.alertTitle = alertTitle
  54. self.alertDescription = alertDescription
  55. self.placeHolder = placeHolder
  56. self.confirmActionTitle = confirmActionTitle
  57. }
  58. }
  59. private func presentTextFieldAlert(with info: TextFieldAlertInfo,
  60. completionHandler: @escaping (String) -> Void) {
  61. let alertController = UIAlertController(title: info.alertTitle,
  62. message: info.alertDescription,
  63. preferredStyle: .alert)
  64. alertController.addTextField(configurationHandler: {
  65. textField in
  66. textField.placeholder = info.placeHolder
  67. })
  68. let cancelButton = UIAlertAction(title: NSLocalizedString("BUTTON_CANCEL", comment: ""),
  69. style: .default)
  70. let confirmAction = UIAlertAction(title: info.confirmActionTitle, style: .default) {
  71. [weak alertController] _ in
  72. guard let alertController = alertController,
  73. let textField = alertController.textFields?.first else { return }
  74. completionHandler(textField.text ?? "")
  75. }
  76. alertController.addAction(cancelButton)
  77. alertController.addAction(confirmAction)
  78. present(alertController, animated: true, completion: nil)
  79. }
  80. private func createPlaylist(_ name: String) {
  81. guard let playlist = mediaLibraryService.createPlaylist(with: name) else {
  82. assertionFailure("MediaModel: createPlaylist: Failed to create a playlist.")
  83. DispatchQueue.main.async {
  84. VLCAlertViewController.alertViewManager(title: NSLocalizedString("ERROR_PLAYLIST_CREATION",
  85. comment: ""),
  86. viewController: self)
  87. }
  88. return
  89. }
  90. // In the case of Video, Tracks
  91. if let files = model.anyfiles as? [VLCMLMedia] {
  92. for index in selectedCellIndexPaths where index.row < files.count {
  93. playlist.appendMedia(withIdentifier: files[index.row].identifier())
  94. }
  95. } else if let mediaCollectionArray = model.anyfiles as? [MediaCollectionModel] {
  96. for index in selectedCellIndexPaths where index.row < mediaCollectionArray.count {
  97. guard let tracks = mediaCollectionArray[index.row].files() else {
  98. assertionFailure("EditController: Fail to retrieve tracks.")
  99. DispatchQueue.main.async {
  100. VLCAlertViewController.alertViewManager(title: NSLocalizedString("ERROR_PLAYLIST_TRACKS",
  101. comment: ""),
  102. viewController: self)
  103. }
  104. return
  105. }
  106. tracks.forEach() {
  107. playlist.appendMedia(withIdentifier: $0.identifier())
  108. }
  109. }
  110. }
  111. selectedCellIndexPaths.removeAll()
  112. }
  113. }
  114. // MARK: - VLCEditToolbarDelegate
  115. extension VLCEditController: EditToolbarDelegate {
  116. func addToNewPlaylist() {
  117. let alertInfo = TextFieldAlertInfo(alertTitle: NSLocalizedString("PLAYLISTS", comment: ""),
  118. placeHolder: NSLocalizedString("PLAYLIST_PLACEHOLDER",
  119. comment: ""))
  120. presentTextFieldAlert(with: alertInfo) {
  121. [unowned self] text -> Void in
  122. guard text != "" else {
  123. DispatchQueue.main.async {
  124. VLCAlertViewController.alertViewManager(title: NSLocalizedString("ERROR_EMPTY_NAME",
  125. comment: ""),
  126. viewController: self)
  127. }
  128. return
  129. }
  130. self.createPlaylist(text)
  131. }
  132. }
  133. func editToolbarDidAddToPlaylist(_ editToolbar: EditToolbar) {
  134. if !mediaLibraryService.playlists().isEmpty && !selectedCellIndexPaths.isEmpty {
  135. addToPlaylistViewController.playlists = mediaLibraryService.playlists()
  136. delegate?.editController(editController: self,
  137. present: addToPlaylistViewController)
  138. } else {
  139. addToNewPlaylist()
  140. }
  141. }
  142. func editToolbarDidDelete(_ editToolbar: EditToolbar) {
  143. var objectsToDelete = [VLCMLObject]()
  144. for indexPath in selectedCellIndexPaths {
  145. objectsToDelete.append(model.anyfiles[indexPath.row])
  146. }
  147. let cancelButton = VLCAlertButton(title: NSLocalizedString("BUTTON_CANCEL", comment: ""))
  148. let deleteButton = VLCAlertButton(title: NSLocalizedString("BUTTON_DELETE", comment: ""),
  149. style: .destructive,
  150. action: {
  151. [weak self] action in
  152. self?.model.delete(objectsToDelete)
  153. self?.selectedCellIndexPaths.removeAll()
  154. })
  155. VLCAlertViewController.alertViewManager(title: NSLocalizedString("DELETE_TITLE", comment: ""),
  156. errorMessage: NSLocalizedString("DELETE_MESSAGE", comment: ""),
  157. viewController: (UIApplication.shared.keyWindow?.rootViewController)!,
  158. buttonsAction: [cancelButton,
  159. deleteButton])
  160. }
  161. func editToolbarDidShare(_ editToolbar: EditToolbar, presentFrom button: UIButton) {
  162. UIApplication.shared.beginIgnoringInteractionEvents()
  163. let rootViewController = UIApplication.shared.keyWindow?.rootViewController
  164. guard let controller = VLCActivityViewControllerVendor.activityViewController(forFiles: fileURLsFromSelection(), presenting: button, presenting: rootViewController) else {
  165. UIApplication.shared.endIgnoringInteractionEvents()
  166. return
  167. }
  168. controller.popoverPresentationController?.sourceView = editToolbar
  169. rootViewController?.present(controller, animated: true) {
  170. UIApplication.shared.endIgnoringInteractionEvents()
  171. }
  172. }
  173. func fileURLsFromSelection() -> [URL] {
  174. var fileURLS = [URL]()
  175. for indexPath in selectedCellIndexPaths {
  176. let file = model.anyfiles[indexPath.row]
  177. if let collection = file as? MediaCollectionModel,
  178. let files = collection.files() {
  179. files.forEach {
  180. if let mainFile = $0.mainFile() {
  181. fileURLS.append(mainFile.mrl)
  182. }
  183. }
  184. } else if let media = file as? VLCMLMedia, let mainFile = media.mainFile() {
  185. fileURLS.append(mainFile.mrl)
  186. } else {
  187. assertionFailure("we're trying to share something that doesn't have an mrl")
  188. return fileURLS
  189. }
  190. }
  191. return fileURLS
  192. }
  193. func editToolbarDidRename(_ editToolbar: EditToolbar) {
  194. // FIXME: Multiple renaming of files(multiple alert can get unfriendly if too many files)
  195. for indexPath in selectedCellIndexPaths {
  196. if let media = model.anyfiles[indexPath.row] as? VLCMLMedia {
  197. // Not using VLCAlertViewController to have more customization in text fields
  198. let alertInfo = TextFieldAlertInfo(alertTitle: String(format: NSLocalizedString("RENAME_MEDIA_TO", comment: ""), media.title),
  199. placeHolder: NSLocalizedString("RENAME_PLACEHOLDER", comment: ""),
  200. confirmActionTitle: NSLocalizedString("BUTTON_RENAME", comment: ""))
  201. presentTextFieldAlert(with: alertInfo, completionHandler: {
  202. [weak self] text -> Void in
  203. guard text != "" else {
  204. VLCAlertViewController.alertViewManager(title: NSLocalizedString("ERROR_RENAME_FAILED", comment: ""),
  205. errorMessage: NSLocalizedString("ERROR_EMPTY_NAME", comment: ""),
  206. viewController: (UIApplication.shared.keyWindow?.rootViewController)!)
  207. return
  208. }
  209. media.updateTitle(text)
  210. if let strongself = self {
  211. strongself.delegate?.editController(editController: strongself, cellforItemAt: indexPath)?.isChecked = false
  212. }
  213. })
  214. }
  215. }
  216. }
  217. }
  218. // MARK: - UICollectionViewDataSource
  219. extension VLCEditController: UICollectionViewDataSource {
  220. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  221. return model.anyfiles.count
  222. }
  223. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  224. guard let editCell = (model as? EditableMLModel)?.editCellType() else {
  225. assertionFailure("The category either doesn't implement EditableMLModel or doesn't have a editcellType defined")
  226. return UICollectionViewCell()
  227. }
  228. if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: editCell.defaultReuseIdentifier,
  229. for: indexPath) as? MediaEditCell {
  230. cell.media = model.anyfiles[indexPath.row]
  231. cell.isChecked = selectedCellIndexPaths.contains(indexPath)
  232. return cell
  233. } else {
  234. assertionFailure("We couldn't dequeue a reusable cell, the cell might not be registered or is not a MediaEditCell")
  235. return UICollectionViewCell()
  236. }
  237. }
  238. func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
  239. guard let collectionModel = model as? CollectionModel, let playlist = collectionModel.mediaCollection as? VLCMLPlaylist else {
  240. assertionFailure("can Move should've been false")
  241. return
  242. }
  243. playlist.moveMedia(fromPosition: UInt32(sourceIndexPath.row), toDestination: UInt32(destinationIndexPath.row))
  244. }
  245. func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
  246. if let collectionModel = model as? CollectionModel, collectionModel.mediaCollection is VLCMLPlaylist {
  247. return true
  248. }
  249. return false
  250. }
  251. }
  252. // MARK: - UICollectionViewDelegate
  253. extension VLCEditController: UICollectionViewDelegate {
  254. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  255. if let cell = collectionView.cellForItem(at: indexPath) as? MediaEditCell {
  256. cell.isChecked = !cell.isChecked
  257. if cell.isChecked {
  258. // cell selected, saving indexPath
  259. selectedCellIndexPaths.insert(indexPath)
  260. } else {
  261. selectedCellIndexPaths.remove(indexPath)
  262. }
  263. }
  264. }
  265. }
  266. // MARK: - UICollectionViewDelegateFlowLayout
  267. extension VLCEditController: UICollectionViewDelegateFlowLayout {
  268. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
  269. let contentInset = collectionView.contentInset
  270. // FIXME: 5 should be cell padding, but not usable maybe static?
  271. let insetToRemove = contentInset.left + contentInset.right + (5 * 2)
  272. var width = collectionView.frame.width
  273. if #available(iOS 11.0, *) {
  274. width = collectionView.safeAreaLayoutGuide.layoutFrame.width
  275. }
  276. return CGSize(width: width - insetToRemove, height: MediaEditCell.height)
  277. }
  278. }
  279. extension VLCEditController: AddToPlaylistViewControllerDelegate {
  280. func addToPlaylistViewController(_ addToPlaylistViewController: AddToPlaylistViewController,
  281. didSelectPlaylist playlist: VLCMLPlaylist) {
  282. let files = model.anyfiles
  283. for index in selectedCellIndexPaths where index.row < files.count {
  284. if !playlist.appendMedia(withIdentifier: files[index.row].identifier()) {
  285. assertionFailure("VLCEditController: AddToPlaylistViewControllerDelegate: Failed to add item.")
  286. }
  287. }
  288. addToPlaylistViewController.dismiss(animated: true, completion: nil)
  289. }
  290. func addToPlaylistViewController(_ addToPlaylistViewController: AddToPlaylistViewController,
  291. newPlaylistWithName name: String) {
  292. createPlaylist(name)
  293. addToPlaylistViewController.dismiss(animated: true, completion: nil)
  294. }
  295. }