PPAssetsActionController.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. // This file is based on third party code, see below for the original author
  2. // and original license.
  3. // Modifications are (c) by Threema GmbH and licensed under the AGPLv3.
  4. // Copyright (c) 2016 Pavel Pantus <pantusp@gmail.com>
  5. // See Resources/License.html for original license
  6. import UIKit
  7. import MobileCoreServices
  8. /**
  9. Assets Picker Delegate methods.
  10. */
  11. public protocol PPAssetsActionControllerDelegate: class {
  12. /**
  13. Called when a user dismisses a picker by tapping cancel or background.
  14. Implementation is optional.
  15. - Parameter picker: Picker Controller that was dismissed.
  16. */
  17. func assetsPickerDidCancel(_ picker: PPAssetsActionController)
  18. /**
  19. Called when a user takes an image.
  20. Assets Picker is not dismissed automatically when the delegate method is called.
  21. Implementation is optional.
  22. - Parameters:
  23. - picker: Current picker controller.
  24. - image: Picture that was taken with system Image Picker Controller.
  25. */
  26. func assetsPicker(_ picker: PPAssetsActionController, didSnapImage image: UIImage)
  27. /**
  28. Called when a user takes a video.
  29. Assets Picker is not dismissed automatically when the delegate method is called.
  30. Implementation is optional.
  31. - Parameters:
  32. - picker: Current picker controller.
  33. - videoURL: URL of video that was taken with system Image Picker Controller.
  34. */
  35. func assetsPicker(_ picker: PPAssetsActionController, didSnapVideo videoURL: URL)
  36. /**
  37. Called when a user selects previews and presses send button.
  38. Assets Picker is not dismissed automatically when the delegate method is called.
  39. Implementation is optional.
  40. - Parameters:
  41. - picker: Current picker controller.
  42. - assets: Assets that were selected with Preview Picker.
  43. */
  44. func assetsPicker(_ picker: PPAssetsActionController, didFinishPicking assets: [MediaProvider])
  45. /**
  46. Called when a user click the own option
  47. Assets Picker is not dismissed automatically when the delegate method is called.
  48. Implementation is optional.
  49. - Parameter picker: Picker Controller.
  50. */
  51. func assetsPickerDidSelectOwnOption(_ picker: PPAssetsActionController, didFinishPicking assets: [MediaProvider])
  52. /**
  53. Called when a user click the own snap button
  54. Assets Picker is not dismissed automatically when the delegate method is called.
  55. Implementation is optional.
  56. - Parameter picker: Picker Controller.
  57. */
  58. func assetsPickerDidSelectOwnSnapButton(_ picker: PPAssetsActionController, didFinishPicking assets: [MediaProvider])
  59. /**
  60. Called when a user click the live camera cell
  61. Assets Picker is not dismissed automatically when the delegate method is called.
  62. Implementation is optional.
  63. - Parameter picker: Picker Controller.
  64. */
  65. func assetsPickerDidSelectLiveCameraCell(_ picker: PPAssetsActionController)
  66. }
  67. /**
  68. Default implementation for delegate methods to make them optional.
  69. */
  70. extension PPAssetsActionControllerDelegate {
  71. func assetsPickerDidCancel(_ picker: PPAssetsActionController) {}
  72. func assetsPicker(_ picker: PPAssetsActionController, didSnapImage image: UIImage) {}
  73. func assetsPicker(_ picker: PPAssetsActionController, didSnapVideo videoURL: URL) {}
  74. func assetsPicker(_ picker: PPAssetsActionController, didFinishPicking assets: [MediaProvider]) {}
  75. func assetsPickerDidSelectOwnOption(_ picker: PPAssetsActionController, didFinishPicking assets: [MediaProvider]) {}
  76. func assetsPickerDidSelectOwnSnapButton(_ picker: PPAssetsActionController, didFinishPicking assets: [MediaProvider]) {}
  77. func assetsPickerDidSelectLiveCameraCell(_ picker: PPAssetsActionController) {}
  78. }
  79. /**
  80. Custom implementation of action sheet controller with assets preview.
  81. It is highly customizable (check out PPAssetsPickerConfig) and easy to use.
  82. */
  83. public class PPAssetsActionController: UIViewController {
  84. public weak var delegate: PPAssetsActionControllerDelegate?
  85. fileprivate var foldedPositionConstraint: NSLayoutConstraint!
  86. fileprivate var shownPositionConstraint: NSLayoutConstraint!
  87. fileprivate var optionsController: PPOptionsViewController!
  88. fileprivate var assetsController: PPAssetsCollectionController!
  89. fileprivate let assetsContainer = UIView()
  90. fileprivate var config = PPAssetsActionConfig()
  91. internal let assetManager = PPAssetManager()
  92. public init(with options: [PPOption], aConfig: PPAssetsActionConfig? = nil) {
  93. super.init(nibName: nil, bundle: nil)
  94. transitioningDelegate = self
  95. modalPresentationStyle = .custom
  96. if let aConfig = aConfig {
  97. config = aConfig
  98. }
  99. optionsController = PPOptionsViewController(aConfig: config)
  100. optionsController.options = options
  101. optionsController.delegate = self
  102. assetsController = PPAssetsCollectionController(aConfig: config)
  103. assetsController.delegate = self
  104. }
  105. required public init?(coder aDecoder: NSCoder) {
  106. super.init(coder: aDecoder)
  107. }
  108. override public func viewDidLoad() {
  109. super.viewDidLoad()
  110. view.accessibilityLabel = "assets-action-view"
  111. view.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0)
  112. let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleBackgroundTap(recognizer:)))
  113. tapRecognizer.delegate = self
  114. view.addGestureRecognizer(tapRecognizer)
  115. /***** BEGIN THREEMA MODIFICATION: tableBackground *********/
  116. if config.tableBackground != nil {
  117. assetsContainer.backgroundColor = config.tableBackground
  118. } else {
  119. assetsContainer.backgroundColor = UIColor.white
  120. }
  121. /***** END THREEMA MODIFICATION: tableBackground *********/
  122. assetsContainer.translatesAutoresizingMaskIntoConstraints = false
  123. assetsContainer.layer.cornerRadius = config.cornerRadius
  124. assetsContainer.isAccessibilityElement = false
  125. view.addSubview(assetsContainer)
  126. let bottomCornersFiller = UIView()
  127. bottomCornersFiller.backgroundColor = assetsContainer.backgroundColor
  128. bottomCornersFiller.translatesAutoresizingMaskIntoConstraints = false
  129. assetsContainer.addSubview(bottomCornersFiller)
  130. let assetsSeparator = UIView()
  131. assetsSeparator.translatesAutoresizingMaskIntoConstraints = false
  132. assetsSeparator.backgroundColor = optionsController.tableView!.separatorColor
  133. bottomCornersFiller.addSubview(assetsSeparator)
  134. assetsController.willMove(toParent: self)
  135. addChild(assetsController)
  136. assetsController.didMove(toParent: self)
  137. assetsContainer.addSubview(assetsController.collectionView!)
  138. optionsController.willMove(toParent: self)
  139. addChild(optionsController)
  140. optionsController.didMove(toParent: self)
  141. view.addSubview(optionsController.tableView)
  142. let views: [String : Any] = ["options": optionsController.tableView!,
  143. "assets": assetsController.collectionView!,
  144. "assetsContainer": assetsContainer,
  145. "filler": bottomCornersFiller,
  146. "assetsSeparator": assetsSeparator]
  147. let si: CGFloat
  148. si = 8.0
  149. let metrics = ["M": config.inset,
  150. "ACM": 6.0,
  151. "MLW": 1 / UIScreen.main.scale,
  152. "SI": si]
  153. if #available(iOS 11.0, *) {
  154. foldedPositionConstraint = NSLayoutConstraint(item: assetsContainer,
  155. attribute: .top,
  156. relatedBy: .equal,
  157. toItem: view.safeAreaLayoutGuide,
  158. attribute: .bottom,
  159. multiplier: 1.0,
  160. constant: 0.0)
  161. /***** BEGIN THREEMA MODIFICATION: bottom padding *********/
  162. var bottomConstant: CGFloat = 8
  163. if UIApplication.shared.keyWindow?.safeAreaInsets.bottom ?? 0 > 0 {
  164. bottomConstant = 0
  165. }
  166. /***** END THREEMA MODIFICATION: bottom padding *********/
  167. shownPositionConstraint = NSLayoutConstraint(item: optionsController.tableView,
  168. attribute: .bottom,
  169. relatedBy: .equal,
  170. toItem: view.safeAreaLayoutGuide,
  171. attribute: .bottom,
  172. multiplier: 1.0,
  173. /***** BEGIN THREEMA MODIFICATION: bottom padding *********/
  174. constant: -bottomConstant)
  175. /***** END THREEMA MODIFICATION: bottom padding *********/
  176. } else {
  177. foldedPositionConstraint = NSLayoutConstraint(item: assetsContainer,
  178. attribute: .top,
  179. relatedBy: .equal,
  180. toItem: view,
  181. attribute: .bottom,
  182. multiplier: 1.0,
  183. constant: 0.0)
  184. shownPositionConstraint = NSLayoutConstraint(item: optionsController.tableView,
  185. attribute: .bottom,
  186. relatedBy: .equal,
  187. toItem: view,
  188. attribute: .bottom,
  189. multiplier: 1.0,
  190. /***** BEGIN THREEMA MODIFICATION: bottom padding *********/
  191. // Devices with iOS 10 support never had any bottom safe area so we can use a constant
  192. constant: -8.0)
  193. /***** END THREEMA MODIFICATION: bottom padding *********/
  194. }
  195. view.addConstraint(NSLayoutConstraint(item: assetsContainer,
  196. attribute: .bottom,
  197. relatedBy: .equal,
  198. toItem: optionsController.tableView,
  199. attribute: .top,
  200. multiplier: 1.0,
  201. constant: 0.0))
  202. shownPositionConstraint.isActive = false
  203. view.addConstraint(foldedPositionConstraint)
  204. assetsContainer.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-ACM-[assets]-ACM-|",
  205. options: [],
  206. metrics: metrics,
  207. views: views))
  208. assetsContainer.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-ACM-[assets]-ACM-|",
  209. options: [],
  210. metrics: metrics,
  211. views: views))
  212. assetsContainer.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[filler]|",
  213. options: [],
  214. metrics: metrics,
  215. views: views))
  216. assetsContainer.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[filler(ACM)]|",
  217. options: [],
  218. metrics: ["M": config.inset,
  219. "ACM": 16.0,
  220. "MLW": 1 / UIScreen.main.scale,
  221. "SI": si],
  222. views: views))
  223. bottomCornersFiller.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-SI-[assetsSeparator]-SI-|",
  224. options: [],
  225. metrics: metrics,
  226. views: views))
  227. bottomCornersFiller.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[assetsSeparator(MLW)]|",
  228. options: [],
  229. metrics: metrics,
  230. views: views))
  231. view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-M-[assetsContainer]-M-|",
  232. options: [],
  233. metrics: metrics,
  234. views: views))
  235. view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-M-[options]-M-|",
  236. options: [],
  237. metrics: metrics,
  238. views: views))
  239. }
  240. override public func viewWillAppear(_ animated: Bool) {
  241. super.viewWillAppear(animated)
  242. let isIpad = UIDevice.current.userInterfaceIdiom == .pad
  243. if (config.isLandscape() && !isIpad) || UIAccessibility.isVoiceOverRunning || assetManager.authorizationStatus() != .authorized || !config.showGalleryPreview {
  244. assetsController.collectionView?.isHidden = true
  245. assetsContainer.isHidden = true
  246. } else {
  247. assetsController.collectionView?.isHidden = false
  248. assetsContainer.isHidden = false
  249. }
  250. }
  251. override public func viewDidAppear(_ animated: Bool) {
  252. super.viewDidAppear(animated)
  253. if(foldedPositionConstraint.isActive) {
  254. view.backgroundColor = config.backgroundColor
  255. foldedPositionConstraint.isActive = false
  256. shownPositionConstraint.isActive = true
  257. assetsContainer.layer.cornerRadius = config.cornerRadius
  258. view.layoutIfNeeded()
  259. }
  260. }
  261. override public func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  262. super.viewWillTransition(to: size, with: coordinator)
  263. let isIpad = UIDevice.current.userInterfaceIdiom == .pad
  264. if (size.height < self.view.frame.size.height && !isIpad) || UIAccessibility.isVoiceOverRunning || assetManager.authorizationStatus() != .authorized || !config.showGalleryPreview {
  265. assetsController.collectionView?.isHidden = true
  266. assetsContainer.isHidden = true
  267. } else {
  268. assetsController.collectionView?.isHidden = false
  269. assetsContainer.isHidden = false
  270. assetsController.updateCollectionView()
  271. }
  272. }
  273. }
  274. // MARK: PPOptionsViewControllerDelegate
  275. extension PPAssetsActionController: PPOptionsViewControllerDelegate {
  276. func optionsViewControllerShouldBeDismissed(_ controller: PPOptionsViewController) {
  277. dismiss(animated: true) {
  278. self.delegate?.assetsPickerDidCancel(self)
  279. }
  280. }
  281. func optionsViewControllerDidRequestTopOption(_ controller: PPOptionsViewController) {
  282. let selectedMedia = assetsController.selectedPHMedia()
  283. if config.useOwnSnapButton && config.ownSnapButtonText != nil {
  284. delegate?.assetsPickerDidSelectOwnSnapButton(self, didFinishPicking: selectedMedia)
  285. } else {
  286. if selectedMedia.count > 0 {
  287. delegate?.assetsPicker(self, didFinishPicking: selectedMedia)
  288. } else {
  289. openImagePicker()
  290. }
  291. }
  292. }
  293. func optionsViewControllerDidRequestOwnOption(_ controller: PPOptionsViewController) {
  294. let selectedMedia = assetsController.selectedPHMedia()
  295. delegate?.assetsPickerDidSelectOwnOption(self, didFinishPicking: selectedMedia)
  296. }
  297. func optionsViewControllerDidRequestPreviewReplacementOption(_ controller: PPOptionsViewController) {
  298. delegate?.assetsPickerDidSelectLiveCameraCell(self)
  299. }
  300. }
  301. // MARK: PPAssetsViewControllerDelegate
  302. extension PPAssetsActionController: PPAssetsViewControllerDelegate {
  303. func assetsViewController(_ controller: PPAssetsCollectionController, didChange itemsCount: Int, _ onlyPhotos: Bool, _ onlyVideos: Bool) {
  304. optionsController.set(sendItemsCount: itemsCount, onlyPhotos, onlyVideos)
  305. }
  306. func assetsViewControllerDidRequestCameraController(_ controller: PPAssetsCollectionController) {
  307. openImagePicker()
  308. }
  309. func assetsViewControllerDidRequestAuthorization(_ controller: PPAssetsCollectionController) {
  310. let isIpad = UIDevice.current.userInterfaceIdiom == .pad
  311. if (config.isLandscape() && !isIpad) || UIAccessibility.isVoiceOverRunning || assetManager.authorizationStatus() != .authorized || !config.showGalleryPreview {
  312. assetsController.collectionView?.isHidden = true
  313. assetsContainer.isHidden = true
  314. } else {
  315. assetsController.collectionView?.isHidden = false
  316. assetsContainer.isHidden = false
  317. assetsController.updateCollectionView()
  318. optionsController.refresh()
  319. }
  320. }
  321. }
  322. // MARK: UIGestureRecognizerDelegate
  323. /**
  324. Handle tap on a background view to dismiss the picker view controller.
  325. */
  326. extension PPAssetsActionController: UIGestureRecognizerDelegate {
  327. @objc fileprivate func handleBackgroundTap(recognizer: UITapGestureRecognizer) {
  328. if recognizer.state == .ended {
  329. dismiss(animated: true) {
  330. self.delegate?.assetsPickerDidCancel(self)
  331. }
  332. }
  333. }
  334. public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
  335. guard let view = touch.view else {
  336. return false
  337. }
  338. if view.isDescendant(of: assetsContainer) ||
  339. view.isDescendant(of: optionsController.view) {
  340. return false
  341. }
  342. return true
  343. }
  344. }
  345. // MARK: UIViewControllerTransitioningDelegate
  346. extension PPAssetsActionController: UIViewControllerTransitioningDelegate {
  347. public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
  348. return self
  349. }
  350. public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
  351. return self
  352. }
  353. }
  354. // MARK: UIViewControllerAnimatedTransitioning
  355. extension PPAssetsActionController: UIViewControllerAnimatedTransitioning {
  356. public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
  357. return config.animationDuration
  358. }
  359. public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
  360. let containerView = transitionContext.containerView
  361. let resultingColor: UIColor
  362. let animationOptions: UIView.AnimationOptions
  363. if shownPositionConstraint.isActive {
  364. shownPositionConstraint.isActive = false
  365. foldedPositionConstraint.isActive = true
  366. resultingColor = UIColor.clear
  367. animationOptions = .curveEaseOut
  368. } else {
  369. let views: [String: Any] = ["view": view]
  370. resultingColor = config.backgroundColor
  371. animationOptions = .curveEaseIn
  372. containerView.addSubview(view)
  373. containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[view]|",
  374. options: [],
  375. metrics: nil,
  376. views: views))
  377. containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[view]|",
  378. options: [],
  379. metrics: nil,
  380. views: views))
  381. containerView.setNeedsLayout()
  382. containerView.layoutIfNeeded()
  383. foldedPositionConstraint.isActive = false
  384. shownPositionConstraint.isActive = true
  385. }
  386. UIView.animate(withDuration: config.animationDuration,
  387. delay: 0.0,
  388. usingSpringWithDamping: 1.0,
  389. initialSpringVelocity: 1.0,
  390. options: animationOptions,
  391. animations:
  392. {
  393. containerView.layoutIfNeeded()
  394. self.view.backgroundColor = resultingColor
  395. }) { result in
  396. transitionContext.completeTransition(result)
  397. }
  398. }
  399. }
  400. // MARK: UIImagePickerControllerDelegate, UINavigationControllerDelegate
  401. extension PPAssetsActionController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
  402. func openImagePicker() {
  403. delegate?.assetsPickerDidSelectLiveCameraCell(self)
  404. }
  405. @nonobjc public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
  406. let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
  407. let videoURL = info[UIImagePickerController.InfoKey.mediaURL] as? URL
  408. dismiss(animated: true) {
  409. if let image = image {
  410. self.delegate?.assetsPicker(self, didSnapImage: image)
  411. } else if let videoURL = videoURL {
  412. self.delegate?.assetsPicker(self, didSnapVideo: videoURL)
  413. }
  414. }
  415. }
  416. }