ChatViewController.swift 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162
  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. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  350. let messageId = messageIds[indexPath.row]
  351. let message = DcMsg(id: messageId)
  352. if message.isSetupMessage {
  353. didTapAsm(msg: message, orgText: "")
  354. } else if message.type == DC_MSG_FILE ||
  355. message.type == DC_MSG_AUDIO ||
  356. message.type == DC_MSG_VOICE {
  357. showMediaGalleryFor(message: message)
  358. }
  359. _ = handleUIMenu()
  360. }
  361. func configureAvatarVisibility(for message: DcMsg, at indexPath: IndexPath) -> Bool {
  362. return isGroupChat && !message.isFromCurrentSender && !isNextMessageSameSender(currentMessage: message, at: indexPath)
  363. }
  364. func configureMessageStyle(for message: DcMsg, at indexPath: IndexPath) -> UIRectCorner {
  365. var corners: UIRectCorner = []
  366. if message.isFromCurrentSender { //isFromCurrentSender(message: message) {
  367. corners.formUnion(.topLeft)
  368. corners.formUnion(.bottomLeft)
  369. if !isPreviousMessageSameSender(currentMessage: message, at: indexPath) {
  370. corners.formUnion(.topRight)
  371. }
  372. if !isNextMessageSameSender(currentMessage: message, at: indexPath) {
  373. corners.formUnion(.bottomRight)
  374. }
  375. } else {
  376. corners.formUnion(.topRight)
  377. corners.formUnion(.bottomRight)
  378. if !isPreviousMessageSameSender(currentMessage: message, at: indexPath) {
  379. corners.formUnion(.topLeft)
  380. }
  381. if !isNextMessageSameSender(currentMessage: message, at: indexPath) {
  382. corners.formUnion(.bottomLeft)
  383. }
  384. }
  385. return corners
  386. }
  387. private func getBackgroundColor(for currentMessage: DcMsg) -> UIColor {
  388. return currentMessage.isFromCurrentSender ? DcColors.messagePrimaryColor : DcColors.messageSecondaryColor
  389. }
  390. private func isPreviousMessageSameSender(currentMessage: DcMsg, at indexPath: IndexPath) -> Bool {
  391. let previousRow = indexPath.row - 1
  392. if previousRow < 0 {
  393. return false
  394. }
  395. let messageId = messageIds[previousRow]
  396. let previousMessage = DcMsg(id: messageId)
  397. return previousMessage.fromContact.id == currentMessage.fromContact.id
  398. }
  399. private func isNextMessageSameSender(currentMessage: DcMsg, at indexPath: IndexPath) -> Bool {
  400. let nextRow = indexPath.row + 1
  401. if nextRow >= messageIds.count {
  402. return false
  403. }
  404. let messageId = messageIds[nextRow]
  405. let nextMessage = DcMsg(id: messageId)
  406. return nextMessage.fromContact.id == currentMessage.fromContact.id
  407. }
  408. private func updateTitle(chat: DcChat) {
  409. let titleView = ChatTitleView()
  410. var subtitle = "ErrSubtitle"
  411. let chatContactIds = chat.contactIds
  412. if chat.isGroup {
  413. subtitle = String.localized(stringID: "n_members", count: chatContactIds.count)
  414. } else if chatContactIds.count >= 1 {
  415. if chat.isDeviceTalk {
  416. subtitle = String.localized("device_talk_subtitle")
  417. } else if chat.isSelfTalk {
  418. subtitle = String.localized("chat_self_talk_subtitle")
  419. } else {
  420. subtitle = DcContact(id: chatContactIds[0]).email
  421. }
  422. }
  423. titleView.updateTitleView(title: chat.name, subtitle: subtitle)
  424. navigationItem.titleView = titleView
  425. var rightBarButtonItems = [badgeItem]
  426. if chat.isSendingLocations {
  427. rightBarButtonItems.append(locationStreamingItem)
  428. }
  429. if chat.isMuted {
  430. rightBarButtonItems.append(muteItem)
  431. }
  432. if dcContext.getChatEphemeralTimer(chatId: chat.id) > 0 {
  433. rightBarButtonItems.append(ephemeralMessageItem)
  434. }
  435. navigationItem.rightBarButtonItems = rightBarButtonItems
  436. }
  437. // TODO: is the delay of one second needed?
  438. @objc
  439. private func refreshMessages() {
  440. DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + 1) {
  441. DispatchQueue.main.async { [weak self] in
  442. guard let self = self else { return }
  443. self.messageIds = self.getMessageIds()
  444. self.tableView.reloadData()
  445. if self.isLastRowVisible() {
  446. self.scrollToBottom(animated: true)
  447. }
  448. self.showEmptyStateView(self.messageIds.isEmpty)
  449. }
  450. }
  451. }
  452. private func loadMessages() {
  453. DispatchQueue.global(qos: .userInitiated).async {
  454. DispatchQueue.main.async { [weak self] in
  455. guard let self = self else { return }
  456. let wasLastRowVisible = self.isLastRowVisible()
  457. let wasMessageIdsEmpty = self.messageIds.isEmpty
  458. // update message ids
  459. self.messageIds = self.getMessageIds()
  460. self.tableView.reloadData()
  461. if wasMessageIdsEmpty ||
  462. wasLastRowVisible {
  463. self.scrollToBottom(animated: false)
  464. }
  465. self.showEmptyStateView(self.messageIds.isEmpty)
  466. }
  467. }
  468. }
  469. func isLastRowVisible() -> Bool {
  470. guard !messageIds.isEmpty else { return false }
  471. let lastIndexPath = IndexPath(item: messageIds.count - 1, section: 0)
  472. return tableView.indexPathsForVisibleRows?.contains(lastIndexPath) ?? false
  473. }
  474. func scrollToBottom(animated: Bool) {
  475. if !messageIds.isEmpty {
  476. self.tableView.scrollToRow(at: IndexPath(row: self.messageIds.count - 1, section: 0), at: .bottom, animated: animated)
  477. }
  478. }
  479. private func showEmptyStateView(_ show: Bool) {
  480. if show {
  481. let dcChat = dcContext.getChat(chatId: chatId)
  482. if chatId == DC_CHAT_ID_DEADDROP {
  483. if dcContext.showEmails != DC_SHOW_EMAILS_ALL {
  484. emptyStateView.text = String.localized("chat_no_contact_requests")
  485. } else {
  486. emptyStateView.text = String.localized("chat_no_messages")
  487. }
  488. } else if dcChat.isGroup {
  489. if dcChat.isUnpromoted {
  490. emptyStateView.text = String.localized("chat_new_group_hint")
  491. } else {
  492. emptyStateView.text = String.localized("chat_no_messages")
  493. }
  494. } else if dcChat.isSelfTalk {
  495. emptyStateView.text = String.localized("saved_messages_explain")
  496. } else if dcChat.isDeviceTalk {
  497. emptyStateView.text = String.localized("device_talk_explain")
  498. } else {
  499. emptyStateView.text = String.localizedStringWithFormat(String.localized("chat_no_messages_hint"), dcChat.name, dcChat.name)
  500. }
  501. emptyStateView.isHidden = false
  502. } else {
  503. emptyStateView.isHidden = true
  504. }
  505. }
  506. private var textDraft: String? {
  507. return dcContext.getDraft(chatId: chatId)
  508. }
  509. private func getMessageIds() -> [Int] {
  510. return dcContext.getMessageIds(chatId: chatId)
  511. }
  512. @objc private func setTextDraft() {
  513. if let text = self.messageInputBar.inputTextView.text {
  514. dcContext.setDraft(chatId: chatId, draftText: text)
  515. }
  516. }
  517. private func configureMessageInputBar() {
  518. messageInputBar.delegate = self
  519. messageInputBar.inputTextView.tintColor = DcColors.primary
  520. messageInputBar.inputTextView.placeholder = String.localized("chat_input_placeholder")
  521. messageInputBar.separatorLine.isHidden = true
  522. messageInputBar.inputTextView.tintColor = DcColors.primary
  523. messageInputBar.inputTextView.textColor = DcColors.defaultTextColor
  524. messageInputBar.backgroundView.backgroundColor = DcColors.chatBackgroundColor
  525. //scrollsToBottomOnKeyboardBeginsEditing = true
  526. messageInputBar.inputTextView.backgroundColor = DcColors.inputFieldColor
  527. messageInputBar.inputTextView.placeholderTextColor = DcColors.placeholderColor
  528. messageInputBar.inputTextView.textContainerInset = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 38)
  529. messageInputBar.inputTextView.placeholderLabelInsets = UIEdgeInsets(top: 8, left: 20, bottom: 8, right: 38)
  530. messageInputBar.inputTextView.layer.borderColor = UIColor.themeColor(light: UIColor(red: 200 / 255, green: 200 / 255, blue: 200 / 255, alpha: 1),
  531. dark: UIColor(red: 55 / 255, green: 55/255, blue: 55/255, alpha: 1)).cgColor
  532. messageInputBar.inputTextView.layer.borderWidth = 1.0
  533. messageInputBar.inputTextView.layer.cornerRadius = 13.0
  534. messageInputBar.inputTextView.layer.masksToBounds = true
  535. messageInputBar.inputTextView.scrollIndicatorInsets = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0)
  536. configureInputBarItems()
  537. }
  538. private func configureInputBarItems() {
  539. messageInputBar.setLeftStackViewWidthConstant(to: 40, animated: false)
  540. messageInputBar.setRightStackViewWidthConstant(to: 40, animated: false)
  541. let sendButtonImage = UIImage(named: "paper_plane")?.withRenderingMode(.alwaysTemplate)
  542. messageInputBar.sendButton.image = sendButtonImage
  543. messageInputBar.sendButton.accessibilityLabel = String.localized("menu_send")
  544. messageInputBar.sendButton.accessibilityTraits = .button
  545. messageInputBar.sendButton.title = nil
  546. messageInputBar.sendButton.tintColor = UIColor(white: 1, alpha: 1)
  547. messageInputBar.sendButton.layer.cornerRadius = 20
  548. messageInputBar.middleContentViewPadding = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 10)
  549. // this adds a padding between textinputfield and send button
  550. messageInputBar.sendButton.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
  551. messageInputBar.sendButton.setSize(CGSize(width: 40, height: 40), animated: false)
  552. messageInputBar.padding = UIEdgeInsets(top: 6, left: 6, bottom: 6, right: 12)
  553. let leftItems = [
  554. InputBarButtonItem()
  555. .configure {
  556. $0.spacing = .fixed(0)
  557. let clipperIcon = #imageLiteral(resourceName: "ic_attach_file_36pt").withRenderingMode(.alwaysTemplate)
  558. $0.image = clipperIcon
  559. $0.tintColor = DcColors.primary
  560. $0.setSize(CGSize(width: 40, height: 40), animated: false)
  561. $0.accessibilityLabel = String.localized("menu_add_attachment")
  562. $0.accessibilityTraits = .button
  563. }.onSelected {
  564. $0.tintColor = UIColor.themeColor(light: .lightGray, dark: .darkGray)
  565. }.onDeselected {
  566. $0.tintColor = DcColors.primary
  567. }.onTouchUpInside { [weak self] _ in
  568. self?.clipperButtonPressed()
  569. }
  570. ]
  571. messageInputBar.setStackViewItems(leftItems, forStack: .left, animated: false)
  572. // This just adds some more flare
  573. messageInputBar.sendButton
  574. .onEnabled { item in
  575. UIView.animate(withDuration: 0.3, animations: {
  576. item.backgroundColor = DcColors.primary
  577. })
  578. }.onDisabled { item in
  579. UIView.animate(withDuration: 0.3, animations: {
  580. item.backgroundColor = DcColors.colorDisabled
  581. })
  582. }
  583. }
  584. @objc private func chatProfilePressed() {
  585. if chatId != DC_CHAT_ID_DEADDROP {
  586. showChatDetail(chatId: chatId)
  587. }
  588. }
  589. @objc private func clipperButtonPressed() {
  590. showClipperOptions()
  591. }
  592. private func showClipperOptions() {
  593. let alert = UIAlertController(title: nil, message: nil, preferredStyle: .safeActionSheet)
  594. let galleryAction = PhotoPickerAlertAction(title: String.localized("gallery"), style: .default, handler: galleryButtonPressed(_:))
  595. let cameraAction = PhotoPickerAlertAction(title: String.localized("camera"), style: .default, handler: cameraButtonPressed(_:))
  596. let documentAction = UIAlertAction(title: String.localized("files"), style: .default, handler: documentActionPressed(_:))
  597. let voiceMessageAction = UIAlertAction(title: String.localized("voice_message"), style: .default, handler: voiceMessageButtonPressed(_:))
  598. let isLocationStreaming = dcContext.isSendingLocationsToChat(chatId: chatId)
  599. let locationStreamingAction = UIAlertAction(title: isLocationStreaming ? String.localized("stop_sharing_location") : String.localized("location"),
  600. style: isLocationStreaming ? .destructive : .default,
  601. handler: locationStreamingButtonPressed(_:))
  602. alert.addAction(cameraAction)
  603. alert.addAction(galleryAction)
  604. alert.addAction(documentAction)
  605. alert.addAction(voiceMessageAction)
  606. if UserDefaults.standard.bool(forKey: "location_streaming") {
  607. alert.addAction(locationStreamingAction)
  608. }
  609. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  610. self.present(alert, animated: true, completion: {
  611. // unfortunately, voiceMessageAction.accessibilityHint does not work,
  612. // but this hack does the trick
  613. if UIAccessibility.isVoiceOverRunning {
  614. if let view = voiceMessageAction.value(forKey: "__representer") as? UIView {
  615. view.accessibilityHint = String.localized("a11y_voice_message_hint_ios")
  616. }
  617. }
  618. })
  619. }
  620. private func confirmationAlert(title: String, actionTitle: String, actionStyle: UIAlertAction.Style = .default, actionHandler: @escaping ((UIAlertAction) -> Void), cancelHandler: ((UIAlertAction) -> Void)? = nil) {
  621. let alert = UIAlertController(title: title,
  622. message: nil,
  623. preferredStyle: .safeActionSheet)
  624. alert.addAction(UIAlertAction(title: actionTitle, style: actionStyle, handler: actionHandler))
  625. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: cancelHandler ?? { _ in
  626. self.dismiss(animated: true, completion: nil)
  627. }))
  628. present(alert, animated: true, completion: nil)
  629. }
  630. private func askToChatWith(email: String) {
  631. let contactId = self.dcContext.createContact(name: "", email: email)
  632. if dcContext.getChatIdByContactId(contactId: contactId) != 0 {
  633. self.dismiss(animated: true, completion: nil)
  634. let chatId = self.dcContext.createChatByContactId(contactId: contactId)
  635. self.showChat(chatId: chatId)
  636. } else {
  637. confirmationAlert(title: String.localizedStringWithFormat(String.localized("ask_start_chat_with"), email),
  638. actionTitle: String.localized("start_chat"),
  639. actionHandler: { _ in
  640. self.dismiss(animated: true, completion: nil)
  641. let chatId = self.dcContext.createChatByContactId(contactId: contactId)
  642. self.showChat(chatId: chatId)})
  643. }
  644. }
  645. private func askToDeleteMessage(id: Int) {
  646. let title = String.localized(stringID: "ask_delete_messages", count: 1)
  647. confirmationAlert(title: title, actionTitle: String.localized("delete"), actionStyle: .destructive,
  648. actionHandler: { _ in
  649. self.dcContext.deleteMessage(msgId: id)
  650. self.dismiss(animated: true, completion: nil)})
  651. }
  652. private func askToForwardMessage() {
  653. let chat = dcContext.getChat(chatId: self.chatId)
  654. if chat.isSelfTalk {
  655. RelayHelper.sharedInstance.forward(to: self.chatId)
  656. } else {
  657. confirmationAlert(title: String.localizedStringWithFormat(String.localized("ask_forward"), chat.name),
  658. actionTitle: String.localized("menu_forward"),
  659. actionHandler: { _ in
  660. RelayHelper.sharedInstance.forward(to: self.chatId)
  661. self.dismiss(animated: true, completion: nil)},
  662. cancelHandler: { _ in
  663. self.dismiss(animated: false, completion: nil)
  664. self.navigationController?.popViewController(animated: true)})
  665. }
  666. }
  667. // MARK: - coordinator
  668. private func showChatDetail(chatId: Int) {
  669. let chat = dcContext.getChat(chatId: chatId)
  670. switch chat.chatType {
  671. case .SINGLE:
  672. if let contactId = chat.contactIds.first {
  673. let contactDetailController = ContactDetailViewController(dcContext: dcContext, contactId: contactId)
  674. navigationController?.pushViewController(contactDetailController, animated: true)
  675. }
  676. case .GROUP, .VERIFIEDGROUP:
  677. let groupChatDetailViewController = GroupChatDetailViewController(chatId: chatId, dcContext: dcContext)
  678. navigationController?.pushViewController(groupChatDetailViewController, animated: true)
  679. }
  680. }
  681. func showChat(chatId: Int) {
  682. if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
  683. navigationController?.popToRootViewController(animated: false)
  684. appDelegate.appCoordinator.showChat(chatId: chatId)
  685. }
  686. }
  687. private func showDocumentLibrary() {
  688. mediaPicker?.showDocumentLibrary()
  689. }
  690. private func showVoiceMessageRecorder() {
  691. mediaPicker?.showVoiceRecorder()
  692. }
  693. private func showCameraViewController() {
  694. mediaPicker?.showCamera()
  695. }
  696. private func showPhotoVideoLibrary(delegate: MediaPickerDelegate) {
  697. mediaPicker?.showPhotoVideoLibrary()
  698. }
  699. private func showMediaGallery(currentIndex: Int, msgIds: [Int]) {
  700. let betterPreviewController = PreviewController(type: .multi(msgIds, currentIndex))
  701. let nav = UINavigationController(rootViewController: betterPreviewController)
  702. nav.modalPresentationStyle = .fullScreen
  703. navigationController?.present(nav, animated: true)
  704. }
  705. private func documentActionPressed(_ action: UIAlertAction) {
  706. showDocumentLibrary()
  707. }
  708. private func voiceMessageButtonPressed(_ action: UIAlertAction) {
  709. showVoiceMessageRecorder()
  710. }
  711. private func cameraButtonPressed(_ action: UIAlertAction) {
  712. showCameraViewController()
  713. }
  714. private func galleryButtonPressed(_ action: UIAlertAction) {
  715. showPhotoVideoLibrary(delegate: self)
  716. }
  717. private func locationStreamingButtonPressed(_ action: UIAlertAction) {
  718. let isLocationStreaming = dcContext.isSendingLocationsToChat(chatId: chatId)
  719. if isLocationStreaming {
  720. locationStreamingFor(seconds: 0)
  721. } else {
  722. let alert = UIAlertController(title: String.localized("title_share_location"), message: nil, preferredStyle: .safeActionSheet)
  723. addDurationSelectionAction(to: alert, key: "share_location_for_5_minutes", duration: Time.fiveMinutes)
  724. addDurationSelectionAction(to: alert, key: "share_location_for_30_minutes", duration: Time.thirtyMinutes)
  725. addDurationSelectionAction(to: alert, key: "share_location_for_one_hour", duration: Time.oneHour)
  726. addDurationSelectionAction(to: alert, key: "share_location_for_two_hours", duration: Time.twoHours)
  727. addDurationSelectionAction(to: alert, key: "share_location_for_six_hours", duration: Time.sixHours)
  728. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  729. self.present(alert, animated: true, completion: nil)
  730. }
  731. }
  732. private func addDurationSelectionAction(to alert: UIAlertController, key: String, duration: Int) {
  733. let action = UIAlertAction(title: String.localized(key), style: .default, handler: { _ in
  734. self.locationStreamingFor(seconds: duration)
  735. })
  736. alert.addAction(action)
  737. }
  738. private func locationStreamingFor(seconds: Int) {
  739. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
  740. return
  741. }
  742. self.dcContext.sendLocationsToChat(chatId: self.chatId, seconds: seconds)
  743. appDelegate.locationManager.shareLocation(chatId: self.chatId, duration: seconds)
  744. }
  745. func updateMessage(_ messageId: Int) {
  746. if messageIds.firstIndex(where: { $0 == messageId }) != nil {
  747. dcContext.markSeenMessages(messageIds: [UInt32(messageId)])
  748. let wasLastSectionVisible = self.isLastRowVisible()
  749. tableView.reloadData()
  750. if wasLastSectionVisible {
  751. self.scrollToBottom(animated: true)
  752. }
  753. } else {
  754. let msg = DcMsg(id: messageId)
  755. if msg.chatId == chatId {
  756. insertMessage(msg)
  757. }
  758. }
  759. }
  760. func insertMessage(_ message: DcMsg) {
  761. dcContext.markSeenMessages(messageIds: [UInt32(message.id)])
  762. messageIds.append(message.id)
  763. emptyStateView.isHidden = true
  764. let wasLastSectionVisible = isLastRowVisible()
  765. tableView.reloadData()
  766. if wasLastSectionVisible || message.isFromCurrentSender {
  767. scrollToBottom(animated: true)
  768. }
  769. }
  770. private func sendTextMessage(message: String) {
  771. DispatchQueue.global().async {
  772. self.dcContext.sendTextInChat(id: self.chatId, message: message)
  773. }
  774. }
  775. private func sendImage(_ image: UIImage, message: String? = nil) {
  776. DispatchQueue.global().async {
  777. if let path = DcUtils.saveImage(image: image) {
  778. self.sendImageMessage(viewType: DC_MSG_IMAGE, image: image, filePath: path)
  779. }
  780. }
  781. }
  782. private func sendAnimatedImage(url: NSURL) {
  783. if let path = url.path {
  784. let result = SDAnimatedImage(contentsOfFile: path)
  785. if let result = result,
  786. let animatedImageData = result.animatedImageData,
  787. let pathInDocDir = DcUtils.saveImage(data: animatedImageData, suffix: "gif") {
  788. self.sendImageMessage(viewType: DC_MSG_GIF, image: result, filePath: pathInDocDir)
  789. }
  790. }
  791. }
  792. private func sendImageMessage(viewType: Int32, image: UIImage, filePath: String, message: String? = nil) {
  793. let msg = DcMsg(viewType: viewType)
  794. msg.setFile(filepath: filePath)
  795. msg.text = (message ?? "").isEmpty ? nil : message
  796. msg.sendInChat(id: self.chatId)
  797. }
  798. private func sendDocumentMessage(url: NSURL) {
  799. DispatchQueue.global().async {
  800. let msg = DcMsg(viewType: DC_MSG_FILE)
  801. msg.setFile(filepath: url.relativePath, mimeType: nil)
  802. msg.sendInChat(id: self.chatId)
  803. }
  804. }
  805. private func sendVoiceMessage(url: NSURL) {
  806. DispatchQueue.global().async {
  807. let msg = DcMsg(viewType: DC_MSG_VOICE)
  808. msg.setFile(filepath: url.relativePath, mimeType: "audio/m4a")
  809. msg.sendInChat(id: self.chatId)
  810. }
  811. }
  812. private func sendVideo(url: NSURL) {
  813. DispatchQueue.global().async {
  814. let msg = DcMsg(viewType: DC_MSG_VIDEO)
  815. msg.setFile(filepath: url.relativePath, mimeType: "video/mp4")
  816. msg.sendInChat(id: self.chatId)
  817. }
  818. }
  819. private func sendImage(url: NSURL) {
  820. if url.pathExtension == "gif" {
  821. sendAnimatedImage(url: url)
  822. } else if let data = try? Data(contentsOf: url as URL),
  823. let image = UIImage(data: data) {
  824. sendImage(image)
  825. }
  826. }
  827. // MARK: - Context menu
  828. private func prepareContextMenu() {
  829. UIMenuController.shared.menuItems = [
  830. UIMenuItem(title: String.localized("info"), action: #selector(BaseMessageCell.messageInfo)),
  831. UIMenuItem(title: String.localized("delete"), action: #selector(BaseMessageCell.messageDelete)),
  832. UIMenuItem(title: String.localized("forward"), action: #selector(BaseMessageCell.messageForward))
  833. ]
  834. UIMenuController.shared.update()
  835. }
  836. override func tableView(_ tableView: UITableView, shouldShowMenuForRowAt indexPath: IndexPath) -> Bool {
  837. return !DcMsg(id: messageIds[indexPath.row]).isInfo
  838. }
  839. override func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
  840. return action == #selector(UIResponderStandardEditActions.copy(_:))
  841. || action == #selector(BaseMessageCell.messageInfo)
  842. || action == #selector(BaseMessageCell.messageDelete)
  843. || action == #selector(BaseMessageCell.messageForward)
  844. }
  845. override func tableView(_ tableView: UITableView, performAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) {
  846. // handle standard actions here, but custom actions never trigger this. it still needs to be present for the menu to display, though.
  847. switch action {
  848. case #selector(copy(_:)):
  849. let id = messageIds[indexPath.row]
  850. let msg = DcMsg(id: id)
  851. let pasteboard = UIPasteboard.general
  852. if msg.type == DC_MSG_TEXT {
  853. pasteboard.string = msg.text
  854. } else {
  855. pasteboard.string = msg.summary(chars: 10000000)
  856. }
  857. case #selector(BaseMessageCell.messageInfo(_:)):
  858. let msg = DcMsg(id: messageIds[indexPath.row])
  859. let msgViewController = MessageInfoViewController(dcContext: dcContext, message: msg)
  860. if let ctrl = navigationController {
  861. ctrl.pushViewController(msgViewController, animated: true)
  862. }
  863. case #selector(BaseMessageCell.messageDelete(_:)):
  864. let msg = DcMsg(id: messageIds[indexPath.row])
  865. askToDeleteMessage(id: msg.id)
  866. case #selector(BaseMessageCell.messageForward(_:)):
  867. let msg = DcMsg(id: messageIds[indexPath.row])
  868. RelayHelper.sharedInstance.setForwardMessage(messageId: msg.id)
  869. navigationController?.popViewController(animated: true)
  870. default:
  871. break
  872. }
  873. }
  874. func showMediaGalleryFor(indexPath: IndexPath) {
  875. let messageId = messageIds[indexPath.row]
  876. let message = DcMsg(id: messageId)
  877. showMediaGalleryFor(message: message)
  878. }
  879. func showMediaGalleryFor(message: DcMsg) {
  880. let msgIds = dcContext.getChatMedia(chatId: chatId, messageType: Int32(message.type), messageType2: 0, messageType3: 0)
  881. let index = msgIds.firstIndex(of: message.id) ?? 0
  882. showMediaGallery(currentIndex: index, msgIds: msgIds)
  883. }
  884. private func didTapAsm(msg: DcMsg, orgText: String) {
  885. let inputDlg = UIAlertController(
  886. title: String.localized("autocrypt_continue_transfer_title"),
  887. message: String.localized("autocrypt_continue_transfer_please_enter_code"),
  888. preferredStyle: .alert)
  889. inputDlg.addTextField(configurationHandler: { (textField) in
  890. textField.placeholder = msg.setupCodeBegin + ".."
  891. textField.text = orgText
  892. textField.keyboardType = UIKeyboardType.numbersAndPunctuation // allows entering spaces; decimalPad would require a mask to keep things readable
  893. })
  894. inputDlg.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  895. let okAction = UIAlertAction(title: String.localized("ok"), style: .default, handler: { _ in
  896. let textField = inputDlg.textFields![0]
  897. let modText = textField.text ?? ""
  898. let success = self.dcContext.continueKeyTransfer(msgId: msg.id, setupCode: modText)
  899. let alert = UIAlertController(
  900. title: String.localized("autocrypt_continue_transfer_title"),
  901. message: String.localized(success ? "autocrypt_continue_transfer_succeeded" : "autocrypt_bad_setup_code"),
  902. preferredStyle: .alert)
  903. if success {
  904. alert.addAction(UIAlertAction(title: String.localized("ok"), style: .default, handler: nil))
  905. } else {
  906. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  907. let retryAction = UIAlertAction(title: String.localized("autocrypt_continue_transfer_retry"), style: .default, handler: { _ in
  908. self.didTapAsm(msg: msg, orgText: modText)
  909. })
  910. alert.addAction(retryAction)
  911. alert.preferredAction = retryAction
  912. }
  913. self.navigationController?.present(alert, animated: true, completion: nil)
  914. })
  915. inputDlg.addAction(okAction)
  916. inputDlg.preferredAction = okAction // without setting preferredAction, cancel become shown *bold* as the preferred action
  917. navigationController?.present(inputDlg, animated: true, completion: nil)
  918. }
  919. func handleUIMenu() -> Bool {
  920. if UIMenuController.shared.isMenuVisible {
  921. UIMenuController.shared.setMenuVisible(false, animated: true)
  922. return true
  923. }
  924. return false
  925. }
  926. }
  927. // MARK: - BaseMessageCellDelegate
  928. extension ChatViewController: BaseMessageCellDelegate {
  929. @objc func quoteTapped(indexPath: IndexPath) {
  930. _ = handleUIMenu()
  931. let msg = DcMsg(id: messageIds[indexPath.row])
  932. if let quoteMsg = msg.quoteMessage,
  933. let index = messageIds.firstIndex(of: quoteMsg.id) {
  934. let indexPath = IndexPath(row: index, section: 0)
  935. tableView.scrollToRow(at: indexPath, at: .top, animated: true)
  936. }
  937. }
  938. @objc func textTapped(indexPath: IndexPath) {
  939. if handleUIMenu() { return }
  940. let message = DcMsg(id: messageIds[indexPath.row])
  941. if message.isSetupMessage {
  942. didTapAsm(msg: message, orgText: "")
  943. }
  944. }
  945. @objc func phoneNumberTapped(number: String) {
  946. if handleUIMenu() { return }
  947. logger.debug("phone number tapped \(number)")
  948. }
  949. @objc func commandTapped(command: String) {
  950. if handleUIMenu() { return }
  951. logger.debug("command tapped \(command)")
  952. }
  953. @objc func urlTapped(url: URL) {
  954. if handleUIMenu() { return }
  955. if Utils.isEmail(url: url) {
  956. logger.debug("tapped on contact")
  957. let email = Utils.getEmailFrom(url)
  958. self.askToChatWith(email: email)
  959. ///TODO: implement handling
  960. } else {
  961. UIApplication.shared.open(url)
  962. }
  963. }
  964. @objc func imageTapped(indexPath: IndexPath) {
  965. if handleUIMenu() { return }
  966. showMediaGalleryFor(indexPath: indexPath)
  967. }
  968. @objc func avatarTapped(indexPath: IndexPath) {
  969. let message = DcMsg(id: messageIds[indexPath.row])
  970. let contactDetailController = ContactDetailViewController(dcContext: dcContext, contactId: message.fromContactId)
  971. navigationController?.pushViewController(contactDetailController, animated: true)
  972. }
  973. }
  974. // MARK: - MediaPickerDelegate
  975. extension ChatViewController: MediaPickerDelegate {
  976. func onVideoSelected(url: NSURL) {
  977. sendVideo(url: url)
  978. }
  979. func onImageSelected(url: NSURL) {
  980. sendImage(url: url)
  981. }
  982. func onImageSelected(image: UIImage) {
  983. sendImage(image)
  984. }
  985. func onVoiceMessageRecorded(url: NSURL) {
  986. sendVoiceMessage(url: url)
  987. }
  988. func onDocumentSelected(url: NSURL) {
  989. sendDocumentMessage(url: url)
  990. }
  991. }
  992. // MARK: - MessageInputBarDelegate
  993. extension ChatViewController: InputBarAccessoryViewDelegate {
  994. func inputBar(_ inputBar: InputBarAccessoryView, didPressSendButtonWith text: String) {
  995. if inputBar.inputTextView.images.isEmpty {
  996. self.sendTextMessage(message: text.trimmingCharacters(in: .whitespacesAndNewlines))
  997. } else {
  998. let trimmedText = text.replacingOccurrences(of: "\u{FFFC}", with: "", options: .literal, range: nil)
  999. .trimmingCharacters(in: .whitespacesAndNewlines)
  1000. // only 1 attachment allowed for now, thus it takes the first one
  1001. self.sendImage(inputBar.inputTextView.images[0], message: trimmedText)
  1002. }
  1003. inputBar.inputTextView.text = String()
  1004. inputBar.inputTextView.attributedText = nil
  1005. }
  1006. }