ChatViewController.swift 73 KB

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