ChatViewController.swift 88 KB

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