ChatViewController.swift 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308
  1. import MapKit
  2. import QuickLook
  3. import UIKit
  4. import InputBarAccessoryView
  5. import AVFoundation
  6. protocol MediaSendHandler {
  7. func onSuccess()
  8. }
  9. extension ChatViewController: MediaSendHandler {
  10. func onSuccess() {
  11. refreshMessages()
  12. }
  13. }
  14. extension ChatViewController: MediaPickerDelegate {
  15. func onVideoSelected(url: NSURL) {
  16. sendVideo(url: url)
  17. }
  18. func onImageSelected(url: NSURL) {
  19. sendImage(url: url)
  20. }
  21. func onImageSelected(image: UIImage) {
  22. sendImage(image)
  23. }
  24. func onVoiceMessageRecorded(url: NSURL) {
  25. sendVoiceMessage(url: url)
  26. }
  27. }
  28. class ChatViewController: MessagesViewController {
  29. var dcContext: DcContext
  30. weak var coordinator: ChatViewCoordinator?
  31. let outgoingAvatarOverlap: CGFloat = 17.5
  32. let loadCount = 30
  33. let chatId: Int
  34. let refreshControl = UIRefreshControl()
  35. var messageList: [DcMsg] = []
  36. var msgChangedObserver: Any?
  37. var incomingMsgObserver: Any?
  38. weak var timer: Timer?
  39. lazy var navBarTap: UITapGestureRecognizer = {
  40. UITapGestureRecognizer(target: self, action: #selector(chatProfilePressed))
  41. }()
  42. /// The `BasicAudioController` controll the AVAudioPlayer state (play, pause, stop) and udpate audio cell UI accordingly.
  43. open lazy var audioController = BasicAudioController(messageCollectionView: messagesCollectionView)
  44. private var disableWriting: Bool
  45. private var showNamesAboveMessage: Bool
  46. var showCustomNavBar = true
  47. var previewView: UIView?
  48. var previewController: PreviewController?
  49. var emptyStateView: PaddingLabel = {
  50. let view = PaddingLabel()
  51. view.backgroundColor = DcColors.systemMessageBackgroundColor
  52. view.textColor = DcColors.defaultTextColor
  53. return view
  54. }()
  55. override var inputAccessoryView: UIView? {
  56. if disableWriting {
  57. return nil
  58. }
  59. return messageInputBar
  60. }
  61. init(dcContext: DcContext, chatId: Int) {
  62. let dcChat = DcChat(id: chatId)
  63. self.dcContext = dcContext
  64. self.chatId = chatId
  65. self.disableWriting = !dcChat.canSend
  66. self.showNamesAboveMessage = dcChat.isGroup
  67. super.init(nibName: nil, bundle: nil)
  68. hidesBottomBarWhenPushed = true
  69. }
  70. required init?(coder _: NSCoder) {
  71. fatalError("init(coder:) has not been implemented")
  72. }
  73. override func viewDidLoad() {
  74. messagesCollectionView.register(CustomMessageCell.self)
  75. super.viewDidLoad()
  76. if !DcConfig.configured {
  77. // TODO: display message about nothing being configured
  78. return
  79. }
  80. configureMessageCollectionView()
  81. configureEmptyStateView()
  82. if !disableWriting {
  83. configureMessageInputBar()
  84. messageInputBar.inputTextView.text = textDraft
  85. messageInputBar.inputTextView.becomeFirstResponder()
  86. }
  87. loadFirstMessages()
  88. let notificationCenter = NotificationCenter.default
  89. notificationCenter.addObserver(self,
  90. selector: #selector(setTextDraft),
  91. name: UIApplication.willResignActiveNotification,
  92. object: nil)
  93. }
  94. private func startTimer() {
  95. timer?.invalidate()
  96. timer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { [weak self] _ in
  97. //reload table
  98. DispatchQueue.main.async {
  99. guard let self = self else { return }
  100. self.messageList = self.getMessageIds(self.messageList.count)
  101. self.messagesCollectionView.reloadDataAndKeepOffset()
  102. self.refreshControl.endRefreshing()
  103. }
  104. }
  105. }
  106. private func stopTimer() {
  107. timer?.invalidate()
  108. }
  109. private func configureEmptyStateView() {
  110. view.addSubview(emptyStateView)
  111. view.addConstraints([emptyStateView.constraintCenterYTo(view),
  112. emptyStateView.constraintCenterXTo(view),
  113. emptyStateView.constraintAlignLeadingTo(view, paddingLeading: 40),
  114. emptyStateView.constraintAlignTrailingTo(view, paddingTrailing: 40)])
  115. }
  116. override func viewWillAppear(_ animated: Bool) {
  117. super.viewWillAppear(animated)
  118. // this will be removed in viewWillDisappear
  119. navigationController?.navigationBar.addGestureRecognizer(navBarTap)
  120. let chat = DcChat(id: chatId)
  121. if showCustomNavBar {
  122. updateTitle(chat: chat)
  123. }
  124. configureMessageMenu()
  125. let nc = NotificationCenter.default
  126. msgChangedObserver = nc.addObserver(
  127. forName: dcNotificationChanged,
  128. object: nil,
  129. queue: OperationQueue.main
  130. ) { notification in
  131. if let ui = notification.userInfo {
  132. if self.disableWriting {
  133. // always refresh, as we can't check currently
  134. self.refreshMessages()
  135. } else if let id = ui["message_id"] as? Int {
  136. if id > 0 {
  137. self.updateMessage(id)
  138. } else {
  139. // change might be a deletion
  140. self.refreshMessages()
  141. }
  142. }
  143. if self.showCustomNavBar {
  144. self.updateTitle(chat: chat)
  145. }
  146. }
  147. }
  148. incomingMsgObserver = nc.addObserver(
  149. forName: dcNotificationIncoming,
  150. object: nil, queue: OperationQueue.main
  151. ) { notification in
  152. if let ui = notification.userInfo {
  153. if self.chatId == ui["chat_id"] as? Int {
  154. if let id = ui["message_id"] as? Int {
  155. if id > 0 {
  156. self.insertMessage(DcMsg(id: id))
  157. }
  158. }
  159. }
  160. }
  161. }
  162. if RelayHelper.sharedInstance.isForwarding() {
  163. askToForwardMessage()
  164. }
  165. }
  166. override func viewDidAppear(_ animated: Bool) {
  167. super.viewDidAppear(animated)
  168. // things that do not affect the chatview
  169. // and are delayed after the view is displayed
  170. dcContext.marknoticedChat(chatId: chatId)
  171. let array = DcArray(arrayPointer: dc_get_fresh_msgs(mailboxPointer))
  172. UIApplication.shared.applicationIconBadgeNumber = array.count
  173. startTimer()
  174. }
  175. override func viewWillDisappear(_ animated: Bool) {
  176. super.viewWillDisappear(animated)
  177. // the navigationController will be used when chatDetail is pushed, so we have to remove that gestureRecognizer
  178. navigationController?.navigationBar.removeGestureRecognizer(navBarTap)
  179. }
  180. override func viewDidDisappear(_ animated: Bool) {
  181. super.viewDidDisappear(animated)
  182. setTextDraft()
  183. let nc = NotificationCenter.default
  184. if let msgChangedObserver = self.msgChangedObserver {
  185. nc.removeObserver(msgChangedObserver)
  186. }
  187. if let incomingMsgObserver = self.incomingMsgObserver {
  188. nc.removeObserver(incomingMsgObserver)
  189. }
  190. audioController.stopAnyOngoingPlaying()
  191. stopTimer()
  192. }
  193. private func updateTitle(chat: DcChat) {
  194. let titleView = ChatTitleView()
  195. var subtitle = "ErrSubtitle"
  196. let chatContactIds = chat.contactIds
  197. if chat.isGroup {
  198. subtitle = String.localizedStringWithFormat(NSLocalizedString("n_members", comment: ""), chatContactIds.count)
  199. } else if chatContactIds.count >= 1 {
  200. if chat.isDeviceTalk {
  201. subtitle = String.localized("device_talk_subtitle")
  202. } else if chat.isSelfTalk {
  203. subtitle = String.localized("chat_self_talk_subtitle")
  204. } else {
  205. subtitle = DcContact(id: chatContactIds[0]).email
  206. }
  207. }
  208. titleView.updateTitleView(title: chat.name, subtitle: subtitle)
  209. navigationItem.titleView = titleView
  210. let badge: InitialsBadge
  211. if let image = chat.profileImage {
  212. badge = InitialsBadge(image: image, size: 28)
  213. } else {
  214. badge = InitialsBadge(name: chat.name, color: chat.color, size: 28)
  215. badge.setLabelFont(UIFont.systemFont(ofSize: 14))
  216. }
  217. badge.setVerified(chat.isVerified)
  218. badge.accessibilityTraits = .button
  219. navigationItem.rightBarButtonItem = UIBarButtonItem(customView: badge)
  220. }
  221. @objc
  222. private func loadMoreMessages() {
  223. DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + 1) {
  224. DispatchQueue.main.async {
  225. self.messageList = self.getMessageIds(self.loadCount, from: self.messageList.count) + self.messageList
  226. self.messagesCollectionView.reloadDataAndKeepOffset()
  227. self.refreshControl.endRefreshing()
  228. }
  229. }
  230. }
  231. @objc
  232. private func refreshMessages() {
  233. DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + 1) {
  234. DispatchQueue.main.async {
  235. self.messageList = self.getMessageIds(self.messageList.count)
  236. self.messagesCollectionView.reloadDataAndKeepOffset()
  237. self.refreshControl.endRefreshing()
  238. if self.isLastSectionVisible() {
  239. self.messagesCollectionView.scrollToBottom(animated: true)
  240. }
  241. self.showEmptyStateView(self.messageList.isEmpty)
  242. }
  243. }
  244. }
  245. private func loadFirstMessages() {
  246. DispatchQueue.global(qos: .userInitiated).async {
  247. DispatchQueue.main.async {
  248. self.messageList = self.getMessageIds(self.loadCount)
  249. self.messagesCollectionView.reloadData()
  250. self.refreshControl.endRefreshing()
  251. self.messagesCollectionView.scrollToBottom(animated: false)
  252. self.showEmptyStateView(self.messageList.isEmpty)
  253. }
  254. }
  255. }
  256. private func showEmptyStateView(_ show: Bool) {
  257. if show {
  258. let dcChat = DcChat(id: chatId)
  259. if chatId == DC_CHAT_ID_DEADDROP {
  260. if DcConfig.showEmails != DC_SHOW_EMAILS_ALL {
  261. emptyStateView.text = String.localized("chat_no_contact_requests")
  262. } else {
  263. emptyStateView.text = String.localized("chat_no_messages")
  264. }
  265. } else if dcChat.isGroup {
  266. if dcChat.isUnpromoted {
  267. emptyStateView.text = String.localized("chat_new_group_hint")
  268. } else {
  269. emptyStateView.text = String.localized("chat_no_messages")
  270. }
  271. } else if dcChat.isSelfTalk {
  272. emptyStateView.text = String.localized("saved_messages_explain")
  273. } else if dcChat.isDeviceTalk {
  274. emptyStateView.text = String.localized("device_talk_explain")
  275. } else {
  276. emptyStateView.text = String.localizedStringWithFormat(String.localized("chat_no_messages_hint"), dcChat.name, dcChat.name)
  277. }
  278. emptyStateView.isHidden = false
  279. } else {
  280. emptyStateView.isHidden = true
  281. }
  282. }
  283. private var textDraft: String? {
  284. if let draft = dc_get_draft(mailboxPointer, UInt32(chatId)) {
  285. if let cString = dc_msg_get_text(draft) {
  286. let swiftString = String(cString: cString)
  287. dc_str_unref(cString)
  288. dc_msg_unref(draft)
  289. return swiftString
  290. }
  291. dc_msg_unref(draft)
  292. return nil
  293. }
  294. return nil
  295. }
  296. private func getMessageIds(_ count: Int, from: Int? = nil) -> [DcMsg] {
  297. let cMessageIds = dc_get_chat_msgs(mailboxPointer, UInt32(chatId), 0, 0)
  298. let ids: [Int]
  299. if let from = from {
  300. ids = Utils.copyAndFreeArrayWithOffset(inputArray: cMessageIds, len: count, skipEnd: from)
  301. } else {
  302. ids = Utils.copyAndFreeArrayWithLen(inputArray: cMessageIds, len: count)
  303. }
  304. let markIds: [UInt32] = ids.map { UInt32($0) }
  305. dc_markseen_msgs(mailboxPointer, UnsafePointer(markIds), Int32(ids.count))
  306. return ids.map {
  307. DcMsg(id: $0)
  308. }
  309. }
  310. @objc private func setTextDraft() {
  311. if let text = self.messageInputBar.inputTextView.text {
  312. let draft = dc_msg_new(mailboxPointer, DC_MSG_TEXT)
  313. dc_msg_set_text(draft, text.cString(using: .utf8))
  314. dc_set_draft(mailboxPointer, UInt32(chatId), draft)
  315. // cleanup
  316. dc_msg_unref(draft)
  317. }
  318. }
  319. private func configureMessageMenu() {
  320. var menuItems: [UIMenuItem]
  321. menuItems = [
  322. UIMenuItem(title: String.localized("info"), action: #selector(MessageCollectionViewCell.messageInfo(_:))),
  323. UIMenuItem(title: String.localized("delete"), action: #selector(MessageCollectionViewCell.messageDelete(_:))),
  324. UIMenuItem(title: String.localized("forward"), action: #selector(MessageCollectionViewCell.messageForward(_:)))
  325. ]
  326. UIMenuController.shared.menuItems = menuItems
  327. }
  328. private func configureMessageCollectionView() {
  329. messagesCollectionView.messagesDataSource = self
  330. messagesCollectionView.messageCellDelegate = self
  331. scrollsToBottomOnKeyboardBeginsEditing = true // default false
  332. maintainPositionOnKeyboardFrameChanged = true // default false
  333. messagesCollectionView.backgroundColor = DcColors.chatBackgroundColor
  334. messagesCollectionView.addSubview(refreshControl)
  335. refreshControl.addTarget(self, action: #selector(loadMoreMessages), for: .valueChanged)
  336. let layout = messagesCollectionView.collectionViewLayout as? MessagesCollectionViewFlowLayout
  337. layout?.sectionInset = UIEdgeInsets(top: 0, left: 8, bottom: 2, right: 8)
  338. // Hide the outgoing avatar and adjust the label alignment to line up with the messages
  339. layout?.setMessageOutgoingAvatarSize(.zero)
  340. layout?.setMessageOutgoingMessageTopLabelAlignment(LabelAlignment(textAlignment: .right,
  341. textInsets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 8)))
  342. layout?.setMessageOutgoingMessageBottomLabelAlignment(LabelAlignment(textAlignment: .right,
  343. textInsets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 8)))
  344. // Set outgoing avatar to overlap with the message bubble
  345. layout?.setMessageIncomingMessageTopLabelAlignment(LabelAlignment(textAlignment: .left,
  346. textInsets: UIEdgeInsets(top: 0, left: 18, bottom: 0, right: 0)))
  347. layout?.setMessageIncomingAvatarSize(CGSize(width: 30, height: 30))
  348. layout?.setMessageIncomingMessagePadding(UIEdgeInsets(
  349. top: 0, left: -18, bottom: 0, right: 0))
  350. layout?.setMessageIncomingMessageBottomLabelAlignment(LabelAlignment(textAlignment: .left,
  351. textInsets: UIEdgeInsets(top: 0, left: 12, bottom: 0, right: 0)))
  352. layout?.setMessageIncomingAccessoryViewSize(CGSize(width: 30, height: 30))
  353. layout?.setMessageIncomingAccessoryViewPadding(HorizontalEdgeInsets(left: 8, right: 0))
  354. layout?.setMessageOutgoingAccessoryViewSize(CGSize(width: 30, height: 30))
  355. layout?.setMessageOutgoingAccessoryViewPadding(HorizontalEdgeInsets(left: 0, right: 8))
  356. messagesCollectionView.messagesLayoutDelegate = self
  357. messagesCollectionView.messagesDisplayDelegate = self
  358. }
  359. private func configureMessageInputBar() {
  360. messageInputBar.delegate = self
  361. messageInputBar.inputTextView.tintColor = DcColors.primary
  362. messageInputBar.inputTextView.placeholder = String.localized("chat_input_placeholder")
  363. messageInputBar.separatorLine.isHidden = true
  364. messageInputBar.inputTextView.tintColor = DcColors.primary
  365. messageInputBar.inputTextView.textColor = DcColors.defaultTextColor
  366. messageInputBar.backgroundView.backgroundColor = DcColors.chatBackgroundColor
  367. scrollsToBottomOnKeyboardBeginsEditing = true
  368. messageInputBar.inputTextView.backgroundColor = DcColors.inputFieldColor
  369. messageInputBar.inputTextView.placeholderTextColor = DcColors.placeholderColor
  370. messageInputBar.inputTextView.textContainerInset = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 38)
  371. messageInputBar.inputTextView.placeholderLabelInsets = UIEdgeInsets(top: 8, left: 20, bottom: 8, right: 38)
  372. messageInputBar.inputTextView.layer.borderColor = UIColor.themeColor(light: UIColor(red: 200 / 255, green: 200 / 255, blue: 200 / 255, alpha: 1),
  373. dark: UIColor(red: 55 / 255, green: 55/255, blue: 55/255, alpha: 1)).cgColor
  374. messageInputBar.inputTextView.layer.borderWidth = 1.0
  375. messageInputBar.inputTextView.layer.cornerRadius = 13.0
  376. messageInputBar.inputTextView.layer.masksToBounds = true
  377. messageInputBar.inputTextView.scrollIndicatorInsets = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0)
  378. configureInputBarItems()
  379. }
  380. private func configureInputBarItems() {
  381. messageInputBar.setLeftStackViewWidthConstant(to: 40, animated: false)
  382. messageInputBar.setRightStackViewWidthConstant(to: 40, animated: false)
  383. let sendButtonImage = UIImage(named: "paper_plane")?.withRenderingMode(.alwaysTemplate)
  384. messageInputBar.sendButton.image = sendButtonImage
  385. messageInputBar.sendButton.accessibilityLabel = String.localized("menu_send")
  386. messageInputBar.sendButton.accessibilityTraits = .button
  387. messageInputBar.sendButton.title = nil
  388. messageInputBar.sendButton.tintColor = UIColor(white: 1, alpha: 1)
  389. messageInputBar.sendButton.layer.cornerRadius = 20
  390. messageInputBar.middleContentViewPadding = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 10)
  391. // this adds a padding between textinputfield and send button
  392. messageInputBar.sendButton.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
  393. messageInputBar.sendButton.setSize(CGSize(width: 40, height: 40), animated: false)
  394. messageInputBar.padding = UIEdgeInsets(top: 6, left: 6, bottom: 6, right: 12)
  395. let leftItems = [
  396. InputBarButtonItem()
  397. .configure {
  398. $0.spacing = .fixed(0)
  399. let clipperIcon = #imageLiteral(resourceName: "ic_attach_file_36pt").withRenderingMode(.alwaysTemplate)
  400. $0.image = clipperIcon
  401. $0.tintColor = UIColor.themeColor(light: .lightGray, dark: .darkGray)
  402. $0.setSize(CGSize(width: 40, height: 40), animated: false)
  403. $0.accessibilityLabel = String.localized("menu_add_attachment")
  404. $0.accessibilityTraits = .button
  405. }.onSelected {
  406. $0.tintColor = DcColors.primary
  407. }.onDeselected {
  408. $0.tintColor = UIColor.themeColor(light: .lightGray, dark: .darkGray)
  409. }.onTouchUpInside { _ in
  410. self.clipperButtonPressed()
  411. }
  412. ]
  413. messageInputBar.setStackViewItems(leftItems, forStack: .left, animated: false)
  414. // This just adds some more flare
  415. messageInputBar.sendButton
  416. .onEnabled { item in
  417. UIView.animate(withDuration: 0.3, animations: {
  418. item.backgroundColor = DcColors.primary
  419. })
  420. }.onDisabled { item in
  421. UIView.animate(withDuration: 0.3, animations: {
  422. item.backgroundColor = DcColors.colorDisabled
  423. })
  424. }
  425. }
  426. @objc private func chatProfilePressed() {
  427. coordinator?.showChatDetail(chatId: chatId)
  428. }
  429. // MARK: - UICollectionViewDataSource
  430. public override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  431. guard let messagesCollectionView = collectionView as? MessagesCollectionView else {
  432. fatalError("notMessagesCollectionView")
  433. }
  434. guard let messagesDataSource = messagesCollectionView.messagesDataSource else {
  435. fatalError("nilMessagesDataSource")
  436. }
  437. let message = messagesDataSource.messageForItem(at: indexPath, in: messagesCollectionView)
  438. switch message.kind {
  439. case .text, .attributedText, .emoji:
  440. let cell = messagesCollectionView.dequeueReusableCell(TextMessageCell.self, for: indexPath)
  441. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  442. return cell
  443. case .photo, .video:
  444. let cell = messagesCollectionView.dequeueReusableCell(MediaMessageCell.self, for: indexPath)
  445. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  446. return cell
  447. case .photoText, .videoText, .fileText:
  448. let cell = messagesCollectionView.dequeueReusableCell(TextMediaMessageCell.self, for: indexPath)
  449. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  450. return cell
  451. case .location:
  452. let cell = messagesCollectionView.dequeueReusableCell(LocationMessageCell.self, for: indexPath)
  453. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  454. return cell
  455. case .contact:
  456. let cell = messagesCollectionView.dequeueReusableCell(ContactMessageCell.self, for: indexPath)
  457. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  458. return cell
  459. case .custom:
  460. let cell = messagesCollectionView.dequeueReusableCell(CustomMessageCell.self, for: indexPath)
  461. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  462. return cell
  463. case .audio:
  464. let cell = messagesCollectionView.dequeueReusableCell(AudioMessageCell.self, for: indexPath)
  465. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  466. return cell
  467. }
  468. }
  469. override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
  470. if action == NSSelectorFromString("messageInfo:") ||
  471. action == NSSelectorFromString("messageDelete:") ||
  472. action == NSSelectorFromString("messageForward:") {
  473. return true
  474. } else {
  475. return super.collectionView(collectionView, canPerformAction: action, forItemAt: indexPath, withSender: sender)
  476. }
  477. }
  478. override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
  479. switch action {
  480. case NSSelectorFromString("messageInfo:"):
  481. let msg = messageList[indexPath.section]
  482. logger.info("message: View info \(msg.messageId)")
  483. let msgViewController = MessageInfoViewController(dcContext: dcContext, message: msg)
  484. if let ctrl = navigationController {
  485. ctrl.pushViewController(msgViewController, animated: true)
  486. }
  487. case NSSelectorFromString("messageDelete:"):
  488. let msg = messageList[indexPath.section]
  489. logger.info("message: delete \(msg.messageId)")
  490. askToDeleteMessage(id: msg.id)
  491. case NSSelectorFromString("messageForward:"):
  492. let msg = messageList[indexPath.section]
  493. RelayHelper.sharedInstance.setForwardMessage(messageId: msg.id)
  494. coordinator?.navigateBack()
  495. default:
  496. super.collectionView(collectionView, performAction: action, forItemAt: indexPath, withSender: sender)
  497. }
  498. }
  499. private func confirmationAlert(title: String, actionTitle: String, actionStyle: UIAlertAction.Style = .default, actionHandler: @escaping ((UIAlertAction) -> Void), cancelHandler: ((UIAlertAction) -> Void)? = nil) {
  500. let alert = UIAlertController(title: title,
  501. message: nil,
  502. preferredStyle: .actionSheet)
  503. alert.addAction(UIAlertAction(title: actionTitle, style: actionStyle, handler: actionHandler))
  504. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: cancelHandler ?? { _ in
  505. self.dismiss(animated: true, completion: nil)
  506. }))
  507. present(alert, animated: true, completion: nil)
  508. }
  509. private func askToChatWith(email: String) {
  510. confirmationAlert(title: String.localizedStringWithFormat(String.localized("ask_start_chat_with"), email),
  511. actionTitle: String.localized("start_chat"),
  512. actionHandler: { _ in
  513. self.dismiss(animated: true, completion: nil)
  514. let contactId = self.dcContext.createContact(name: "", email: email)
  515. let chatId = self.dcContext.createChat(contactId: contactId)
  516. self.coordinator?.showChat(chatId: chatId)})
  517. }
  518. private func askToDeleteMessage(id: Int) {
  519. confirmationAlert(title: String.localized("delete"), actionTitle: String.localized("delete"), actionStyle: .destructive,
  520. actionHandler: { _ in
  521. self.dcContext.deleteMessage(msgId: id)
  522. self.dismiss(animated: true, completion: nil)})
  523. }
  524. private func askToForwardMessage() {
  525. let chat = DcChat(id: self.chatId)
  526. confirmationAlert(title: String.localizedStringWithFormat(String.localized("ask_forward"), chat.name),
  527. actionTitle: String.localized("menu_forward"),
  528. actionHandler: { _ in
  529. RelayHelper.sharedInstance.forward(to: self.chatId)
  530. self.dismiss(animated: true, completion: nil)},
  531. cancelHandler: { _ in
  532. self.dismiss(animated: false, completion: nil)
  533. self.coordinator?.navigateBack()})
  534. }
  535. }
  536. // MARK: - MessagesDataSource
  537. extension ChatViewController: MessagesDataSource {
  538. func numberOfSections(in _: MessagesCollectionView) -> Int {
  539. return messageList.count
  540. }
  541. func currentSender() -> SenderType {
  542. let currentSender = Sender(senderId: "1", displayName: "Alice")
  543. return currentSender
  544. }
  545. func messageForItem(at indexPath: IndexPath, in _: MessagesCollectionView) -> MessageType {
  546. return messageList[indexPath.section]
  547. }
  548. func avatar(for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> Avatar {
  549. let message = messageList[indexPath.section]
  550. let contact = message.fromContact
  551. return Avatar(image: contact.profileImage, initials: Utils.getInitials(inputName: contact.displayName))
  552. }
  553. func cellTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
  554. if isInfoMessage(at: indexPath) {
  555. return nil
  556. }
  557. if isTimeLabelVisible(at: indexPath) {
  558. return NSAttributedString(
  559. string: MessageKitDateFormatter.shared.string(from: message.sentDate),
  560. attributes: [
  561. NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 10),
  562. NSAttributedString.Key.foregroundColor: DcColors.grayTextColor,
  563. ]
  564. )
  565. }
  566. return nil
  567. }
  568. func messageTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
  569. var attributedString: NSMutableAttributedString?
  570. if showNamesAboveMessage && !isPreviousMessageSameSender(at: indexPath) {
  571. let name = message.sender.displayName
  572. let m = messageList[indexPath.section]
  573. attributedString = NSMutableAttributedString(string: name, attributes: [
  574. .font: UIFont.systemFont(ofSize: 14),
  575. .foregroundColor: m.fromContact.color,
  576. ])
  577. }
  578. if isMessageForwarded(at: indexPath) {
  579. let forwardedString = NSMutableAttributedString(string: String.localized("forwarded_message"), attributes: [
  580. .font: UIFont.systemFont(ofSize: 14),
  581. .foregroundColor: DcColors.grayTextColor,
  582. ])
  583. if attributedString == nil {
  584. attributedString = forwardedString
  585. } else {
  586. attributedString?.append(NSAttributedString(string: "\n", attributes: nil))
  587. attributedString?.append(forwardedString)
  588. }
  589. }
  590. return attributedString
  591. }
  592. func isMessageForwarded(at indexPath: IndexPath) -> Bool {
  593. let m = messageList[indexPath.section]
  594. return m.isForwarded
  595. }
  596. func isTimeLabelVisible(at indexPath: IndexPath) -> Bool {
  597. guard indexPath.section + 1 < messageList.count else { return false }
  598. let messageA = messageList[indexPath.section]
  599. let messageB = messageList[indexPath.section + 1]
  600. if messageA.fromContactId == messageB.fromContactId {
  601. return false
  602. }
  603. let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)
  604. let dateA = messageA.sentDate
  605. let dateB = messageB.sentDate
  606. let dayA = (calendar?.component(.day, from: dateA))
  607. let dayB = (calendar?.component(.day, from: dateB))
  608. return dayA != dayB
  609. }
  610. func isPreviousMessageSameSender(at indexPath: IndexPath) -> Bool {
  611. guard indexPath.section - 1 >= 0 else { return false }
  612. let messageA = messageList[indexPath.section - 1]
  613. let messageB = messageList[indexPath.section]
  614. if messageA.isInfo {
  615. return false
  616. }
  617. return messageA.fromContactId == messageB.fromContactId
  618. }
  619. func isInfoMessage(at indexPath: IndexPath) -> Bool {
  620. return messageList[indexPath.section].isInfo
  621. }
  622. func isImmediateNextMessageSameSender(at indexPath: IndexPath) -> Bool {
  623. guard indexPath.section + 1 < messageList.count else { return false }
  624. let messageA = messageList[indexPath.section]
  625. let messageB = messageList[indexPath.section + 1]
  626. if messageA.isInfo {
  627. return false
  628. }
  629. let dateA = messageA.sentDate
  630. let dateB = messageB.sentDate
  631. let timeinterval = dateB.timeIntervalSince(dateA)
  632. let minute = 60.0
  633. return messageA.fromContactId == messageB.fromContactId && timeinterval.isLessThanOrEqualTo(minute)
  634. }
  635. func isAvatarHidden(at indexPath: IndexPath) -> Bool {
  636. let message = messageList[indexPath.section]
  637. return isNextMessageSameSender(at: indexPath) || message.isInfo
  638. }
  639. func isNextMessageSameSender(at indexPath: IndexPath) -> Bool {
  640. guard indexPath.section + 1 < messageList.count else { return false }
  641. let messageA = messageList[indexPath.section]
  642. let messageB = messageList[indexPath.section + 1]
  643. if messageA.isInfo {
  644. return false
  645. }
  646. return messageA.fromContactId == messageB.fromContactId
  647. }
  648. func messageBottomLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
  649. guard indexPath.section < messageList.count else { return nil }
  650. let m = messageList[indexPath.section]
  651. if m.isInfo || isImmediateNextMessageSameSender(at: indexPath) {
  652. return nil
  653. }
  654. let timestampAttributes: [NSAttributedString.Key: Any] = [
  655. .font: UIFont.systemFont(ofSize: 12),
  656. .foregroundColor: UIColor.lightGray,
  657. ]
  658. if isFromCurrentSender(message: message) {
  659. let text = NSMutableAttributedString()
  660. text.append(NSAttributedString(string: m.formattedSentDate(), attributes: timestampAttributes))
  661. // TODO: this should be replaced by the respective icons,
  662. // for accessibility, the a11y strings should be added
  663. var stateDescription: String
  664. switch Int32(m.state) {
  665. case DC_STATE_OUT_PENDING:
  666. stateDescription = "Pending"
  667. case DC_STATE_OUT_DELIVERED:
  668. stateDescription = "Sent"
  669. case DC_STATE_OUT_MDN_RCVD:
  670. stateDescription = "Read"
  671. case DC_STATE_OUT_FAILED:
  672. stateDescription = "Failed"
  673. default:
  674. stateDescription = "Unknown"
  675. }
  676. text.append(NSAttributedString(
  677. string: " - " + stateDescription,
  678. attributes: [
  679. .font: UIFont.systemFont(ofSize: 12),
  680. .foregroundColor: DcColors.defaultTextColor,
  681. ]
  682. ))
  683. return text
  684. }
  685. if !isAvatarHidden(at: indexPath) {
  686. let text = NSMutableAttributedString()
  687. text.append(NSAttributedString(string: " "))
  688. text.append(NSAttributedString(string: m.formattedSentDate(), attributes: timestampAttributes))
  689. return text
  690. }
  691. return NSAttributedString(string: m.formattedSentDate(), attributes: timestampAttributes)
  692. }
  693. func updateMessage(_ messageId: Int) {
  694. if let index = messageList.firstIndex(where: { $0.id == messageId }) {
  695. dc_markseen_msgs(mailboxPointer, UnsafePointer([UInt32(messageId)]), 1)
  696. messageList[index] = DcMsg(id: messageId)
  697. // Reload section to update header/footer labels
  698. messagesCollectionView.performBatchUpdates({
  699. messagesCollectionView.reloadSections([index])
  700. if index > 0 {
  701. messagesCollectionView.reloadSections([index - 1])
  702. }
  703. if index < messageList.count - 1 {
  704. messagesCollectionView.reloadSections([index + 1])
  705. }
  706. }, completion: { [weak self] _ in
  707. if self?.isLastSectionVisible() == true {
  708. self?.messagesCollectionView.scrollToBottom(animated: true)
  709. }
  710. })
  711. } else {
  712. let msg = DcMsg(id: messageId)
  713. if msg.chatId == chatId {
  714. insertMessage(msg)
  715. }
  716. }
  717. }
  718. func insertMessage(_ message: DcMsg) {
  719. dc_markseen_msgs(mailboxPointer, UnsafePointer([UInt32(message.id)]), 1)
  720. messageList.append(message)
  721. emptyStateView.isHidden = true
  722. // Reload last section to update header/footer labels and insert a new one
  723. messagesCollectionView.performBatchUpdates({
  724. messagesCollectionView.insertSections([messageList.count - 1])
  725. if messageList.count >= 2 {
  726. messagesCollectionView.reloadSections([messageList.count - 2])
  727. }
  728. }, completion: { [weak self] _ in
  729. if self?.isLastSectionVisible() == true {
  730. self?.messagesCollectionView.scrollToBottom(animated: true)
  731. }
  732. })
  733. }
  734. private func sendImage(_ image: UIImage) {
  735. DispatchQueue.global().async {
  736. if let compressedImage = image.dcCompress() {
  737. // at this point image is compressed by 85% by default
  738. let pixelSize = compressedImage.imageSizeInPixel()
  739. let path = Utils.saveImage(image: compressedImage)
  740. let msg = DcMsg(viewType: DC_MSG_IMAGE)
  741. msg.setFile(filepath: path, mimeType: "image/jpeg")
  742. msg.setDimension(width: pixelSize.width, height: pixelSize.height)
  743. msg.sendInChat(id: self.chatId)
  744. }
  745. }
  746. }
  747. private func sendVoiceMessage(url: NSURL) {
  748. DispatchQueue.global().async {
  749. let msg = DcMsg(viewType: DC_MSG_VOICE)
  750. msg.setFile(filepath: url.relativePath, mimeType: "audio/m4a")
  751. msg.sendInChat(id: self.chatId)
  752. }
  753. }
  754. private func sendVideo(url: NSURL) {
  755. DispatchQueue.global().async {
  756. let msg = DcMsg(viewType: DC_MSG_VIDEO)
  757. msg.setFile(filepath: url.relativePath, mimeType: "video/mp4")
  758. msg.sendInChat(id: self.chatId)
  759. }
  760. }
  761. private func sendImage(url: NSURL) {
  762. if let data = try? Data(contentsOf: url as URL) {
  763. if let image = UIImage(data: data) {
  764. sendImage(image)
  765. }
  766. }
  767. }
  768. func isLastSectionVisible() -> Bool {
  769. guard !messageList.isEmpty else { return false }
  770. let lastIndexPath = IndexPath(item: 0, section: messageList.count - 1)
  771. return messagesCollectionView.indexPathsForVisibleItems.contains(lastIndexPath)
  772. }
  773. }
  774. // MARK: - MessagesDisplayDelegate
  775. extension ChatViewController: MessagesDisplayDelegate {
  776. // MARK: - Text Messages
  777. func textColor(for _: MessageType, at _: IndexPath, in _: MessagesCollectionView) -> UIColor {
  778. return DcColors.defaultTextColor
  779. }
  780. // MARK: - All Messages
  781. func backgroundColor(for message: MessageType, at _: IndexPath, in _: MessagesCollectionView) -> UIColor {
  782. return isFromCurrentSender(message: message) ? DcColors.messagePrimaryColor : DcColors.messageSecondaryColor
  783. }
  784. func messageStyle(for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> MessageStyle {
  785. if isInfoMessage(at: indexPath) {
  786. return .custom { view in
  787. view.style = .none
  788. view.backgroundColor = DcColors.systemMessageBackgroundColor
  789. let radius: CGFloat = 16
  790. let path = UIBezierPath(roundedRect: view.bounds,
  791. byRoundingCorners: UIRectCorner.allCorners,
  792. cornerRadii: CGSize(width: radius, height: radius))
  793. let mask = CAShapeLayer()
  794. mask.path = path.cgPath
  795. view.layer.mask = mask
  796. view.center.x = self.view.center.x
  797. }
  798. }
  799. var corners: UIRectCorner = []
  800. if isFromCurrentSender(message: message) {
  801. corners.formUnion(.topLeft)
  802. corners.formUnion(.bottomLeft)
  803. if !isPreviousMessageSameSender(at: indexPath) {
  804. corners.formUnion(.topRight)
  805. }
  806. if !isNextMessageSameSender(at: indexPath) {
  807. corners.formUnion(.bottomRight)
  808. }
  809. } else {
  810. corners.formUnion(.topRight)
  811. corners.formUnion(.bottomRight)
  812. if !isPreviousMessageSameSender(at: indexPath) {
  813. corners.formUnion(.topLeft)
  814. }
  815. if !isNextMessageSameSender(at: indexPath) {
  816. corners.formUnion(.bottomLeft)
  817. }
  818. }
  819. return .custom { view in
  820. let radius: CGFloat = 16
  821. let path = UIBezierPath(roundedRect: view.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
  822. let mask = CAShapeLayer()
  823. mask.path = path.cgPath
  824. view.layer.mask = mask
  825. }
  826. }
  827. func configureAvatarView(_ avatarView: AvatarView, for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) {
  828. let message = messageList[indexPath.section]
  829. let contact = message.fromContact
  830. let avatar = Avatar(image: contact.profileImage, initials: Utils.getInitials(inputName: contact.displayName))
  831. avatarView.set(avatar: avatar)
  832. avatarView.isHidden = isAvatarHidden(at: indexPath)
  833. avatarView.backgroundColor = contact.color
  834. }
  835. func enabledDetectors(for _: MessageType, at _: IndexPath, in _: MessagesCollectionView) -> [DetectorType] {
  836. return [.url, .phoneNumber]
  837. }
  838. func detectorAttributes(for detector: DetectorType, and message: MessageType, at indexPath: IndexPath) -> [NSAttributedString.Key: Any] {
  839. return [ NSAttributedString.Key.foregroundColor: DcColors.defaultTextColor,
  840. NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue,
  841. NSAttributedString.Key.underlineColor: DcColors.defaultTextColor ]
  842. }
  843. }
  844. // MARK: - MessagesLayoutDelegate
  845. extension ChatViewController: MessagesLayoutDelegate {
  846. func cellTopLabelHeight(for _: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> CGFloat {
  847. if isTimeLabelVisible(at: indexPath) {
  848. return 18
  849. }
  850. return 0
  851. }
  852. func messageTopLabelHeight(for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> CGFloat {
  853. if isInfoMessage(at: indexPath) {
  854. return 0
  855. }
  856. if !isPreviousMessageSameSender(at: indexPath) {
  857. return 40
  858. } else if isMessageForwarded(at: indexPath) {
  859. return 20
  860. }
  861. return 0
  862. }
  863. func messageBottomLabelHeight(for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> CGFloat {
  864. if isInfoMessage(at: indexPath) {
  865. return 0
  866. }
  867. if !isImmediateNextMessageSameSender(at: indexPath) {
  868. return 16
  869. }
  870. return 0
  871. }
  872. func heightForLocation(message _: MessageType, at _: IndexPath, with _: CGFloat, in _: MessagesCollectionView) -> CGFloat {
  873. return 40
  874. }
  875. func footerViewSize(for _: MessageType, at _: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGSize {
  876. return CGSize(width: messagesCollectionView.bounds.width, height: 20)
  877. }
  878. @objc private func clipperButtonPressed() {
  879. showClipperOptions()
  880. }
  881. private func showClipperOptions() {
  882. let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
  883. let galleryAction = PhotoPickerAlertAction(title: String.localized("gallery"), style: .default, handler: galleryButtonPressed(_:))
  884. let cameraAction = PhotoPickerAlertAction(title: String.localized("camera"), style: .default, handler: cameraButtonPressed(_:))
  885. let voiceMessageAction = UIAlertAction(title: String.localized("voice_message"), style: .default, handler: voiceMessageButtonPressed(_:))
  886. alert.addAction(cameraAction)
  887. alert.addAction(galleryAction)
  888. alert.addAction(voiceMessageAction)
  889. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  890. self.present(alert, animated: true, completion: nil)
  891. }
  892. private func voiceMessageButtonPressed(_ action: UIAlertAction) {
  893. coordinator?.showVoiceMessageRecorder(delegate: self)
  894. }
  895. private func cameraButtonPressed(_ action: UIAlertAction) {
  896. coordinator?.showCameraViewController(delegate: self)
  897. }
  898. private func galleryButtonPressed(_ action: UIAlertAction) {
  899. coordinator?.showPhotoVideoLibrary(delegate: self)
  900. }
  901. }
  902. // MARK: - MessageCellDelegate
  903. extension ChatViewController: MessageCellDelegate {
  904. @objc func didTapMessage(in cell: MessageCollectionViewCell) {
  905. if let indexPath = messagesCollectionView.indexPath(for: cell) {
  906. let message = messageList[indexPath.section]
  907. if message.isSetupMessage {
  908. didTapAsm(msg: message, orgText: "")
  909. } else if let url = message.fileURL {
  910. // find all other messages with same message type
  911. var previousUrls: [URL] = []
  912. var nextUrls: [URL] = []
  913. var prev: Int = Int(dc_get_next_media(mailboxPointer, UInt32(message.id), -1, Int32(message.type), 0, 0))
  914. while prev != 0 {
  915. let prevMessage = DcMsg(id: prev)
  916. if let url = prevMessage.fileURL {
  917. previousUrls.insert(url, at: 0)
  918. }
  919. prev = Int(dc_get_next_media(mailboxPointer, UInt32(prevMessage.id), -1, Int32(prevMessage.type), 0, 0))
  920. }
  921. var next: Int = Int(dc_get_next_media(mailboxPointer, UInt32(message.id), 1, Int32(message.type), 0, 0))
  922. while next != 0 {
  923. let nextMessage = DcMsg(id: next)
  924. if let url = nextMessage.fileURL {
  925. nextUrls.insert(url, at: 0)
  926. }
  927. next = Int(dc_get_next_media(mailboxPointer, UInt32(nextMessage.id), 1, Int32(nextMessage.type), 0, 0))
  928. }
  929. // these are the files user will be able to swipe trough
  930. let mediaUrls: [URL] = previousUrls + [url] + nextUrls
  931. previewController = PreviewController(currentIndex: previousUrls.count, urls: mediaUrls)
  932. present(previewController!.qlController, animated: true)
  933. }
  934. }
  935. }
  936. private func didTapAsm(msg: DcMsg, orgText: String) {
  937. let inputDlg = UIAlertController(
  938. title: String.localized("autocrypt_continue_transfer_title"),
  939. message: String.localized("autocrypt_continue_transfer_please_enter_code"),
  940. preferredStyle: .alert)
  941. inputDlg.addTextField(configurationHandler: { (textField) in
  942. textField.placeholder = msg.setupCodeBegin + ".."
  943. textField.text = orgText
  944. textField.keyboardType = UIKeyboardType.numbersAndPunctuation // allows entering spaces; decimalPad would require a mask to keep things readable
  945. })
  946. inputDlg.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  947. let okAction = UIAlertAction(title: String.localized("ok"), style: .default, handler: { _ in
  948. let textField = inputDlg.textFields![0]
  949. let modText = textField.text ?? ""
  950. let success = self.dcContext.continueKeyTransfer(msgId: msg.id, setupCode: modText)
  951. let alert = UIAlertController(
  952. title: String.localized("autocrypt_continue_transfer_title"),
  953. message: String.localized(success ? "autocrypt_continue_transfer_succeeded" : "autocrypt_bad_setup_code"),
  954. preferredStyle: .alert)
  955. if success {
  956. alert.addAction(UIAlertAction(title: String.localized("ok"), style: .default, handler: nil))
  957. } else {
  958. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  959. let retryAction = UIAlertAction(title: String.localized("autocrypt_continue_transfer_retry"), style: .default, handler: { _ in
  960. self.didTapAsm(msg: msg, orgText: modText)
  961. })
  962. alert.addAction(retryAction)
  963. alert.preferredAction = retryAction
  964. }
  965. self.navigationController?.present(alert, animated: true, completion: nil)
  966. })
  967. inputDlg.addAction(okAction)
  968. inputDlg.preferredAction = okAction // without setting preferredAction, cancel become shown *bold* as the preferred action
  969. navigationController?.present(inputDlg, animated: true, completion: nil)
  970. }
  971. @objc func didTapAvatar(in cell: MessageCollectionViewCell) {
  972. if let indexPath = messagesCollectionView.indexPath(for: cell) {
  973. let message = messageList[indexPath.section]
  974. let chat = DcChat(id: chatId)
  975. coordinator?.showContactDetail(of: message.fromContact.id, in: chat.chatType)
  976. }
  977. }
  978. @objc(didTapCellTopLabelIn:) func didTapCellTopLabel(in _: MessageCollectionViewCell) {
  979. logger.info("Top label tapped")
  980. }
  981. @objc(didTapCellBottomLabelIn:) func didTapCellBottomLabel(in _: MessageCollectionViewCell) {
  982. print("Bottom label tapped")
  983. }
  984. func didTapPlayButton(in cell: AudioMessageCell) {
  985. guard let indexPath = messagesCollectionView.indexPath(for: cell),
  986. let message = messagesCollectionView.messagesDataSource?.messageForItem(at: indexPath, in: messagesCollectionView) else {
  987. print("Failed to identify message when audio cell receive tap gesture")
  988. return
  989. }
  990. guard audioController.state != .stopped else {
  991. // There is no audio sound playing - prepare to start playing for given audio message
  992. audioController.playSound(for: message, in: cell)
  993. return
  994. }
  995. if audioController.playingMessage?.messageId == message.messageId {
  996. // tap occur in the current cell that is playing audio sound
  997. if audioController.state == .playing {
  998. audioController.pauseSound(for: message, in: cell)
  999. } else {
  1000. audioController.resumeSound()
  1001. }
  1002. } else {
  1003. // tap occur in a difference cell that the one is currently playing sound. First stop currently playing and start the sound for given message
  1004. audioController.stopAnyOngoingPlaying()
  1005. audioController.playSound(for: message, in: cell)
  1006. }
  1007. }
  1008. func didStartAudio(in cell: AudioMessageCell) {
  1009. print("audio started")
  1010. }
  1011. func didStopAudio(in cell: AudioMessageCell) {
  1012. print("audio stopped")
  1013. }
  1014. func didPauseAudio(in cell: AudioMessageCell) {
  1015. print("audio paused")
  1016. }
  1017. @objc func didTapBackground(in cell: MessageCollectionViewCell) {
  1018. print("background of message tapped")
  1019. }
  1020. }
  1021. // MARK: - MessageLabelDelegate
  1022. extension ChatViewController: MessageLabelDelegate {
  1023. func didSelectPhoneNumber(_ phoneNumber: String) {
  1024. logger.info("phone open", phoneNumber)
  1025. if let escapedPhoneNumber = phoneNumber.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
  1026. if let url = NSURL(string: "tel:\(escapedPhoneNumber)") {
  1027. UIApplication.shared.open(url as URL)
  1028. }
  1029. }
  1030. }
  1031. func didSelectURL(_ url: URL) {
  1032. if Utils.isEmail(url: url) {
  1033. print("tapped on contact")
  1034. let email = Utils.getEmailFrom(url)
  1035. self.askToChatWith(email: email)
  1036. ///TODO: implement handling
  1037. } else {
  1038. UIApplication.shared.open(url)
  1039. }
  1040. }
  1041. }
  1042. // MARK: - LocationMessageDisplayDelegate
  1043. /*
  1044. extension ChatViewController: LocationMessageDisplayDelegate {
  1045. func annotationViewForLocation(message: MessageType, at indexPath: IndexPath, in messageCollectionView: MessagesCollectionView) -> MKAnnotationView? {
  1046. let annotationView = MKAnnotationView(annotation: nil, reuseIdentifier: nil)
  1047. let pinImage = #imageLiteral(resourceName: "ic_block_36pt").withRenderingMode(.alwaysTemplate)
  1048. annotationView.image = pinImage
  1049. annotationView.centerOffset = CGPoint(x: 0, y: -pinImage.size.height / 2)
  1050. return annotationView
  1051. }
  1052. func animationBlockForLocation(message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> ((UIImageView) -> Void)? {
  1053. return { view in
  1054. view.layer.transform = CATransform3DMakeScale(0, 0, 0)
  1055. view.alpha = 0.0
  1056. UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0, options: [], animations: {
  1057. view.layer.transform = CATransform3DIdentity
  1058. view.alpha = 1.0
  1059. }, completion: nil)
  1060. }
  1061. }
  1062. }
  1063. */
  1064. // MARK: - MessageInputBarDelegate
  1065. extension ChatViewController: InputBarAccessoryViewDelegate {
  1066. func inputBar(_ inputBar: InputBarAccessoryView, didPressSendButtonWith text: String) {
  1067. DispatchQueue.global().async {
  1068. dc_send_text_msg(mailboxPointer, UInt32(self.chatId), text)
  1069. }
  1070. inputBar.inputTextView.text = String()
  1071. }
  1072. }
  1073. /*
  1074. extension ChatViewController: MessageInputBarDelegate {
  1075. }
  1076. */
  1077. // MARK: - MessageCollectionViewCell
  1078. extension MessageCollectionViewCell {
  1079. @objc func messageForward(_ sender: Any?) {
  1080. // Get the collectionView
  1081. if let collectionView = self.superview as? UICollectionView {
  1082. // Get indexPath
  1083. if let indexPath = collectionView.indexPath(for: self) {
  1084. // Trigger action
  1085. collectionView.delegate?.collectionView?(collectionView,
  1086. performAction: #selector(MessageCollectionViewCell.messageForward(_:)),
  1087. forItemAt: indexPath, withSender: sender)
  1088. }
  1089. }
  1090. }
  1091. @objc func messageDelete(_ sender: Any?) {
  1092. // Get the collectionView
  1093. if let collectionView = self.superview as? UICollectionView {
  1094. // Get indexPath
  1095. if let indexPath = collectionView.indexPath(for: self) {
  1096. // Trigger action
  1097. collectionView.delegate?.collectionView?(collectionView,
  1098. performAction: #selector(MessageCollectionViewCell.messageDelete(_:)),
  1099. forItemAt: indexPath, withSender: sender)
  1100. }
  1101. }
  1102. }
  1103. @objc func messageInfo(_ sender: Any?) {
  1104. // Get the collectionView
  1105. if let collectionView = self.superview as? UICollectionView {
  1106. // Get indexPath
  1107. if let indexPath = collectionView.indexPath(for: self) {
  1108. // Trigger action
  1109. collectionView.delegate?.collectionView?(collectionView,
  1110. performAction: #selector(MessageCollectionViewCell.messageInfo(_:)),
  1111. forItemAt: indexPath, withSender: sender)
  1112. }
  1113. }
  1114. }
  1115. }