ChatViewController.swift 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752
  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. func configureMessageStyle(for message: DcMsg, at indexPath: IndexPath) -> UIRectCorner {
  646. var corners: UIRectCorner = []
  647. if message.isFromCurrentSender {
  648. corners.formUnion(.topLeft)
  649. corners.formUnion(.bottomLeft)
  650. corners.formUnion(.topRight)
  651. } else {
  652. corners.formUnion(.topRight)
  653. corners.formUnion(.bottomRight)
  654. corners.formUnion(.topLeft)
  655. }
  656. return corners
  657. }
  658. private func getBackgroundColor(for currentMessage: DcMsg) -> UIColor {
  659. return currentMessage.isFromCurrentSender ? DcColors.messagePrimaryColor : DcColors.messageSecondaryColor
  660. }
  661. private func updateTitle(chat: DcChat) {
  662. let titleView = ChatTitleView()
  663. var subtitle = "ErrSubtitle"
  664. let chatContactIds = chat.getContactIds(dcContext)
  665. if chat.isMailinglist {
  666. subtitle = String.localized("mailing_list")
  667. } else if chat.isGroup {
  668. subtitle = String.localized(stringID: "n_members", count: chatContactIds.count)
  669. } else if chat.isDeviceTalk {
  670. subtitle = String.localized("device_talk_subtitle")
  671. } else if chat.isSelfTalk {
  672. subtitle = String.localized("chat_self_talk_subtitle")
  673. } else if chatContactIds.count >= 1 {
  674. subtitle = dcContext.getContact(id: chatContactIds[0]).email
  675. }
  676. titleView.updateTitleView(title: chat.name, subtitle: subtitle)
  677. navigationItem.titleView = titleView
  678. var rightBarButtonItems = [badgeItem]
  679. if chat.isSendingLocations {
  680. rightBarButtonItems.append(locationStreamingItem)
  681. }
  682. if chat.isMuted {
  683. rightBarButtonItems.append(muteItem)
  684. }
  685. if dcContext.getChatEphemeralTimer(chatId: chat.id) > 0 {
  686. rightBarButtonItems.append(ephemeralMessageItem)
  687. }
  688. navigationItem.rightBarButtonItems = rightBarButtonItems
  689. }
  690. @objc
  691. private func refreshMessages() {
  692. self.messageIds = self.getMessageIds()
  693. let wasLastSectionVisible = self.isLastRowVisible()
  694. self.reloadData()
  695. if wasLastSectionVisible {
  696. self.scrollToBottom(animated: true)
  697. }
  698. self.showEmptyStateView(self.messageIds.isEmpty)
  699. }
  700. private func reloadData() {
  701. let selectredRows = tableView.indexPathsForSelectedRows
  702. tableView.reloadData()
  703. // There's an iOS bug, filling up the console output but which can be ignored: https://developer.apple.com/forums/thread/668295
  704. // [Assert] Attempted to call -cellForRowAtIndexPath: on the table view while it was in the process of updating its visible cells, which is not allowed.
  705. selectredRows?.forEach({ (selectedRow) in
  706. tableView.selectRow(at: selectedRow, animated: false, scrollPosition: .none)
  707. })
  708. }
  709. private func loadMessages() {
  710. // update message ids
  711. var msgIds = self.getMessageIds()
  712. let freshMsgsCount = self.dcContext.getUnreadMessages(chatId: self.chatId)
  713. if freshMsgsCount > 0 && msgIds.count >= freshMsgsCount {
  714. let index = msgIds.count - freshMsgsCount
  715. msgIds.insert(Int(DC_MSG_ID_MARKER1), at: index)
  716. }
  717. self.messageIds = msgIds
  718. self.showEmptyStateView(self.messageIds.isEmpty)
  719. self.reloadData()
  720. }
  721. private func isLastRowVisible() -> Bool {
  722. guard !messageIds.isEmpty else { return false }
  723. let lastIndexPath = IndexPath(item: messageIds.count - 1, section: 0)
  724. return tableView.indexPathsForVisibleRows?.contains(lastIndexPath) ?? false
  725. }
  726. @objc func onScrollDownButtonPressed() {
  727. scrollToBottom(animated: true)
  728. }
  729. private func scrollToBottom(animated: Bool) {
  730. if !messageIds.isEmpty {
  731. DispatchQueue.main.async { [weak self] in
  732. guard let self = self else { return }
  733. let numberOfRows = self.tableView.numberOfRows(inSection: 0)
  734. if numberOfRows > 0 {
  735. self.tableView.scrollToRow(at: IndexPath(row: numberOfRows - 1, section: 0), at: .bottom, animated: animated)
  736. }
  737. }
  738. }
  739. }
  740. private func scrollToLastUnseenMessage() {
  741. DispatchQueue.main.async { [weak self] in
  742. guard let self = self else { return }
  743. if let markerMessageIndex = self.messageIds.index(of: Int(DC_MSG_ID_MARKER1)) {
  744. let indexPath = IndexPath(row: markerMessageIndex, section: 0)
  745. self.tableView.scrollToRow(at: indexPath, at: .top, animated: false)
  746. } else {
  747. // scroll to bottom
  748. let numberOfRows = self.tableView.numberOfRows(inSection: 0)
  749. if numberOfRows > 0 {
  750. self.tableView.scrollToRow(at: IndexPath(row: numberOfRows - 1, section: 0), at: .bottom, animated: false)
  751. }
  752. }
  753. }
  754. }
  755. private func scrollToMessage(msgId: Int, animated: Bool = true) {
  756. DispatchQueue.main.async { [weak self] in
  757. guard let self = self else { return }
  758. guard let index = self.messageIds.firstIndex(of: msgId) else {
  759. return
  760. }
  761. let indexPath = IndexPath(row: index, section: 0)
  762. self.tableView.scrollToRow(at: indexPath, at: .top, animated: animated)
  763. }
  764. }
  765. private func showEmptyStateView(_ show: Bool) {
  766. if show {
  767. let dcChat = dcContext.getChat(chatId: chatId)
  768. if chatId == DC_CHAT_ID_DEADDROP {
  769. if dcContext.showEmails != DC_SHOW_EMAILS_ALL {
  770. emptyStateView.text = String.localized("chat_no_contact_requests")
  771. } else {
  772. emptyStateView.text = String.localized("chat_no_messages")
  773. }
  774. } else if dcChat.isGroup {
  775. if dcChat.isUnpromoted {
  776. emptyStateView.text = String.localized("chat_new_group_hint")
  777. } else {
  778. emptyStateView.text = String.localized("chat_no_messages")
  779. }
  780. } else if dcChat.isSelfTalk {
  781. emptyStateView.text = String.localized("saved_messages_explain")
  782. } else if dcChat.isDeviceTalk {
  783. emptyStateView.text = String.localized("device_talk_explain")
  784. } else {
  785. emptyStateView.text = String.localizedStringWithFormat(String.localized("chat_no_messages_hint"), dcChat.name, dcChat.name)
  786. }
  787. emptyStateView.isHidden = false
  788. } else {
  789. emptyStateView.isHidden = true
  790. }
  791. }
  792. private func getMessageIds() -> [Int] {
  793. return dcContext.getMessageIds(chatId: chatId)
  794. }
  795. @objc private func saveDraft() {
  796. draft.save(context: dcContext)
  797. }
  798. private func configureMessageInputBar() {
  799. messageInputBar.delegate = self
  800. messageInputBar.inputTextView.tintColor = DcColors.primary
  801. messageInputBar.inputTextView.placeholder = String.localized("chat_input_placeholder")
  802. messageInputBar.separatorLine.backgroundColor = DcColors.colorDisabled
  803. messageInputBar.inputTextView.tintColor = DcColors.primary
  804. messageInputBar.inputTextView.textColor = DcColors.defaultTextColor
  805. messageInputBar.backgroundView.backgroundColor = DcColors.chatBackgroundColor
  806. messageInputBar.backgroundColor = DcColors.chatBackgroundColor
  807. messageInputBar.inputTextView.backgroundColor = DcColors.inputFieldColor
  808. messageInputBar.inputTextView.placeholderTextColor = DcColors.placeholderColor
  809. messageInputBar.inputTextView.textContainerInset = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 38)
  810. messageInputBar.inputTextView.placeholderLabelInsets = UIEdgeInsets(top: 8, left: 20, bottom: 8, right: 38)
  811. messageInputBar.inputTextView.layer.borderColor = UIColor.themeColor(light: UIColor(red: 200 / 255, green: 200 / 255, blue: 200 / 255, alpha: 1),
  812. dark: UIColor(red: 55 / 255, green: 55/255, blue: 55/255, alpha: 1)).cgColor
  813. messageInputBar.inputTextView.layer.borderWidth = 1.0
  814. messageInputBar.inputTextView.layer.cornerRadius = 13.0
  815. messageInputBar.inputTextView.layer.masksToBounds = true
  816. messageInputBar.inputTextView.scrollIndicatorInsets = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0)
  817. configureInputBarItems()
  818. messageInputBar.inputTextView.delegate = self
  819. if let inputTextView = messageInputBar.inputTextView as? ChatInputTextView {
  820. inputTextView.imagePasteDelegate = self
  821. }
  822. }
  823. private func evaluateInputBar(draft: DraftModel) {
  824. messageInputBar.sendButton.isEnabled = draft.canSend()
  825. }
  826. private func configureInputBarItems() {
  827. messageInputBar.setLeftStackViewWidthConstant(to: 40, animated: false)
  828. messageInputBar.setRightStackViewWidthConstant(to: 40, animated: false)
  829. let sendButtonImage = UIImage(named: "paper_plane")?.withRenderingMode(.alwaysTemplate)
  830. messageInputBar.sendButton.image = sendButtonImage
  831. messageInputBar.sendButton.accessibilityLabel = String.localized("menu_send")
  832. messageInputBar.sendButton.accessibilityTraits = .button
  833. messageInputBar.sendButton.title = nil
  834. messageInputBar.sendButton.tintColor = UIColor(white: 1, alpha: 1)
  835. messageInputBar.sendButton.layer.cornerRadius = 20
  836. messageInputBar.middleContentViewPadding = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 10)
  837. // this adds a padding between textinputfield and send button
  838. messageInputBar.sendButton.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
  839. messageInputBar.sendButton.setSize(CGSize(width: 40, height: 40), animated: false)
  840. messageInputBar.padding = UIEdgeInsets(top: 6, left: 6, bottom: 6, right: 12)
  841. messageInputBar.shouldManageSendButtonEnabledState = false
  842. let leftItems = [
  843. InputBarButtonItem()
  844. .configure {
  845. $0.spacing = .fixed(0)
  846. let clipperIcon = #imageLiteral(resourceName: "ic_attach_file_36pt").withRenderingMode(.alwaysTemplate)
  847. $0.image = clipperIcon
  848. $0.tintColor = DcColors.primary
  849. $0.setSize(CGSize(width: 40, height: 40), animated: false)
  850. $0.accessibilityLabel = String.localized("menu_add_attachment")
  851. $0.accessibilityTraits = .button
  852. }.onSelected {
  853. $0.tintColor = UIColor.themeColor(light: .lightGray, dark: .darkGray)
  854. }.onDeselected {
  855. $0.tintColor = DcColors.primary
  856. }.onTouchUpInside { [weak self] _ in
  857. self?.clipperButtonPressed()
  858. }
  859. ]
  860. messageInputBar.setStackViewItems(leftItems, forStack: .left, animated: false)
  861. // This just adds some more flare
  862. messageInputBar.sendButton
  863. .onEnabled { item in
  864. UIView.animate(withDuration: 0.3, animations: {
  865. item.backgroundColor = DcColors.primary
  866. })}
  867. .onDisabled { item in
  868. UIView.animate(withDuration: 0.3, animations: {
  869. item.backgroundColor = DcColors.colorDisabled
  870. })}
  871. }
  872. func setupScrollDownButton() {
  873. NSLayoutConstraint.activate([
  874. scrollDownButton.constraintAlignBottomTo(tableView, paddingBottom: 64),
  875. scrollDownButton.constraintAlignTrailingTo(tableView, paddingTrailing: 12),
  876. scrollDownButton.constraintHeightTo(40),
  877. scrollDownButton.constraintWidthTo(40)
  878. ])
  879. scrollDownButton.backgroundColor = DcColors.defaultBackgroundColor
  880. scrollDownButton.setImage(UIImage(named: "ic_scrolldown")?.sd_tintedImage(with: .systemBlue), for: .normal)
  881. scrollDownButton.layer.cornerRadius = 20
  882. scrollDownButton.layer.borderColor = DcColors.colorDisabled.cgColor
  883. scrollDownButton.layer.borderWidth = 1
  884. scrollDownButton.layer.masksToBounds = true
  885. }
  886. @objc private func chatProfilePressed() {
  887. if chatId != DC_CHAT_ID_DEADDROP {
  888. showChatDetail(chatId: chatId)
  889. }
  890. }
  891. @objc private func clipperButtonPressed() {
  892. showClipperOptions()
  893. }
  894. private func showClipperOptions() {
  895. let alert = UIAlertController(title: nil, message: nil, preferredStyle: .safeActionSheet)
  896. let galleryAction = PhotoPickerAlertAction(title: String.localized("gallery"), style: .default, handler: galleryButtonPressed(_:))
  897. let cameraAction = PhotoPickerAlertAction(title: String.localized("camera"), style: .default, handler: cameraButtonPressed(_:))
  898. let documentAction = UIAlertAction(title: String.localized("files"), style: .default, handler: documentActionPressed(_:))
  899. let voiceMessageAction = UIAlertAction(title: String.localized("voice_message"), style: .default, handler: voiceMessageButtonPressed(_:))
  900. let isLocationStreaming = dcContext.isSendingLocationsToChat(chatId: chatId)
  901. let locationStreamingAction = UIAlertAction(title: isLocationStreaming ? String.localized("stop_sharing_location") : String.localized("location"),
  902. style: isLocationStreaming ? .destructive : .default,
  903. handler: locationStreamingButtonPressed(_:))
  904. alert.addAction(cameraAction)
  905. alert.addAction(galleryAction)
  906. alert.addAction(documentAction)
  907. alert.addAction(voiceMessageAction)
  908. if let config = dcContext.getConfig("webrtc_instance"), !config.isEmpty {
  909. let videoChatInvitation = UIAlertAction(title: String.localized("videochat"), style: .default, handler: videoChatButtonPressed(_:))
  910. alert.addAction(videoChatInvitation)
  911. }
  912. if UserDefaults.standard.bool(forKey: "location_streaming") {
  913. alert.addAction(locationStreamingAction)
  914. }
  915. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  916. self.present(alert, animated: true, completion: {
  917. // unfortunately, voiceMessageAction.accessibilityHint does not work,
  918. // but this hack does the trick
  919. if UIAccessibility.isVoiceOverRunning {
  920. if let view = voiceMessageAction.value(forKey: "__representer") as? UIView {
  921. view.accessibilityHint = String.localized("a11y_voice_message_hint_ios")
  922. }
  923. }
  924. })
  925. }
  926. private func confirmationAlert(title: String, actionTitle: String, actionStyle: UIAlertAction.Style = .default, actionHandler: @escaping ((UIAlertAction) -> Void), cancelHandler: ((UIAlertAction) -> Void)? = nil) {
  927. let alert = UIAlertController(title: title,
  928. message: nil,
  929. preferredStyle: .safeActionSheet)
  930. alert.addAction(UIAlertAction(title: actionTitle, style: actionStyle, handler: actionHandler))
  931. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: cancelHandler ?? { _ in
  932. self.dismiss(animated: true, completion: nil)
  933. }))
  934. present(alert, animated: true, completion: nil)
  935. }
  936. private func askToChatWith(email: String) {
  937. let contactId = self.dcContext.createContact(name: "", email: email)
  938. if dcContext.getChatIdByContactId(contactId: contactId) != 0 {
  939. self.dismiss(animated: true, completion: nil)
  940. let chatId = self.dcContext.createChatByContactId(contactId: contactId)
  941. self.showChat(chatId: chatId)
  942. } else {
  943. confirmationAlert(title: String.localizedStringWithFormat(String.localized("ask_start_chat_with"), email),
  944. actionTitle: String.localized("start_chat"),
  945. actionHandler: { _ in
  946. self.dismiss(animated: true, completion: nil)
  947. let chatId = self.dcContext.createChatByContactId(contactId: contactId)
  948. self.showChat(chatId: chatId)})
  949. }
  950. }
  951. private func askToDeleteMessage(id: Int) {
  952. self.askToDeleteMessages(ids: [id])
  953. }
  954. private func askToDeleteMessages(ids: [Int]) {
  955. let title = String.localized(stringID: "ask_delete_messages", count: ids.count)
  956. confirmationAlert(title: title, actionTitle: String.localized("delete"), actionStyle: .destructive,
  957. actionHandler: { _ in
  958. self.dcContext.deleteMessages(msgIds: ids)
  959. if self.tableView.isEditing {
  960. self.setEditing(isEditing: false)
  961. }
  962. })
  963. }
  964. private func askToForwardMessage() {
  965. let chat = dcContext.getChat(chatId: self.chatId)
  966. if chat.isSelfTalk {
  967. RelayHelper.sharedInstance.forward(to: self.chatId)
  968. refreshMessages()
  969. } else {
  970. confirmationAlert(title: String.localizedStringWithFormat(String.localized("ask_forward"), chat.name),
  971. actionTitle: String.localized("menu_forward"),
  972. actionHandler: { _ in
  973. RelayHelper.sharedInstance.forward(to: self.chatId)
  974. self.dismiss(animated: true, completion: nil)},
  975. cancelHandler: { _ in
  976. self.dismiss(animated: false, completion: nil)
  977. self.navigationController?.popViewController(animated: true)})
  978. }
  979. }
  980. // MARK: - coordinator
  981. private func showChatDetail(chatId: Int) {
  982. let chat = dcContext.getChat(chatId: chatId)
  983. if !chat.isGroup {
  984. if let contactId = chat.getContactIds(dcContext).first {
  985. let contactDetailController = ContactDetailViewController(dcContext: dcContext, contactId: contactId)
  986. navigationController?.pushViewController(contactDetailController, animated: true)
  987. }
  988. } else {
  989. let groupChatDetailViewController = GroupChatDetailViewController(chatId: chatId, dcContext: dcContext)
  990. navigationController?.pushViewController(groupChatDetailViewController, animated: true)
  991. }
  992. }
  993. func showChat(chatId: Int, messageId: Int? = nil, animated: Bool = true) {
  994. if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
  995. appDelegate.appCoordinator.showChat(chatId: chatId, msgId: messageId, animated: animated, clearViewControllerStack: true)
  996. }
  997. }
  998. private func showDocumentLibrary() {
  999. mediaPicker?.showDocumentLibrary()
  1000. }
  1001. private func showVoiceMessageRecorder() {
  1002. mediaPicker?.showVoiceRecorder()
  1003. }
  1004. private func showCameraViewController() {
  1005. if AVCaptureDevice.authorizationStatus(for: .video) == .authorized {
  1006. self.mediaPicker?.showCamera()
  1007. } else {
  1008. AVCaptureDevice.requestAccess(for: .video, completionHandler: { [weak self] (granted: Bool) in
  1009. guard let self = self else { return }
  1010. if granted {
  1011. self.mediaPicker?.showCamera()
  1012. } else {
  1013. self.showCameraPermissionAlert()
  1014. }
  1015. })
  1016. }
  1017. }
  1018. private func showCameraPermissionAlert() {
  1019. DispatchQueue.main.async { [weak self] in
  1020. let alert = UIAlertController(title: String.localized("perm_required_title"),
  1021. message: String.localized("perm_ios_explain_access_to_camera_denied"),
  1022. preferredStyle: .alert)
  1023. if let appSettings = URL(string: UIApplication.openSettingsURLString) {
  1024. alert.addAction(UIAlertAction(title: String.localized("open_settings"), style: .default, handler: { _ in
  1025. UIApplication.shared.open(appSettings, options: [:], completionHandler: nil)}))
  1026. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .destructive, handler: nil))
  1027. }
  1028. self?.present(alert, animated: true, completion: nil)
  1029. }
  1030. }
  1031. private func showPhotoVideoLibrary(delegate: MediaPickerDelegate) {
  1032. mediaPicker?.showPhotoVideoLibrary()
  1033. }
  1034. private func showMediaGallery(currentIndex: Int, msgIds: [Int]) {
  1035. let betterPreviewController = PreviewController(dcContext: dcContext, type: .multi(msgIds, currentIndex))
  1036. let nav = UINavigationController(rootViewController: betterPreviewController)
  1037. nav.modalPresentationStyle = .fullScreen
  1038. navigationController?.present(nav, animated: true)
  1039. }
  1040. private func documentActionPressed(_ action: UIAlertAction) {
  1041. showDocumentLibrary()
  1042. }
  1043. private func voiceMessageButtonPressed(_ action: UIAlertAction) {
  1044. showVoiceMessageRecorder()
  1045. }
  1046. private func cameraButtonPressed(_ action: UIAlertAction) {
  1047. showCameraViewController()
  1048. }
  1049. private func galleryButtonPressed(_ action: UIAlertAction) {
  1050. showPhotoVideoLibrary(delegate: self)
  1051. }
  1052. private func locationStreamingButtonPressed(_ action: UIAlertAction) {
  1053. let isLocationStreaming = dcContext.isSendingLocationsToChat(chatId: chatId)
  1054. if isLocationStreaming {
  1055. locationStreamingFor(seconds: 0)
  1056. } else {
  1057. let alert = UIAlertController(title: String.localized("title_share_location"), message: nil, preferredStyle: .safeActionSheet)
  1058. addDurationSelectionAction(to: alert, key: "share_location_for_5_minutes", duration: Time.fiveMinutes)
  1059. addDurationSelectionAction(to: alert, key: "share_location_for_30_minutes", duration: Time.thirtyMinutes)
  1060. addDurationSelectionAction(to: alert, key: "share_location_for_one_hour", duration: Time.oneHour)
  1061. addDurationSelectionAction(to: alert, key: "share_location_for_two_hours", duration: Time.twoHours)
  1062. addDurationSelectionAction(to: alert, key: "share_location_for_six_hours", duration: Time.sixHours)
  1063. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  1064. self.present(alert, animated: true, completion: nil)
  1065. }
  1066. }
  1067. private func videoChatButtonPressed(_ action: UIAlertAction) {
  1068. let chat = dcContext.getChat(chatId: chatId)
  1069. let alert = UIAlertController(title: String.localizedStringWithFormat(String.localized("videochat_invite_user_to_videochat"), chat.name),
  1070. message: String.localized("videochat_invite_user_hint"),
  1071. preferredStyle: .alert)
  1072. let cancel = UIAlertAction(title: String.localized("cancel"), style: .default, handler: nil)
  1073. let ok = UIAlertAction(title: String.localized("ok"),
  1074. style: .default,
  1075. handler: { _ in
  1076. DispatchQueue.global(qos: .userInitiated).async { [weak self] in
  1077. guard let self = self else { return }
  1078. let messageId = self.dcContext.sendVideoChatInvitation(chatId: self.chatId)
  1079. let inviteMessage = self.dcContext.getMessage(id: messageId)
  1080. if let url = NSURL(string: inviteMessage.getVideoChatUrl()) {
  1081. DispatchQueue.main.async {
  1082. UIApplication.shared.open(url as URL)
  1083. }
  1084. }
  1085. }})
  1086. alert.addAction(cancel)
  1087. alert.addAction(ok)
  1088. self.present(alert, animated: true, completion: nil)
  1089. }
  1090. private func addDurationSelectionAction(to alert: UIAlertController, key: String, duration: Int) {
  1091. let action = UIAlertAction(title: String.localized(key), style: .default, handler: { _ in
  1092. self.locationStreamingFor(seconds: duration)
  1093. })
  1094. alert.addAction(action)
  1095. }
  1096. private func locationStreamingFor(seconds: Int) {
  1097. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
  1098. return
  1099. }
  1100. appDelegate.locationManager.shareLocation(chatId: self.chatId, duration: seconds)
  1101. }
  1102. func updateMessage(_ messageId: Int) {
  1103. if messageIds.firstIndex(where: { $0 == messageId }) != nil {
  1104. reloadData()
  1105. } else {
  1106. // new outgoing message
  1107. let msg = dcContext.getMessage(id: messageId)
  1108. if msg.chatId == chatId {
  1109. if let newMsgMarkerIndex = messageIds.index(of: Int(DC_MSG_ID_MARKER1)) {
  1110. messageIds.remove(at: newMsgMarkerIndex)
  1111. }
  1112. insertMessage(msg)
  1113. }
  1114. }
  1115. }
  1116. func insertMessage(_ message: DcMsg) {
  1117. markSeenMessage(id: message.id)
  1118. let wasLastSectionVisible = isLastRowVisible()
  1119. messageIds.append(message.id)
  1120. emptyStateView.isHidden = true
  1121. reloadData()
  1122. if wasLastSectionVisible || message.isFromCurrentSender {
  1123. scrollToBottom(animated: true)
  1124. }
  1125. }
  1126. private func sendTextMessage(text: String, quoteMessage: DcMsg?) {
  1127. DispatchQueue.global().async {
  1128. let message = self.dcContext.newMessage(viewType: DC_MSG_TEXT)
  1129. message.text = text
  1130. if let quoteMessage = quoteMessage {
  1131. message.quoteMessage = quoteMessage
  1132. }
  1133. self.dcContext.sendMessage(chatId: self.chatId, message: message)
  1134. }
  1135. }
  1136. private func stageDocument(url: NSURL) {
  1137. keepKeyboard = true
  1138. self.draft.setAttachment(viewType: DC_MSG_FILE, path: url.relativePath)
  1139. self.configureDraftArea(draft: self.draft)
  1140. self.messageInputBar.inputTextView.becomeFirstResponder()
  1141. }
  1142. private func stageVideo(url: NSURL) {
  1143. keepKeyboard = true
  1144. DispatchQueue.main.async {
  1145. self.draft.setAttachment(viewType: DC_MSG_VIDEO, path: url.relativePath)
  1146. self.configureDraftArea(draft: self.draft)
  1147. self.messageInputBar.inputTextView.becomeFirstResponder()
  1148. }
  1149. }
  1150. private func stageImage(url: NSURL) {
  1151. keepKeyboard = true
  1152. DispatchQueue.global().async { [weak self] in
  1153. if let image = ImageFormat.loadImageFrom(url: url as URL) {
  1154. self?.stageImage(image)
  1155. }
  1156. }
  1157. }
  1158. private func stageImage(_ image: UIImage) {
  1159. DispatchQueue.global().async {
  1160. if let pathInDocDir = ImageFormat.saveImage(image: image) {
  1161. DispatchQueue.main.async {
  1162. if pathInDocDir.suffix(4).contains(".gif") {
  1163. self.draft.setAttachment(viewType: DC_MSG_GIF, path: pathInDocDir)
  1164. } else {
  1165. self.draft.setAttachment(viewType: DC_MSG_IMAGE, path: pathInDocDir)
  1166. }
  1167. self.configureDraftArea(draft: self.draft)
  1168. self.messageInputBar.inputTextView.becomeFirstResponder()
  1169. }
  1170. }
  1171. }
  1172. }
  1173. private func sendImage(_ image: UIImage, message: String? = nil) {
  1174. DispatchQueue.global().async {
  1175. if let path = ImageFormat.saveImage(image: image) {
  1176. self.sendAttachmentMessage(viewType: DC_MSG_IMAGE, filePath: path, message: message)
  1177. }
  1178. }
  1179. }
  1180. private func sendSticker(_ image: UIImage) {
  1181. DispatchQueue.global().async {
  1182. if let path = ImageFormat.saveImage(image: image) {
  1183. self.sendAttachmentMessage(viewType: DC_MSG_STICKER, filePath: path, message: nil)
  1184. }
  1185. }
  1186. }
  1187. private func sendAttachmentMessage(viewType: Int32, filePath: String, message: String? = nil, quoteMessage: DcMsg? = nil) {
  1188. let msg = dcContext.newMessage(viewType: viewType)
  1189. msg.setFile(filepath: filePath)
  1190. msg.text = (message ?? "").isEmpty ? nil : message
  1191. if quoteMessage != nil {
  1192. msg.quoteMessage = quoteMessage
  1193. }
  1194. dcContext.sendMessage(chatId: self.chatId, message: msg)
  1195. }
  1196. private func sendVoiceMessage(url: NSURL) {
  1197. DispatchQueue.global().async {
  1198. let msg = self.dcContext.newMessage(viewType: DC_MSG_VOICE)
  1199. msg.setFile(filepath: url.relativePath, mimeType: "audio/m4a")
  1200. self.dcContext.sendMessage(chatId: self.chatId, message: msg)
  1201. }
  1202. }
  1203. // MARK: - Context menu
  1204. private func prepareContextMenu() {
  1205. UIMenuController.shared.menuItems = contextMenu.menuItems
  1206. UIMenuController.shared.update()
  1207. }
  1208. override func tableView(_ tableView: UITableView, shouldShowMenuForRowAt indexPath: IndexPath) -> Bool {
  1209. let messageId = messageIds[indexPath.row]
  1210. return !(dcContext.getMessage(id: messageId).isInfo || messageId == DC_MSG_ID_MARKER1 || messageId == DC_MSG_ID_DAYMARKER)
  1211. }
  1212. override func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
  1213. return !tableView.isEditing && contextMenu.canPerformAction(action: action)
  1214. }
  1215. override func tableView(_ tableView: UITableView, performAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) {
  1216. // handle standard actions here, but custom actions never trigger this. it still needs to be present for the menu to display, though.
  1217. contextMenu.performAction(action: action, indexPath: indexPath)
  1218. }
  1219. // context menu for iOS 13+
  1220. @available(iOS 13, *)
  1221. override func tableView(_ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
  1222. let messageId = messageIds[indexPath.row]
  1223. if tableView.isEditing || dcContext.getMessage(id: messageId).isInfo || messageId == DC_MSG_ID_MARKER1 || messageId == DC_MSG_ID_DAYMARKER {
  1224. return nil
  1225. }
  1226. return UIContextMenuConfiguration(
  1227. identifier: nil,
  1228. previewProvider: nil,
  1229. actionProvider: { [weak self] _ in
  1230. self?.contextMenu.actionProvider(indexPath: indexPath)
  1231. }
  1232. )
  1233. }
  1234. func showMediaGalleryFor(indexPath: IndexPath) {
  1235. let messageId = messageIds[indexPath.row]
  1236. let message = dcContext.getMessage(id: messageId)
  1237. if message.type != DC_MSG_STICKER {
  1238. showMediaGalleryFor(message: message)
  1239. }
  1240. }
  1241. func showMediaGalleryFor(message: DcMsg) {
  1242. let msgIds = dcContext.getChatMedia(chatId: chatId, messageType: Int32(message.type), messageType2: 0, messageType3: 0)
  1243. let index = msgIds.firstIndex(of: message.id) ?? 0
  1244. showMediaGallery(currentIndex: index, msgIds: msgIds)
  1245. }
  1246. private func didTapAsm(msg: DcMsg, orgText: String) {
  1247. let inputDlg = UIAlertController(
  1248. title: String.localized("autocrypt_continue_transfer_title"),
  1249. message: String.localized("autocrypt_continue_transfer_please_enter_code"),
  1250. preferredStyle: .alert)
  1251. inputDlg.addTextField(configurationHandler: { (textField) in
  1252. textField.placeholder = msg.setupCodeBegin + ".."
  1253. textField.text = orgText
  1254. textField.keyboardType = UIKeyboardType.numbersAndPunctuation // allows entering spaces; decimalPad would require a mask to keep things readable
  1255. })
  1256. inputDlg.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  1257. let okAction = UIAlertAction(title: String.localized("ok"), style: .default, handler: { _ in
  1258. let textField = inputDlg.textFields![0]
  1259. let modText = textField.text ?? ""
  1260. let success = self.dcContext.continueKeyTransfer(msgId: msg.id, setupCode: modText)
  1261. let alert = UIAlertController(
  1262. title: String.localized("autocrypt_continue_transfer_title"),
  1263. message: String.localized(success ? "autocrypt_continue_transfer_succeeded" : "autocrypt_bad_setup_code"),
  1264. preferredStyle: .alert)
  1265. if success {
  1266. alert.addAction(UIAlertAction(title: String.localized("ok"), style: .default, handler: nil))
  1267. } else {
  1268. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  1269. let retryAction = UIAlertAction(title: String.localized("autocrypt_continue_transfer_retry"), style: .default, handler: { _ in
  1270. self.didTapAsm(msg: msg, orgText: modText)
  1271. })
  1272. alert.addAction(retryAction)
  1273. alert.preferredAction = retryAction
  1274. }
  1275. self.navigationController?.present(alert, animated: true, completion: nil)
  1276. })
  1277. inputDlg.addAction(okAction)
  1278. inputDlg.preferredAction = okAction // without setting preferredAction, cancel become shown *bold* as the preferred action
  1279. navigationController?.present(inputDlg, animated: true, completion: nil)
  1280. }
  1281. func handleUIMenu() -> Bool {
  1282. if UIMenuController.shared.isMenuVisible {
  1283. UIMenuController.shared.setMenuVisible(false, animated: true)
  1284. return true
  1285. }
  1286. return false
  1287. }
  1288. func handleSelection(indexPath: IndexPath) -> Bool {
  1289. if tableView.isEditing {
  1290. if tableView.indexPathsForSelectedRows?.contains(indexPath) ?? false {
  1291. tableView.deselectRow(at: indexPath, animated: false)
  1292. } else {
  1293. tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
  1294. }
  1295. handleEditingBar()
  1296. return true
  1297. }
  1298. return false
  1299. }
  1300. func handleEditingBar() {
  1301. if let rows = tableView.indexPathsForSelectedRows,
  1302. !rows.isEmpty {
  1303. editingBar.isEnabled = true
  1304. } else {
  1305. editingBar.isEnabled = false
  1306. }
  1307. }
  1308. func setEditing(isEditing: Bool, selectedAtIndexPath: IndexPath? = nil) {
  1309. self.tableView.setEditing(isEditing, animated: true)
  1310. self.draft.isEditing = isEditing
  1311. self.configureDraftArea(draft: self.draft)
  1312. if let indexPath = selectedAtIndexPath {
  1313. _ = handleSelection(indexPath: indexPath)
  1314. }
  1315. }
  1316. }
  1317. // MARK: - BaseMessageCellDelegate
  1318. extension ChatViewController: BaseMessageCellDelegate {
  1319. @objc func fullMessageTapped(indexPath: IndexPath) {
  1320. if handleUIMenu() || handleSelection(indexPath: indexPath) {
  1321. return
  1322. }
  1323. let msg = dcContext.getMessage(id: messageIds[indexPath.row])
  1324. let fullMessageViewController = FullMessageViewController(dcContext: dcContext, messageId: msg.id)
  1325. navigationController?.pushViewController(fullMessageViewController, animated: true)
  1326. }
  1327. @objc func quoteTapped(indexPath: IndexPath) {
  1328. if handleSelection(indexPath: indexPath) { return }
  1329. _ = handleUIMenu()
  1330. let msg = dcContext.getMessage(id: messageIds[indexPath.row])
  1331. if let quoteMsg = msg.quoteMessage {
  1332. if self.chatId == quoteMsg.chatId {
  1333. scrollToMessage(msgId: quoteMsg.id)
  1334. } else {
  1335. showChat(chatId: quoteMsg.chatId, messageId: quoteMsg.id, animated: false)
  1336. }
  1337. }
  1338. }
  1339. @objc func textTapped(indexPath: IndexPath) {
  1340. if handleUIMenu() || handleSelection(indexPath: indexPath) {
  1341. return
  1342. }
  1343. let message = dcContext.getMessage(id: messageIds[indexPath.row])
  1344. if message.isSetupMessage {
  1345. didTapAsm(msg: message, orgText: "")
  1346. }
  1347. }
  1348. @objc func phoneNumberTapped(number: String, indexPath: IndexPath) {
  1349. if handleUIMenu() || handleSelection(indexPath: indexPath) {
  1350. return
  1351. }
  1352. let sanitizedNumber = number.filter("0123456789".contains)
  1353. if let phoneURL = URL(string: "tel://\(sanitizedNumber)") {
  1354. UIApplication.shared.open(phoneURL, options: [:], completionHandler: nil)
  1355. }
  1356. logger.debug("phone number tapped \(sanitizedNumber)")
  1357. }
  1358. @objc func commandTapped(command: String, indexPath: IndexPath) {
  1359. if handleUIMenu() || handleSelection(indexPath: indexPath) {
  1360. return
  1361. }
  1362. logger.debug("command tapped \(command)")
  1363. }
  1364. @objc func urlTapped(url: URL, indexPath: IndexPath) {
  1365. if handleUIMenu() || handleSelection(indexPath: indexPath) {
  1366. return
  1367. }
  1368. if Utils.isEmail(url: url) {
  1369. logger.debug("tapped on contact")
  1370. let email = Utils.getEmailFrom(url)
  1371. self.askToChatWith(email: email)
  1372. } else {
  1373. UIApplication.shared.open(url)
  1374. }
  1375. }
  1376. @objc func imageTapped(indexPath: IndexPath) {
  1377. if handleUIMenu() || handleSelection(indexPath: indexPath) {
  1378. return
  1379. }
  1380. showMediaGalleryFor(indexPath: indexPath)
  1381. }
  1382. @objc func avatarTapped(indexPath: IndexPath) {
  1383. let message = dcContext.getMessage(id: messageIds[indexPath.row])
  1384. let contactDetailController = ContactDetailViewController(dcContext: dcContext, contactId: message.fromContactId)
  1385. navigationController?.pushViewController(contactDetailController, animated: true)
  1386. }
  1387. }
  1388. // MARK: - MediaPickerDelegate
  1389. extension ChatViewController: MediaPickerDelegate {
  1390. func onVideoSelected(url: NSURL) {
  1391. stageVideo(url: url)
  1392. }
  1393. func onImageSelected(url: NSURL) {
  1394. stageImage(url: url)
  1395. }
  1396. func onImageSelected(image: UIImage) {
  1397. stageImage(image)
  1398. }
  1399. func onVoiceMessageRecorded(url: NSURL) {
  1400. sendVoiceMessage(url: url)
  1401. }
  1402. func onDocumentSelected(url: NSURL) {
  1403. stageDocument(url: url)
  1404. }
  1405. }
  1406. // MARK: - MessageInputBarDelegate
  1407. extension ChatViewController: InputBarAccessoryViewDelegate {
  1408. func inputBar(_ inputBar: InputBarAccessoryView, didPressSendButtonWith text: String) {
  1409. keepKeyboard = true
  1410. let trimmedText = text.replacingOccurrences(of: "\u{FFFC}", with: "", options: .literal, range: nil)
  1411. .trimmingCharacters(in: .whitespacesAndNewlines)
  1412. if let filePath = draft.attachment, let viewType = draft.viewType {
  1413. switch viewType {
  1414. case DC_MSG_GIF, DC_MSG_IMAGE, DC_MSG_FILE, DC_MSG_VIDEO:
  1415. self.sendAttachmentMessage(viewType: viewType, filePath: filePath, message: trimmedText, quoteMessage: draft.quoteMessage)
  1416. default:
  1417. logger.warning("Unsupported viewType for drafted messages.")
  1418. }
  1419. } else if inputBar.inputTextView.images.isEmpty {
  1420. self.sendTextMessage(text: trimmedText, quoteMessage: draft.quoteMessage)
  1421. } else {
  1422. // only 1 attachment allowed for now, thus it takes the first one
  1423. self.sendImage(inputBar.inputTextView.images[0], message: trimmedText)
  1424. }
  1425. inputBar.inputTextView.text = String()
  1426. inputBar.inputTextView.attributedText = nil
  1427. draftArea.cancel()
  1428. }
  1429. func inputBar(_ inputBar: InputBarAccessoryView, textViewTextDidChangeTo text: String) {
  1430. draft.text = text
  1431. evaluateInputBar(draft: draft)
  1432. }
  1433. func inputBar(_ inputBar: InputBarAccessoryView, didChangeIntrinsicContentTo size: CGSize) {
  1434. if isDismissing {
  1435. return
  1436. }
  1437. self.tableView.contentInset = UIEdgeInsets(top: self.getTopInsetHeight(),
  1438. left: 0,
  1439. bottom: size.height + messageInputBar.keyboardHeight,
  1440. right: 0)
  1441. if isLastRowVisible() && !tableView.isDragging && !tableView.isDecelerating && highlightedMsg == nil && !ignoreInputBarChange {
  1442. self.scrollToBottom(animated: true)
  1443. }
  1444. }
  1445. }
  1446. // MARK: - DraftPreviewDelegate
  1447. extension ChatViewController: DraftPreviewDelegate {
  1448. func onCancelQuote() {
  1449. keepKeyboard = true
  1450. draft.setQuote(quotedMsg: nil)
  1451. configureDraftArea(draft: draft)
  1452. }
  1453. func onCancelAttachment() {
  1454. keepKeyboard = true
  1455. draft.setAttachment(viewType: nil, path: nil, mimetype: nil)
  1456. configureDraftArea(draft: draft)
  1457. evaluateInputBar(draft: draft)
  1458. }
  1459. func onAttachmentAdded() {
  1460. evaluateInputBar(draft: draft)
  1461. }
  1462. func onAttachmentTapped() {
  1463. if let attachmentPath = draft.attachment {
  1464. let attachmentURL = URL(fileURLWithPath: attachmentPath, isDirectory: false)
  1465. let previewController = PreviewController(dcContext: dcContext, type: .single(attachmentURL))
  1466. if #available(iOS 13.0, *), draft.viewType == DC_MSG_IMAGE || draft.viewType == DC_MSG_VIDEO {
  1467. previewController.setEditing(true, animated: true)
  1468. previewController.delegate = self
  1469. }
  1470. let nav = UINavigationController(rootViewController: previewController)
  1471. nav.modalPresentationStyle = .fullScreen
  1472. navigationController?.present(nav, animated: true)
  1473. }
  1474. }
  1475. }
  1476. // MARK: - ChatEditingDelegate
  1477. extension ChatViewController: ChatEditingDelegate {
  1478. func onDeletePressed() {
  1479. if let rows = tableView.indexPathsForSelectedRows {
  1480. let messageIdsToDelete = rows.compactMap { messageIds[$0.row] }
  1481. askToDeleteMessages(ids: messageIdsToDelete)
  1482. }
  1483. }
  1484. func onForwardPressed() {
  1485. if let rows = tableView.indexPathsForSelectedRows {
  1486. let messageIdsToForward = rows.compactMap { messageIds[$0.row] }
  1487. RelayHelper.sharedInstance.setForwardMessages(messageIds: messageIdsToForward)
  1488. self.navigationController?.popViewController(animated: true)
  1489. }
  1490. }
  1491. func onCancelPressed() {
  1492. setEditing(isEditing: false)
  1493. }
  1494. }
  1495. // MARK: - QLPreviewControllerDelegate
  1496. extension ChatViewController: QLPreviewControllerDelegate {
  1497. @available(iOS 13.0, *)
  1498. func previewController(_ controller: QLPreviewController, editingModeFor previewItem: QLPreviewItem) -> QLPreviewItemEditingMode {
  1499. return .updateContents
  1500. }
  1501. func previewController(_ controller: QLPreviewController, didUpdateContentsOf previewItem: QLPreviewItem) {
  1502. DispatchQueue.main.async { [weak self] in
  1503. guard let self = self else { return }
  1504. self.draftArea.reload(draft: self.draft)
  1505. }
  1506. }
  1507. }
  1508. // MARK: - AudioControllerDelegate
  1509. extension ChatViewController: AudioControllerDelegate {
  1510. func onAudioPlayFailed() {
  1511. let alert = UIAlertController(title: String.localized("error"),
  1512. message: String.localized("cannot_play_unsupported_file_type"),
  1513. preferredStyle: .safeActionSheet)
  1514. alert.addAction(UIAlertAction(title: String.localized("ok"), style: .default, handler: nil))
  1515. self.present(alert, animated: true, completion: nil)
  1516. }
  1517. }
  1518. // MARK: - UITextViewDelegate
  1519. extension ChatViewController: UITextViewDelegate {
  1520. func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
  1521. if keepKeyboard {
  1522. DispatchQueue.main.async { [weak self] in
  1523. self?.messageInputBar.inputTextView.becomeFirstResponder()
  1524. }
  1525. keepKeyboard = false
  1526. return false
  1527. }
  1528. return true
  1529. }
  1530. }
  1531. // MARK: - ChatInputTextViewPasteDelegate
  1532. extension ChatViewController: ChatInputTextViewPasteDelegate {
  1533. func onImagePasted(image: UIImage) {
  1534. sendSticker(image)
  1535. }
  1536. }