ChatViewController.swift 72 KB

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