ChatViewController.swift 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207
  1. import MapKit
  2. import QuickLook
  3. import UIKit
  4. import InputBarAccessoryView
  5. import AVFoundation
  6. import DcCore
  7. import SDWebImage
  8. class ChatViewController: UITableViewController {
  9. var dcContext: DcContext
  10. private var draftMessage: DcMsg?
  11. let outgoingAvatarOverlap: CGFloat = 17.5
  12. let loadCount = 30
  13. let chatId: Int
  14. var messageIds: [Int] = []
  15. var msgChangedObserver: Any?
  16. var incomingMsgObserver: Any?
  17. var ephemeralTimerModifiedObserver: Any?
  18. var lastContentOffset: CGFloat = -1
  19. var isKeyboardShown: Bool = false
  20. lazy var isGroupChat: Bool = {
  21. return dcContext.getChat(chatId: chatId).isGroup
  22. }()
  23. lazy var draft: DraftModel = {
  24. let draft = DraftModel(chatId: chatId)
  25. return draft
  26. }()
  27. /// The `InputBarAccessoryView` used as the `inputAccessoryView` in the view controller.
  28. open var messageInputBar = InputBarAccessoryView()
  29. lazy var quotePreview: QuotePreview = {
  30. let view = QuotePreview()
  31. view.delegate = self
  32. view.translatesAutoresizingMaskIntoConstraints = false
  33. return view
  34. }()
  35. open override var shouldAutorotate: Bool {
  36. return false
  37. }
  38. private weak var timer: Timer?
  39. lazy var navBarTap: UITapGestureRecognizer = {
  40. UITapGestureRecognizer(target: self, action: #selector(chatProfilePressed))
  41. }()
  42. private var locationStreamingItem: UIBarButtonItem = {
  43. let indicator = LocationStreamingIndicator()
  44. return UIBarButtonItem(customView: indicator)
  45. }()
  46. private lazy var muteItem: UIBarButtonItem = {
  47. let imageView = UIImageView()
  48. imageView.tintColor = DcColors.defaultTextColor
  49. imageView.image = #imageLiteral(resourceName: "volume_off").withRenderingMode(.alwaysTemplate)
  50. imageView.translatesAutoresizingMaskIntoConstraints = false
  51. imageView.heightAnchor.constraint(equalToConstant: 20).isActive = true
  52. imageView.widthAnchor.constraint(equalToConstant: 20).isActive = true
  53. return UIBarButtonItem(customView: imageView)
  54. }()
  55. private lazy var ephemeralMessageItem: UIBarButtonItem = {
  56. let imageView = UIImageView()
  57. imageView.tintColor = DcColors.defaultTextColor
  58. imageView.image = #imageLiteral(resourceName: "ephemeral_timer").withRenderingMode(.alwaysTemplate)
  59. imageView.translatesAutoresizingMaskIntoConstraints = false
  60. imageView.heightAnchor.constraint(equalToConstant: 20).isActive = true
  61. imageView.widthAnchor.constraint(equalToConstant: 20).isActive = true
  62. return UIBarButtonItem(customView: imageView)
  63. }()
  64. private lazy var badgeItem: UIBarButtonItem = {
  65. let badge: InitialsBadge
  66. let chat = dcContext.getChat(chatId: chatId)
  67. if let image = chat.profileImage {
  68. badge = InitialsBadge(image: image, size: 28, accessibilityLabel: String.localized("menu_view_profile"))
  69. } else {
  70. badge = InitialsBadge(
  71. name: chat.name,
  72. color: chat.color,
  73. size: 28,
  74. accessibilityLabel: String.localized("menu_view_profile")
  75. )
  76. badge.setLabelFont(UIFont.systemFont(ofSize: 14))
  77. }
  78. badge.setVerified(chat.isProtected)
  79. badge.accessibilityTraits = .button
  80. return UIBarButtonItem(customView: badge)
  81. }()
  82. /// The `BasicAudioController` controll the AVAudioPlayer state (play, pause, stop) and update audio cell UI accordingly.
  83. private lazy var audioController = AudioController(dcContext: dcContext, chatId: chatId)
  84. private var disableWriting: Bool
  85. private var showNamesAboveMessage: Bool
  86. var showCustomNavBar = true
  87. var highlightedMsg: Int?
  88. private lazy var mediaPicker: MediaPicker? = {
  89. let mediaPicker = MediaPicker(navigationController: navigationController)
  90. mediaPicker.delegate = self
  91. return mediaPicker
  92. }()
  93. var emptyStateView: EmptyStateLabel = {
  94. let view = EmptyStateLabel()
  95. return view
  96. }()
  97. init(dcContext: DcContext, chatId: Int, highlightedMsg: Int? = nil) {
  98. let dcChat = dcContext.getChat(chatId: chatId)
  99. self.dcContext = dcContext
  100. self.chatId = chatId
  101. self.disableWriting = !dcChat.canSend
  102. self.showNamesAboveMessage = dcChat.isGroup
  103. self.highlightedMsg = highlightedMsg
  104. super.init(nibName: nil, bundle: nil)
  105. hidesBottomBarWhenPushed = true
  106. }
  107. required init?(coder _: NSCoder) {
  108. fatalError("init(coder:) has not been implemented")
  109. }
  110. override func loadView() {
  111. self.tableView = ChatTableView(messageInputBar: self.disableWriting ? nil : messageInputBar)
  112. self.tableView.delegate = self
  113. self.tableView.dataSource = self
  114. self.view = self.tableView
  115. }
  116. override func viewDidLoad() {
  117. tableView.register(TextMessageCell.self, forCellReuseIdentifier: "text")
  118. tableView.register(ImageTextCell.self, forCellReuseIdentifier: "image")
  119. tableView.register(FileTextCell.self, forCellReuseIdentifier: "file")
  120. tableView.register(InfoMessageCell.self, forCellReuseIdentifier: "info")
  121. tableView.register(AudioMessageCell.self, forCellReuseIdentifier: "audio")
  122. tableView.rowHeight = UITableView.automaticDimension
  123. tableView.separatorStyle = .none
  124. super.viewDidLoad()
  125. if !dcContext.isConfigured() {
  126. // TODO: display message about nothing being configured
  127. return
  128. }
  129. configureEmptyStateView()
  130. if !disableWriting {
  131. configureMessageInputBar()
  132. draft.parse(draftMsg: dcContext.getDraft(chatId: chatId))
  133. messageInputBar.inputTextView.text = draft.draftText
  134. configureDraftArea(draft: draft)
  135. }
  136. let notificationCenter = NotificationCenter.default
  137. notificationCenter.addObserver(self,
  138. selector: #selector(saveDraft),
  139. name: UIApplication.willResignActiveNotification,
  140. object: nil)
  141. notificationCenter.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
  142. notificationCenter.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
  143. notificationCenter.addObserver(self, selector: #selector(keyboardDidShow(_:)), name: UIResponder.keyboardDidShowNotification, object: nil)
  144. prepareContextMenu()
  145. }
  146. @objc func keyboardDidShow(_ notification: Notification) {
  147. if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
  148. if keyboardSize.height > tableView.inputAccessoryView?.frame.height ?? 0 {
  149. isKeyboardShown = true
  150. }
  151. }
  152. }
  153. @objc func keyboardWillShow(_ notification: Notification) {
  154. if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
  155. if keyboardSize.height > tableView.inputAccessoryView?.frame.height ?? 0 {
  156. if self.isLastRowVisible() {
  157. DispatchQueue.main.async { [weak self] in
  158. self?.scrollToBottom(animated: true)
  159. }
  160. }
  161. }
  162. }
  163. }
  164. @objc func keyboardWillHide(_ notification: Notification) {
  165. isKeyboardShown = false
  166. }
  167. private func startTimer() {
  168. timer?.invalidate()
  169. timer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { [weak self] _ in
  170. //reload table
  171. DispatchQueue.main.async {
  172. guard let self = self else { return }
  173. self.messageIds = self.getMessageIds()
  174. self.tableView.reloadData()
  175. }
  176. }
  177. }
  178. private func stopTimer() {
  179. timer?.invalidate()
  180. }
  181. private func configureEmptyStateView() {
  182. view.addSubview(emptyStateView)
  183. emptyStateView.translatesAutoresizingMaskIntoConstraints = false
  184. emptyStateView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 40).isActive = true
  185. emptyStateView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -40).isActive = true
  186. emptyStateView.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor).isActive = true
  187. emptyStateView.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor).isActive = true
  188. }
  189. override func viewWillAppear(_ animated: Bool) {
  190. super.viewWillAppear(animated)
  191. self.tableView.becomeFirstResponder()
  192. // this will be removed in viewWillDisappear
  193. navigationController?.navigationBar.addGestureRecognizer(navBarTap)
  194. if showCustomNavBar {
  195. updateTitle(chat: dcContext.getChat(chatId: chatId))
  196. }
  197. let nc = NotificationCenter.default
  198. msgChangedObserver = nc.addObserver(
  199. forName: dcNotificationChanged,
  200. object: nil,
  201. queue: OperationQueue.main
  202. ) { [weak self] notification in
  203. guard let self = self else { return }
  204. if let ui = notification.userInfo {
  205. if self.disableWriting {
  206. // always refresh, as we can't check currently
  207. self.refreshMessages()
  208. } else if let id = ui["message_id"] as? Int {
  209. if id > 0 {
  210. self.updateMessage(id)
  211. } else {
  212. // change might be a deletion
  213. self.refreshMessages()
  214. }
  215. }
  216. if self.showCustomNavBar {
  217. self.updateTitle(chat: self.dcContext.getChat(chatId: self.chatId))
  218. }
  219. }
  220. }
  221. incomingMsgObserver = nc.addObserver(
  222. forName: dcNotificationIncoming,
  223. object: nil, queue: OperationQueue.main
  224. ) { [weak self] notification in
  225. guard let self = self else { return }
  226. if let ui = notification.userInfo {
  227. if self.chatId == ui["chat_id"] as? Int {
  228. if let id = ui["message_id"] as? Int {
  229. if id > 0 {
  230. self.insertMessage(DcMsg(id: id))
  231. }
  232. }
  233. }
  234. }
  235. }
  236. ephemeralTimerModifiedObserver = nc.addObserver(
  237. forName: dcEphemeralTimerModified,
  238. object: nil, queue: OperationQueue.main
  239. ) { [weak self] _ in
  240. guard let self = self else { return }
  241. self.updateTitle(chat: self.dcContext.getChat(chatId: self.chatId))
  242. }
  243. loadMessages()
  244. if RelayHelper.sharedInstance.isForwarding() {
  245. askToForwardMessage()
  246. }
  247. }
  248. override func viewDidAppear(_ animated: Bool) {
  249. super.viewDidAppear(animated)
  250. AppStateRestorer.shared.storeLastActiveChat(chatId: chatId)
  251. // things that do not affect the chatview
  252. // and are delayed after the view is displayed
  253. DispatchQueue.global(qos: .background).async { [weak self] in
  254. guard let self = self else { return }
  255. self.dcContext.marknoticedChat(chatId: self.chatId)
  256. }
  257. startTimer()
  258. }
  259. override func viewWillDisappear(_ animated: Bool) {
  260. super.viewWillDisappear(animated)
  261. // the navigationController will be used when chatDetail is pushed, so we have to remove that gestureRecognizer
  262. navigationController?.navigationBar.removeGestureRecognizer(navBarTap)
  263. }
  264. override func viewDidDisappear(_ animated: Bool) {
  265. super.viewDidDisappear(animated)
  266. AppStateRestorer.shared.resetLastActiveChat()
  267. saveDraft()
  268. let nc = NotificationCenter.default
  269. if let msgChangedObserver = self.msgChangedObserver {
  270. nc.removeObserver(msgChangedObserver)
  271. }
  272. if let incomingMsgObserver = self.incomingMsgObserver {
  273. nc.removeObserver(incomingMsgObserver)
  274. }
  275. if let ephemeralTimerModifiedObserver = self.ephemeralTimerModifiedObserver {
  276. nc.removeObserver(ephemeralTimerModifiedObserver)
  277. }
  278. audioController.stopAnyOngoingPlaying()
  279. stopTimer()
  280. }
  281. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  282. let lastSectionVisibleBeforeTransition = self.isLastRowVisible()
  283. coordinator.animate(
  284. alongsideTransition: { [weak self] _ in
  285. guard let self = self else { return }
  286. if self.showCustomNavBar {
  287. self.navigationItem.setRightBarButton(self.badgeItem, animated: true)
  288. }
  289. if lastSectionVisibleBeforeTransition {
  290. self.scrollToBottom(animated: false)
  291. }
  292. },
  293. completion: {[weak self] _ in
  294. guard let self = self else { return }
  295. self.updateTitle(chat: self.dcContext.getChat(chatId: self.chatId))
  296. if lastSectionVisibleBeforeTransition {
  297. DispatchQueue.main.async { [weak self] in
  298. self?.tableView.reloadData()
  299. self?.scrollToBottom(animated: false)
  300. }
  301. }
  302. }
  303. )
  304. super.viewWillTransition(to: size, with: coordinator)
  305. }
  306. /// UITableView methods
  307. override func numberOfSections(in tableView: UITableView) -> Int {
  308. return 1
  309. }
  310. override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
  311. return messageIds.count //viewModel.numberOfRowsIn(section: section)
  312. }
  313. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  314. _ = handleUIMenu()
  315. let id = messageIds[indexPath.row]
  316. let message = DcMsg(id: id)
  317. if message.isInfo {
  318. let cell = tableView.dequeueReusableCell(withIdentifier: "info", for: indexPath) as? InfoMessageCell ?? InfoMessageCell()
  319. cell.update(msg: message)
  320. return cell
  321. }
  322. let cell: BaseMessageCell
  323. if message.type == DC_MSG_IMAGE || message.type == DC_MSG_GIF || message.type == DC_MSG_VIDEO {
  324. cell = tableView.dequeueReusableCell(withIdentifier: "image", for: indexPath) as? ImageTextCell ?? ImageTextCell()
  325. } else if message.type == DC_MSG_FILE {
  326. if message.isSetupMessage {
  327. cell = tableView.dequeueReusableCell(withIdentifier: "text", for: indexPath) as? TextMessageCell ?? TextMessageCell()
  328. message.text = String.localized("autocrypt_asm_click_body")
  329. } else {
  330. cell = tableView.dequeueReusableCell(withIdentifier: "file", for: indexPath) as? FileTextCell ?? FileTextCell()
  331. }
  332. } else if message.type == DC_MSG_AUDIO || message.type == DC_MSG_VOICE {
  333. let audioMessageCell: AudioMessageCell = tableView.dequeueReusableCell(withIdentifier: "audio",
  334. for: indexPath) as? AudioMessageCell ?? AudioMessageCell()
  335. audioController.update(audioMessageCell, with: message.id)
  336. cell = audioMessageCell
  337. } else {
  338. cell = tableView.dequeueReusableCell(withIdentifier: "text", for: indexPath) as? TextMessageCell ?? TextMessageCell()
  339. }
  340. cell.baseDelegate = self
  341. cell.update(msg: message,
  342. messageStyle: configureMessageStyle(for: message, at: indexPath),
  343. isAvatarVisible: configureAvatarVisibility(for: message, at: indexPath),
  344. isGroup: isGroupChat)
  345. return cell
  346. }
  347. public override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
  348. lastContentOffset = scrollView.contentOffset.y
  349. }
  350. public override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  351. if !decelerate {
  352. markSeenMessagesInVisibleArea()
  353. }
  354. if scrollView.contentOffset.y < lastContentOffset {
  355. if isKeyboardShown {
  356. tableView.endEditing(true)
  357. tableView.becomeFirstResponder()
  358. }
  359. }
  360. lastContentOffset = -1
  361. }
  362. public override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  363. markSeenMessagesInVisibleArea()
  364. }
  365. private func configureDraftArea(draft: DraftModel) {
  366. quotePreview.configure(draft: draft)
  367. // setStackViewItems recalculates the proper messageInputBar height
  368. messageInputBar.setStackViewItems([quotePreview], forStack: .top, animated: true)
  369. }
  370. override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
  371. if disableWriting {
  372. return nil
  373. }
  374. let action = UIContextualAction(style: .normal, title: nil,
  375. handler: { (_, _, completionHandler) in
  376. let message = DcMsg(id: self.messageIds[indexPath.row])
  377. self.draft.setQuote(quotedMsg: message)
  378. self.configureDraftArea(draft: self.draft)
  379. self.messageInputBar.inputTextView.becomeFirstResponder()
  380. completionHandler(true)
  381. })
  382. if #available(iOS 12.0, *) {
  383. action.image = UIImage(named: traitCollection.userInterfaceStyle == .light ? "ic_reply_black" : "ic_reply")
  384. } else {
  385. action.image = UIImage(named: "ic_reply_black")
  386. }
  387. action.image?.accessibilityTraits = .button
  388. action.image?.accessibilityLabel = String.localized("menu_reply")
  389. action.backgroundColor = DcColors.chatBackgroundColor
  390. let configuration = UISwipeActionsConfiguration(actions: [action])
  391. return configuration
  392. }
  393. func markSeenMessagesInVisibleArea() {
  394. if let indexPaths = tableView.indexPathsForVisibleRows {
  395. let visibleMessagesIds = indexPaths.map { UInt32(messageIds[$0.row]) }
  396. if !visibleMessagesIds.isEmpty {
  397. DispatchQueue.global(qos: .background).async { [weak self] in
  398. self?.dcContext.markSeenMessages(messageIds: visibleMessagesIds)
  399. }
  400. }
  401. }
  402. }
  403. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  404. let messageId = messageIds[indexPath.row]
  405. let message = DcMsg(id: messageId)
  406. if message.isSetupMessage {
  407. didTapAsm(msg: message, orgText: "")
  408. } else if message.type == DC_MSG_FILE ||
  409. message.type == DC_MSG_AUDIO ||
  410. message.type == DC_MSG_VOICE {
  411. showMediaGalleryFor(message: message)
  412. }
  413. _ = handleUIMenu()
  414. }
  415. func configureAvatarVisibility(for message: DcMsg, at indexPath: IndexPath) -> Bool {
  416. return isGroupChat && !message.isFromCurrentSender
  417. }
  418. func configureMessageStyle(for message: DcMsg, at indexPath: IndexPath) -> UIRectCorner {
  419. var corners: UIRectCorner = []
  420. if message.isFromCurrentSender {
  421. corners.formUnion(.topLeft)
  422. corners.formUnion(.bottomLeft)
  423. corners.formUnion(.topRight)
  424. } else {
  425. corners.formUnion(.topRight)
  426. corners.formUnion(.bottomRight)
  427. corners.formUnion(.topLeft)
  428. }
  429. return corners
  430. }
  431. private func getBackgroundColor(for currentMessage: DcMsg) -> UIColor {
  432. return currentMessage.isFromCurrentSender ? DcColors.messagePrimaryColor : DcColors.messageSecondaryColor
  433. }
  434. private func updateTitle(chat: DcChat) {
  435. let titleView = ChatTitleView()
  436. var subtitle = "ErrSubtitle"
  437. let chatContactIds = chat.contactIds
  438. if chat.isGroup {
  439. subtitle = String.localized(stringID: "n_members", count: chatContactIds.count)
  440. } else if chatContactIds.count >= 1 {
  441. if chat.isDeviceTalk {
  442. subtitle = String.localized("device_talk_subtitle")
  443. } else if chat.isSelfTalk {
  444. subtitle = String.localized("chat_self_talk_subtitle")
  445. } else {
  446. subtitle = DcContact(id: chatContactIds[0]).email
  447. }
  448. }
  449. titleView.updateTitleView(title: chat.name, subtitle: subtitle)
  450. navigationItem.titleView = titleView
  451. var rightBarButtonItems = [badgeItem]
  452. if chat.isSendingLocations {
  453. rightBarButtonItems.append(locationStreamingItem)
  454. }
  455. if chat.isMuted {
  456. rightBarButtonItems.append(muteItem)
  457. }
  458. if dcContext.getChatEphemeralTimer(chatId: chat.id) > 0 {
  459. rightBarButtonItems.append(ephemeralMessageItem)
  460. }
  461. navigationItem.rightBarButtonItems = rightBarButtonItems
  462. }
  463. // TODO: is the delay of one second needed?
  464. @objc
  465. private func refreshMessages() {
  466. DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + 1) {
  467. DispatchQueue.main.async { [weak self] in
  468. guard let self = self else { return }
  469. self.messageIds = self.getMessageIds()
  470. self.tableView.reloadData()
  471. if self.isLastRowVisible() {
  472. self.scrollToBottom(animated: true)
  473. }
  474. self.showEmptyStateView(self.messageIds.isEmpty)
  475. }
  476. }
  477. }
  478. private func loadMessages() {
  479. DispatchQueue.global(qos: .userInitiated).async {
  480. DispatchQueue.main.async { [weak self] in
  481. guard let self = self else { return }
  482. let wasLastRowVisible = self.isLastRowVisible()
  483. let wasMessageIdsEmpty = self.messageIds.isEmpty
  484. // update message ids
  485. self.messageIds = self.getMessageIds()
  486. self.tableView.reloadData()
  487. if let msgId = self.highlightedMsg, let msgPosition = self.messageIds.firstIndex(of: msgId) {
  488. self.tableView.scrollToRow(at: IndexPath(row: msgPosition, section: 0), at: .top, animated: false)
  489. self.highlightedMsg = nil
  490. } else if wasMessageIdsEmpty ||
  491. wasLastRowVisible {
  492. self.scrollToBottom(animated: false)
  493. }
  494. self.showEmptyStateView(self.messageIds.isEmpty)
  495. }
  496. }
  497. }
  498. func isLastRowVisible() -> Bool {
  499. guard !messageIds.isEmpty else { return false }
  500. let lastIndexPath = IndexPath(item: messageIds.count - 1, section: 0)
  501. return tableView.indexPathsForVisibleRows?.contains(lastIndexPath) ?? false
  502. }
  503. func scrollToBottom(animated: Bool) {
  504. if !messageIds.isEmpty {
  505. self.tableView.scrollToRow(at: IndexPath(row: self.messageIds.count - 1, section: 0), at: .bottom, animated: animated)
  506. }
  507. }
  508. private func showEmptyStateView(_ show: Bool) {
  509. if show {
  510. let dcChat = dcContext.getChat(chatId: chatId)
  511. if chatId == DC_CHAT_ID_DEADDROP {
  512. if dcContext.showEmails != DC_SHOW_EMAILS_ALL {
  513. emptyStateView.text = String.localized("chat_no_contact_requests")
  514. } else {
  515. emptyStateView.text = String.localized("chat_no_messages")
  516. }
  517. } else if dcChat.isGroup {
  518. if dcChat.isUnpromoted {
  519. emptyStateView.text = String.localized("chat_new_group_hint")
  520. } else {
  521. emptyStateView.text = String.localized("chat_no_messages")
  522. }
  523. } else if dcChat.isSelfTalk {
  524. emptyStateView.text = String.localized("saved_messages_explain")
  525. } else if dcChat.isDeviceTalk {
  526. emptyStateView.text = String.localized("device_talk_explain")
  527. } else {
  528. emptyStateView.text = String.localizedStringWithFormat(String.localized("chat_no_messages_hint"), dcChat.name, dcChat.name)
  529. }
  530. emptyStateView.isHidden = false
  531. } else {
  532. emptyStateView.isHidden = true
  533. }
  534. }
  535. private func getMessageIds() -> [Int] {
  536. return dcContext.getMessageIds(chatId: chatId)
  537. }
  538. @objc private func saveDraft() {
  539. draft.save(context: dcContext)
  540. }
  541. private func configureMessageInputBar() {
  542. messageInputBar.delegate = self
  543. messageInputBar.inputTextView.tintColor = DcColors.primary
  544. messageInputBar.inputTextView.placeholder = String.localized("chat_input_placeholder")
  545. messageInputBar.separatorLine.isHidden = true
  546. messageInputBar.inputTextView.tintColor = DcColors.primary
  547. messageInputBar.inputTextView.textColor = DcColors.defaultTextColor
  548. messageInputBar.backgroundView.backgroundColor = DcColors.chatBackgroundColor
  549. //scrollsToBottomOnKeyboardBeginsEditing = true
  550. messageInputBar.inputTextView.backgroundColor = DcColors.inputFieldColor
  551. messageInputBar.inputTextView.placeholderTextColor = DcColors.placeholderColor
  552. messageInputBar.inputTextView.textContainerInset = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 38)
  553. messageInputBar.inputTextView.placeholderLabelInsets = UIEdgeInsets(top: 8, left: 20, bottom: 8, right: 38)
  554. messageInputBar.inputTextView.layer.borderColor = UIColor.themeColor(light: UIColor(red: 200 / 255, green: 200 / 255, blue: 200 / 255, alpha: 1),
  555. dark: UIColor(red: 55 / 255, green: 55/255, blue: 55/255, alpha: 1)).cgColor
  556. messageInputBar.inputTextView.layer.borderWidth = 1.0
  557. messageInputBar.inputTextView.layer.cornerRadius = 13.0
  558. messageInputBar.inputTextView.layer.masksToBounds = true
  559. messageInputBar.inputTextView.scrollIndicatorInsets = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0)
  560. configureInputBarItems()
  561. }
  562. private func configureInputBarItems() {
  563. messageInputBar.setLeftStackViewWidthConstant(to: 40, animated: false)
  564. messageInputBar.setRightStackViewWidthConstant(to: 40, animated: false)
  565. let sendButtonImage = UIImage(named: "paper_plane")?.withRenderingMode(.alwaysTemplate)
  566. messageInputBar.sendButton.image = sendButtonImage
  567. messageInputBar.sendButton.accessibilityLabel = String.localized("menu_send")
  568. messageInputBar.sendButton.accessibilityTraits = .button
  569. messageInputBar.sendButton.title = nil
  570. messageInputBar.sendButton.tintColor = UIColor(white: 1, alpha: 1)
  571. messageInputBar.sendButton.layer.cornerRadius = 20
  572. messageInputBar.middleContentViewPadding = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 10)
  573. // this adds a padding between textinputfield and send button
  574. messageInputBar.sendButton.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
  575. messageInputBar.sendButton.setSize(CGSize(width: 40, height: 40), animated: false)
  576. messageInputBar.padding = UIEdgeInsets(top: 6, left: 6, bottom: 6, right: 12)
  577. let leftItems = [
  578. InputBarButtonItem()
  579. .configure {
  580. $0.spacing = .fixed(0)
  581. let clipperIcon = #imageLiteral(resourceName: "ic_attach_file_36pt").withRenderingMode(.alwaysTemplate)
  582. $0.image = clipperIcon
  583. $0.tintColor = DcColors.primary
  584. $0.setSize(CGSize(width: 40, height: 40), animated: false)
  585. $0.accessibilityLabel = String.localized("menu_add_attachment")
  586. $0.accessibilityTraits = .button
  587. }.onSelected {
  588. $0.tintColor = UIColor.themeColor(light: .lightGray, dark: .darkGray)
  589. }.onDeselected {
  590. $0.tintColor = DcColors.primary
  591. }.onTouchUpInside { [weak self] _ in
  592. self?.clipperButtonPressed()
  593. }
  594. ]
  595. messageInputBar.setStackViewItems(leftItems, forStack: .left, animated: false)
  596. // This just adds some more flare
  597. messageInputBar.sendButton
  598. .onEnabled { item in
  599. UIView.animate(withDuration: 0.3, animations: {
  600. item.backgroundColor = DcColors.primary
  601. })
  602. }.onDisabled { item in
  603. UIView.animate(withDuration: 0.3, animations: {
  604. item.backgroundColor = DcColors.colorDisabled
  605. })
  606. }
  607. }
  608. @objc private func chatProfilePressed() {
  609. if chatId != DC_CHAT_ID_DEADDROP {
  610. showChatDetail(chatId: chatId)
  611. }
  612. }
  613. @objc private func clipperButtonPressed() {
  614. showClipperOptions()
  615. }
  616. private func showClipperOptions() {
  617. let alert = UIAlertController(title: nil, message: nil, preferredStyle: .safeActionSheet)
  618. let galleryAction = PhotoPickerAlertAction(title: String.localized("gallery"), style: .default, handler: galleryButtonPressed(_:))
  619. let cameraAction = PhotoPickerAlertAction(title: String.localized("camera"), style: .default, handler: cameraButtonPressed(_:))
  620. let documentAction = UIAlertAction(title: String.localized("files"), style: .default, handler: documentActionPressed(_:))
  621. let voiceMessageAction = UIAlertAction(title: String.localized("voice_message"), style: .default, handler: voiceMessageButtonPressed(_:))
  622. let isLocationStreaming = dcContext.isSendingLocationsToChat(chatId: chatId)
  623. let locationStreamingAction = UIAlertAction(title: isLocationStreaming ? String.localized("stop_sharing_location") : String.localized("location"),
  624. style: isLocationStreaming ? .destructive : .default,
  625. handler: locationStreamingButtonPressed(_:))
  626. alert.addAction(cameraAction)
  627. alert.addAction(galleryAction)
  628. alert.addAction(documentAction)
  629. alert.addAction(voiceMessageAction)
  630. if UserDefaults.standard.bool(forKey: "location_streaming") {
  631. alert.addAction(locationStreamingAction)
  632. }
  633. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  634. self.present(alert, animated: true, completion: {
  635. // unfortunately, voiceMessageAction.accessibilityHint does not work,
  636. // but this hack does the trick
  637. if UIAccessibility.isVoiceOverRunning {
  638. if let view = voiceMessageAction.value(forKey: "__representer") as? UIView {
  639. view.accessibilityHint = String.localized("a11y_voice_message_hint_ios")
  640. }
  641. }
  642. })
  643. }
  644. private func confirmationAlert(title: String, actionTitle: String, actionStyle: UIAlertAction.Style = .default, actionHandler: @escaping ((UIAlertAction) -> Void), cancelHandler: ((UIAlertAction) -> Void)? = nil) {
  645. let alert = UIAlertController(title: title,
  646. message: nil,
  647. preferredStyle: .safeActionSheet)
  648. alert.addAction(UIAlertAction(title: actionTitle, style: actionStyle, handler: actionHandler))
  649. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: cancelHandler ?? { _ in
  650. self.dismiss(animated: true, completion: nil)
  651. }))
  652. present(alert, animated: true, completion: nil)
  653. }
  654. private func askToChatWith(email: String) {
  655. let contactId = self.dcContext.createContact(name: "", email: email)
  656. if dcContext.getChatIdByContactId(contactId: contactId) != 0 {
  657. self.dismiss(animated: true, completion: nil)
  658. let chatId = self.dcContext.createChatByContactId(contactId: contactId)
  659. self.showChat(chatId: chatId)
  660. } else {
  661. confirmationAlert(title: String.localizedStringWithFormat(String.localized("ask_start_chat_with"), email),
  662. actionTitle: String.localized("start_chat"),
  663. actionHandler: { _ in
  664. self.dismiss(animated: true, completion: nil)
  665. let chatId = self.dcContext.createChatByContactId(contactId: contactId)
  666. self.showChat(chatId: chatId)})
  667. }
  668. }
  669. private func askToDeleteMessage(id: Int) {
  670. let title = String.localized(stringID: "ask_delete_messages", count: 1)
  671. confirmationAlert(title: title, actionTitle: String.localized("delete"), actionStyle: .destructive,
  672. actionHandler: { _ in
  673. self.dcContext.deleteMessage(msgId: id)
  674. self.dismiss(animated: true, completion: nil)})
  675. }
  676. private func askToForwardMessage() {
  677. let chat = dcContext.getChat(chatId: self.chatId)
  678. if chat.isSelfTalk {
  679. RelayHelper.sharedInstance.forward(to: self.chatId)
  680. } else {
  681. confirmationAlert(title: String.localizedStringWithFormat(String.localized("ask_forward"), chat.name),
  682. actionTitle: String.localized("menu_forward"),
  683. actionHandler: { _ in
  684. RelayHelper.sharedInstance.forward(to: self.chatId)
  685. self.dismiss(animated: true, completion: nil)},
  686. cancelHandler: { _ in
  687. self.dismiss(animated: false, completion: nil)
  688. self.navigationController?.popViewController(animated: true)})
  689. }
  690. }
  691. // MARK: - coordinator
  692. private func showChatDetail(chatId: Int) {
  693. let chat = dcContext.getChat(chatId: chatId)
  694. switch chat.chatType {
  695. case .SINGLE:
  696. if let contactId = chat.contactIds.first {
  697. let contactDetailController = ContactDetailViewController(dcContext: dcContext, contactId: contactId)
  698. navigationController?.pushViewController(contactDetailController, animated: true)
  699. }
  700. case .GROUP, .VERIFIEDGROUP:
  701. let groupChatDetailViewController = GroupChatDetailViewController(chatId: chatId, dcContext: dcContext)
  702. navigationController?.pushViewController(groupChatDetailViewController, animated: true)
  703. }
  704. }
  705. func showChat(chatId: Int) {
  706. if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
  707. navigationController?.popToRootViewController(animated: false)
  708. appDelegate.appCoordinator.showChat(chatId: chatId)
  709. }
  710. }
  711. private func showDocumentLibrary() {
  712. mediaPicker?.showDocumentLibrary()
  713. }
  714. private func showVoiceMessageRecorder() {
  715. mediaPicker?.showVoiceRecorder()
  716. }
  717. private func showCameraViewController() {
  718. mediaPicker?.showCamera()
  719. }
  720. private func showPhotoVideoLibrary(delegate: MediaPickerDelegate) {
  721. mediaPicker?.showPhotoVideoLibrary()
  722. }
  723. private func showMediaGallery(currentIndex: Int, msgIds: [Int]) {
  724. let betterPreviewController = PreviewController(type: .multi(msgIds, currentIndex))
  725. let nav = UINavigationController(rootViewController: betterPreviewController)
  726. nav.modalPresentationStyle = .fullScreen
  727. navigationController?.present(nav, animated: true)
  728. }
  729. private func documentActionPressed(_ action: UIAlertAction) {
  730. showDocumentLibrary()
  731. }
  732. private func voiceMessageButtonPressed(_ action: UIAlertAction) {
  733. showVoiceMessageRecorder()
  734. }
  735. private func cameraButtonPressed(_ action: UIAlertAction) {
  736. showCameraViewController()
  737. }
  738. private func galleryButtonPressed(_ action: UIAlertAction) {
  739. showPhotoVideoLibrary(delegate: self)
  740. }
  741. private func locationStreamingButtonPressed(_ action: UIAlertAction) {
  742. let isLocationStreaming = dcContext.isSendingLocationsToChat(chatId: chatId)
  743. if isLocationStreaming {
  744. locationStreamingFor(seconds: 0)
  745. } else {
  746. let alert = UIAlertController(title: String.localized("title_share_location"), message: nil, preferredStyle: .safeActionSheet)
  747. addDurationSelectionAction(to: alert, key: "share_location_for_5_minutes", duration: Time.fiveMinutes)
  748. addDurationSelectionAction(to: alert, key: "share_location_for_30_minutes", duration: Time.thirtyMinutes)
  749. addDurationSelectionAction(to: alert, key: "share_location_for_one_hour", duration: Time.oneHour)
  750. addDurationSelectionAction(to: alert, key: "share_location_for_two_hours", duration: Time.twoHours)
  751. addDurationSelectionAction(to: alert, key: "share_location_for_six_hours", duration: Time.sixHours)
  752. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  753. self.present(alert, animated: true, completion: nil)
  754. }
  755. }
  756. private func addDurationSelectionAction(to alert: UIAlertController, key: String, duration: Int) {
  757. let action = UIAlertAction(title: String.localized(key), style: .default, handler: { _ in
  758. self.locationStreamingFor(seconds: duration)
  759. })
  760. alert.addAction(action)
  761. }
  762. private func locationStreamingFor(seconds: Int) {
  763. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
  764. return
  765. }
  766. self.dcContext.sendLocationsToChat(chatId: self.chatId, seconds: seconds)
  767. appDelegate.locationManager.shareLocation(chatId: self.chatId, duration: seconds)
  768. }
  769. func updateMessage(_ messageId: Int) {
  770. if messageIds.firstIndex(where: { $0 == messageId }) != nil {
  771. DispatchQueue.global(qos: .background).async { [weak self] in
  772. self?.dcContext.markSeenMessages(messageIds: [UInt32(messageId)])
  773. }
  774. let wasLastSectionVisible = self.isLastRowVisible()
  775. tableView.reloadData()
  776. if wasLastSectionVisible {
  777. self.scrollToBottom(animated: true)
  778. }
  779. } else {
  780. let msg = DcMsg(id: messageId)
  781. if msg.chatId == chatId {
  782. insertMessage(msg)
  783. }
  784. }
  785. }
  786. func insertMessage(_ message: DcMsg) {
  787. DispatchQueue.global(qos: .background).async { [weak self] in
  788. self?.dcContext.markSeenMessages(messageIds: [UInt32(message.id)])
  789. }
  790. let wasLastSectionVisible = isLastRowVisible()
  791. messageIds.append(message.id)
  792. emptyStateView.isHidden = true
  793. tableView.reloadData()
  794. if wasLastSectionVisible || message.isFromCurrentSender {
  795. scrollToBottom(animated: true)
  796. }
  797. }
  798. private func sendTextMessage(text: String, quoteMessage: DcMsg?) {
  799. DispatchQueue.global().async {
  800. let message = DcMsg(viewType: DC_MSG_TEXT)
  801. message.text = text
  802. if let quoteMessage = quoteMessage {
  803. message.quoteMessage = quoteMessage
  804. }
  805. message.sendInChat(id: self.chatId)
  806. }
  807. }
  808. private func sendImage(_ image: UIImage, message: String? = nil) {
  809. DispatchQueue.global().async {
  810. if let path = DcUtils.saveImage(image: image) {
  811. self.sendImageMessage(viewType: DC_MSG_IMAGE, image: image, filePath: path)
  812. }
  813. }
  814. }
  815. private func sendAnimatedImage(url: NSURL) {
  816. if let path = url.path {
  817. let result = SDAnimatedImage(contentsOfFile: path)
  818. if let result = result,
  819. let animatedImageData = result.animatedImageData,
  820. let pathInDocDir = DcUtils.saveImage(data: animatedImageData, suffix: "gif") {
  821. self.sendImageMessage(viewType: DC_MSG_GIF, image: result, filePath: pathInDocDir)
  822. }
  823. }
  824. }
  825. private func sendImageMessage(viewType: Int32, image: UIImage, filePath: String, message: String? = nil) {
  826. let msg = DcMsg(viewType: viewType)
  827. msg.setFile(filepath: filePath)
  828. msg.text = (message ?? "").isEmpty ? nil : message
  829. msg.sendInChat(id: self.chatId)
  830. }
  831. private func sendDocumentMessage(url: NSURL) {
  832. DispatchQueue.global().async {
  833. let msg = DcMsg(viewType: DC_MSG_FILE)
  834. msg.setFile(filepath: url.relativePath, mimeType: nil)
  835. msg.sendInChat(id: self.chatId)
  836. }
  837. }
  838. private func sendVoiceMessage(url: NSURL) {
  839. DispatchQueue.global().async {
  840. let msg = DcMsg(viewType: DC_MSG_VOICE)
  841. msg.setFile(filepath: url.relativePath, mimeType: "audio/m4a")
  842. msg.sendInChat(id: self.chatId)
  843. }
  844. }
  845. private func sendVideo(url: NSURL) {
  846. DispatchQueue.global().async {
  847. let msg = DcMsg(viewType: DC_MSG_VIDEO)
  848. msg.setFile(filepath: url.relativePath, mimeType: "video/mp4")
  849. msg.sendInChat(id: self.chatId)
  850. }
  851. }
  852. private func sendImage(url: NSURL) {
  853. if url.pathExtension == "gif" {
  854. sendAnimatedImage(url: url)
  855. } else if let data = try? Data(contentsOf: url as URL),
  856. let image = UIImage(data: data) {
  857. sendImage(image)
  858. }
  859. }
  860. // MARK: - Context menu
  861. private func prepareContextMenu() {
  862. UIMenuController.shared.menuItems = [
  863. UIMenuItem(title: String.localized("info"), action: #selector(BaseMessageCell.messageInfo)),
  864. UIMenuItem(title: String.localized("delete"), action: #selector(BaseMessageCell.messageDelete)),
  865. UIMenuItem(title: String.localized("forward"), action: #selector(BaseMessageCell.messageForward))
  866. ]
  867. UIMenuController.shared.update()
  868. }
  869. override func tableView(_ tableView: UITableView, shouldShowMenuForRowAt indexPath: IndexPath) -> Bool {
  870. return !DcMsg(id: messageIds[indexPath.row]).isInfo
  871. }
  872. override func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
  873. return action == #selector(UIResponderStandardEditActions.copy(_:))
  874. || action == #selector(BaseMessageCell.messageInfo)
  875. || action == #selector(BaseMessageCell.messageDelete)
  876. || action == #selector(BaseMessageCell.messageForward)
  877. }
  878. override func tableView(_ tableView: UITableView, performAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) {
  879. // handle standard actions here, but custom actions never trigger this. it still needs to be present for the menu to display, though.
  880. switch action {
  881. case #selector(copy(_:)):
  882. let id = messageIds[indexPath.row]
  883. let msg = DcMsg(id: id)
  884. let pasteboard = UIPasteboard.general
  885. if msg.type == DC_MSG_TEXT {
  886. pasteboard.string = msg.text
  887. } else {
  888. pasteboard.string = msg.summary(chars: 10000000)
  889. }
  890. case #selector(BaseMessageCell.messageInfo(_:)):
  891. let msg = DcMsg(id: messageIds[indexPath.row])
  892. let msgViewController = MessageInfoViewController(dcContext: dcContext, message: msg)
  893. if let ctrl = navigationController {
  894. ctrl.pushViewController(msgViewController, animated: true)
  895. }
  896. case #selector(BaseMessageCell.messageDelete(_:)):
  897. let msg = DcMsg(id: messageIds[indexPath.row])
  898. askToDeleteMessage(id: msg.id)
  899. case #selector(BaseMessageCell.messageForward(_:)):
  900. let msg = DcMsg(id: messageIds[indexPath.row])
  901. RelayHelper.sharedInstance.setForwardMessage(messageId: msg.id)
  902. navigationController?.popViewController(animated: true)
  903. default:
  904. break
  905. }
  906. }
  907. func showMediaGalleryFor(indexPath: IndexPath) {
  908. let messageId = messageIds[indexPath.row]
  909. let message = DcMsg(id: messageId)
  910. showMediaGalleryFor(message: message)
  911. }
  912. func showMediaGalleryFor(message: DcMsg) {
  913. let msgIds = dcContext.getChatMedia(chatId: chatId, messageType: Int32(message.type), messageType2: 0, messageType3: 0)
  914. let index = msgIds.firstIndex(of: message.id) ?? 0
  915. showMediaGallery(currentIndex: index, msgIds: msgIds)
  916. }
  917. private func didTapAsm(msg: DcMsg, orgText: String) {
  918. let inputDlg = UIAlertController(
  919. title: String.localized("autocrypt_continue_transfer_title"),
  920. message: String.localized("autocrypt_continue_transfer_please_enter_code"),
  921. preferredStyle: .alert)
  922. inputDlg.addTextField(configurationHandler: { (textField) in
  923. textField.placeholder = msg.setupCodeBegin + ".."
  924. textField.text = orgText
  925. textField.keyboardType = UIKeyboardType.numbersAndPunctuation // allows entering spaces; decimalPad would require a mask to keep things readable
  926. })
  927. inputDlg.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  928. let okAction = UIAlertAction(title: String.localized("ok"), style: .default, handler: { _ in
  929. let textField = inputDlg.textFields![0]
  930. let modText = textField.text ?? ""
  931. let success = self.dcContext.continueKeyTransfer(msgId: msg.id, setupCode: modText)
  932. let alert = UIAlertController(
  933. title: String.localized("autocrypt_continue_transfer_title"),
  934. message: String.localized(success ? "autocrypt_continue_transfer_succeeded" : "autocrypt_bad_setup_code"),
  935. preferredStyle: .alert)
  936. if success {
  937. alert.addAction(UIAlertAction(title: String.localized("ok"), style: .default, handler: nil))
  938. } else {
  939. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  940. let retryAction = UIAlertAction(title: String.localized("autocrypt_continue_transfer_retry"), style: .default, handler: { _ in
  941. self.didTapAsm(msg: msg, orgText: modText)
  942. })
  943. alert.addAction(retryAction)
  944. alert.preferredAction = retryAction
  945. }
  946. self.navigationController?.present(alert, animated: true, completion: nil)
  947. })
  948. inputDlg.addAction(okAction)
  949. inputDlg.preferredAction = okAction // without setting preferredAction, cancel become shown *bold* as the preferred action
  950. navigationController?.present(inputDlg, animated: true, completion: nil)
  951. }
  952. func handleUIMenu() -> Bool {
  953. if UIMenuController.shared.isMenuVisible {
  954. UIMenuController.shared.setMenuVisible(false, animated: true)
  955. return true
  956. }
  957. return false
  958. }
  959. }
  960. // MARK: - BaseMessageCellDelegate
  961. extension ChatViewController: BaseMessageCellDelegate {
  962. @objc func quoteTapped(indexPath: IndexPath) {
  963. _ = handleUIMenu()
  964. let msg = DcMsg(id: messageIds[indexPath.row])
  965. if let quoteMsg = msg.quoteMessage,
  966. let index = messageIds.firstIndex(of: quoteMsg.id) {
  967. let indexPath = IndexPath(row: index, section: 0)
  968. tableView.scrollToRow(at: indexPath, at: .top, animated: true)
  969. }
  970. }
  971. @objc func textTapped(indexPath: IndexPath) {
  972. if handleUIMenu() { return }
  973. let message = DcMsg(id: messageIds[indexPath.row])
  974. if message.isSetupMessage {
  975. didTapAsm(msg: message, orgText: "")
  976. }
  977. }
  978. @objc func phoneNumberTapped(number: String) {
  979. if handleUIMenu() { return }
  980. logger.debug("phone number tapped \(number)")
  981. }
  982. @objc func commandTapped(command: String) {
  983. if handleUIMenu() { return }
  984. logger.debug("command tapped \(command)")
  985. }
  986. @objc func urlTapped(url: URL) {
  987. if handleUIMenu() { return }
  988. if Utils.isEmail(url: url) {
  989. logger.debug("tapped on contact")
  990. let email = Utils.getEmailFrom(url)
  991. self.askToChatWith(email: email)
  992. ///TODO: implement handling
  993. } else {
  994. UIApplication.shared.open(url)
  995. }
  996. }
  997. @objc func imageTapped(indexPath: IndexPath) {
  998. if handleUIMenu() { return }
  999. showMediaGalleryFor(indexPath: indexPath)
  1000. }
  1001. @objc func avatarTapped(indexPath: IndexPath) {
  1002. let message = DcMsg(id: messageIds[indexPath.row])
  1003. let contactDetailController = ContactDetailViewController(dcContext: dcContext, contactId: message.fromContactId)
  1004. navigationController?.pushViewController(contactDetailController, animated: true)
  1005. }
  1006. }
  1007. // MARK: - MediaPickerDelegate
  1008. extension ChatViewController: MediaPickerDelegate {
  1009. func onVideoSelected(url: NSURL) {
  1010. sendVideo(url: url)
  1011. }
  1012. func onImageSelected(url: NSURL) {
  1013. sendImage(url: url)
  1014. }
  1015. func onImageSelected(image: UIImage) {
  1016. sendImage(image)
  1017. }
  1018. func onVoiceMessageRecorded(url: NSURL) {
  1019. sendVoiceMessage(url: url)
  1020. }
  1021. func onDocumentSelected(url: NSURL) {
  1022. sendDocumentMessage(url: url)
  1023. }
  1024. }
  1025. // MARK: - MessageInputBarDelegate
  1026. extension ChatViewController: InputBarAccessoryViewDelegate {
  1027. func inputBar(_ inputBar: InputBarAccessoryView, didPressSendButtonWith text: String) {
  1028. let trimmedText = text.replacingOccurrences(of: "\u{FFFC}", with: "", options: .literal, range: nil)
  1029. .trimmingCharacters(in: .whitespacesAndNewlines)
  1030. if inputBar.inputTextView.images.isEmpty {
  1031. self.sendTextMessage(text: trimmedText, quoteMessage: draft.quoteMessage)
  1032. self.quotePreview.cancel()
  1033. } else {
  1034. // only 1 attachment allowed for now, thus it takes the first one
  1035. self.sendImage(inputBar.inputTextView.images[0], message: trimmedText)
  1036. }
  1037. inputBar.inputTextView.text = String()
  1038. inputBar.inputTextView.attributedText = nil
  1039. }
  1040. func inputBar(_ inputBar: InputBarAccessoryView, textViewTextDidChangeTo text: String) {
  1041. draft.draftText = text
  1042. }
  1043. }
  1044. extension ChatViewController: QuotePreviewDelegate {
  1045. func onCancel() {
  1046. draft.setQuote(quotedMsg: nil)
  1047. configureDraftArea(draft: draft)
  1048. }
  1049. }