ChatViewController.swift 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375
  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: Any?
  16. var incomingMsgObserver: Any?
  17. var ephemeralTimerModifiedObserver: Any?
  18. var dismissCancelled = false
  19. lazy var isGroupChat: Bool = {
  20. return dcContext.getChat(chatId: chatId).isGroup
  21. }()
  22. lazy var draft: DraftModel = {
  23. let draft = DraftModel(chatId: chatId)
  24. return draft
  25. }()
  26. /// The `InputBarAccessoryView` used as the `inputAccessoryView` in the view controller.
  27. open var messageInputBar = ChatInputBar()
  28. lazy var draftArea: DraftArea = {
  29. let view = DraftArea()
  30. view.translatesAutoresizingMaskIntoConstraints = false
  31. view.delegate = self
  32. view.inputBarAccessoryView = messageInputBar
  33. return view
  34. }()
  35. open override var shouldAutorotate: Bool {
  36. return false
  37. }
  38. private weak var timer: Timer?
  39. lazy var navBarTap: UITapGestureRecognizer = {
  40. UITapGestureRecognizer(target: self, action: #selector(chatProfilePressed))
  41. }()
  42. private var locationStreamingItem: UIBarButtonItem = {
  43. let indicator = LocationStreamingIndicator()
  44. return UIBarButtonItem(customView: indicator)
  45. }()
  46. private lazy var muteItem: UIBarButtonItem = {
  47. let imageView = UIImageView()
  48. imageView.tintColor = DcColors.defaultTextColor
  49. imageView.image = #imageLiteral(resourceName: "volume_off").withRenderingMode(.alwaysTemplate)
  50. imageView.translatesAutoresizingMaskIntoConstraints = false
  51. imageView.heightAnchor.constraint(equalToConstant: 20).isActive = true
  52. imageView.widthAnchor.constraint(equalToConstant: 20).isActive = true
  53. return UIBarButtonItem(customView: imageView)
  54. }()
  55. private lazy var ephemeralMessageItem: UIBarButtonItem = {
  56. let imageView = UIImageView()
  57. imageView.tintColor = DcColors.defaultTextColor
  58. imageView.image = #imageLiteral(resourceName: "ephemeral_timer").withRenderingMode(.alwaysTemplate)
  59. imageView.translatesAutoresizingMaskIntoConstraints = false
  60. imageView.heightAnchor.constraint(equalToConstant: 20).isActive = true
  61. imageView.widthAnchor.constraint(equalToConstant: 20).isActive = true
  62. return UIBarButtonItem(customView: imageView)
  63. }()
  64. private lazy var badgeItem: UIBarButtonItem = {
  65. let badge: InitialsBadge
  66. let chat = dcContext.getChat(chatId: chatId)
  67. if let image = chat.profileImage {
  68. badge = InitialsBadge(image: image, size: 28, accessibilityLabel: String.localized("menu_view_profile"))
  69. } else {
  70. badge = InitialsBadge(
  71. name: chat.name,
  72. color: chat.color,
  73. size: 28,
  74. accessibilityLabel: String.localized("menu_view_profile")
  75. )
  76. badge.setLabelFont(UIFont.systemFont(ofSize: 14))
  77. }
  78. badge.setVerified(chat.isProtected)
  79. badge.accessibilityTraits = .button
  80. return UIBarButtonItem(customView: badge)
  81. }()
  82. private lazy var contextMenu: ContextMenuProvider = {
  83. let copyItem = ContextMenuProvider.ContextMenuItem(
  84. title: String.localized("global_menu_edit_copy_desktop"),
  85. imageName: "ic_content_copy_white_36pt",
  86. action: #selector(BaseMessageCell.messageCopy),
  87. onPerform: { [weak self] indexPath in
  88. guard let self = self else { return }
  89. let id = self.messageIds[indexPath.row]
  90. let msg = DcMsg(id: id)
  91. let pasteboard = UIPasteboard.general
  92. if msg.type == DC_MSG_TEXT {
  93. pasteboard.string = msg.text
  94. } else {
  95. pasteboard.string = msg.summary(chars: 10000000)
  96. }
  97. }
  98. )
  99. let infoItem = ContextMenuProvider.ContextMenuItem(
  100. title: String.localized("info"),
  101. imageName: "info",
  102. action: #selector(BaseMessageCell.messageInfo),
  103. onPerform: { [weak self] indexPath in
  104. guard let self = self else { return }
  105. let msg = DcMsg(id: self.messageIds[indexPath.row])
  106. let msgViewController = MessageInfoViewController(dcContext: self.dcContext, message: msg)
  107. if let ctrl = self.navigationController {
  108. ctrl.pushViewController(msgViewController, animated: true)
  109. }
  110. }
  111. )
  112. let deleteItem = ContextMenuProvider.ContextMenuItem(
  113. title: String.localized("delete"),
  114. imageName: "trash",
  115. isDestructive: true,
  116. action: #selector(BaseMessageCell.messageDelete),
  117. onPerform: { [weak self] indexPath in
  118. DispatchQueue.main.async { [weak self] in
  119. guard let self = self else { return }
  120. self.tableView.becomeFirstResponder()
  121. let msg = DcMsg(id: self.messageIds[indexPath.row])
  122. self.askToDeleteMessage(id: msg.id)
  123. }
  124. }
  125. )
  126. let forwardItem = ContextMenuProvider.ContextMenuItem(
  127. title: String.localized("forward"),
  128. imageName: "ic_forward_white_36pt",
  129. action: #selector(BaseMessageCell.messageForward),
  130. onPerform: { [weak self] indexPath in
  131. guard let self = self else { return }
  132. let msg = DcMsg(id: self.messageIds[indexPath.row])
  133. RelayHelper.sharedInstance.setForwardMessage(messageId: msg.id)
  134. self.navigationController?.popViewController(animated: true)
  135. }
  136. )
  137. let replyItem = ContextMenuProvider.ContextMenuItem(
  138. title: String.localized("notify_reply_button"),
  139. imageName: "ic_reply",
  140. action: #selector(BaseMessageCell.messageReply),
  141. onPerform: { indexPath in
  142. DispatchQueue.main.async { [weak self] in
  143. self?.replyToMessage(at: indexPath)
  144. }
  145. }
  146. )
  147. let selectMoreItem = ContextMenuProvider.ContextMenuItem(
  148. title: String.localized("select_more"),
  149. imageName: "ic_check",
  150. action: #selector(BaseMessageCell.messageSelectMore),
  151. onPerform: { indexPath in
  152. DispatchQueue.main.async { [weak self] in
  153. guard let self = self else { return }
  154. let messageId = self.messageIds[indexPath.row]
  155. self.tableView.setEditing(true, animated: true)
  156. UIView.performWithoutAnimation {
  157. if let indexPaths = self.tableView.indexPathsForVisibleRows {
  158. self.tableView.reloadRows(at: indexPaths, with: .none)
  159. }
  160. self.tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
  161. }
  162. }
  163. }
  164. )
  165. let config = ContextMenuProvider()
  166. if #available(iOS 13.0, *), !disableWriting {
  167. config.setMenu([replyItem, forwardItem, infoItem, copyItem, selectMoreItem, deleteItem])
  168. } else {
  169. config.setMenu([forwardItem, infoItem, copyItem, deleteItem, selectMoreItem])
  170. }
  171. return config
  172. }()
  173. /// The `BasicAudioController` controll the AVAudioPlayer state (play, pause, stop) and update audio cell UI accordingly.
  174. private lazy var audioController = AudioController(dcContext: dcContext, chatId: chatId)
  175. private var disableWriting: Bool
  176. private var showNamesAboveMessage: Bool
  177. var showCustomNavBar = true
  178. var highlightedMsg: Int?
  179. private lazy var mediaPicker: MediaPicker? = {
  180. let mediaPicker = MediaPicker(navigationController: navigationController)
  181. mediaPicker.delegate = self
  182. return mediaPicker
  183. }()
  184. var emptyStateView: EmptyStateLabel = {
  185. let view = EmptyStateLabel()
  186. view.isHidden = true
  187. return view
  188. }()
  189. init(dcContext: DcContext, chatId: Int, highlightedMsg: Int? = nil) {
  190. let dcChat = dcContext.getChat(chatId: chatId)
  191. self.dcContext = dcContext
  192. self.chatId = chatId
  193. self.disableWriting = !dcChat.canSend
  194. self.showNamesAboveMessage = dcChat.isGroup
  195. self.highlightedMsg = highlightedMsg
  196. super.init(nibName: nil, bundle: nil)
  197. hidesBottomBarWhenPushed = true
  198. }
  199. required init?(coder _: NSCoder) {
  200. fatalError("init(coder:) has not been implemented")
  201. }
  202. override func loadView() {
  203. self.tableView = ChatTableView(messageInputBar: self.disableWriting ? nil : messageInputBar)
  204. self.tableView.delegate = self
  205. self.tableView.dataSource = self
  206. self.view = self.tableView
  207. }
  208. override func viewDidLoad() {
  209. super.viewDidLoad()
  210. tableView.register(TextMessageCell.self, forCellReuseIdentifier: "text")
  211. tableView.register(ImageTextCell.self, forCellReuseIdentifier: "image")
  212. tableView.register(FileTextCell.self, forCellReuseIdentifier: "file")
  213. tableView.register(InfoMessageCell.self, forCellReuseIdentifier: "info")
  214. tableView.register(AudioMessageCell.self, forCellReuseIdentifier: "audio")
  215. tableView.rowHeight = UITableView.automaticDimension
  216. tableView.separatorStyle = .none
  217. tableView.keyboardDismissMode = .interactive
  218. tableView.allowsMultipleSelectionDuringEditing = true
  219. if !dcContext.isConfigured() {
  220. // TODO: display message about nothing being configured
  221. return
  222. }
  223. configureEmptyStateView()
  224. if !disableWriting {
  225. configureMessageInputBar()
  226. draft.parse(draftMsg: dcContext.getDraft(chatId: chatId))
  227. messageInputBar.inputTextView.text = draft.text
  228. configureDraftArea(draft: draft)
  229. }
  230. let notificationCenter = NotificationCenter.default
  231. notificationCenter.addObserver(self,
  232. selector: #selector(saveDraft),
  233. name: UIApplication.willResignActiveNotification,
  234. object: nil)
  235. notificationCenter.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
  236. }
  237. @objc func keyboardWillShow(_ notification: Notification) {
  238. if self.isLastRowVisible() {
  239. DispatchQueue.main.async { [weak self] in
  240. if self?.messageInputBar.keyboardHeight ?? 0 > 0 {
  241. self?.scrollToBottom(animated: true)
  242. } else { // inputbar height increased, probably because of draft area changes
  243. self?.scrollToBottom(animated: false)
  244. }
  245. }
  246. }
  247. }
  248. private func startTimer() {
  249. timer?.invalidate()
  250. timer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { [weak self] _ in
  251. //reload table
  252. DispatchQueue.main.async {
  253. guard let self = self else { return }
  254. self.messageIds = self.getMessageIds()
  255. self.reloadData()
  256. }
  257. }
  258. }
  259. private func stopTimer() {
  260. timer?.invalidate()
  261. }
  262. private func configureEmptyStateView() {
  263. emptyStateView.addCenteredTo(parentView: view)
  264. }
  265. override func viewWillAppear(_ animated: Bool) {
  266. super.viewWillAppear(animated)
  267. if dismissCancelled {
  268. self.dismissCancelled = false
  269. } else {
  270. self.tableView.becomeFirstResponder()
  271. }
  272. // this will be removed in viewWillDisappear
  273. navigationController?.navigationBar.addGestureRecognizer(navBarTap)
  274. if showCustomNavBar {
  275. updateTitle(chat: dcContext.getChat(chatId: chatId))
  276. }
  277. loadMessages()
  278. if RelayHelper.sharedInstance.isForwarding() {
  279. askToForwardMessage()
  280. }
  281. prepareContextMenu()
  282. }
  283. override func viewDidAppear(_ animated: Bool) {
  284. super.viewDidAppear(animated)
  285. AppStateRestorer.shared.storeLastActiveChat(chatId: chatId)
  286. let nc = NotificationCenter.default
  287. msgChangedObserver = nc.addObserver(
  288. forName: dcNotificationChanged,
  289. object: nil,
  290. queue: OperationQueue.main
  291. ) { [weak self] notification in
  292. guard let self = self else { return }
  293. if let ui = notification.userInfo {
  294. if self.disableWriting {
  295. // always refresh, as we can't check currently
  296. self.refreshMessages()
  297. } else if let id = ui["message_id"] as? Int {
  298. if id > 0 {
  299. self.updateMessage(id)
  300. } else {
  301. // change might be a deletion
  302. self.refreshMessages()
  303. }
  304. }
  305. if self.showCustomNavBar {
  306. self.updateTitle(chat: self.dcContext.getChat(chatId: self.chatId))
  307. }
  308. }
  309. }
  310. incomingMsgObserver = nc.addObserver(
  311. forName: dcNotificationIncoming,
  312. object: nil, queue: OperationQueue.main
  313. ) { [weak self] notification in
  314. guard let self = self else { return }
  315. if let ui = notification.userInfo {
  316. if self.chatId == ui["chat_id"] as? Int {
  317. if let id = ui["message_id"] as? Int {
  318. if id > 0 {
  319. self.insertMessage(DcMsg(id: id))
  320. }
  321. }
  322. }
  323. }
  324. }
  325. ephemeralTimerModifiedObserver = nc.addObserver(
  326. forName: dcEphemeralTimerModified,
  327. object: nil, queue: OperationQueue.main
  328. ) { [weak self] _ in
  329. guard let self = self else { return }
  330. self.updateTitle(chat: self.dcContext.getChat(chatId: self.chatId))
  331. }
  332. // things that do not affect the chatview
  333. // and are delayed after the view is displayed
  334. DispatchQueue.global(qos: .background).async { [weak self] in
  335. guard let self = self else { return }
  336. self.dcContext.marknoticedChat(chatId: self.chatId)
  337. }
  338. startTimer()
  339. }
  340. override func viewWillDisappear(_ animated: Bool) {
  341. super.viewWillDisappear(animated)
  342. // the navigationController will be used when chatDetail is pushed, so we have to remove that gestureRecognizer
  343. navigationController?.navigationBar.removeGestureRecognizer(navBarTap)
  344. dismissCancelled = true
  345. }
  346. override func viewDidDisappear(_ animated: Bool) {
  347. super.viewDidDisappear(animated)
  348. dismissCancelled = false
  349. AppStateRestorer.shared.resetLastActiveChat()
  350. saveDraft()
  351. let nc = NotificationCenter.default
  352. if let msgChangedObserver = self.msgChangedObserver {
  353. nc.removeObserver(msgChangedObserver)
  354. }
  355. if let incomingMsgObserver = self.incomingMsgObserver {
  356. nc.removeObserver(incomingMsgObserver)
  357. }
  358. if let ephemeralTimerModifiedObserver = self.ephemeralTimerModifiedObserver {
  359. nc.removeObserver(ephemeralTimerModifiedObserver)
  360. }
  361. audioController.stopAnyOngoingPlaying()
  362. stopTimer()
  363. }
  364. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  365. let lastSectionVisibleBeforeTransition = self.isLastRowVisible()
  366. coordinator.animate(
  367. alongsideTransition: { [weak self] _ in
  368. guard let self = self else { return }
  369. if self.showCustomNavBar {
  370. self.navigationItem.setRightBarButton(self.badgeItem, animated: true)
  371. }
  372. if lastSectionVisibleBeforeTransition {
  373. self.scrollToBottom(animated: false)
  374. }
  375. },
  376. completion: {[weak self] _ in
  377. guard let self = self else { return }
  378. self.updateTitle(chat: self.dcContext.getChat(chatId: self.chatId))
  379. if lastSectionVisibleBeforeTransition {
  380. DispatchQueue.main.async { [weak self] in
  381. self?.reloadData()
  382. self?.scrollToBottom(animated: false)
  383. }
  384. }
  385. }
  386. )
  387. super.viewWillTransition(to: size, with: coordinator)
  388. }
  389. /// UITableView methods
  390. override func numberOfSections(in tableView: UITableView) -> Int {
  391. return 1
  392. }
  393. override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
  394. return messageIds.count
  395. }
  396. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  397. _ = handleUIMenu()
  398. let id = messageIds[indexPath.row]
  399. let message = DcMsg(id: id)
  400. if message.isInfo {
  401. let cell = tableView.dequeueReusableCell(withIdentifier: "info", for: indexPath) as? InfoMessageCell ?? InfoMessageCell()
  402. cell.update(msg: message)
  403. return cell
  404. }
  405. let cell: BaseMessageCell
  406. if message.type == DC_MSG_IMAGE || message.type == DC_MSG_GIF || message.type == DC_MSG_VIDEO {
  407. cell = tableView.dequeueReusableCell(withIdentifier: "image", for: indexPath) as? ImageTextCell ?? ImageTextCell()
  408. } else if message.type == DC_MSG_FILE {
  409. if message.isSetupMessage {
  410. cell = tableView.dequeueReusableCell(withIdentifier: "text", for: indexPath) as? TextMessageCell ?? TextMessageCell()
  411. message.text = String.localized("autocrypt_asm_click_body")
  412. } else {
  413. cell = tableView.dequeueReusableCell(withIdentifier: "file", for: indexPath) as? FileTextCell ?? FileTextCell()
  414. }
  415. } else if message.type == DC_MSG_AUDIO || message.type == DC_MSG_VOICE {
  416. let audioMessageCell: AudioMessageCell = tableView.dequeueReusableCell(withIdentifier: "audio",
  417. for: indexPath) as? AudioMessageCell ?? AudioMessageCell()
  418. audioController.update(audioMessageCell, with: message.id)
  419. cell = audioMessageCell
  420. } else {
  421. cell = tableView.dequeueReusableCell(withIdentifier: "text", for: indexPath) as? TextMessageCell ?? TextMessageCell()
  422. }
  423. cell.baseDelegate = self
  424. cell.update(msg: message,
  425. messageStyle: configureMessageStyle(for: message, at: indexPath),
  426. isAvatarVisible: configureAvatarVisibility(for: message, at: indexPath),
  427. isGroup: isGroupChat)
  428. cell.selectionStyle = tableView.isEditing ? .default : .none
  429. return cell
  430. }
  431. public override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  432. if !decelerate {
  433. markSeenMessagesInVisibleArea()
  434. }
  435. }
  436. public override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  437. markSeenMessagesInVisibleArea()
  438. }
  439. private func configureDraftArea(draft: DraftModel) {
  440. draftArea.configure(draft: draft)
  441. // setStackViewItems recalculates the proper messageInputBar height
  442. messageInputBar.setStackViewItems([draftArea], forStack: .top, animated: true)
  443. }
  444. override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
  445. if disableWriting {
  446. return nil
  447. }
  448. let action = UIContextualAction(style: .normal, title: nil,
  449. handler: { [weak self] (_, _, completionHandler) in
  450. self?.replyToMessage(at: indexPath)
  451. completionHandler(true)
  452. })
  453. if #available(iOS 12.0, *) {
  454. action.image = UIImage(named: traitCollection.userInterfaceStyle == .light ? "ic_reply_black" : "ic_reply")
  455. } else {
  456. action.image = UIImage(named: "ic_reply_black")
  457. }
  458. action.image?.accessibilityTraits = .button
  459. action.image?.accessibilityLabel = String.localized("menu_reply")
  460. action.backgroundColor = DcColors.chatBackgroundColor
  461. let configuration = UISwipeActionsConfiguration(actions: [action])
  462. return configuration
  463. }
  464. func replyToMessage(at indexPath: IndexPath) {
  465. let message = DcMsg(id: self.messageIds[indexPath.row])
  466. self.draft.setQuote(quotedMsg: message)
  467. self.configureDraftArea(draft: self.draft)
  468. self.messageInputBar.inputTextView.becomeFirstResponder()
  469. }
  470. func markSeenMessagesInVisibleArea() {
  471. if let indexPaths = tableView.indexPathsForVisibleRows {
  472. let visibleMessagesIds = indexPaths.map { UInt32(messageIds[$0.row]) }
  473. if !visibleMessagesIds.isEmpty {
  474. DispatchQueue.global(qos: .background).async { [weak self] in
  475. self?.dcContext.markSeenMessages(messageIds: visibleMessagesIds)
  476. }
  477. }
  478. }
  479. }
  480. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  481. if tableView.isEditing {
  482. return
  483. }
  484. let messageId = messageIds[indexPath.row]
  485. let message = DcMsg(id: messageId)
  486. if message.isSetupMessage {
  487. didTapAsm(msg: message, orgText: "")
  488. } else if message.type == DC_MSG_FILE ||
  489. message.type == DC_MSG_AUDIO ||
  490. message.type == DC_MSG_VOICE {
  491. showMediaGalleryFor(message: message)
  492. }
  493. _ = handleUIMenu()
  494. }
  495. func configureAvatarVisibility(for message: DcMsg, at indexPath: IndexPath) -> Bool {
  496. return isGroupChat && !message.isFromCurrentSender
  497. }
  498. func configureMessageStyle(for message: DcMsg, at indexPath: IndexPath) -> UIRectCorner {
  499. var corners: UIRectCorner = []
  500. if message.isFromCurrentSender {
  501. corners.formUnion(.topLeft)
  502. corners.formUnion(.bottomLeft)
  503. corners.formUnion(.topRight)
  504. } else {
  505. corners.formUnion(.topRight)
  506. corners.formUnion(.bottomRight)
  507. corners.formUnion(.topLeft)
  508. }
  509. return corners
  510. }
  511. private func getBackgroundColor(for currentMessage: DcMsg) -> UIColor {
  512. return currentMessage.isFromCurrentSender ? DcColors.messagePrimaryColor : DcColors.messageSecondaryColor
  513. }
  514. private func updateTitle(chat: DcChat) {
  515. let titleView = ChatTitleView()
  516. var subtitle = "ErrSubtitle"
  517. let chatContactIds = chat.contactIds
  518. if chat.isGroup {
  519. subtitle = String.localized(stringID: "n_members", count: chatContactIds.count)
  520. } else if chatContactIds.count >= 1 {
  521. if chat.isDeviceTalk {
  522. subtitle = String.localized("device_talk_subtitle")
  523. } else if chat.isSelfTalk {
  524. subtitle = String.localized("chat_self_talk_subtitle")
  525. } else {
  526. subtitle = DcContact(id: chatContactIds[0]).email
  527. }
  528. }
  529. titleView.updateTitleView(title: chat.name, subtitle: subtitle)
  530. navigationItem.titleView = titleView
  531. var rightBarButtonItems = [badgeItem]
  532. if chat.isSendingLocations {
  533. rightBarButtonItems.append(locationStreamingItem)
  534. }
  535. if chat.isMuted {
  536. rightBarButtonItems.append(muteItem)
  537. }
  538. if dcContext.getChatEphemeralTimer(chatId: chat.id) > 0 {
  539. rightBarButtonItems.append(ephemeralMessageItem)
  540. }
  541. navigationItem.rightBarButtonItems = rightBarButtonItems
  542. }
  543. @objc
  544. private func refreshMessages() {
  545. self.messageIds = self.getMessageIds()
  546. let wasLastSectionVisible = self.isLastRowVisible()
  547. self.reloadData()
  548. if wasLastSectionVisible {
  549. self.scrollToBottom(animated: true)
  550. }
  551. self.showEmptyStateView(self.messageIds.isEmpty)
  552. }
  553. func reloadData() {
  554. let selectredRows = tableView.indexPathsForSelectedRows
  555. tableView.reloadData()
  556. // There's an iOS bug, filling up the console output but which can be ignored: https://developer.apple.com/forums/thread/668295
  557. // [Assert] Attempted to call -cellForRowAtIndexPath: on the table view while it was in the process of updating its visible cells, which is not allowed.
  558. selectredRows?.forEach({ (selectedRow) in
  559. tableView.selectRow(at: selectedRow, animated: false, scrollPosition: .none)
  560. })
  561. }
  562. private func loadMessages() {
  563. DispatchQueue.global(qos: .userInitiated).async {
  564. DispatchQueue.main.async { [weak self] in
  565. guard let self = self else { return }
  566. let wasLastRowVisible = self.isLastRowVisible()
  567. let wasMessageIdsEmpty = self.messageIds.isEmpty
  568. // update message ids
  569. self.messageIds = self.getMessageIds()
  570. self.reloadData()
  571. if let msgId = self.highlightedMsg, let msgPosition = self.messageIds.firstIndex(of: msgId) {
  572. self.tableView.scrollToRow(at: IndexPath(row: msgPosition, section: 0), at: .top, animated: false)
  573. self.highlightedMsg = nil
  574. } else if wasMessageIdsEmpty ||
  575. wasLastRowVisible {
  576. self.scrollToBottom(animated: false)
  577. }
  578. self.showEmptyStateView(self.messageIds.isEmpty)
  579. }
  580. }
  581. }
  582. func isLastRowVisible() -> Bool {
  583. guard !messageIds.isEmpty else { return false }
  584. let lastIndexPath = IndexPath(item: messageIds.count - 1, section: 0)
  585. return tableView.indexPathsForVisibleRows?.contains(lastIndexPath) ?? false
  586. }
  587. func scrollToBottom(animated: Bool) {
  588. if !messageIds.isEmpty {
  589. self.tableView.scrollToRow(at: IndexPath(row: self.messageIds.count - 1, section: 0), at: .bottom, animated: animated)
  590. }
  591. }
  592. func scrollToMessage(msgId: Int, animated: Bool = true) {
  593. guard let index = messageIds.firstIndex(of: msgId) else {
  594. return
  595. }
  596. let indexPath = IndexPath(row: index, section: 0)
  597. tableView.scrollToRow(at: indexPath, at: .top, animated: animated)
  598. }
  599. private func showEmptyStateView(_ show: Bool) {
  600. if show {
  601. let dcChat = dcContext.getChat(chatId: chatId)
  602. if chatId == DC_CHAT_ID_DEADDROP {
  603. if dcContext.showEmails != DC_SHOW_EMAILS_ALL {
  604. emptyStateView.text = String.localized("chat_no_contact_requests")
  605. } else {
  606. emptyStateView.text = String.localized("chat_no_messages")
  607. }
  608. } else if dcChat.isGroup {
  609. if dcChat.isUnpromoted {
  610. emptyStateView.text = String.localized("chat_new_group_hint")
  611. } else {
  612. emptyStateView.text = String.localized("chat_no_messages")
  613. }
  614. } else if dcChat.isSelfTalk {
  615. emptyStateView.text = String.localized("saved_messages_explain")
  616. } else if dcChat.isDeviceTalk {
  617. emptyStateView.text = String.localized("device_talk_explain")
  618. } else {
  619. emptyStateView.text = String.localizedStringWithFormat(String.localized("chat_no_messages_hint"), dcChat.name, dcChat.name)
  620. }
  621. emptyStateView.isHidden = false
  622. } else {
  623. emptyStateView.isHidden = true
  624. }
  625. }
  626. private func getMessageIds() -> [Int] {
  627. return dcContext.getMessageIds(chatId: chatId)
  628. }
  629. @objc private func saveDraft() {
  630. draft.save(context: dcContext)
  631. }
  632. private func configureMessageInputBar() {
  633. messageInputBar.delegate = self
  634. messageInputBar.inputTextView.tintColor = DcColors.primary
  635. messageInputBar.inputTextView.placeholder = String.localized("chat_input_placeholder")
  636. messageInputBar.separatorLine.isHidden = true
  637. messageInputBar.inputTextView.tintColor = DcColors.primary
  638. messageInputBar.inputTextView.textColor = DcColors.defaultTextColor
  639. messageInputBar.backgroundView.backgroundColor = DcColors.chatBackgroundColor
  640. //scrollsToBottomOnKeyboardBeginsEditing = true
  641. messageInputBar.inputTextView.backgroundColor = DcColors.inputFieldColor
  642. messageInputBar.inputTextView.placeholderTextColor = DcColors.placeholderColor
  643. messageInputBar.inputTextView.textContainerInset = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 38)
  644. messageInputBar.inputTextView.placeholderLabelInsets = UIEdgeInsets(top: 8, left: 20, bottom: 8, right: 38)
  645. messageInputBar.inputTextView.layer.borderColor = UIColor.themeColor(light: UIColor(red: 200 / 255, green: 200 / 255, blue: 200 / 255, alpha: 1),
  646. dark: UIColor(red: 55 / 255, green: 55/255, blue: 55/255, alpha: 1)).cgColor
  647. messageInputBar.inputTextView.layer.borderWidth = 1.0
  648. messageInputBar.inputTextView.layer.cornerRadius = 13.0
  649. messageInputBar.inputTextView.layer.masksToBounds = true
  650. messageInputBar.inputTextView.scrollIndicatorInsets = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0)
  651. configureInputBarItems()
  652. }
  653. func evaluateInputBar(draft: DraftModel) {
  654. messageInputBar.sendButton.isEnabled = draft.canSend()
  655. }
  656. private func configureInputBarItems() {
  657. messageInputBar.setLeftStackViewWidthConstant(to: 40, animated: false)
  658. messageInputBar.setRightStackViewWidthConstant(to: 40, animated: false)
  659. let sendButtonImage = UIImage(named: "paper_plane")?.withRenderingMode(.alwaysTemplate)
  660. messageInputBar.sendButton.image = sendButtonImage
  661. messageInputBar.sendButton.accessibilityLabel = String.localized("menu_send")
  662. messageInputBar.sendButton.accessibilityTraits = .button
  663. messageInputBar.sendButton.title = nil
  664. messageInputBar.sendButton.tintColor = UIColor(white: 1, alpha: 1)
  665. messageInputBar.sendButton.layer.cornerRadius = 20
  666. messageInputBar.middleContentViewPadding = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 10)
  667. // this adds a padding between textinputfield and send button
  668. messageInputBar.sendButton.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
  669. messageInputBar.sendButton.setSize(CGSize(width: 40, height: 40), animated: false)
  670. messageInputBar.padding = UIEdgeInsets(top: 6, left: 6, bottom: 6, right: 12)
  671. messageInputBar.shouldManageSendButtonEnabledState = false
  672. let leftItems = [
  673. InputBarButtonItem()
  674. .configure {
  675. $0.spacing = .fixed(0)
  676. let clipperIcon = #imageLiteral(resourceName: "ic_attach_file_36pt").withRenderingMode(.alwaysTemplate)
  677. $0.image = clipperIcon
  678. $0.tintColor = DcColors.primary
  679. $0.setSize(CGSize(width: 40, height: 40), animated: false)
  680. $0.accessibilityLabel = String.localized("menu_add_attachment")
  681. $0.accessibilityTraits = .button
  682. }.onSelected {
  683. $0.tintColor = UIColor.themeColor(light: .lightGray, dark: .darkGray)
  684. }.onDeselected {
  685. $0.tintColor = DcColors.primary
  686. }.onTouchUpInside { [weak self] _ in
  687. self?.clipperButtonPressed()
  688. }
  689. ]
  690. messageInputBar.setStackViewItems(leftItems, forStack: .left, animated: false)
  691. // This just adds some more flare
  692. messageInputBar.sendButton
  693. .onEnabled { item in
  694. UIView.animate(withDuration: 0.3, animations: {
  695. item.backgroundColor = DcColors.primary
  696. })
  697. }.onDisabled { item in
  698. UIView.animate(withDuration: 0.3, animations: {
  699. item.backgroundColor = DcColors.colorDisabled
  700. })
  701. }
  702. }
  703. @objc private func chatProfilePressed() {
  704. if chatId != DC_CHAT_ID_DEADDROP {
  705. showChatDetail(chatId: chatId)
  706. }
  707. }
  708. @objc private func clipperButtonPressed() {
  709. showClipperOptions()
  710. }
  711. private func showClipperOptions() {
  712. let alert = UIAlertController(title: nil, message: nil, preferredStyle: .safeActionSheet)
  713. let galleryAction = PhotoPickerAlertAction(title: String.localized("gallery"), style: .default, handler: galleryButtonPressed(_:))
  714. let cameraAction = PhotoPickerAlertAction(title: String.localized("camera"), style: .default, handler: cameraButtonPressed(_:))
  715. let documentAction = UIAlertAction(title: String.localized("files"), style: .default, handler: documentActionPressed(_:))
  716. let voiceMessageAction = UIAlertAction(title: String.localized("voice_message"), style: .default, handler: voiceMessageButtonPressed(_:))
  717. let isLocationStreaming = dcContext.isSendingLocationsToChat(chatId: chatId)
  718. let locationStreamingAction = UIAlertAction(title: isLocationStreaming ? String.localized("stop_sharing_location") : String.localized("location"),
  719. style: isLocationStreaming ? .destructive : .default,
  720. handler: locationStreamingButtonPressed(_:))
  721. alert.addAction(cameraAction)
  722. alert.addAction(galleryAction)
  723. alert.addAction(documentAction)
  724. alert.addAction(voiceMessageAction)
  725. if UserDefaults.standard.bool(forKey: "location_streaming") {
  726. alert.addAction(locationStreamingAction)
  727. }
  728. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  729. self.present(alert, animated: true, completion: {
  730. // unfortunately, voiceMessageAction.accessibilityHint does not work,
  731. // but this hack does the trick
  732. if UIAccessibility.isVoiceOverRunning {
  733. if let view = voiceMessageAction.value(forKey: "__representer") as? UIView {
  734. view.accessibilityHint = String.localized("a11y_voice_message_hint_ios")
  735. }
  736. }
  737. })
  738. }
  739. private func confirmationAlert(title: String, actionTitle: String, actionStyle: UIAlertAction.Style = .default, actionHandler: @escaping ((UIAlertAction) -> Void), cancelHandler: ((UIAlertAction) -> Void)? = nil) {
  740. let alert = UIAlertController(title: title,
  741. message: nil,
  742. preferredStyle: .safeActionSheet)
  743. alert.addAction(UIAlertAction(title: actionTitle, style: actionStyle, handler: actionHandler))
  744. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: cancelHandler ?? { _ in
  745. self.dismiss(animated: true, completion: nil)
  746. }))
  747. present(alert, animated: true, completion: nil)
  748. }
  749. private func askToChatWith(email: String) {
  750. let contactId = self.dcContext.createContact(name: "", email: email)
  751. if dcContext.getChatIdByContactId(contactId: contactId) != 0 {
  752. self.dismiss(animated: true, completion: nil)
  753. let chatId = self.dcContext.createChatByContactId(contactId: contactId)
  754. self.showChat(chatId: chatId)
  755. } else {
  756. confirmationAlert(title: String.localizedStringWithFormat(String.localized("ask_start_chat_with"), email),
  757. actionTitle: String.localized("start_chat"),
  758. actionHandler: { _ in
  759. self.dismiss(animated: true, completion: nil)
  760. let chatId = self.dcContext.createChatByContactId(contactId: contactId)
  761. self.showChat(chatId: chatId)})
  762. }
  763. }
  764. private func askToDeleteMessage(id: Int) {
  765. let title = String.localized(stringID: "ask_delete_messages", count: 1)
  766. confirmationAlert(title: title, actionTitle: String.localized("delete"), actionStyle: .destructive,
  767. actionHandler: { _ in
  768. self.dcContext.deleteMessage(msgId: id)
  769. })
  770. }
  771. private func askToForwardMessage() {
  772. let chat = dcContext.getChat(chatId: self.chatId)
  773. if chat.isSelfTalk {
  774. RelayHelper.sharedInstance.forward(to: self.chatId)
  775. } else {
  776. confirmationAlert(title: String.localizedStringWithFormat(String.localized("ask_forward"), chat.name),
  777. actionTitle: String.localized("menu_forward"),
  778. actionHandler: { _ in
  779. RelayHelper.sharedInstance.forward(to: self.chatId)
  780. self.dismiss(animated: true, completion: nil)},
  781. cancelHandler: { _ in
  782. self.dismiss(animated: false, completion: nil)
  783. self.navigationController?.popViewController(animated: true)})
  784. }
  785. }
  786. // MARK: - coordinator
  787. private func showChatDetail(chatId: Int) {
  788. let chat = dcContext.getChat(chatId: chatId)
  789. switch chat.chatType {
  790. case .SINGLE:
  791. if let contactId = chat.contactIds.first {
  792. let contactDetailController = ContactDetailViewController(dcContext: dcContext, contactId: contactId)
  793. navigationController?.pushViewController(contactDetailController, animated: true)
  794. }
  795. case .GROUP, .VERIFIEDGROUP:
  796. let groupChatDetailViewController = GroupChatDetailViewController(chatId: chatId, dcContext: dcContext)
  797. navigationController?.pushViewController(groupChatDetailViewController, animated: true)
  798. }
  799. }
  800. func showChat(chatId: Int) {
  801. if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
  802. navigationController?.popToRootViewController(animated: false)
  803. appDelegate.appCoordinator.showChat(chatId: chatId)
  804. }
  805. }
  806. private func showDocumentLibrary() {
  807. mediaPicker?.showDocumentLibrary()
  808. }
  809. private func showVoiceMessageRecorder() {
  810. mediaPicker?.showVoiceRecorder()
  811. }
  812. private func showCameraViewController() {
  813. mediaPicker?.showCamera()
  814. }
  815. private func showPhotoVideoLibrary(delegate: MediaPickerDelegate) {
  816. mediaPicker?.showPhotoVideoLibrary()
  817. }
  818. private func showMediaGallery(currentIndex: Int, msgIds: [Int]) {
  819. let betterPreviewController = PreviewController(type: .multi(msgIds, currentIndex))
  820. let nav = UINavigationController(rootViewController: betterPreviewController)
  821. nav.modalPresentationStyle = .fullScreen
  822. navigationController?.present(nav, animated: true)
  823. }
  824. private func documentActionPressed(_ action: UIAlertAction) {
  825. showDocumentLibrary()
  826. }
  827. private func voiceMessageButtonPressed(_ action: UIAlertAction) {
  828. showVoiceMessageRecorder()
  829. }
  830. private func cameraButtonPressed(_ action: UIAlertAction) {
  831. showCameraViewController()
  832. }
  833. private func galleryButtonPressed(_ action: UIAlertAction) {
  834. showPhotoVideoLibrary(delegate: self)
  835. }
  836. private func locationStreamingButtonPressed(_ action: UIAlertAction) {
  837. let isLocationStreaming = dcContext.isSendingLocationsToChat(chatId: chatId)
  838. if isLocationStreaming {
  839. locationStreamingFor(seconds: 0)
  840. } else {
  841. let alert = UIAlertController(title: String.localized("title_share_location"), message: nil, preferredStyle: .safeActionSheet)
  842. addDurationSelectionAction(to: alert, key: "share_location_for_5_minutes", duration: Time.fiveMinutes)
  843. addDurationSelectionAction(to: alert, key: "share_location_for_30_minutes", duration: Time.thirtyMinutes)
  844. addDurationSelectionAction(to: alert, key: "share_location_for_one_hour", duration: Time.oneHour)
  845. addDurationSelectionAction(to: alert, key: "share_location_for_two_hours", duration: Time.twoHours)
  846. addDurationSelectionAction(to: alert, key: "share_location_for_six_hours", duration: Time.sixHours)
  847. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  848. self.present(alert, animated: true, completion: nil)
  849. }
  850. }
  851. private func addDurationSelectionAction(to alert: UIAlertController, key: String, duration: Int) {
  852. let action = UIAlertAction(title: String.localized(key), style: .default, handler: { _ in
  853. self.locationStreamingFor(seconds: duration)
  854. })
  855. alert.addAction(action)
  856. }
  857. private func locationStreamingFor(seconds: Int) {
  858. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
  859. return
  860. }
  861. self.dcContext.sendLocationsToChat(chatId: self.chatId, seconds: seconds)
  862. appDelegate.locationManager.shareLocation(chatId: self.chatId, duration: seconds)
  863. }
  864. func updateMessage(_ messageId: Int) {
  865. if messageIds.firstIndex(where: { $0 == messageId }) != nil {
  866. DispatchQueue.global(qos: .background).async { [weak self] in
  867. self?.dcContext.markSeenMessages(messageIds: [UInt32(messageId)])
  868. }
  869. let wasLastSectionVisible = self.isLastRowVisible()
  870. reloadData()
  871. if wasLastSectionVisible {
  872. self.scrollToBottom(animated: true)
  873. }
  874. } else {
  875. let msg = DcMsg(id: messageId)
  876. if msg.chatId == chatId {
  877. insertMessage(msg)
  878. }
  879. }
  880. }
  881. func insertMessage(_ message: DcMsg) {
  882. DispatchQueue.global(qos: .background).async { [weak self] in
  883. self?.dcContext.markSeenMessages(messageIds: [UInt32(message.id)])
  884. }
  885. let wasLastSectionVisible = isLastRowVisible()
  886. messageIds.append(message.id)
  887. emptyStateView.isHidden = true
  888. reloadData()
  889. if wasLastSectionVisible || message.isFromCurrentSender {
  890. scrollToBottom(animated: true)
  891. }
  892. }
  893. private func sendTextMessage(text: String, quoteMessage: DcMsg?) {
  894. DispatchQueue.global().async {
  895. let message = DcMsg(viewType: DC_MSG_TEXT)
  896. message.text = text
  897. if let quoteMessage = quoteMessage {
  898. message.quoteMessage = quoteMessage
  899. }
  900. message.sendInChat(id: self.chatId)
  901. }
  902. }
  903. private func stageDocument(url: NSURL) {
  904. self.draft.setAttachment(viewType: DC_MSG_FILE, path: url.relativePath)
  905. self.configureDraftArea(draft: self.draft)
  906. self.messageInputBar.inputTextView.becomeFirstResponder()
  907. }
  908. private func stageVideo(url: NSURL) {
  909. DispatchQueue.main.async {
  910. self.draft.setAttachment(viewType: DC_MSG_VIDEO, path: url.relativePath)
  911. self.configureDraftArea(draft: self.draft)
  912. self.messageInputBar.inputTextView.becomeFirstResponder()
  913. }
  914. }
  915. private func stageImage(url: NSURL) {
  916. if url.pathExtension == "gif" {
  917. stageAnimatedImage(url: url)
  918. } else if let data = try? Data(contentsOf: url as URL),
  919. let image = UIImage(data: data) {
  920. stageImage(image)
  921. }
  922. }
  923. private func stageAnimatedImage(url: NSURL) {
  924. DispatchQueue.global().async {
  925. if let path = url.path,
  926. let result = SDAnimatedImage(contentsOfFile: path),
  927. let animatedImageData = result.animatedImageData,
  928. let pathInDocDir = DcUtils.saveImage(data: animatedImageData, suffix: "gif") {
  929. DispatchQueue.main.async {
  930. self.draft.setAttachment(viewType: DC_MSG_GIF, path: pathInDocDir)
  931. self.configureDraftArea(draft: self.draft)
  932. self.messageInputBar.inputTextView.becomeFirstResponder()
  933. }
  934. }
  935. }
  936. }
  937. private func stageImage(_ image: UIImage) {
  938. DispatchQueue.global().async {
  939. if let pathInDocDir = DcUtils.saveImage(image: image) {
  940. DispatchQueue.main.async {
  941. self.draft.setAttachment(viewType: DC_MSG_IMAGE, path: pathInDocDir)
  942. self.configureDraftArea(draft: self.draft)
  943. self.messageInputBar.inputTextView.becomeFirstResponder()
  944. }
  945. }
  946. }
  947. }
  948. private func sendImage(_ image: UIImage, message: String? = nil) {
  949. DispatchQueue.global().async {
  950. if let path = DcUtils.saveImage(image: image) {
  951. self.sendAttachmentMessage(viewType: DC_MSG_IMAGE, filePath: path, message: message)
  952. }
  953. }
  954. }
  955. private func sendAttachmentMessage(viewType: Int32, filePath: String, message: String? = nil, quoteMessage: DcMsg? = nil) {
  956. let msg = DcMsg(viewType: viewType)
  957. msg.setFile(filepath: filePath)
  958. msg.text = (message ?? "").isEmpty ? nil : message
  959. if quoteMessage != nil {
  960. msg.quoteMessage = quoteMessage
  961. }
  962. msg.sendInChat(id: self.chatId)
  963. }
  964. private func sendVoiceMessage(url: NSURL) {
  965. DispatchQueue.global().async {
  966. let msg = DcMsg(viewType: DC_MSG_VOICE)
  967. msg.setFile(filepath: url.relativePath, mimeType: "audio/m4a")
  968. msg.sendInChat(id: self.chatId)
  969. }
  970. }
  971. // MARK: - Context menu
  972. private func prepareContextMenu() {
  973. UIMenuController.shared.menuItems = contextMenu.menuItems
  974. UIMenuController.shared.update()
  975. }
  976. override func tableView(_ tableView: UITableView, shouldShowMenuForRowAt indexPath: IndexPath) -> Bool {
  977. return !DcMsg(id: messageIds[indexPath.row]).isInfo
  978. }
  979. override func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
  980. return contextMenu.canPerformAction(action: action)
  981. }
  982. override func tableView(_ tableView: UITableView, performAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) {
  983. // handle standard actions here, but custom actions never trigger this. it still needs to be present for the menu to display, though.
  984. contextMenu.performAction(action: action, indexPath: indexPath)
  985. }
  986. // context menu for iOS 13+
  987. @available(iOS 13, *)
  988. override func tableView(_ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
  989. return UIContextMenuConfiguration(
  990. identifier: nil,
  991. previewProvider: nil,
  992. actionProvider: { [weak self] _ in
  993. self?.contextMenu.actionProvider(indexPath: indexPath)
  994. }
  995. )
  996. }
  997. func showMediaGalleryFor(indexPath: IndexPath) {
  998. let messageId = messageIds[indexPath.row]
  999. let message = DcMsg(id: messageId)
  1000. showMediaGalleryFor(message: message)
  1001. }
  1002. func showMediaGalleryFor(message: DcMsg) {
  1003. let msgIds = dcContext.getChatMedia(chatId: chatId, messageType: Int32(message.type), messageType2: 0, messageType3: 0)
  1004. let index = msgIds.firstIndex(of: message.id) ?? 0
  1005. showMediaGallery(currentIndex: index, msgIds: msgIds)
  1006. }
  1007. private func didTapAsm(msg: DcMsg, orgText: String) {
  1008. let inputDlg = UIAlertController(
  1009. title: String.localized("autocrypt_continue_transfer_title"),
  1010. message: String.localized("autocrypt_continue_transfer_please_enter_code"),
  1011. preferredStyle: .alert)
  1012. inputDlg.addTextField(configurationHandler: { (textField) in
  1013. textField.placeholder = msg.setupCodeBegin + ".."
  1014. textField.text = orgText
  1015. textField.keyboardType = UIKeyboardType.numbersAndPunctuation // allows entering spaces; decimalPad would require a mask to keep things readable
  1016. })
  1017. inputDlg.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  1018. let okAction = UIAlertAction(title: String.localized("ok"), style: .default, handler: { _ in
  1019. let textField = inputDlg.textFields![0]
  1020. let modText = textField.text ?? ""
  1021. let success = self.dcContext.continueKeyTransfer(msgId: msg.id, setupCode: modText)
  1022. let alert = UIAlertController(
  1023. title: String.localized("autocrypt_continue_transfer_title"),
  1024. message: String.localized(success ? "autocrypt_continue_transfer_succeeded" : "autocrypt_bad_setup_code"),
  1025. preferredStyle: .alert)
  1026. if success {
  1027. alert.addAction(UIAlertAction(title: String.localized("ok"), style: .default, handler: nil))
  1028. } else {
  1029. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  1030. let retryAction = UIAlertAction(title: String.localized("autocrypt_continue_transfer_retry"), style: .default, handler: { _ in
  1031. self.didTapAsm(msg: msg, orgText: modText)
  1032. })
  1033. alert.addAction(retryAction)
  1034. alert.preferredAction = retryAction
  1035. }
  1036. self.navigationController?.present(alert, animated: true, completion: nil)
  1037. })
  1038. inputDlg.addAction(okAction)
  1039. inputDlg.preferredAction = okAction // without setting preferredAction, cancel become shown *bold* as the preferred action
  1040. navigationController?.present(inputDlg, animated: true, completion: nil)
  1041. }
  1042. func handleUIMenu() -> Bool {
  1043. if UIMenuController.shared.isMenuVisible {
  1044. UIMenuController.shared.setMenuVisible(false, animated: true)
  1045. return true
  1046. }
  1047. return false
  1048. }
  1049. func handleSelection(indexPath: IndexPath) -> Bool {
  1050. if tableView.isEditing {
  1051. if tableView.indexPathsForSelectedRows?.contains(indexPath) ?? false {
  1052. tableView.deselectRow(at: indexPath, animated: false)
  1053. } else {
  1054. tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
  1055. }
  1056. return true
  1057. }
  1058. return false
  1059. }
  1060. }
  1061. // MARK: - BaseMessageCellDelegate
  1062. extension ChatViewController: BaseMessageCellDelegate {
  1063. @objc func quoteTapped(indexPath: IndexPath) {
  1064. if handleSelection(indexPath: indexPath) { return }
  1065. _ = handleUIMenu()
  1066. let msg = DcMsg(id: messageIds[indexPath.row])
  1067. if let quoteMsg = msg.quoteMessage {
  1068. scrollToMessage(msgId: quoteMsg.id)
  1069. }
  1070. }
  1071. @objc func textTapped(indexPath: IndexPath) {
  1072. if handleUIMenu() || handleSelection(indexPath: indexPath) {
  1073. return
  1074. }
  1075. let message = DcMsg(id: messageIds[indexPath.row])
  1076. if message.isSetupMessage {
  1077. didTapAsm(msg: message, orgText: "")
  1078. }
  1079. }
  1080. @objc func phoneNumberTapped(number: String, indexPath: IndexPath) {
  1081. if handleUIMenu() || handleSelection(indexPath: indexPath) {
  1082. return
  1083. }
  1084. logger.debug("phone number tapped \(number)")
  1085. }
  1086. @objc func commandTapped(command: String, indexPath: IndexPath) {
  1087. if handleUIMenu() || handleSelection(indexPath: indexPath) {
  1088. return
  1089. }
  1090. logger.debug("command tapped \(command)")
  1091. }
  1092. @objc func urlTapped(url: URL, indexPath: IndexPath) {
  1093. if handleUIMenu() || handleSelection(indexPath: indexPath) {
  1094. return
  1095. }
  1096. if Utils.isEmail(url: url) {
  1097. logger.debug("tapped on contact")
  1098. let email = Utils.getEmailFrom(url)
  1099. self.askToChatWith(email: email)
  1100. } else {
  1101. UIApplication.shared.open(url)
  1102. }
  1103. }
  1104. @objc func imageTapped(indexPath: IndexPath) {
  1105. if handleUIMenu() || handleSelection(indexPath: indexPath) {
  1106. return
  1107. }
  1108. showMediaGalleryFor(indexPath: indexPath)
  1109. }
  1110. @objc func avatarTapped(indexPath: IndexPath) {
  1111. let message = DcMsg(id: messageIds[indexPath.row])
  1112. let contactDetailController = ContactDetailViewController(dcContext: dcContext, contactId: message.fromContactId)
  1113. navigationController?.pushViewController(contactDetailController, animated: true)
  1114. }
  1115. }
  1116. // MARK: - MediaPickerDelegate
  1117. extension ChatViewController: MediaPickerDelegate {
  1118. func onVideoSelected(url: NSURL) {
  1119. stageVideo(url: url)
  1120. }
  1121. func onImageSelected(url: NSURL) {
  1122. stageImage(url: url)
  1123. }
  1124. func onImageSelected(image: UIImage) {
  1125. stageImage(image)
  1126. }
  1127. func onVoiceMessageRecorded(url: NSURL) {
  1128. sendVoiceMessage(url: url)
  1129. }
  1130. func onDocumentSelected(url: NSURL) {
  1131. stageDocument(url: url)
  1132. }
  1133. }
  1134. // MARK: - MessageInputBarDelegate
  1135. extension ChatViewController: InputBarAccessoryViewDelegate {
  1136. func inputBar(_ inputBar: InputBarAccessoryView, didPressSendButtonWith text: String) {
  1137. let trimmedText = text.replacingOccurrences(of: "\u{FFFC}", with: "", options: .literal, range: nil)
  1138. .trimmingCharacters(in: .whitespacesAndNewlines)
  1139. if let filePath = draft.attachment, let viewType = draft.viewType {
  1140. switch viewType {
  1141. case DC_MSG_GIF, DC_MSG_IMAGE, DC_MSG_FILE, DC_MSG_VIDEO:
  1142. self.sendAttachmentMessage(viewType: viewType, filePath: filePath, message: trimmedText, quoteMessage: draft.quoteMessage)
  1143. default:
  1144. logger.warning("Unsupported viewType for drafted messages.")
  1145. }
  1146. } else if inputBar.inputTextView.images.isEmpty {
  1147. self.sendTextMessage(text: trimmedText, quoteMessage: draft.quoteMessage)
  1148. } else {
  1149. // only 1 attachment allowed for now, thus it takes the first one
  1150. self.sendImage(inputBar.inputTextView.images[0], message: trimmedText)
  1151. }
  1152. inputBar.inputTextView.text = String()
  1153. inputBar.inputTextView.attributedText = nil
  1154. draftArea.cancel()
  1155. }
  1156. func inputBar(_ inputBar: InputBarAccessoryView, textViewTextDidChangeTo text: String) {
  1157. draft.text = text
  1158. evaluateInputBar(draft: draft)
  1159. }
  1160. }
  1161. // MARK: - DraftPreviewDelegate
  1162. extension ChatViewController: DraftPreviewDelegate {
  1163. func onCancelQuote() {
  1164. draft.setQuote(quotedMsg: nil)
  1165. configureDraftArea(draft: draft)
  1166. }
  1167. func onCancelAttachment() {
  1168. draft.setAttachment(viewType: nil, path: nil, mimetype: nil)
  1169. configureDraftArea(draft: draft)
  1170. evaluateInputBar(draft: draft)
  1171. }
  1172. func onAttachmentAdded() {
  1173. evaluateInputBar(draft: draft)
  1174. }
  1175. func onAttachmentTapped() {
  1176. if let attachmentPath = draft.attachment {
  1177. let attachmentURL = URL(fileURLWithPath: attachmentPath, isDirectory: false)
  1178. let previewController = PreviewController(type: .single(attachmentURL))
  1179. if #available(iOS 13.0, *), draft.viewType == DC_MSG_IMAGE || draft.viewType == DC_MSG_VIDEO {
  1180. previewController.setEditing(true, animated: true)
  1181. previewController.delegate = self
  1182. }
  1183. let nav = UINavigationController(rootViewController: previewController)
  1184. nav.modalPresentationStyle = .fullScreen
  1185. navigationController?.present(nav, animated: true)
  1186. }
  1187. }
  1188. }
  1189. extension ChatViewController: QLPreviewControllerDelegate {
  1190. @available(iOS 13.0, *)
  1191. func previewController(_ controller: QLPreviewController, editingModeFor previewItem: QLPreviewItem) -> QLPreviewItemEditingMode {
  1192. return .updateContents
  1193. }
  1194. func previewController(_ controller: QLPreviewController, didUpdateContentsOf previewItem: QLPreviewItem) {
  1195. DispatchQueue.main.async { [weak self] in
  1196. guard let self = self else { return }
  1197. self.draftArea.reload(draft: self.draft)
  1198. }
  1199. }
  1200. }