ChatViewController.swift 48 KB

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