ChatViewController.swift 74 KB

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