ChatViewController.swift 49 KB

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