ChatViewController.swift 86 KB

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