ChatViewController.swift 60 KB

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