ChatViewController.swift 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657
  1. import MapKit
  2. import QuickLook
  3. import UIKit
  4. import InputBarAccessoryView
  5. import AVFoundation
  6. import DcCore
  7. import SDWebImage
  8. class ChatViewController: UITableViewController {
  9. var dcContext: DcContext
  10. private var draftMessage: DcMsg?
  11. let outgoingAvatarOverlap: CGFloat = 17.5
  12. let loadCount = 30
  13. let chatId: Int
  14. var messageIds: [Int] = []
  15. var msgChangedObserver: NSObjectProtocol?
  16. var incomingMsgObserver: NSObjectProtocol?
  17. var ephemeralTimerModifiedObserver: NSObjectProtocol?
  18. // isDismissing indicates whether the ViewController is/was about to dismissed.
  19. // The VC can be dismissed by pressing back '<' or by a swipe-to-dismiss gesture.
  20. // The latter is cancelable and leads to viewWillAppear is called in case the gesture is cancelled
  21. // We need the flag to handle that special case correctly in viewWillAppear
  22. private var isDismissing = false
  23. private var isInitial = true
  24. private var ignoreInputBarChange = false
  25. private var isVisibleToUser: Bool = false
  26. private var keepKeyboard: Bool = false
  27. lazy var isGroupChat: Bool = {
  28. return dcContext.getChat(chatId: chatId).isGroup
  29. }()
  30. lazy var draft: DraftModel = {
  31. let draft = DraftModel(chatId: chatId)
  32. return draft
  33. }()
  34. /// The `InputBarAccessoryView` used as the `inputAccessoryView` in the view controller.
  35. open var messageInputBar = ChatInputBar()
  36. lazy var draftArea: DraftArea = {
  37. let view = DraftArea()
  38. view.translatesAutoresizingMaskIntoConstraints = false
  39. view.delegate = self
  40. view.inputBarAccessoryView = messageInputBar
  41. return view
  42. }()
  43. public lazy var editingBar: ChatEditingBar = {
  44. let view = ChatEditingBar()
  45. view.delegate = self
  46. view.translatesAutoresizingMaskIntoConstraints = false
  47. return view
  48. }()
  49. open override var shouldAutorotate: Bool {
  50. return false
  51. }
  52. private weak var timer: Timer?
  53. lazy var navBarTap: UITapGestureRecognizer = {
  54. UITapGestureRecognizer(target: self, action: #selector(chatProfilePressed))
  55. }()
  56. private var locationStreamingItem: UIBarButtonItem = {
  57. let indicator = LocationStreamingIndicator()
  58. return UIBarButtonItem(customView: indicator)
  59. }()
  60. private lazy var muteItem: UIBarButtonItem = {
  61. let imageView = UIImageView()
  62. imageView.tintColor = DcColors.defaultTextColor
  63. imageView.image = #imageLiteral(resourceName: "volume_off").withRenderingMode(.alwaysTemplate)
  64. imageView.translatesAutoresizingMaskIntoConstraints = false
  65. imageView.heightAnchor.constraint(equalToConstant: 20).isActive = true
  66. imageView.widthAnchor.constraint(equalToConstant: 20).isActive = true
  67. return UIBarButtonItem(customView: imageView)
  68. }()
  69. private lazy var ephemeralMessageItem: UIBarButtonItem = {
  70. let imageView = UIImageView()
  71. imageView.tintColor = DcColors.defaultTextColor
  72. imageView.image = #imageLiteral(resourceName: "ephemeral_timer").withRenderingMode(.alwaysTemplate)
  73. imageView.translatesAutoresizingMaskIntoConstraints = false
  74. imageView.heightAnchor.constraint(equalToConstant: 20).isActive = true
  75. imageView.widthAnchor.constraint(equalToConstant: 20).isActive = true
  76. return UIBarButtonItem(customView: imageView)
  77. }()
  78. private lazy var badgeItem: UIBarButtonItem = {
  79. let badge: InitialsBadge
  80. let chat = dcContext.getChat(chatId: chatId)
  81. if let image = chat.profileImage {
  82. badge = InitialsBadge(image: image, size: 28, accessibilityLabel: String.localized("menu_view_profile"))
  83. } else {
  84. badge = InitialsBadge(
  85. name: chat.name,
  86. color: chat.color,
  87. size: 28,
  88. accessibilityLabel: String.localized("menu_view_profile")
  89. )
  90. badge.setLabelFont(UIFont.systemFont(ofSize: 14))
  91. }
  92. badge.setVerified(chat.isProtected)
  93. badge.accessibilityTraits = .button
  94. return UIBarButtonItem(customView: badge)
  95. }()
  96. private lazy var contextMenu: ContextMenuProvider = {
  97. let copyItem = ContextMenuProvider.ContextMenuItem(
  98. title: String.localized("global_menu_edit_copy_desktop"),
  99. imageName: "doc.on.doc",
  100. action: #selector(BaseMessageCell.messageCopy),
  101. onPerform: { [weak self] indexPath in
  102. guard let self = self else { return }
  103. let id = self.messageIds[indexPath.row]
  104. let msg = DcMsg(id: id)
  105. let pasteboard = UIPasteboard.general
  106. if msg.type == DC_MSG_TEXT {
  107. pasteboard.string = msg.text
  108. } else {
  109. pasteboard.string = msg.summary(chars: 10000000)
  110. }
  111. }
  112. )
  113. let infoItem = ContextMenuProvider.ContextMenuItem(
  114. title: String.localized("info"),
  115. imageName: "info",
  116. action: #selector(BaseMessageCell.messageInfo),
  117. onPerform: { [weak self] indexPath in
  118. guard let self = self else { return }
  119. let msg = DcMsg(id: self.messageIds[indexPath.row])
  120. let msgViewController = MessageInfoViewController(dcContext: self.dcContext, message: msg)
  121. if let ctrl = self.navigationController {
  122. ctrl.pushViewController(msgViewController, animated: true)
  123. }
  124. }
  125. )
  126. let deleteItem = ContextMenuProvider.ContextMenuItem(
  127. title: String.localized("delete"),
  128. imageName: "trash",
  129. isDestructive: true,
  130. action: #selector(BaseMessageCell.messageDelete),
  131. onPerform: { [weak self] indexPath in
  132. DispatchQueue.main.async { [weak self] in
  133. guard let self = self else { return }
  134. self.tableView.becomeFirstResponder()
  135. let msg = DcMsg(id: self.messageIds[indexPath.row])
  136. self.askToDeleteMessage(id: msg.id)
  137. }
  138. }
  139. )
  140. let forwardItem = ContextMenuProvider.ContextMenuItem(
  141. title: String.localized("forward"),
  142. imageName: "ic_forward_white_36pt",
  143. action: #selector(BaseMessageCell.messageForward),
  144. onPerform: { [weak self] indexPath in
  145. guard let self = self else { return }
  146. let msg = DcMsg(id: self.messageIds[indexPath.row])
  147. RelayHelper.sharedInstance.setForwardMessage(messageId: msg.id)
  148. self.navigationController?.popViewController(animated: true)
  149. }
  150. )
  151. let replyItem = ContextMenuProvider.ContextMenuItem(
  152. title: String.localized("notify_reply_button"),
  153. imageName: "ic_reply",
  154. action: #selector(BaseMessageCell.messageReply),
  155. onPerform: { indexPath in
  156. DispatchQueue.main.async { [weak self] in
  157. self?.replyToMessage(at: indexPath)
  158. }
  159. }
  160. )
  161. let selectMoreItem = ContextMenuProvider.ContextMenuItem(
  162. title: String.localized("select_more"),
  163. imageName: "checkmark.circle",
  164. action: #selector(BaseMessageCell.messageSelectMore),
  165. onPerform: { indexPath in
  166. DispatchQueue.main.async { [weak self] in
  167. guard let self = self else { return }
  168. let messageId = self.messageIds[indexPath.row]
  169. self.setEditing(isEditing: true, selectedAtIndexPath: indexPath)
  170. }
  171. }
  172. )
  173. let config = ContextMenuProvider()
  174. if #available(iOS 13.0, *), !disableWriting {
  175. let mainContextMenu = ContextMenuProvider.ContextMenuItem(submenuitems: [replyItem, forwardItem, infoItem, copyItem, deleteItem])
  176. config.setMenu([mainContextMenu, selectMoreItem])
  177. } else if !disableWriting {
  178. config.setMenu([forwardItem, infoItem, copyItem, deleteItem, selectMoreItem])
  179. } else {
  180. config.setMenu([forwardItem, infoItem, copyItem, deleteItem])
  181. }
  182. return config
  183. }()
  184. /// The `BasicAudioController` controll the AVAudioPlayer state (play, pause, stop) and update audio cell UI accordingly.
  185. private lazy var audioController = AudioController(dcContext: dcContext, chatId: chatId, delegate: self)
  186. private var disableWriting: Bool
  187. var showCustomNavBar = true
  188. var highlightedMsg: Int?
  189. private lazy var mediaPicker: MediaPicker? = {
  190. let mediaPicker = MediaPicker(navigationController: navigationController)
  191. mediaPicker.delegate = self
  192. return mediaPicker
  193. }()
  194. var emptyStateView: EmptyStateLabel = {
  195. let view = EmptyStateLabel()
  196. view.isHidden = true
  197. return view
  198. }()
  199. init(dcContext: DcContext, chatId: Int, highlightedMsg: Int? = nil) {
  200. let dcChat = dcContext.getChat(chatId: chatId)
  201. self.dcContext = dcContext
  202. self.chatId = chatId
  203. self.disableWriting = !dcChat.canSend
  204. self.highlightedMsg = highlightedMsg
  205. super.init(nibName: nil, bundle: nil)
  206. hidesBottomBarWhenPushed = true
  207. }
  208. required init?(coder _: NSCoder) {
  209. fatalError("init(coder:) has not been implemented")
  210. }
  211. override func loadView() {
  212. self.tableView = ChatTableView(messageInputBar: self.disableWriting ? nil : messageInputBar)
  213. self.tableView.delegate = self
  214. self.tableView.dataSource = self
  215. self.view = self.tableView
  216. }
  217. override func viewDidLoad() {
  218. super.viewDidLoad()
  219. tableView.register(TextMessageCell.self, forCellReuseIdentifier: "text")
  220. tableView.register(ImageTextCell.self, forCellReuseIdentifier: "image")
  221. tableView.register(FileTextCell.self, forCellReuseIdentifier: "file")
  222. tableView.register(InfoMessageCell.self, forCellReuseIdentifier: "info")
  223. tableView.register(AudioMessageCell.self, forCellReuseIdentifier: "audio")
  224. tableView.rowHeight = UITableView.automaticDimension
  225. tableView.separatorStyle = .none
  226. tableView.keyboardDismissMode = .interactive
  227. tableView.contentInsetAdjustmentBehavior = .never
  228. navigationController?.setNavigationBarHidden(false, animated: false)
  229. if !dcContext.isConfigured() {
  230. // TODO: display message about nothing being configured
  231. return
  232. }
  233. configureEmptyStateView()
  234. if !disableWriting {
  235. configureMessageInputBar()
  236. draft.parse(draftMsg: dcContext.getDraft(chatId: chatId))
  237. messageInputBar.inputTextView.text = draft.text
  238. configureDraftArea(draft: draft, animated: false)
  239. editingBar.delegate = self
  240. tableView.allowsMultipleSelectionDuringEditing = true
  241. }
  242. }
  243. private func getTopInsetHeight() -> CGFloat {
  244. return UIApplication.shared.statusBarFrame.height + (navigationController?.navigationBar.bounds.height ?? 0)
  245. }
  246. private func startTimer() {
  247. stopTimer()
  248. timer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { [weak self] _ in
  249. // reload table
  250. DispatchQueue.main.async { [weak self] in
  251. guard let self = self,
  252. let appDelegate = UIApplication.shared.delegate as? AppDelegate
  253. else { return }
  254. if appDelegate.appIsInForeground() {
  255. self.messageIds = self.getMessageIds()
  256. self.reloadData()
  257. } else {
  258. logger.warning("startTimer() must not be executed in background")
  259. }
  260. }
  261. }
  262. }
  263. private func stopTimer() {
  264. if let timer = timer {
  265. timer.invalidate()
  266. }
  267. timer = nil
  268. }
  269. private func configureEmptyStateView() {
  270. emptyStateView.addCenteredTo(parentView: view)
  271. }
  272. override func viewWillAppear(_ animated: Bool) {
  273. super.viewWillAppear(animated)
  274. // this will be removed in viewWillDisappear
  275. navigationController?.navigationBar.addGestureRecognizer(navBarTap)
  276. if showCustomNavBar {
  277. updateTitle(chat: dcContext.getChat(chatId: chatId))
  278. }
  279. if !isDismissing {
  280. self.tableView.becomeFirstResponder()
  281. loadMessages()
  282. self.tableView.contentInset = UIEdgeInsets(top: self.getTopInsetHeight(),
  283. left: 0,
  284. bottom: self.messageInputBar.calculateIntrinsicContentSize().height,
  285. right: 0)
  286. if let msgId = self.highlightedMsg, self.messageIds.firstIndex(of: msgId) != nil {
  287. UIView.animate(withDuration: 0.1, delay: 0, options: .allowAnimatedContent, animations: { [weak self] in
  288. self?.scrollToMessage(msgId: msgId, animated: false)
  289. }, completion: { [weak self] finished in
  290. if finished {
  291. guard let self = self else { return }
  292. self.highlightedMsg = nil
  293. self.isInitial = false
  294. self.ignoreInputBarChange = false
  295. }
  296. })
  297. } else {
  298. UIView.animate(withDuration: 0.1, delay: 0, options: .allowAnimatedContent, animations: { [weak self] in
  299. guard let self = self else { return }
  300. if self.isInitial {
  301. self.scrollToLastUnseenMessage()
  302. }
  303. }, completion: { [weak self] finished in
  304. if finished {
  305. self?.isInitial = false
  306. self?.ignoreInputBarChange = false
  307. }
  308. })
  309. }
  310. }
  311. isDismissing = false
  312. if RelayHelper.sharedInstance.isForwarding() {
  313. askToForwardMessage()
  314. }
  315. prepareContextMenu()
  316. }
  317. override func viewDidAppear(_ animated: Bool) {
  318. super.viewDidAppear(animated)
  319. AppStateRestorer.shared.storeLastActiveChat(chatId: chatId)
  320. let nc = NotificationCenter.default
  321. msgChangedObserver = nc.addObserver(
  322. forName: dcNotificationChanged,
  323. object: nil,
  324. queue: OperationQueue.main
  325. ) { [weak self] notification in
  326. guard let self = self else { return }
  327. if let ui = notification.userInfo {
  328. if self.disableWriting {
  329. // always refresh, as we can't check currently
  330. self.refreshMessages()
  331. } else if let id = ui["message_id"] as? Int {
  332. if id > 0 {
  333. self.updateMessage(id)
  334. } else {
  335. // change might be a deletion
  336. self.refreshMessages()
  337. }
  338. }
  339. if self.showCustomNavBar {
  340. self.updateTitle(chat: self.dcContext.getChat(chatId: self.chatId))
  341. }
  342. }
  343. }
  344. incomingMsgObserver = nc.addObserver(
  345. forName: dcNotificationIncoming,
  346. object: nil, queue: OperationQueue.main
  347. ) { [weak self] notification in
  348. guard let self = self else { return }
  349. if let ui = notification.userInfo {
  350. if self.chatId == ui["chat_id"] as? Int {
  351. if let id = ui["message_id"] as? Int {
  352. if id > 0 {
  353. self.insertMessage(DcMsg(id: id))
  354. }
  355. }
  356. }
  357. }
  358. }
  359. ephemeralTimerModifiedObserver = nc.addObserver(
  360. forName: dcEphemeralTimerModified,
  361. object: nil, queue: OperationQueue.main
  362. ) { [weak self] _ in
  363. guard let self = self else { return }
  364. self.updateTitle(chat: self.dcContext.getChat(chatId: self.chatId))
  365. }
  366. nc.addObserver(self,
  367. selector: #selector(applicationDidBecomeActive(_:)),
  368. name: UIApplication.didBecomeActiveNotification,
  369. object: nil)
  370. nc.addObserver(self,
  371. selector: #selector(applicationWillResignActive(_:)),
  372. name: UIApplication.willResignActiveNotification,
  373. object: nil)
  374. // things that do not affect the chatview
  375. // and are delayed after the view is displayed
  376. DispatchQueue.global(qos: .background).async { [weak self] in
  377. guard let self = self else { return }
  378. self.dcContext.marknoticedChat(chatId: self.chatId)
  379. }
  380. handleUserVisibility(isVisible: true)
  381. }
  382. override func viewWillDisappear(_ animated: Bool) {
  383. super.viewWillDisappear(animated)
  384. // the navigationController will be used when chatDetail is pushed, so we have to remove that gestureRecognizer
  385. navigationController?.navigationBar.removeGestureRecognizer(navBarTap)
  386. isDismissing = true
  387. }
  388. override func viewDidDisappear(_ animated: Bool) {
  389. super.viewDidDisappear(animated)
  390. isDismissing = false
  391. ignoreInputBarChange = true
  392. AppStateRestorer.shared.resetLastActiveChat()
  393. handleUserVisibility(isVisible: false)
  394. let nc = NotificationCenter.default
  395. if let msgChangedObserver = self.msgChangedObserver {
  396. nc.removeObserver(msgChangedObserver)
  397. }
  398. if let incomingMsgObserver = self.incomingMsgObserver {
  399. nc.removeObserver(incomingMsgObserver)
  400. }
  401. if let ephemeralTimerModifiedObserver = self.ephemeralTimerModifiedObserver {
  402. nc.removeObserver(ephemeralTimerModifiedObserver)
  403. }
  404. nc.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil)
  405. nc.removeObserver(self, name: UIApplication.willResignActiveNotification, object: nil)
  406. audioController.stopAnyOngoingPlaying()
  407. }
  408. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  409. let lastSectionVisibleBeforeTransition = self.isLastRowVisible()
  410. coordinator.animate(
  411. alongsideTransition: { [weak self] _ in
  412. guard let self = self else { return }
  413. if self.showCustomNavBar {
  414. self.navigationItem.setRightBarButton(self.badgeItem, animated: true)
  415. }
  416. if lastSectionVisibleBeforeTransition {
  417. self.scrollToBottom(animated: false)
  418. }
  419. },
  420. completion: {[weak self] _ in
  421. guard let self = self else { return }
  422. self.updateTitle(chat: self.dcContext.getChat(chatId: self.chatId))
  423. if lastSectionVisibleBeforeTransition {
  424. DispatchQueue.main.async { [weak self] in
  425. self?.reloadData()
  426. self?.scrollToBottom(animated: false)
  427. }
  428. }
  429. }
  430. )
  431. super.viewWillTransition(to: size, with: coordinator)
  432. }
  433. @objc func applicationDidBecomeActive(_ notification: NSNotification) {
  434. if navigationController?.visibleViewController == self {
  435. handleUserVisibility(isVisible: true)
  436. }
  437. }
  438. @objc func applicationWillResignActive(_ notification: NSNotification) {
  439. if navigationController?.visibleViewController == self {
  440. handleUserVisibility(isVisible: false)
  441. }
  442. }
  443. func handleUserVisibility(isVisible: Bool) {
  444. if isVisible {
  445. isVisibleToUser = true
  446. startTimer()
  447. markSeenMessagesInVisibleArea()
  448. } else {
  449. isVisibleToUser = false
  450. stopTimer()
  451. draft.save(context: dcContext)
  452. }
  453. }
  454. /// UITableView methods
  455. override func numberOfSections(in tableView: UITableView) -> Int {
  456. return 1
  457. }
  458. override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
  459. return messageIds.count
  460. }
  461. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  462. _ = handleUIMenu()
  463. let id = messageIds[indexPath.row]
  464. if id == DC_MSG_ID_DAYMARKER {
  465. let cell = tableView.dequeueReusableCell(withIdentifier: "info", for: indexPath) as? InfoMessageCell ?? InfoMessageCell()
  466. if messageIds.count > indexPath.row + 1 {
  467. let nextMessageId = messageIds[indexPath.row + 1]
  468. let nextMessage = DcMsg(id: nextMessageId)
  469. cell.update(text: DateUtils.getDateString(date: nextMessage.sentDate))
  470. } else {
  471. cell.update(text: "ErrDaymarker")
  472. }
  473. return cell
  474. } else if id == DC_MSG_ID_MARKER1 {
  475. // unread messages marker
  476. let cell = tableView.dequeueReusableCell(withIdentifier: "info", for: indexPath) as? InfoMessageCell ?? InfoMessageCell()
  477. let freshMsgsCount = self.messageIds.count - (indexPath.row + 1)
  478. cell.update(text: String.localized(stringID: "chat_n_new_messages", count: freshMsgsCount))
  479. return cell
  480. }
  481. let message = DcMsg(id: id)
  482. if message.isInfo {
  483. let cell = tableView.dequeueReusableCell(withIdentifier: "info", for: indexPath) as? InfoMessageCell ?? InfoMessageCell()
  484. cell.update(text: message.text)
  485. return cell
  486. }
  487. let cell: BaseMessageCell
  488. if message.type == DC_MSG_IMAGE || message.type == DC_MSG_GIF || message.type == DC_MSG_VIDEO || message.type == DC_MSG_STICKER {
  489. cell = tableView.dequeueReusableCell(withIdentifier: "image", for: indexPath) as? ImageTextCell ?? ImageTextCell()
  490. } else if message.type == DC_MSG_FILE {
  491. if message.isSetupMessage {
  492. cell = tableView.dequeueReusableCell(withIdentifier: "text", for: indexPath) as? TextMessageCell ?? TextMessageCell()
  493. message.text = String.localized("autocrypt_asm_click_body")
  494. } else {
  495. cell = tableView.dequeueReusableCell(withIdentifier: "file", for: indexPath) as? FileTextCell ?? FileTextCell()
  496. }
  497. } else if message.type == DC_MSG_AUDIO || message.type == DC_MSG_VOICE {
  498. let audioMessageCell: AudioMessageCell = tableView.dequeueReusableCell(withIdentifier: "audio",
  499. for: indexPath) as? AudioMessageCell ?? AudioMessageCell()
  500. audioController.update(audioMessageCell, with: message.id)
  501. cell = audioMessageCell
  502. } else {
  503. cell = tableView.dequeueReusableCell(withIdentifier: "text", for: indexPath) as? TextMessageCell ?? TextMessageCell()
  504. }
  505. var showAvatar = isGroupChat && !message.isFromCurrentSender
  506. var showName = isGroupChat
  507. if message.overrideSenderName != nil {
  508. showAvatar = !message.isFromCurrentSender
  509. showName = true
  510. }
  511. cell.baseDelegate = self
  512. cell.update(msg: message,
  513. messageStyle: configureMessageStyle(for: message, at: indexPath),
  514. showAvatar: showAvatar,
  515. showName: showName)
  516. return cell
  517. }
  518. public override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  519. if !decelerate {
  520. markSeenMessagesInVisibleArea()
  521. }
  522. }
  523. public override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  524. markSeenMessagesInVisibleArea()
  525. }
  526. private func configureDraftArea(draft: DraftModel, animated: Bool = true) {
  527. draftArea.configure(draft: draft)
  528. if draft.isEditing {
  529. messageInputBar.setMiddleContentView(editingBar, animated: false)
  530. messageInputBar.setLeftStackViewWidthConstant(to: 0, animated: false)
  531. messageInputBar.setRightStackViewWidthConstant(to: 0, animated: false)
  532. messageInputBar.padding = UIEdgeInsets(top: 6, left: 0, bottom: 6, right: 0)
  533. } else {
  534. messageInputBar.setMiddleContentView(messageInputBar.inputTextView, animated: false)
  535. messageInputBar.setLeftStackViewWidthConstant(to: 40, animated: false)
  536. messageInputBar.setRightStackViewWidthConstant(to: 40, animated: false)
  537. messageInputBar.padding = UIEdgeInsets(top: 6, left: 6, bottom: 6, right: 12)
  538. }
  539. messageInputBar.setStackViewItems([draftArea], forStack: .top, animated: animated)
  540. }
  541. override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
  542. let swipeAction = UISwipeActionsConfiguration(actions: [])
  543. return swipeAction
  544. }
  545. override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
  546. if disableWriting || DcMsg(id: messageIds[indexPath.row]).isInfo {
  547. return nil
  548. }
  549. let action = UIContextualAction(style: .normal, title: nil,
  550. handler: { [weak self] (_, _, completionHandler) in
  551. self?.keepKeyboard = true
  552. self?.replyToMessage(at: indexPath)
  553. completionHandler(true)
  554. })
  555. if #available(iOS 13.0, *) {
  556. action.image = UIImage(named: traitCollection.userInterfaceStyle == .light ? "ic_reply_black" : "ic_reply")
  557. action.backgroundColor = DcColors.chatBackgroundColor
  558. } else {
  559. action.image = UIImage(named: "ic_reply_black")
  560. action.backgroundColor = .systemBlue
  561. }
  562. action.image?.accessibilityTraits = .button
  563. action.image?.accessibilityLabel = String.localized("menu_reply")
  564. let configuration = UISwipeActionsConfiguration(actions: [action])
  565. return configuration
  566. }
  567. func replyToMessage(at indexPath: IndexPath) {
  568. let message = DcMsg(id: self.messageIds[indexPath.row])
  569. self.draft.setQuote(quotedMsg: message)
  570. self.configureDraftArea(draft: self.draft)
  571. self.messageInputBar.inputTextView.becomeFirstResponder()
  572. }
  573. func markSeenMessagesInVisibleArea() {
  574. if isVisibleToUser,
  575. let indexPaths = tableView.indexPathsForVisibleRows {
  576. let visibleMessagesIds = indexPaths.map { UInt32(messageIds[$0.row]) }
  577. if !visibleMessagesIds.isEmpty {
  578. DispatchQueue.global(qos: .background).async { [weak self] in
  579. self?.dcContext.markSeenMessages(messageIds: visibleMessagesIds)
  580. }
  581. }
  582. }
  583. }
  584. func markSeenMessage(id: Int) {
  585. if isVisibleToUser {
  586. DispatchQueue.global(qos: .background).async { [weak self] in
  587. self?.dcContext.markSeenMessages(messageIds: [UInt32(id)])
  588. }
  589. }
  590. }
  591. override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
  592. if tableView.isEditing {
  593. handleEditingBar()
  594. }
  595. }
  596. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  597. if tableView.isEditing {
  598. handleEditingBar()
  599. return
  600. }
  601. let messageId = messageIds[indexPath.row]
  602. let message = DcMsg(id: messageId)
  603. if message.isSetupMessage {
  604. didTapAsm(msg: message, orgText: "")
  605. } else if message.type == DC_MSG_FILE ||
  606. message.type == DC_MSG_AUDIO ||
  607. message.type == DC_MSG_VOICE {
  608. showMediaGalleryFor(message: message)
  609. }
  610. _ = handleUIMenu()
  611. }
  612. func configureMessageStyle(for message: DcMsg, at indexPath: IndexPath) -> UIRectCorner {
  613. var corners: UIRectCorner = []
  614. if message.isFromCurrentSender {
  615. corners.formUnion(.topLeft)
  616. corners.formUnion(.bottomLeft)
  617. corners.formUnion(.topRight)
  618. } else {
  619. corners.formUnion(.topRight)
  620. corners.formUnion(.bottomRight)
  621. corners.formUnion(.topLeft)
  622. }
  623. return corners
  624. }
  625. private func getBackgroundColor(for currentMessage: DcMsg) -> UIColor {
  626. return currentMessage.isFromCurrentSender ? DcColors.messagePrimaryColor : DcColors.messageSecondaryColor
  627. }
  628. private func updateTitle(chat: DcChat) {
  629. let titleView = ChatTitleView()
  630. var subtitle = "ErrSubtitle"
  631. let chatContactIds = chat.contactIds
  632. if chat.isMailinglist {
  633. subtitle = String.localized("mailing_list")
  634. } else if chat.isGroup {
  635. subtitle = String.localized(stringID: "n_members", count: chatContactIds.count)
  636. } else if chat.isDeviceTalk {
  637. subtitle = String.localized("device_talk_subtitle")
  638. } else if chat.isSelfTalk {
  639. subtitle = String.localized("chat_self_talk_subtitle")
  640. } else if chatContactIds.count >= 1 {
  641. subtitle = DcContact(id: chatContactIds[0]).email
  642. }
  643. titleView.updateTitleView(title: chat.name, subtitle: subtitle)
  644. navigationItem.titleView = titleView
  645. var rightBarButtonItems = [badgeItem]
  646. if chat.isSendingLocations {
  647. rightBarButtonItems.append(locationStreamingItem)
  648. }
  649. if chat.isMuted {
  650. rightBarButtonItems.append(muteItem)
  651. }
  652. if dcContext.getChatEphemeralTimer(chatId: chat.id) > 0 {
  653. rightBarButtonItems.append(ephemeralMessageItem)
  654. }
  655. navigationItem.rightBarButtonItems = rightBarButtonItems
  656. }
  657. @objc
  658. private func refreshMessages() {
  659. self.messageIds = self.getMessageIds()
  660. let wasLastSectionVisible = self.isLastRowVisible()
  661. self.reloadData()
  662. if wasLastSectionVisible {
  663. self.scrollToBottom(animated: true)
  664. }
  665. self.showEmptyStateView(self.messageIds.isEmpty)
  666. }
  667. private func reloadData() {
  668. let selectredRows = tableView.indexPathsForSelectedRows
  669. tableView.reloadData()
  670. // There's an iOS bug, filling up the console output but which can be ignored: https://developer.apple.com/forums/thread/668295
  671. // [Assert] Attempted to call -cellForRowAtIndexPath: on the table view while it was in the process of updating its visible cells, which is not allowed.
  672. selectredRows?.forEach({ (selectedRow) in
  673. tableView.selectRow(at: selectedRow, animated: false, scrollPosition: .none)
  674. })
  675. }
  676. private func loadMessages() {
  677. // update message ids
  678. var msgIds = self.getMessageIds()
  679. let freshMsgsCount = self.dcContext.getUnreadMessages(chatId: self.chatId)
  680. if freshMsgsCount > 0 && msgIds.count >= freshMsgsCount {
  681. let index = msgIds.count - freshMsgsCount
  682. msgIds.insert(Int(DC_MSG_ID_MARKER1), at: index)
  683. }
  684. self.messageIds = msgIds
  685. self.showEmptyStateView(self.messageIds.isEmpty)
  686. self.reloadData()
  687. }
  688. private func isLastRowVisible() -> Bool {
  689. guard !messageIds.isEmpty else { return false }
  690. let lastIndexPath = IndexPath(item: messageIds.count - 1, section: 0)
  691. return tableView.indexPathsForVisibleRows?.contains(lastIndexPath) ?? false
  692. }
  693. private func scrollToBottom(animated: Bool) {
  694. if !messageIds.isEmpty {
  695. DispatchQueue.main.async { [weak self] in
  696. guard let self = self else { return }
  697. let numberOfRows = self.tableView.numberOfRows(inSection: 0)
  698. if numberOfRows > 0 {
  699. self.tableView.scrollToRow(at: IndexPath(row: numberOfRows - 1, section: 0), at: .bottom, animated: animated)
  700. }
  701. }
  702. }
  703. }
  704. private func scrollToLastUnseenMessage() {
  705. DispatchQueue.main.async { [weak self] in
  706. guard let self = self else { return }
  707. if let markerMessageIndex = self.messageIds.index(of: Int(DC_MSG_ID_MARKER1)) {
  708. let indexPath = IndexPath(row: markerMessageIndex, section: 0)
  709. self.tableView.scrollToRow(at: indexPath, at: .top, animated: false)
  710. } else {
  711. // scroll to bottom
  712. let numberOfRows = self.tableView.numberOfRows(inSection: 0)
  713. if numberOfRows > 0 {
  714. self.tableView.scrollToRow(at: IndexPath(row: numberOfRows - 1, section: 0), at: .bottom, animated: false)
  715. }
  716. }
  717. }
  718. }
  719. private func scrollToMessage(msgId: Int, animated: Bool = true) {
  720. DispatchQueue.main.async { [weak self] in
  721. guard let self = self else { return }
  722. guard let index = self.messageIds.firstIndex(of: msgId) else {
  723. return
  724. }
  725. let indexPath = IndexPath(row: index, section: 0)
  726. self.tableView.scrollToRow(at: indexPath, at: .top, animated: animated)
  727. }
  728. }
  729. private func showEmptyStateView(_ show: Bool) {
  730. if show {
  731. let dcChat = dcContext.getChat(chatId: chatId)
  732. if chatId == DC_CHAT_ID_DEADDROP {
  733. if dcContext.showEmails != DC_SHOW_EMAILS_ALL {
  734. emptyStateView.text = String.localized("chat_no_contact_requests")
  735. } else {
  736. emptyStateView.text = String.localized("chat_no_messages")
  737. }
  738. } else if dcChat.isGroup {
  739. if dcChat.isUnpromoted {
  740. emptyStateView.text = String.localized("chat_new_group_hint")
  741. } else {
  742. emptyStateView.text = String.localized("chat_no_messages")
  743. }
  744. } else if dcChat.isSelfTalk {
  745. emptyStateView.text = String.localized("saved_messages_explain")
  746. } else if dcChat.isDeviceTalk {
  747. emptyStateView.text = String.localized("device_talk_explain")
  748. } else {
  749. emptyStateView.text = String.localizedStringWithFormat(String.localized("chat_no_messages_hint"), dcChat.name, dcChat.name)
  750. }
  751. emptyStateView.isHidden = false
  752. } else {
  753. emptyStateView.isHidden = true
  754. }
  755. }
  756. private func getMessageIds() -> [Int] {
  757. return dcContext.getMessageIds(chatId: chatId)
  758. }
  759. @objc private func saveDraft() {
  760. draft.save(context: dcContext)
  761. }
  762. private func configureMessageInputBar() {
  763. messageInputBar.delegate = self
  764. messageInputBar.inputTextView.tintColor = DcColors.primary
  765. messageInputBar.inputTextView.placeholder = String.localized("chat_input_placeholder")
  766. messageInputBar.separatorLine.backgroundColor = DcColors.colorDisabled
  767. messageInputBar.inputTextView.tintColor = DcColors.primary
  768. messageInputBar.inputTextView.textColor = DcColors.defaultTextColor
  769. messageInputBar.backgroundView.backgroundColor = DcColors.chatBackgroundColor
  770. messageInputBar.backgroundColor = DcColors.chatBackgroundColor
  771. messageInputBar.inputTextView.backgroundColor = DcColors.inputFieldColor
  772. messageInputBar.inputTextView.placeholderTextColor = DcColors.placeholderColor
  773. messageInputBar.inputTextView.textContainerInset = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 38)
  774. messageInputBar.inputTextView.placeholderLabelInsets = UIEdgeInsets(top: 8, left: 20, bottom: 8, right: 38)
  775. messageInputBar.inputTextView.layer.borderColor = UIColor.themeColor(light: UIColor(red: 200 / 255, green: 200 / 255, blue: 200 / 255, alpha: 1),
  776. dark: UIColor(red: 55 / 255, green: 55/255, blue: 55/255, alpha: 1)).cgColor
  777. messageInputBar.inputTextView.layer.borderWidth = 1.0
  778. messageInputBar.inputTextView.layer.cornerRadius = 13.0
  779. messageInputBar.inputTextView.layer.masksToBounds = true
  780. messageInputBar.inputTextView.scrollIndicatorInsets = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0)
  781. configureInputBarItems()
  782. messageInputBar.inputTextView.delegate = self
  783. if let inputTextView = messageInputBar.inputTextView as? ChatInputTextView {
  784. inputTextView.imagePasteDelegate = self
  785. }
  786. }
  787. private func evaluateInputBar(draft: DraftModel) {
  788. messageInputBar.sendButton.isEnabled = draft.canSend()
  789. }
  790. private func configureInputBarItems() {
  791. messageInputBar.setLeftStackViewWidthConstant(to: 40, animated: false)
  792. messageInputBar.setRightStackViewWidthConstant(to: 40, animated: false)
  793. let sendButtonImage = UIImage(named: "paper_plane")?.withRenderingMode(.alwaysTemplate)
  794. messageInputBar.sendButton.image = sendButtonImage
  795. messageInputBar.sendButton.accessibilityLabel = String.localized("menu_send")
  796. messageInputBar.sendButton.accessibilityTraits = .button
  797. messageInputBar.sendButton.title = nil
  798. messageInputBar.sendButton.tintColor = UIColor(white: 1, alpha: 1)
  799. messageInputBar.sendButton.layer.cornerRadius = 20
  800. messageInputBar.middleContentViewPadding = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 10)
  801. // this adds a padding between textinputfield and send button
  802. messageInputBar.sendButton.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
  803. messageInputBar.sendButton.setSize(CGSize(width: 40, height: 40), animated: false)
  804. messageInputBar.padding = UIEdgeInsets(top: 6, left: 6, bottom: 6, right: 12)
  805. messageInputBar.shouldManageSendButtonEnabledState = false
  806. let leftItems = [
  807. InputBarButtonItem()
  808. .configure {
  809. $0.spacing = .fixed(0)
  810. let clipperIcon = #imageLiteral(resourceName: "ic_attach_file_36pt").withRenderingMode(.alwaysTemplate)
  811. $0.image = clipperIcon
  812. $0.tintColor = DcColors.primary
  813. $0.setSize(CGSize(width: 40, height: 40), animated: false)
  814. $0.accessibilityLabel = String.localized("menu_add_attachment")
  815. $0.accessibilityTraits = .button
  816. }.onSelected {
  817. $0.tintColor = UIColor.themeColor(light: .lightGray, dark: .darkGray)
  818. }.onDeselected {
  819. $0.tintColor = DcColors.primary
  820. }.onTouchUpInside { [weak self] _ in
  821. self?.clipperButtonPressed()
  822. }
  823. ]
  824. messageInputBar.setStackViewItems(leftItems, forStack: .left, animated: false)
  825. // This just adds some more flare
  826. messageInputBar.sendButton
  827. .onEnabled { item in
  828. UIView.animate(withDuration: 0.3, animations: {
  829. item.backgroundColor = DcColors.primary
  830. })}
  831. .onDisabled { item in
  832. UIView.animate(withDuration: 0.3, animations: {
  833. item.backgroundColor = DcColors.colorDisabled
  834. })}
  835. }
  836. @objc private func chatProfilePressed() {
  837. if chatId != DC_CHAT_ID_DEADDROP {
  838. showChatDetail(chatId: chatId)
  839. }
  840. }
  841. @objc private func clipperButtonPressed() {
  842. showClipperOptions()
  843. }
  844. private func showClipperOptions() {
  845. let alert = UIAlertController(title: nil, message: nil, preferredStyle: .safeActionSheet)
  846. let galleryAction = PhotoPickerAlertAction(title: String.localized("gallery"), style: .default, handler: galleryButtonPressed(_:))
  847. let cameraAction = PhotoPickerAlertAction(title: String.localized("camera"), style: .default, handler: cameraButtonPressed(_:))
  848. let documentAction = UIAlertAction(title: String.localized("files"), style: .default, handler: documentActionPressed(_:))
  849. let voiceMessageAction = UIAlertAction(title: String.localized("voice_message"), style: .default, handler: voiceMessageButtonPressed(_:))
  850. let isLocationStreaming = dcContext.isSendingLocationsToChat(chatId: chatId)
  851. let locationStreamingAction = UIAlertAction(title: isLocationStreaming ? String.localized("stop_sharing_location") : String.localized("location"),
  852. style: isLocationStreaming ? .destructive : .default,
  853. handler: locationStreamingButtonPressed(_:))
  854. alert.addAction(cameraAction)
  855. alert.addAction(galleryAction)
  856. alert.addAction(documentAction)
  857. alert.addAction(voiceMessageAction)
  858. if UserDefaults.standard.bool(forKey: "location_streaming") {
  859. alert.addAction(locationStreamingAction)
  860. }
  861. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  862. self.present(alert, animated: true, completion: {
  863. // unfortunately, voiceMessageAction.accessibilityHint does not work,
  864. // but this hack does the trick
  865. if UIAccessibility.isVoiceOverRunning {
  866. if let view = voiceMessageAction.value(forKey: "__representer") as? UIView {
  867. view.accessibilityHint = String.localized("a11y_voice_message_hint_ios")
  868. }
  869. }
  870. })
  871. }
  872. private func confirmationAlert(title: String, actionTitle: String, actionStyle: UIAlertAction.Style = .default, actionHandler: @escaping ((UIAlertAction) -> Void), cancelHandler: ((UIAlertAction) -> Void)? = nil) {
  873. let alert = UIAlertController(title: title,
  874. message: nil,
  875. preferredStyle: .safeActionSheet)
  876. alert.addAction(UIAlertAction(title: actionTitle, style: actionStyle, handler: actionHandler))
  877. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: cancelHandler ?? { _ in
  878. self.dismiss(animated: true, completion: nil)
  879. }))
  880. present(alert, animated: true, completion: nil)
  881. }
  882. private func askToChatWith(email: String) {
  883. let contactId = self.dcContext.createContact(name: "", email: email)
  884. if dcContext.getChatIdByContactId(contactId: contactId) != 0 {
  885. self.dismiss(animated: true, completion: nil)
  886. let chatId = self.dcContext.createChatByContactId(contactId: contactId)
  887. self.showChat(chatId: chatId)
  888. } else {
  889. confirmationAlert(title: String.localizedStringWithFormat(String.localized("ask_start_chat_with"), email),
  890. actionTitle: String.localized("start_chat"),
  891. actionHandler: { _ in
  892. self.dismiss(animated: true, completion: nil)
  893. let chatId = self.dcContext.createChatByContactId(contactId: contactId)
  894. self.showChat(chatId: chatId)})
  895. }
  896. }
  897. private func askToDeleteMessage(id: Int) {
  898. self.askToDeleteMessages(ids: [id])
  899. }
  900. private func askToDeleteMessages(ids: [Int]) {
  901. let title = String.localized(stringID: "ask_delete_messages", count: ids.count)
  902. confirmationAlert(title: title, actionTitle: String.localized("delete"), actionStyle: .destructive,
  903. actionHandler: { _ in
  904. self.dcContext.deleteMessages(msgIds: ids)
  905. if self.tableView.isEditing {
  906. self.setEditing(isEditing: false)
  907. }
  908. })
  909. }
  910. private func askToForwardMessage() {
  911. let chat = dcContext.getChat(chatId: self.chatId)
  912. if chat.isSelfTalk {
  913. RelayHelper.sharedInstance.forward(to: self.chatId)
  914. refreshMessages()
  915. } else {
  916. confirmationAlert(title: String.localizedStringWithFormat(String.localized("ask_forward"), chat.name),
  917. actionTitle: String.localized("menu_forward"),
  918. actionHandler: { _ in
  919. RelayHelper.sharedInstance.forward(to: self.chatId)
  920. self.dismiss(animated: true, completion: nil)},
  921. cancelHandler: { _ in
  922. self.dismiss(animated: false, completion: nil)
  923. self.navigationController?.popViewController(animated: true)})
  924. }
  925. }
  926. // MARK: - coordinator
  927. private func showChatDetail(chatId: Int) {
  928. let chat = dcContext.getChat(chatId: chatId)
  929. if !chat.isGroup {
  930. if let contactId = chat.contactIds.first {
  931. let contactDetailController = ContactDetailViewController(dcContext: dcContext, contactId: contactId)
  932. navigationController?.pushViewController(contactDetailController, animated: true)
  933. }
  934. } else {
  935. let groupChatDetailViewController = GroupChatDetailViewController(chatId: chatId, dcContext: dcContext)
  936. navigationController?.pushViewController(groupChatDetailViewController, animated: true)
  937. }
  938. }
  939. func showChat(chatId: Int, messageId: Int? = nil, animated: Bool = true) {
  940. if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
  941. appDelegate.appCoordinator.showChat(chatId: chatId, msgId: messageId, animated: animated, clearViewControllerStack: true)
  942. }
  943. }
  944. private func showDocumentLibrary() {
  945. mediaPicker?.showDocumentLibrary()
  946. }
  947. private func showVoiceMessageRecorder() {
  948. mediaPicker?.showVoiceRecorder()
  949. }
  950. private func showCameraViewController() {
  951. if AVCaptureDevice.authorizationStatus(for: .video) == .authorized {
  952. self.mediaPicker?.showCamera()
  953. } else {
  954. AVCaptureDevice.requestAccess(for: .video, completionHandler: { [weak self] (granted: Bool) in
  955. guard let self = self else { return }
  956. if granted {
  957. self.mediaPicker?.showCamera()
  958. } else {
  959. self.showCameraPermissionAlert()
  960. }
  961. })
  962. }
  963. }
  964. private func showCameraPermissionAlert() {
  965. DispatchQueue.main.async { [weak self] in
  966. let alert = UIAlertController(title: String.localized("perm_required_title"),
  967. message: String.localized("perm_ios_explain_access_to_camera_denied"),
  968. preferredStyle: .alert)
  969. if let appSettings = URL(string: UIApplication.openSettingsURLString) {
  970. alert.addAction(UIAlertAction(title: String.localized("open_settings"), style: .default, handler: { _ in
  971. UIApplication.shared.open(appSettings, options: [:], completionHandler: nil)}))
  972. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .destructive, handler: nil))
  973. }
  974. self?.present(alert, animated: true, completion: nil)
  975. }
  976. }
  977. private func showPhotoVideoLibrary(delegate: MediaPickerDelegate) {
  978. mediaPicker?.showPhotoVideoLibrary()
  979. }
  980. private func showMediaGallery(currentIndex: Int, msgIds: [Int]) {
  981. let betterPreviewController = PreviewController(type: .multi(msgIds, currentIndex))
  982. let nav = UINavigationController(rootViewController: betterPreviewController)
  983. nav.modalPresentationStyle = .fullScreen
  984. navigationController?.present(nav, animated: true)
  985. }
  986. private func documentActionPressed(_ action: UIAlertAction) {
  987. showDocumentLibrary()
  988. }
  989. private func voiceMessageButtonPressed(_ action: UIAlertAction) {
  990. showVoiceMessageRecorder()
  991. }
  992. private func cameraButtonPressed(_ action: UIAlertAction) {
  993. showCameraViewController()
  994. }
  995. private func galleryButtonPressed(_ action: UIAlertAction) {
  996. showPhotoVideoLibrary(delegate: self)
  997. }
  998. private func locationStreamingButtonPressed(_ action: UIAlertAction) {
  999. let isLocationStreaming = dcContext.isSendingLocationsToChat(chatId: chatId)
  1000. if isLocationStreaming {
  1001. locationStreamingFor(seconds: 0)
  1002. } else {
  1003. let alert = UIAlertController(title: String.localized("title_share_location"), message: nil, preferredStyle: .safeActionSheet)
  1004. addDurationSelectionAction(to: alert, key: "share_location_for_5_minutes", duration: Time.fiveMinutes)
  1005. addDurationSelectionAction(to: alert, key: "share_location_for_30_minutes", duration: Time.thirtyMinutes)
  1006. addDurationSelectionAction(to: alert, key: "share_location_for_one_hour", duration: Time.oneHour)
  1007. addDurationSelectionAction(to: alert, key: "share_location_for_two_hours", duration: Time.twoHours)
  1008. addDurationSelectionAction(to: alert, key: "share_location_for_six_hours", duration: Time.sixHours)
  1009. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  1010. self.present(alert, animated: true, completion: nil)
  1011. }
  1012. }
  1013. private func addDurationSelectionAction(to alert: UIAlertController, key: String, duration: Int) {
  1014. let action = UIAlertAction(title: String.localized(key), style: .default, handler: { _ in
  1015. self.locationStreamingFor(seconds: duration)
  1016. })
  1017. alert.addAction(action)
  1018. }
  1019. private func locationStreamingFor(seconds: Int) {
  1020. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
  1021. return
  1022. }
  1023. appDelegate.locationManager.shareLocation(chatId: self.chatId, duration: seconds)
  1024. }
  1025. func updateMessage(_ messageId: Int) {
  1026. if messageIds.firstIndex(where: { $0 == messageId }) != nil {
  1027. reloadData()
  1028. } else {
  1029. // new outgoing message
  1030. let msg = DcMsg(id: messageId)
  1031. if msg.chatId == chatId {
  1032. if let newMsgMarkerIndex = messageIds.index(of: Int(DC_MSG_ID_MARKER1)) {
  1033. messageIds.remove(at: newMsgMarkerIndex)
  1034. }
  1035. insertMessage(msg)
  1036. }
  1037. }
  1038. }
  1039. func insertMessage(_ message: DcMsg) {
  1040. markSeenMessage(id: message.id)
  1041. let wasLastSectionVisible = isLastRowVisible()
  1042. messageIds.append(message.id)
  1043. emptyStateView.isHidden = true
  1044. reloadData()
  1045. if wasLastSectionVisible || message.isFromCurrentSender {
  1046. scrollToBottom(animated: true)
  1047. }
  1048. }
  1049. private func sendTextMessage(text: String, quoteMessage: DcMsg?) {
  1050. DispatchQueue.global().async {
  1051. let message = DcMsg(viewType: DC_MSG_TEXT)
  1052. message.text = text
  1053. if let quoteMessage = quoteMessage {
  1054. message.quoteMessage = quoteMessage
  1055. }
  1056. message.sendInChat(id: self.chatId)
  1057. }
  1058. }
  1059. private func stageDocument(url: NSURL) {
  1060. keepKeyboard = true
  1061. self.draft.setAttachment(viewType: DC_MSG_FILE, path: url.relativePath)
  1062. self.configureDraftArea(draft: self.draft)
  1063. self.messageInputBar.inputTextView.becomeFirstResponder()
  1064. }
  1065. private func stageVideo(url: NSURL) {
  1066. keepKeyboard = true
  1067. DispatchQueue.main.async {
  1068. self.draft.setAttachment(viewType: DC_MSG_VIDEO, path: url.relativePath)
  1069. self.configureDraftArea(draft: self.draft)
  1070. self.messageInputBar.inputTextView.becomeFirstResponder()
  1071. }
  1072. }
  1073. private func stageImage(url: NSURL) {
  1074. keepKeyboard = true
  1075. DispatchQueue.global().async { [weak self] in
  1076. if let image = ImageFormat.loadImageFrom(url: url as URL) {
  1077. self?.stageImage(image)
  1078. }
  1079. }
  1080. }
  1081. private func stageImage(_ image: UIImage) {
  1082. DispatchQueue.global().async {
  1083. if let pathInDocDir = ImageFormat.saveImage(image: image) {
  1084. DispatchQueue.main.async {
  1085. if pathInDocDir.suffix(4).contains(".gif") {
  1086. self.draft.setAttachment(viewType: DC_MSG_GIF, path: pathInDocDir)
  1087. } else {
  1088. self.draft.setAttachment(viewType: DC_MSG_IMAGE, path: pathInDocDir)
  1089. }
  1090. self.configureDraftArea(draft: self.draft)
  1091. self.messageInputBar.inputTextView.becomeFirstResponder()
  1092. }
  1093. }
  1094. }
  1095. }
  1096. private func sendImage(_ image: UIImage, message: String? = nil) {
  1097. DispatchQueue.global().async {
  1098. if let path = ImageFormat.saveImage(image: image) {
  1099. self.sendAttachmentMessage(viewType: DC_MSG_IMAGE, filePath: path, message: message)
  1100. }
  1101. }
  1102. }
  1103. private func sendSticker(_ image: UIImage) {
  1104. DispatchQueue.global().async {
  1105. if let path = ImageFormat.saveImage(image: image) {
  1106. self.sendAttachmentMessage(viewType: DC_MSG_STICKER, filePath: path, message: nil)
  1107. }
  1108. }
  1109. }
  1110. private func sendAttachmentMessage(viewType: Int32, filePath: String, message: String? = nil, quoteMessage: DcMsg? = nil) {
  1111. let msg = DcMsg(viewType: viewType)
  1112. msg.setFile(filepath: filePath)
  1113. msg.text = (message ?? "").isEmpty ? nil : message
  1114. if quoteMessage != nil {
  1115. msg.quoteMessage = quoteMessage
  1116. }
  1117. msg.sendInChat(id: self.chatId)
  1118. }
  1119. private func sendVoiceMessage(url: NSURL) {
  1120. DispatchQueue.global().async {
  1121. let msg = DcMsg(viewType: DC_MSG_VOICE)
  1122. msg.setFile(filepath: url.relativePath, mimeType: "audio/m4a")
  1123. msg.sendInChat(id: self.chatId)
  1124. }
  1125. }
  1126. // MARK: - Context menu
  1127. private func prepareContextMenu() {
  1128. UIMenuController.shared.menuItems = contextMenu.menuItems
  1129. UIMenuController.shared.update()
  1130. }
  1131. override func tableView(_ tableView: UITableView, shouldShowMenuForRowAt indexPath: IndexPath) -> Bool {
  1132. return !DcMsg(id: messageIds[indexPath.row]).isInfo
  1133. }
  1134. override func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
  1135. return !tableView.isEditing && contextMenu.canPerformAction(action: action)
  1136. }
  1137. override func tableView(_ tableView: UITableView, performAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) {
  1138. // handle standard actions here, but custom actions never trigger this. it still needs to be present for the menu to display, though.
  1139. contextMenu.performAction(action: action, indexPath: indexPath)
  1140. }
  1141. // context menu for iOS 13+
  1142. @available(iOS 13, *)
  1143. override func tableView(_ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
  1144. if tableView.isEditing {
  1145. return nil
  1146. }
  1147. return UIContextMenuConfiguration(
  1148. identifier: nil,
  1149. previewProvider: nil,
  1150. actionProvider: { [weak self] _ in
  1151. self?.contextMenu.actionProvider(indexPath: indexPath)
  1152. }
  1153. )
  1154. }
  1155. func showMediaGalleryFor(indexPath: IndexPath) {
  1156. let messageId = messageIds[indexPath.row]
  1157. let message = DcMsg(id: messageId)
  1158. if message.type != DC_MSG_STICKER {
  1159. showMediaGalleryFor(message: message)
  1160. }
  1161. }
  1162. func showMediaGalleryFor(message: DcMsg) {
  1163. let msgIds = dcContext.getChatMedia(chatId: chatId, messageType: Int32(message.type), messageType2: 0, messageType3: 0)
  1164. let index = msgIds.firstIndex(of: message.id) ?? 0
  1165. showMediaGallery(currentIndex: index, msgIds: msgIds)
  1166. }
  1167. private func didTapAsm(msg: DcMsg, orgText: String) {
  1168. let inputDlg = UIAlertController(
  1169. title: String.localized("autocrypt_continue_transfer_title"),
  1170. message: String.localized("autocrypt_continue_transfer_please_enter_code"),
  1171. preferredStyle: .alert)
  1172. inputDlg.addTextField(configurationHandler: { (textField) in
  1173. textField.placeholder = msg.setupCodeBegin + ".."
  1174. textField.text = orgText
  1175. textField.keyboardType = UIKeyboardType.numbersAndPunctuation // allows entering spaces; decimalPad would require a mask to keep things readable
  1176. })
  1177. inputDlg.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  1178. let okAction = UIAlertAction(title: String.localized("ok"), style: .default, handler: { _ in
  1179. let textField = inputDlg.textFields![0]
  1180. let modText = textField.text ?? ""
  1181. let success = self.dcContext.continueKeyTransfer(msgId: msg.id, setupCode: modText)
  1182. let alert = UIAlertController(
  1183. title: String.localized("autocrypt_continue_transfer_title"),
  1184. message: String.localized(success ? "autocrypt_continue_transfer_succeeded" : "autocrypt_bad_setup_code"),
  1185. preferredStyle: .alert)
  1186. if success {
  1187. alert.addAction(UIAlertAction(title: String.localized("ok"), style: .default, handler: nil))
  1188. } else {
  1189. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  1190. let retryAction = UIAlertAction(title: String.localized("autocrypt_continue_transfer_retry"), style: .default, handler: { _ in
  1191. self.didTapAsm(msg: msg, orgText: modText)
  1192. })
  1193. alert.addAction(retryAction)
  1194. alert.preferredAction = retryAction
  1195. }
  1196. self.navigationController?.present(alert, animated: true, completion: nil)
  1197. })
  1198. inputDlg.addAction(okAction)
  1199. inputDlg.preferredAction = okAction // without setting preferredAction, cancel become shown *bold* as the preferred action
  1200. navigationController?.present(inputDlg, animated: true, completion: nil)
  1201. }
  1202. func handleUIMenu() -> Bool {
  1203. if UIMenuController.shared.isMenuVisible {
  1204. UIMenuController.shared.setMenuVisible(false, animated: true)
  1205. return true
  1206. }
  1207. return false
  1208. }
  1209. func handleSelection(indexPath: IndexPath) -> Bool {
  1210. if tableView.isEditing {
  1211. if tableView.indexPathsForSelectedRows?.contains(indexPath) ?? false {
  1212. tableView.deselectRow(at: indexPath, animated: false)
  1213. } else {
  1214. tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
  1215. }
  1216. handleEditingBar()
  1217. return true
  1218. }
  1219. return false
  1220. }
  1221. func handleEditingBar() {
  1222. if let rows = tableView.indexPathsForSelectedRows,
  1223. !rows.isEmpty {
  1224. editingBar.isEnabled = true
  1225. } else {
  1226. editingBar.isEnabled = false
  1227. }
  1228. }
  1229. func setEditing(isEditing: Bool, selectedAtIndexPath: IndexPath? = nil) {
  1230. self.tableView.setEditing(isEditing, animated: true)
  1231. self.draft.isEditing = isEditing
  1232. self.configureDraftArea(draft: self.draft)
  1233. if let indexPath = selectedAtIndexPath {
  1234. _ = handleSelection(indexPath: indexPath)
  1235. }
  1236. }
  1237. }
  1238. // MARK: - BaseMessageCellDelegate
  1239. extension ChatViewController: BaseMessageCellDelegate {
  1240. @objc func fullMessageTapped(indexPath: IndexPath) {
  1241. if handleUIMenu() || handleSelection(indexPath: indexPath) {
  1242. return
  1243. }
  1244. let msg = DcMsg(id: messageIds[indexPath.row])
  1245. let fullMessageViewController = FullMessageViewController(dcContext: dcContext, messageId: msg.id)
  1246. navigationController?.pushViewController(fullMessageViewController, animated: true)
  1247. }
  1248. @objc func quoteTapped(indexPath: IndexPath) {
  1249. if handleSelection(indexPath: indexPath) { return }
  1250. _ = handleUIMenu()
  1251. let msg = DcMsg(id: messageIds[indexPath.row])
  1252. if let quoteMsg = msg.quoteMessage {
  1253. if self.chatId == quoteMsg.chatId {
  1254. scrollToMessage(msgId: quoteMsg.id)
  1255. } else {
  1256. showChat(chatId: quoteMsg.chatId, messageId: quoteMsg.id, animated: false)
  1257. }
  1258. }
  1259. }
  1260. @objc func textTapped(indexPath: IndexPath) {
  1261. if handleUIMenu() || handleSelection(indexPath: indexPath) {
  1262. return
  1263. }
  1264. let message = DcMsg(id: messageIds[indexPath.row])
  1265. if message.isSetupMessage {
  1266. didTapAsm(msg: message, orgText: "")
  1267. }
  1268. }
  1269. @objc func phoneNumberTapped(number: String, indexPath: IndexPath) {
  1270. if handleUIMenu() || handleSelection(indexPath: indexPath) {
  1271. return
  1272. }
  1273. let sanitizedNumber = number.filter("0123456789".contains)
  1274. if let phoneURL = URL(string: "tel://\(sanitizedNumber)") {
  1275. UIApplication.shared.open(phoneURL, options: [:], completionHandler: nil)
  1276. }
  1277. logger.debug("phone number tapped \(sanitizedNumber)")
  1278. }
  1279. @objc func commandTapped(command: String, indexPath: IndexPath) {
  1280. if handleUIMenu() || handleSelection(indexPath: indexPath) {
  1281. return
  1282. }
  1283. logger.debug("command tapped \(command)")
  1284. }
  1285. @objc func urlTapped(url: URL, indexPath: IndexPath) {
  1286. if handleUIMenu() || handleSelection(indexPath: indexPath) {
  1287. return
  1288. }
  1289. if Utils.isEmail(url: url) {
  1290. logger.debug("tapped on contact")
  1291. let email = Utils.getEmailFrom(url)
  1292. self.askToChatWith(email: email)
  1293. } else {
  1294. UIApplication.shared.open(url)
  1295. }
  1296. }
  1297. @objc func imageTapped(indexPath: IndexPath) {
  1298. if handleUIMenu() || handleSelection(indexPath: indexPath) {
  1299. return
  1300. }
  1301. showMediaGalleryFor(indexPath: indexPath)
  1302. }
  1303. @objc func avatarTapped(indexPath: IndexPath) {
  1304. let message = DcMsg(id: messageIds[indexPath.row])
  1305. let contactDetailController = ContactDetailViewController(dcContext: dcContext, contactId: message.fromContactId)
  1306. navigationController?.pushViewController(contactDetailController, animated: true)
  1307. }
  1308. }
  1309. // MARK: - MediaPickerDelegate
  1310. extension ChatViewController: MediaPickerDelegate {
  1311. func onVideoSelected(url: NSURL) {
  1312. stageVideo(url: url)
  1313. }
  1314. func onImageSelected(url: NSURL) {
  1315. stageImage(url: url)
  1316. }
  1317. func onImageSelected(image: UIImage) {
  1318. stageImage(image)
  1319. }
  1320. func onVoiceMessageRecorded(url: NSURL) {
  1321. sendVoiceMessage(url: url)
  1322. }
  1323. func onDocumentSelected(url: NSURL) {
  1324. stageDocument(url: url)
  1325. }
  1326. }
  1327. // MARK: - MessageInputBarDelegate
  1328. extension ChatViewController: InputBarAccessoryViewDelegate {
  1329. func inputBar(_ inputBar: InputBarAccessoryView, didPressSendButtonWith text: String) {
  1330. keepKeyboard = true
  1331. let trimmedText = text.replacingOccurrences(of: "\u{FFFC}", with: "", options: .literal, range: nil)
  1332. .trimmingCharacters(in: .whitespacesAndNewlines)
  1333. if let filePath = draft.attachment, let viewType = draft.viewType {
  1334. switch viewType {
  1335. case DC_MSG_GIF, DC_MSG_IMAGE, DC_MSG_FILE, DC_MSG_VIDEO:
  1336. self.sendAttachmentMessage(viewType: viewType, filePath: filePath, message: trimmedText, quoteMessage: draft.quoteMessage)
  1337. default:
  1338. logger.warning("Unsupported viewType for drafted messages.")
  1339. }
  1340. } else if inputBar.inputTextView.images.isEmpty {
  1341. self.sendTextMessage(text: trimmedText, quoteMessage: draft.quoteMessage)
  1342. } else {
  1343. // only 1 attachment allowed for now, thus it takes the first one
  1344. self.sendImage(inputBar.inputTextView.images[0], message: trimmedText)
  1345. }
  1346. inputBar.inputTextView.text = String()
  1347. inputBar.inputTextView.attributedText = nil
  1348. draftArea.cancel()
  1349. }
  1350. func inputBar(_ inputBar: InputBarAccessoryView, textViewTextDidChangeTo text: String) {
  1351. draft.text = text
  1352. evaluateInputBar(draft: draft)
  1353. }
  1354. func inputBar(_ inputBar: InputBarAccessoryView, didChangeIntrinsicContentTo size: CGSize) {
  1355. if isDismissing {
  1356. return
  1357. }
  1358. self.tableView.contentInset = UIEdgeInsets(top: self.getTopInsetHeight(),
  1359. left: 0,
  1360. bottom: size.height + messageInputBar.keyboardHeight,
  1361. right: 0)
  1362. if isLastRowVisible() && !tableView.isDragging && !tableView.isDecelerating && highlightedMsg == nil && !ignoreInputBarChange {
  1363. self.scrollToBottom(animated: true)
  1364. }
  1365. }
  1366. }
  1367. // MARK: - DraftPreviewDelegate
  1368. extension ChatViewController: DraftPreviewDelegate {
  1369. func onCancelQuote() {
  1370. draft.setQuote(quotedMsg: nil)
  1371. configureDraftArea(draft: draft)
  1372. }
  1373. func onCancelAttachment() {
  1374. draft.setAttachment(viewType: nil, path: nil, mimetype: nil)
  1375. configureDraftArea(draft: draft)
  1376. evaluateInputBar(draft: draft)
  1377. }
  1378. func onAttachmentAdded() {
  1379. evaluateInputBar(draft: draft)
  1380. }
  1381. func onAttachmentTapped() {
  1382. if let attachmentPath = draft.attachment {
  1383. let attachmentURL = URL(fileURLWithPath: attachmentPath, isDirectory: false)
  1384. let previewController = PreviewController(type: .single(attachmentURL))
  1385. if #available(iOS 13.0, *), draft.viewType == DC_MSG_IMAGE || draft.viewType == DC_MSG_VIDEO {
  1386. previewController.setEditing(true, animated: true)
  1387. previewController.delegate = self
  1388. }
  1389. let nav = UINavigationController(rootViewController: previewController)
  1390. nav.modalPresentationStyle = .fullScreen
  1391. navigationController?.present(nav, animated: true)
  1392. }
  1393. }
  1394. }
  1395. // MARK: - ChatEditingDelegate
  1396. extension ChatViewController: ChatEditingDelegate {
  1397. func onDeletePressed() {
  1398. if let rows = tableView.indexPathsForSelectedRows {
  1399. let messageIdsToDelete = rows.compactMap { messageIds[$0.row] }
  1400. askToDeleteMessages(ids: messageIdsToDelete)
  1401. }
  1402. }
  1403. func onForwardPressed() {
  1404. if let rows = tableView.indexPathsForSelectedRows {
  1405. let messageIdsToForward = rows.compactMap { messageIds[$0.row] }
  1406. RelayHelper.sharedInstance.setForwardMessages(messageIds: messageIdsToForward)
  1407. self.navigationController?.popViewController(animated: true)
  1408. }
  1409. }
  1410. func onCancelPressed() {
  1411. setEditing(isEditing: false)
  1412. }
  1413. }
  1414. // MARK: - QLPreviewControllerDelegate
  1415. extension ChatViewController: QLPreviewControllerDelegate {
  1416. @available(iOS 13.0, *)
  1417. func previewController(_ controller: QLPreviewController, editingModeFor previewItem: QLPreviewItem) -> QLPreviewItemEditingMode {
  1418. return .updateContents
  1419. }
  1420. func previewController(_ controller: QLPreviewController, didUpdateContentsOf previewItem: QLPreviewItem) {
  1421. DispatchQueue.main.async { [weak self] in
  1422. guard let self = self else { return }
  1423. self.draftArea.reload(draft: self.draft)
  1424. }
  1425. }
  1426. }
  1427. // MARK: - AudioControllerDelegate
  1428. extension ChatViewController: AudioControllerDelegate {
  1429. func onAudioPlayFailed() {
  1430. let alert = UIAlertController(title: String.localized("error"),
  1431. message: String.localized("cannot_play_unsupported_file_type"),
  1432. preferredStyle: .safeActionSheet)
  1433. alert.addAction(UIAlertAction(title: String.localized("ok"), style: .default, handler: nil))
  1434. self.present(alert, animated: true, completion: nil)
  1435. }
  1436. }
  1437. // MARK: - UITextViewDelegate
  1438. extension ChatViewController: UITextViewDelegate {
  1439. func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
  1440. if keepKeyboard {
  1441. DispatchQueue.main.async { [weak self] in
  1442. self?.messageInputBar.inputTextView.becomeFirstResponder()
  1443. }
  1444. keepKeyboard = false
  1445. return false
  1446. }
  1447. return true
  1448. }
  1449. }
  1450. // MARK: - ChatInputTextViewPasteDelegate
  1451. extension ChatViewController: ChatInputTextViewPasteDelegate {
  1452. func onImagePasted(image: UIImage) {
  1453. sendSticker(image)
  1454. }
  1455. }