SendMediaNavigationController.swift 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  1. //
  2. // Copyright (c) 2019 Open Whisper Systems. All rights reserved.
  3. //
  4. import Foundation
  5. import Photos
  6. import PromiseKit
  7. @objc
  8. protocol SendMediaNavDelegate: AnyObject {
  9. func sendMediaNavDidCancel(_ sendMediaNavigationController: SendMediaNavigationController)
  10. func sendMediaNav(_ sendMediaNavigationController: SendMediaNavigationController, didApproveAttachments attachments: [SignalAttachment], messageText: String?)
  11. func sendMediaNavInitialMessageText(_ sendMediaNavigationController: SendMediaNavigationController) -> String?
  12. func sendMediaNav(_ sendMediaNavigationController: SendMediaNavigationController, didChangeMessageText newMessageText: String?)
  13. }
  14. @objc
  15. class SendMediaNavigationController: OWSNavigationController {
  16. // This is a sensitive constant, if you change it make sure to check
  17. // on iPhone5, 6, 6+, X, layouts.
  18. static let bottomButtonsCenterOffset: CGFloat = -34
  19. var attachmentCount: Int {
  20. return attachmentDraftCollection.count - attachmentDraftCollection.pickerAttachments.count + mediaLibrarySelections.count
  21. }
  22. // MARK: - Overrides
  23. override var prefersStatusBarHidden: Bool {
  24. guard !OWSWindowManager.shared().hasCall() else {
  25. return false
  26. }
  27. return true
  28. }
  29. override func viewDidLoad() {
  30. super.viewDidLoad()
  31. self.delegate = self
  32. let bottomButtonsCenterOffset = SendMediaNavigationController.bottomButtonsCenterOffset
  33. view.addSubview(batchModeButton)
  34. batchModeButton.setCompressionResistanceHigh()
  35. batchModeButton.centerYAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor, constant: bottomButtonsCenterOffset).isActive = true
  36. batchModeButton.autoPinEdge(toSuperviewMargin: .trailing)
  37. view.addSubview(doneButton)
  38. doneButton.setCompressionResistanceHigh()
  39. doneButton.centerYAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor, constant: bottomButtonsCenterOffset).isActive = true
  40. doneButton.autoPinEdge(toSuperviewMargin: .trailing)
  41. view.addSubview(cameraModeButton)
  42. cameraModeButton.setCompressionResistanceHigh()
  43. cameraModeButton.centerYAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor, constant: bottomButtonsCenterOffset).isActive = true
  44. cameraModeButton.autoPinEdge(toSuperviewMargin: .leading)
  45. view.addSubview(mediaLibraryModeButton)
  46. mediaLibraryModeButton.setCompressionResistanceHigh()
  47. mediaLibraryModeButton.centerYAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor, constant: bottomButtonsCenterOffset).isActive = true
  48. mediaLibraryModeButton.autoPinEdge(toSuperviewMargin: .leading)
  49. }
  50. // MARK: -
  51. @objc
  52. public weak var sendMediaNavDelegate: SendMediaNavDelegate?
  53. @objc
  54. public class func showingCameraFirst() -> SendMediaNavigationController {
  55. let navController = SendMediaNavigationController()
  56. navController.setViewControllers([navController.captureViewController], animated: false)
  57. return navController
  58. }
  59. @objc
  60. public class func showingMediaLibraryFirst() -> SendMediaNavigationController {
  61. let navController = SendMediaNavigationController()
  62. navController.setViewControllers([navController.mediaLibraryViewController], animated: false)
  63. return navController
  64. }
  65. var isInBatchSelectMode: Bool {
  66. get {
  67. return self.batchModeButton.isSelected
  68. }
  69. set {
  70. let didChange = newValue != isInBatchSelectMode
  71. self.batchModeButton.isSelected = newValue
  72. if didChange {
  73. mediaLibraryViewController.batchSelectModeDidChange()
  74. guard let topViewController = viewControllers.last else {
  75. return
  76. }
  77. updateButtons(topViewController: topViewController)
  78. }
  79. }
  80. }
  81. func updateButtons(topViewController: UIViewController) {
  82. switch topViewController {
  83. case is AttachmentApprovalViewController:
  84. batchModeButton.isHidden = true
  85. doneButton.isHidden = true
  86. cameraModeButton.isHidden = true
  87. mediaLibraryModeButton.isHidden = true
  88. case is ImagePickerGridController:
  89. let showDoneButton = isInBatchSelectMode && attachmentCount > 0
  90. batchModeButton.isHidden = showDoneButton
  91. doneButton.isHidden = !showDoneButton
  92. cameraModeButton.isHidden = false
  93. mediaLibraryModeButton.isHidden = true
  94. case is PhotoCaptureViewController:
  95. let showDoneButton = isInBatchSelectMode && attachmentCount > 0
  96. batchModeButton.isHidden = showDoneButton
  97. doneButton.isHidden = !showDoneButton
  98. cameraModeButton.isHidden = true
  99. mediaLibraryModeButton.isHidden = false
  100. default:
  101. owsFailDebug("unexpected topViewController: \(topViewController)")
  102. }
  103. doneButton.updateCount()
  104. }
  105. func fadeTo(viewControllers: [UIViewController]) {
  106. let transition: CATransition = CATransition()
  107. transition.duration = 0.1
  108. transition.type = CATransitionType.fade
  109. view.layer.add(transition, forKey: nil)
  110. setViewControllers(viewControllers, animated: false)
  111. }
  112. // MARK: - Events
  113. private func didTapBatchModeButton() {
  114. isInBatchSelectMode = !isInBatchSelectMode
  115. assert(isInBatchSelectMode || attachmentCount <= 1)
  116. }
  117. private func didTapCameraModeButton() {
  118. fadeTo(viewControllers: [captureViewController])
  119. }
  120. private func didTapMediaLibraryModeButton() {
  121. fadeTo(viewControllers: [mediaLibraryViewController])
  122. }
  123. // MARK: Views
  124. public static let bottomButtonWidth: CGFloat = 44
  125. private lazy var doneButton: DoneButton = {
  126. let button = DoneButton()
  127. button.delegate = self
  128. button.setShadow()
  129. return button
  130. }()
  131. private lazy var batchModeButton: SendMediaBottomButton = {
  132. return SendMediaBottomButton(imageName: "media_send_batch_mode_disabled",
  133. tintColor: .ows_white,
  134. diameter: type(of: self).bottomButtonWidth,
  135. block: { [weak self] in self?.didTapBatchModeButton() })
  136. }()
  137. private lazy var cameraModeButton: UIView = {
  138. return SendMediaBottomButton(imageName: "settings-avatar-camera-2",
  139. tintColor: .ows_white,
  140. diameter: type(of: self).bottomButtonWidth,
  141. block: { [weak self] in self?.didTapCameraModeButton() })
  142. }()
  143. private lazy var mediaLibraryModeButton: UIView = {
  144. return SendMediaBottomButton(imageName: "actionsheet_camera_roll_black",
  145. tintColor: .ows_white,
  146. diameter: type(of: self).bottomButtonWidth,
  147. block: { [weak self] in self?.didTapMediaLibraryModeButton() })
  148. }()
  149. // MARK: State
  150. private var attachmentDraftCollection: AttachmentDraftCollection = .empty
  151. private var attachments: [SignalAttachment] {
  152. return attachmentDraftCollection.attachmentDrafts.map { $0.attachment }
  153. }
  154. private let mediaLibrarySelections: OrderedDictionary<PHAsset, MediaLibrarySelection> = OrderedDictionary()
  155. // MARK: Child VC's
  156. private lazy var captureViewController: PhotoCaptureViewController = {
  157. let vc = PhotoCaptureViewController()
  158. vc.delegate = self
  159. return vc
  160. }()
  161. private lazy var mediaLibraryViewController: ImagePickerGridController = {
  162. let vc = ImagePickerGridController()
  163. vc.delegate = self
  164. return vc
  165. }()
  166. private func pushApprovalViewController() {
  167. guard let sendMediaNavDelegate = self.sendMediaNavDelegate else {
  168. owsFailDebug("sendMediaNavDelegate was unexpectedly nil")
  169. return
  170. }
  171. let approvalViewController = AttachmentApprovalViewController(mode: .sharedNavigation, attachments: self.attachments)
  172. approvalViewController.approvalDelegate = self
  173. approvalViewController.messageText = sendMediaNavDelegate.sendMediaNavInitialMessageText(self)
  174. pushViewController(approvalViewController, animated: true)
  175. }
  176. private func didRequestExit(dontAbandonText: String) {
  177. if attachmentDraftCollection.count == 0 {
  178. self.sendMediaNavDelegate?.sendMediaNavDidCancel(self)
  179. } else {
  180. let alertTitle = NSLocalizedString("SEND_MEDIA_ABANDON_TITLE", comment: "alert title when user attempts to leave the send media flow when they have an in-progress album")
  181. let alert = UIAlertController(title: alertTitle, message: nil, preferredStyle: .alert)
  182. let confirmAbandonText = NSLocalizedString("SEND_MEDIA_CONFIRM_ABANDON_ALBUM", comment: "alert action, confirming the user wants to exit the media flow and abandon any photos they've taken")
  183. let confirmAbandonAction = UIAlertAction(title: confirmAbandonText,
  184. style: .destructive,
  185. handler: { [weak self] _ in
  186. guard let self = self else { return }
  187. self.sendMediaNavDelegate?.sendMediaNavDidCancel(self)
  188. })
  189. alert.addAction(confirmAbandonAction)
  190. let dontAbandonAction = UIAlertAction(title: dontAbandonText,
  191. style: .default,
  192. handler: { _ in })
  193. alert.addAction(dontAbandonAction)
  194. self.presentAlert(alert)
  195. }
  196. }
  197. }
  198. extension SendMediaNavigationController: UINavigationControllerDelegate {
  199. func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
  200. if let navbarTheme = preferredNavbarTheme(viewController: viewController) {
  201. if let owsNavBar = navigationBar as? OWSNavigationBar {
  202. owsNavBar.overrideTheme(type: navbarTheme)
  203. } else {
  204. owsFailDebug("unexpected navigationBar: \(navigationBar)")
  205. }
  206. }
  207. switch viewController {
  208. case is PhotoCaptureViewController:
  209. if attachmentDraftCollection.count == 1 && !isInBatchSelectMode {
  210. // User is navigating "back" to the previous view, indicating
  211. // they want to discard the previously captured item
  212. discardDraft()
  213. }
  214. case is ImagePickerGridController:
  215. if attachmentDraftCollection.count == 1 && !isInBatchSelectMode {
  216. isInBatchSelectMode = true
  217. self.mediaLibraryViewController.batchSelectModeDidChange()
  218. }
  219. default:
  220. break
  221. }
  222. self.updateButtons(topViewController: viewController)
  223. }
  224. // In case back navigation was canceled, we re-apply whatever is showing.
  225. func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
  226. if let navbarTheme = preferredNavbarTheme(viewController: viewController) {
  227. if let owsNavBar = navigationBar as? OWSNavigationBar {
  228. owsNavBar.overrideTheme(type: navbarTheme)
  229. } else {
  230. owsFailDebug("unexpected navigationBar: \(navigationBar)")
  231. }
  232. }
  233. self.updateButtons(topViewController: viewController)
  234. }
  235. // MARK: - Helpers
  236. private func preferredNavbarTheme(viewController: UIViewController) -> OWSNavigationBar.NavigationBarThemeOverride? {
  237. switch viewController {
  238. case is AttachmentApprovalViewController:
  239. return .clear
  240. case is ImagePickerGridController:
  241. return .alwaysDark
  242. case is PhotoCaptureViewController:
  243. return .clear
  244. default:
  245. owsFailDebug("unexpected viewController: \(viewController)")
  246. return nil
  247. }
  248. }
  249. // MARK: - Too Many
  250. func showTooManySelectedToast() {
  251. Logger.info("")
  252. let toastFormat = NSLocalizedString("IMAGE_PICKER_CAN_SELECT_NO_MORE_TOAST_FORMAT",
  253. comment: "Momentarily shown to the user when attempting to select more images than is allowed. Embeds {{max number of items}} that can be shared.")
  254. let toastText = String(format: toastFormat, NSNumber(value: SignalAttachment.maxAttachmentsAllowed))
  255. let toastController = ToastController(text: toastText)
  256. let kToastInset: CGFloat = 10
  257. let bottomInset = kToastInset + view.layoutMargins.bottom
  258. toastController.presentToastView(fromBottomOfView: view, inset: bottomInset)
  259. }
  260. }
  261. extension SendMediaNavigationController: PhotoCaptureViewControllerDelegate {
  262. func photoCaptureViewController(_ photoCaptureViewController: PhotoCaptureViewController, didFinishProcessingAttachment attachment: SignalAttachment) {
  263. attachmentDraftCollection.append(.camera(attachment: attachment))
  264. if isInBatchSelectMode {
  265. updateButtons(topViewController: photoCaptureViewController)
  266. } else {
  267. pushApprovalViewController()
  268. }
  269. }
  270. func photoCaptureViewControllerDidCancel(_ photoCaptureViewController: PhotoCaptureViewController) {
  271. let dontAbandonText = NSLocalizedString("SEND_MEDIA_RETURN_TO_CAMERA", comment: "alert action when the user decides not to cancel the media flow after all.")
  272. didRequestExit(dontAbandonText: dontAbandonText)
  273. }
  274. func photoCaptureViewControllerDidTryToCaptureTooMany(_ photoCaptureViewController: PhotoCaptureViewController) {
  275. showTooManySelectedToast()
  276. }
  277. func photoCaptureViewControllerCanCaptureMoreItems(_ photoCaptureViewController: PhotoCaptureViewController) -> Bool {
  278. return attachmentCount < SignalAttachment.maxAttachmentsAllowed
  279. }
  280. func discardDraft() {
  281. assert(attachmentDraftCollection.attachmentDrafts.count <= 1)
  282. if let lastAttachmentDraft = attachmentDraftCollection.attachmentDrafts.last {
  283. attachmentDraftCollection.remove(attachment: lastAttachmentDraft.attachment)
  284. }
  285. assert(attachmentDraftCollection.attachmentDrafts.count == 0)
  286. }
  287. }
  288. extension SendMediaNavigationController: ImagePickerGridControllerDelegate {
  289. func imagePickerDidCompleteSelection(_ imagePicker: ImagePickerGridController) {
  290. showApprovalAfterProcessingAnyMediaLibrarySelections()
  291. }
  292. func imagePickerDidCancel(_ imagePicker: ImagePickerGridController) {
  293. let dontAbandonText = NSLocalizedString("SEND_MEDIA_RETURN_TO_MEDIA_LIBRARY", comment: "alert action when the user decides not to cancel the media flow after all.")
  294. didRequestExit(dontAbandonText: dontAbandonText)
  295. }
  296. func showApprovalAfterProcessingAnyMediaLibrarySelections() {
  297. let mediaLibrarySelections: [MediaLibrarySelection] = self.mediaLibrarySelections.orderedValues
  298. let backgroundBlock: (ModalActivityIndicatorViewController) -> Void = { modal in
  299. let attachmentPromises: [Promise<MediaLibraryAttachment>] = mediaLibrarySelections.map { $0.promise }
  300. when(fulfilled: attachmentPromises).map { attachments in
  301. Logger.debug("built all attachments")
  302. modal.dismiss {
  303. self.attachmentDraftCollection.selectedFromPicker(attachments: attachments)
  304. self.pushApprovalViewController()
  305. }
  306. }.catch { error in
  307. Logger.error("failed to prepare attachments. error: \(error)")
  308. modal.dismiss {
  309. OWSAlerts.showAlert(title: NSLocalizedString("IMAGE_PICKER_FAILED_TO_PROCESS_ATTACHMENTS", comment: "alert title"))
  310. }
  311. }.retainUntilComplete()
  312. }
  313. ModalActivityIndicatorViewController.present(fromViewController: self,
  314. canCancel: false,
  315. backgroundBlock: backgroundBlock)
  316. }
  317. func imagePicker(_ imagePicker: ImagePickerGridController, isAssetSelected asset: PHAsset) -> Bool {
  318. return mediaLibrarySelections.hasValue(forKey: asset)
  319. }
  320. func imagePicker(_ imagePicker: ImagePickerGridController, didSelectAsset asset: PHAsset, attachmentPromise: Promise<SignalAttachment>) {
  321. guard !mediaLibrarySelections.hasValue(forKey: asset) else {
  322. return
  323. }
  324. let libraryMedia = MediaLibrarySelection(asset: asset, signalAttachmentPromise: attachmentPromise)
  325. mediaLibrarySelections.append(key: asset, value: libraryMedia)
  326. updateButtons(topViewController: imagePicker)
  327. }
  328. func imagePicker(_ imagePicker: ImagePickerGridController, didDeselectAsset asset: PHAsset) {
  329. guard mediaLibrarySelections.hasValue(forKey: asset) else {
  330. return
  331. }
  332. mediaLibrarySelections.remove(key: asset)
  333. updateButtons(topViewController: imagePicker)
  334. }
  335. func imagePickerCanSelectMoreItems(_ imagePicker: ImagePickerGridController) -> Bool {
  336. return attachmentCount < SignalAttachment.maxAttachmentsAllowed
  337. }
  338. func imagePickerDidTryToSelectTooMany(_ imagePicker: ImagePickerGridController) {
  339. showTooManySelectedToast()
  340. }
  341. }
  342. extension SendMediaNavigationController: AttachmentApprovalViewControllerDelegate {
  343. func attachmentApproval(_ attachmentApproval: AttachmentApprovalViewController, didChangeMessageText newMessageText: String?) {
  344. sendMediaNavDelegate?.sendMediaNav(self, didChangeMessageText: newMessageText)
  345. }
  346. func attachmentApproval(_ attachmentApproval: AttachmentApprovalViewController, didRemoveAttachment attachment: SignalAttachment) {
  347. guard let removedDraft = attachmentDraftCollection.attachmentDrafts.first(where: { $0.attachment == attachment}) else {
  348. owsFailDebug("removedDraft was unexpectedly nil")
  349. return
  350. }
  351. switch removedDraft.source {
  352. case .picker(attachment: let pickerAttachment):
  353. mediaLibrarySelections.remove(key: pickerAttachment.asset)
  354. case .camera(attachment: _):
  355. break
  356. }
  357. attachmentDraftCollection.remove(attachment: attachment)
  358. }
  359. func attachmentApproval(_ attachmentApproval: AttachmentApprovalViewController, didApproveAttachments attachments: [SignalAttachment], messageText: String?) {
  360. sendMediaNavDelegate?.sendMediaNav(self, didApproveAttachments: attachments, messageText: messageText)
  361. }
  362. func attachmentApprovalDidCancel(_ attachmentApproval: AttachmentApprovalViewController) {
  363. sendMediaNavDelegate?.sendMediaNavDidCancel(self)
  364. }
  365. func attachmentApprovalDidTapAddMore(_ attachmentApproval: AttachmentApprovalViewController) {
  366. // Current design dicates we'll go "back" to the single thing before us.
  367. assert(viewControllers.count == 2)
  368. // regardless of which VC we're going "back" to, we're in "batch" mode at this point.
  369. isInBatchSelectMode = true
  370. mediaLibraryViewController.batchSelectModeDidChange()
  371. popViewController(animated: true)
  372. }
  373. }
  374. private enum AttachmentDraft {
  375. case camera(attachment: SignalAttachment)
  376. case picker(attachment: MediaLibraryAttachment)
  377. }
  378. private extension AttachmentDraft {
  379. var attachment: SignalAttachment {
  380. switch self {
  381. case .camera(let cameraAttachment):
  382. return cameraAttachment
  383. case .picker(let pickerAttachment):
  384. return pickerAttachment.signalAttachment
  385. }
  386. }
  387. var source: AttachmentDraft {
  388. return self
  389. }
  390. }
  391. private struct AttachmentDraftCollection {
  392. private(set) var attachmentDrafts: [AttachmentDraft]
  393. static var empty: AttachmentDraftCollection {
  394. return AttachmentDraftCollection(attachmentDrafts: [])
  395. }
  396. // MARK: -
  397. var count: Int {
  398. return attachmentDrafts.count
  399. }
  400. var pickerAttachments: [MediaLibraryAttachment] {
  401. return attachmentDrafts.compactMap { attachmentDraft in
  402. switch attachmentDraft.source {
  403. case .picker(let pickerAttachment):
  404. return pickerAttachment
  405. case .camera:
  406. return nil
  407. }
  408. }
  409. }
  410. var cameraAttachments: [SignalAttachment] {
  411. return attachmentDrafts.compactMap { attachmentDraft in
  412. switch attachmentDraft.source {
  413. case .picker:
  414. return nil
  415. case .camera(let cameraAttachment):
  416. return cameraAttachment
  417. }
  418. }
  419. }
  420. mutating func append(_ element: AttachmentDraft) {
  421. attachmentDrafts.append(element)
  422. }
  423. mutating func remove(attachment: SignalAttachment) {
  424. attachmentDrafts = attachmentDrafts.filter { $0.attachment != attachment }
  425. }
  426. mutating func selectedFromPicker(attachments: [MediaLibraryAttachment]) {
  427. let pickedAttachments: Set<MediaLibraryAttachment> = Set(attachments)
  428. let oldPickerAttachments: Set<MediaLibraryAttachment> = Set(self.pickerAttachments)
  429. for removedAttachment in oldPickerAttachments.subtracting(pickedAttachments) {
  430. remove(attachment: removedAttachment.signalAttachment)
  431. }
  432. // enumerate over new attachments to maintain order from picker
  433. for attachment in attachments {
  434. guard !oldPickerAttachments.contains(attachment) else {
  435. continue
  436. }
  437. append(.picker(attachment: attachment))
  438. }
  439. }
  440. }
  441. private struct MediaLibrarySelection: Hashable, Equatable {
  442. let asset: PHAsset
  443. let signalAttachmentPromise: Promise<SignalAttachment>
  444. var hashValue: Int {
  445. return asset.hashValue
  446. }
  447. var promise: Promise<MediaLibraryAttachment> {
  448. let asset = self.asset
  449. return signalAttachmentPromise.map { signalAttachment in
  450. return MediaLibraryAttachment(asset: asset, signalAttachment: signalAttachment)
  451. }
  452. }
  453. static func ==(lhs: MediaLibrarySelection, rhs: MediaLibrarySelection) -> Bool {
  454. return lhs.asset == rhs.asset
  455. }
  456. }
  457. private struct MediaLibraryAttachment: Hashable, Equatable {
  458. let asset: PHAsset
  459. let signalAttachment: SignalAttachment
  460. public var hashValue: Int {
  461. return asset.hashValue
  462. }
  463. public static func == (lhs: MediaLibraryAttachment, rhs: MediaLibraryAttachment) -> Bool {
  464. return lhs.asset == rhs.asset
  465. }
  466. }
  467. extension SendMediaNavigationController: DoneButtonDelegate {
  468. var doneButtonCount: Int {
  469. return attachmentCount
  470. }
  471. fileprivate func doneButtonWasTapped(_ doneButton: DoneButton) {
  472. assert(attachmentDraftCollection.count > 0 || mediaLibrarySelections.count > 0)
  473. showApprovalAfterProcessingAnyMediaLibrarySelections()
  474. }
  475. }
  476. private protocol DoneButtonDelegate: AnyObject {
  477. func doneButtonWasTapped(_ doneButton: DoneButton)
  478. var doneButtonCount: Int { get }
  479. }
  480. private class DoneButton: UIView {
  481. weak var delegate: DoneButtonDelegate?
  482. init() {
  483. super.init(frame: .zero)
  484. let tapGesture = UITapGestureRecognizer(target: self, action: #selector(didTap(tapGesture:)))
  485. addGestureRecognizer(tapGesture)
  486. let container = UIView()
  487. container.backgroundColor = .ows_white
  488. container.layer.cornerRadius = 20
  489. container.layoutMargins = UIEdgeInsets(top: 7, leading: 8, bottom: 7, trailing: 8)
  490. addSubview(container)
  491. container.autoPinEdgesToSuperviewMargins()
  492. let stackView = UIStackView(arrangedSubviews: [badge, chevron])
  493. stackView.axis = .horizontal
  494. stackView.alignment = .center
  495. stackView.spacing = 9
  496. container.addSubview(stackView)
  497. stackView.autoPinEdgesToSuperviewMargins()
  498. }
  499. let numberFormatter: NumberFormatter = NumberFormatter()
  500. func updateCount() {
  501. guard let delegate = delegate else {
  502. return
  503. }
  504. badgeLabel.text = numberFormatter.string(for: delegate.doneButtonCount)
  505. }
  506. required init?(coder aDecoder: NSCoder) {
  507. fatalError("init(coder:) has not been implemented")
  508. }
  509. // MARK: - Subviews
  510. private lazy var badge: UIView = {
  511. let badge = CircleView()
  512. badge.layoutMargins = UIEdgeInsets(top: 4, leading: 4, bottom: 4, trailing: 4)
  513. badge.backgroundColor = .ows_signalBlue
  514. badge.addSubview(badgeLabel)
  515. badgeLabel.autoPinEdgesToSuperviewMargins()
  516. // Constrain to be a pill that is at least a circle, and maybe wider.
  517. badgeLabel.autoPin(toAspectRatio: 1.0, relation: .greaterThanOrEqual)
  518. NSLayoutConstraint.autoSetPriority(.defaultLow) {
  519. badgeLabel.autoPinToSquareAspectRatio()
  520. }
  521. return badge
  522. }()
  523. private lazy var badgeLabel: UILabel = {
  524. let label = UILabel()
  525. label.textColor = .ows_white
  526. label.font = UIFont.ows_dynamicTypeSubheadline.ows_monospaced()
  527. label.textAlignment = .center
  528. return label
  529. }()
  530. private lazy var chevron: UIView = {
  531. let image: UIImage
  532. if CurrentAppContext().isRTL {
  533. image = #imageLiteral(resourceName: "small_chevron_left")
  534. } else {
  535. image = #imageLiteral(resourceName: "small_chevron_right")
  536. }
  537. let chevron = UIImageView(image: image.withRenderingMode(.alwaysTemplate))
  538. chevron.contentMode = .scaleAspectFit
  539. chevron.tintColor = .ows_gray60
  540. chevron.autoSetDimensions(to: CGSize(width: 10, height: 18))
  541. return chevron
  542. }()
  543. @objc
  544. func didTap(tapGesture: UITapGestureRecognizer) {
  545. delegate?.doneButtonWasTapped(self)
  546. }
  547. }