ChatViewController.swift 73 KB

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