ChatViewController.swift 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452
  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. }
  344. override func viewWillDisappear(_ animated: Bool) {
  345. super.viewWillDisappear(animated)
  346. // the navigationController will be used when chatDetail is pushed, so we have to remove that gestureRecognizer
  347. navigationController?.navigationBar.removeGestureRecognizer(navBarTap)
  348. dismissCancelled = true
  349. }
  350. override func viewDidDisappear(_ animated: Bool) {
  351. super.viewDidDisappear(animated)
  352. dismissCancelled = false
  353. AppStateRestorer.shared.resetLastActiveChat()
  354. saveDraft()
  355. let nc = NotificationCenter.default
  356. if let msgChangedObserver = self.msgChangedObserver {
  357. nc.removeObserver(msgChangedObserver)
  358. }
  359. if let incomingMsgObserver = self.incomingMsgObserver {
  360. nc.removeObserver(incomingMsgObserver)
  361. }
  362. if let ephemeralTimerModifiedObserver = self.ephemeralTimerModifiedObserver {
  363. nc.removeObserver(ephemeralTimerModifiedObserver)
  364. }
  365. audioController.stopAnyOngoingPlaying()
  366. stopTimer()
  367. }
  368. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  369. let lastSectionVisibleBeforeTransition = self.isLastRowVisible()
  370. coordinator.animate(
  371. alongsideTransition: { [weak self] _ in
  372. guard let self = self else { return }
  373. if self.showCustomNavBar {
  374. self.navigationItem.setRightBarButton(self.badgeItem, animated: true)
  375. }
  376. if lastSectionVisibleBeforeTransition {
  377. self.scrollToBottom(animated: false)
  378. }
  379. },
  380. completion: {[weak self] _ in
  381. guard let self = self else { return }
  382. self.updateTitle(chat: self.dcContext.getChat(chatId: self.chatId))
  383. if lastSectionVisibleBeforeTransition {
  384. DispatchQueue.main.async { [weak self] in
  385. self?.reloadData()
  386. self?.scrollToBottom(animated: false)
  387. }
  388. }
  389. }
  390. )
  391. super.viewWillTransition(to: size, with: coordinator)
  392. }
  393. /// UITableView methods
  394. override func numberOfSections(in tableView: UITableView) -> Int {
  395. return 1
  396. }
  397. override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
  398. return messageIds.count
  399. }
  400. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  401. _ = handleUIMenu()
  402. let id = messageIds[indexPath.row]
  403. let message = DcMsg(id: id)
  404. if message.isInfo {
  405. let cell = tableView.dequeueReusableCell(withIdentifier: "info", for: indexPath) as? InfoMessageCell ?? InfoMessageCell()
  406. cell.update(msg: message)
  407. return cell
  408. }
  409. let cell: BaseMessageCell
  410. if message.type == DC_MSG_IMAGE || message.type == DC_MSG_GIF || message.type == DC_MSG_VIDEO {
  411. cell = tableView.dequeueReusableCell(withIdentifier: "image", for: indexPath) as? ImageTextCell ?? ImageTextCell()
  412. } else if message.type == DC_MSG_FILE {
  413. if message.isSetupMessage {
  414. cell = tableView.dequeueReusableCell(withIdentifier: "text", for: indexPath) as? TextMessageCell ?? TextMessageCell()
  415. message.text = String.localized("autocrypt_asm_click_body")
  416. } else {
  417. cell = tableView.dequeueReusableCell(withIdentifier: "file", for: indexPath) as? FileTextCell ?? FileTextCell()
  418. }
  419. } else if message.type == DC_MSG_AUDIO || message.type == DC_MSG_VOICE {
  420. let audioMessageCell: AudioMessageCell = tableView.dequeueReusableCell(withIdentifier: "audio",
  421. for: indexPath) as? AudioMessageCell ?? AudioMessageCell()
  422. audioController.update(audioMessageCell, with: message.id)
  423. cell = audioMessageCell
  424. } else {
  425. cell = tableView.dequeueReusableCell(withIdentifier: "text", for: indexPath) as? TextMessageCell ?? TextMessageCell()
  426. }
  427. cell.baseDelegate = self
  428. cell.update(msg: message,
  429. messageStyle: configureMessageStyle(for: message, at: indexPath),
  430. isAvatarVisible: configureAvatarVisibility(for: message, at: indexPath),
  431. isGroup: isGroupChat)
  432. return cell
  433. }
  434. public override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  435. if !decelerate {
  436. markSeenMessagesInVisibleArea()
  437. }
  438. }
  439. public override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  440. markSeenMessagesInVisibleArea()
  441. }
  442. private func configureDraftArea(draft: DraftModel) {
  443. draftArea.configure(draft: draft)
  444. if draft.isEditing {
  445. messageInputBar.setMiddleContentView(editingBar, animated: false)
  446. messageInputBar.setLeftStackViewWidthConstant(to: 0, animated: false)
  447. messageInputBar.setRightStackViewWidthConstant(to: 0, animated: false)
  448. messageInputBar.padding = UIEdgeInsets(top: 6, left: 0, bottom: 6, right: 0)
  449. } else {
  450. messageInputBar.setMiddleContentView(messageInputBar.inputTextView, animated: false)
  451. messageInputBar.setLeftStackViewWidthConstant(to: 40, animated: false)
  452. messageInputBar.setRightStackViewWidthConstant(to: 40, animated: false)
  453. messageInputBar.padding = UIEdgeInsets(top: 6, left: 6, bottom: 6, right: 12)
  454. }
  455. messageInputBar.setStackViewItems([draftArea], forStack: .top, animated: true)
  456. }
  457. override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
  458. let swipeAction = UISwipeActionsConfiguration(actions: [])
  459. return swipeAction
  460. }
  461. override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
  462. if disableWriting {
  463. return nil
  464. }
  465. let action = UIContextualAction(style: .normal, title: nil,
  466. handler: { [weak self] (_, _, completionHandler) in
  467. self?.replyToMessage(at: indexPath)
  468. completionHandler(true)
  469. })
  470. if #available(iOS 13.0, *) {
  471. action.image = UIImage(named: traitCollection.userInterfaceStyle == .light ? "ic_reply_black" : "ic_reply")
  472. action.backgroundColor = DcColors.chatBackgroundColor
  473. } else {
  474. action.image = UIImage(named: "ic_reply_black")
  475. action.backgroundColor = .systemBlue
  476. }
  477. action.image?.accessibilityTraits = .button
  478. action.image?.accessibilityLabel = String.localized("menu_reply")
  479. let configuration = UISwipeActionsConfiguration(actions: [action])
  480. return configuration
  481. }
  482. func replyToMessage(at indexPath: IndexPath) {
  483. let message = DcMsg(id: self.messageIds[indexPath.row])
  484. self.draft.setQuote(quotedMsg: message)
  485. self.configureDraftArea(draft: self.draft)
  486. self.messageInputBar.inputTextView.becomeFirstResponder()
  487. }
  488. func markSeenMessagesInVisibleArea() {
  489. if let indexPaths = tableView.indexPathsForVisibleRows {
  490. let visibleMessagesIds = indexPaths.map { UInt32(messageIds[$0.row]) }
  491. if !visibleMessagesIds.isEmpty {
  492. DispatchQueue.global(qos: .background).async { [weak self] in
  493. self?.dcContext.markSeenMessages(messageIds: visibleMessagesIds)
  494. }
  495. }
  496. }
  497. }
  498. override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
  499. if tableView.isEditing {
  500. handleEditingBar()
  501. }
  502. }
  503. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  504. if tableView.isEditing {
  505. handleEditingBar()
  506. return
  507. }
  508. let messageId = messageIds[indexPath.row]
  509. let message = DcMsg(id: messageId)
  510. if message.isSetupMessage {
  511. didTapAsm(msg: message, orgText: "")
  512. } else if message.type == DC_MSG_FILE ||
  513. message.type == DC_MSG_AUDIO ||
  514. message.type == DC_MSG_VOICE {
  515. showMediaGalleryFor(message: message)
  516. }
  517. _ = handleUIMenu()
  518. }
  519. func configureAvatarVisibility(for message: DcMsg, at indexPath: IndexPath) -> Bool {
  520. return isGroupChat && !message.isFromCurrentSender
  521. }
  522. func configureMessageStyle(for message: DcMsg, at indexPath: IndexPath) -> UIRectCorner {
  523. var corners: UIRectCorner = []
  524. if message.isFromCurrentSender {
  525. corners.formUnion(.topLeft)
  526. corners.formUnion(.bottomLeft)
  527. corners.formUnion(.topRight)
  528. } else {
  529. corners.formUnion(.topRight)
  530. corners.formUnion(.bottomRight)
  531. corners.formUnion(.topLeft)
  532. }
  533. return corners
  534. }
  535. private func getBackgroundColor(for currentMessage: DcMsg) -> UIColor {
  536. return currentMessage.isFromCurrentSender ? DcColors.messagePrimaryColor : DcColors.messageSecondaryColor
  537. }
  538. private func updateTitle(chat: DcChat) {
  539. let titleView = ChatTitleView()
  540. var subtitle = "ErrSubtitle"
  541. let chatContactIds = chat.contactIds
  542. if chat.isGroup {
  543. subtitle = String.localized(stringID: "n_members", count: chatContactIds.count)
  544. } else if chatContactIds.count >= 1 {
  545. if chat.isDeviceTalk {
  546. subtitle = String.localized("device_talk_subtitle")
  547. } else if chat.isSelfTalk {
  548. subtitle = String.localized("chat_self_talk_subtitle")
  549. } else {
  550. subtitle = DcContact(id: chatContactIds[0]).email
  551. }
  552. }
  553. titleView.updateTitleView(title: chat.name, subtitle: subtitle)
  554. navigationItem.titleView = titleView
  555. var rightBarButtonItems = [badgeItem]
  556. if chat.isSendingLocations {
  557. rightBarButtonItems.append(locationStreamingItem)
  558. }
  559. if chat.isMuted {
  560. rightBarButtonItems.append(muteItem)
  561. }
  562. if dcContext.getChatEphemeralTimer(chatId: chat.id) > 0 {
  563. rightBarButtonItems.append(ephemeralMessageItem)
  564. }
  565. navigationItem.rightBarButtonItems = rightBarButtonItems
  566. }
  567. @objc
  568. private func refreshMessages() {
  569. self.messageIds = self.getMessageIds()
  570. let wasLastSectionVisible = self.isLastRowVisible()
  571. self.reloadData()
  572. if wasLastSectionVisible {
  573. self.scrollToBottom(animated: true)
  574. }
  575. self.showEmptyStateView(self.messageIds.isEmpty)
  576. }
  577. func reloadData() {
  578. let selectredRows = tableView.indexPathsForSelectedRows
  579. tableView.reloadData()
  580. // There's an iOS bug, filling up the console output but which can be ignored: https://developer.apple.com/forums/thread/668295
  581. // [Assert] Attempted to call -cellForRowAtIndexPath: on the table view while it was in the process of updating its visible cells, which is not allowed.
  582. selectredRows?.forEach({ (selectedRow) in
  583. tableView.selectRow(at: selectedRow, animated: false, scrollPosition: .none)
  584. })
  585. }
  586. private func loadMessages() {
  587. DispatchQueue.global(qos: .userInitiated).async {
  588. DispatchQueue.main.async { [weak self] in
  589. guard let self = self else { return }
  590. let wasLastRowVisible = self.isLastRowVisible()
  591. let wasMessageIdsEmpty = self.messageIds.isEmpty
  592. // update message ids
  593. self.messageIds = self.getMessageIds()
  594. self.reloadData()
  595. if let msgId = self.highlightedMsg, let msgPosition = self.messageIds.firstIndex(of: msgId) {
  596. self.tableView.scrollToRow(at: IndexPath(row: msgPosition, section: 0), at: .top, animated: false)
  597. self.highlightedMsg = nil
  598. } else if wasMessageIdsEmpty ||
  599. wasLastRowVisible {
  600. self.scrollToBottom(animated: false)
  601. }
  602. self.showEmptyStateView(self.messageIds.isEmpty)
  603. }
  604. }
  605. }
  606. func isLastRowVisible() -> Bool {
  607. guard !messageIds.isEmpty else { return false }
  608. let lastIndexPath = IndexPath(item: messageIds.count - 1, section: 0)
  609. return tableView.indexPathsForVisibleRows?.contains(lastIndexPath) ?? false
  610. }
  611. func scrollToBottom(animated: Bool) {
  612. if !messageIds.isEmpty {
  613. self.tableView.scrollToRow(at: IndexPath(row: self.messageIds.count - 1, section: 0), at: .bottom, animated: animated)
  614. }
  615. }
  616. func scrollToMessage(msgId: Int, animated: Bool = true) {
  617. guard let index = messageIds.firstIndex(of: msgId) else {
  618. return
  619. }
  620. let indexPath = IndexPath(row: index, section: 0)
  621. tableView.scrollToRow(at: indexPath, at: .top, animated: animated)
  622. }
  623. private func showEmptyStateView(_ show: Bool) {
  624. if show {
  625. let dcChat = dcContext.getChat(chatId: chatId)
  626. if chatId == DC_CHAT_ID_DEADDROP {
  627. if dcContext.showEmails != DC_SHOW_EMAILS_ALL {
  628. emptyStateView.text = String.localized("chat_no_contact_requests")
  629. } else {
  630. emptyStateView.text = String.localized("chat_no_messages")
  631. }
  632. } else if dcChat.isGroup {
  633. if dcChat.isUnpromoted {
  634. emptyStateView.text = String.localized("chat_new_group_hint")
  635. } else {
  636. emptyStateView.text = String.localized("chat_no_messages")
  637. }
  638. } else if dcChat.isSelfTalk {
  639. emptyStateView.text = String.localized("saved_messages_explain")
  640. } else if dcChat.isDeviceTalk {
  641. emptyStateView.text = String.localized("device_talk_explain")
  642. } else {
  643. emptyStateView.text = String.localizedStringWithFormat(String.localized("chat_no_messages_hint"), dcChat.name, dcChat.name)
  644. }
  645. emptyStateView.isHidden = false
  646. } else {
  647. emptyStateView.isHidden = true
  648. }
  649. }
  650. private func getMessageIds() -> [Int] {
  651. return dcContext.getMessageIds(chatId: chatId)
  652. }
  653. @objc private func saveDraft() {
  654. draft.save(context: dcContext)
  655. }
  656. private func configureMessageInputBar() {
  657. messageInputBar.delegate = self
  658. messageInputBar.inputTextView.tintColor = DcColors.primary
  659. messageInputBar.inputTextView.placeholder = String.localized("chat_input_placeholder")
  660. messageInputBar.separatorLine.backgroundColor = DcColors.colorDisabled
  661. messageInputBar.inputTextView.tintColor = DcColors.primary
  662. messageInputBar.inputTextView.textColor = DcColors.defaultTextColor
  663. messageInputBar.backgroundView.backgroundColor = DcColors.chatBackgroundColor
  664. messageInputBar.inputTextView.backgroundColor = DcColors.inputFieldColor
  665. messageInputBar.inputTextView.placeholderTextColor = DcColors.placeholderColor
  666. messageInputBar.inputTextView.textContainerInset = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 38)
  667. messageInputBar.inputTextView.placeholderLabelInsets = UIEdgeInsets(top: 8, left: 20, bottom: 8, right: 38)
  668. messageInputBar.inputTextView.layer.borderColor = UIColor.themeColor(light: UIColor(red: 200 / 255, green: 200 / 255, blue: 200 / 255, alpha: 1),
  669. dark: UIColor(red: 55 / 255, green: 55/255, blue: 55/255, alpha: 1)).cgColor
  670. messageInputBar.inputTextView.layer.borderWidth = 1.0
  671. messageInputBar.inputTextView.layer.cornerRadius = 13.0
  672. messageInputBar.inputTextView.layer.masksToBounds = true
  673. messageInputBar.inputTextView.scrollIndicatorInsets = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0)
  674. configureInputBarItems()
  675. }
  676. func evaluateInputBar(draft: DraftModel) {
  677. messageInputBar.sendButton.isEnabled = draft.canSend()
  678. }
  679. private func configureInputBarItems() {
  680. messageInputBar.setLeftStackViewWidthConstant(to: 40, animated: false)
  681. messageInputBar.setRightStackViewWidthConstant(to: 40, animated: false)
  682. let sendButtonImage = UIImage(named: "paper_plane")?.withRenderingMode(.alwaysTemplate)
  683. messageInputBar.sendButton.image = sendButtonImage
  684. messageInputBar.sendButton.accessibilityLabel = String.localized("menu_send")
  685. messageInputBar.sendButton.accessibilityTraits = .button
  686. messageInputBar.sendButton.title = nil
  687. messageInputBar.sendButton.tintColor = UIColor(white: 1, alpha: 1)
  688. messageInputBar.sendButton.layer.cornerRadius = 20
  689. messageInputBar.middleContentViewPadding = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 10)
  690. // this adds a padding between textinputfield and send button
  691. messageInputBar.sendButton.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
  692. messageInputBar.sendButton.setSize(CGSize(width: 40, height: 40), animated: false)
  693. messageInputBar.padding = UIEdgeInsets(top: 6, left: 6, bottom: 6, right: 12)
  694. messageInputBar.shouldManageSendButtonEnabledState = false
  695. let leftItems = [
  696. InputBarButtonItem()
  697. .configure {
  698. $0.spacing = .fixed(0)
  699. let clipperIcon = #imageLiteral(resourceName: "ic_attach_file_36pt").withRenderingMode(.alwaysTemplate)
  700. $0.image = clipperIcon
  701. $0.tintColor = DcColors.primary
  702. $0.setSize(CGSize(width: 40, height: 40), animated: false)
  703. $0.accessibilityLabel = String.localized("menu_add_attachment")
  704. $0.accessibilityTraits = .button
  705. }.onSelected {
  706. $0.tintColor = UIColor.themeColor(light: .lightGray, dark: .darkGray)
  707. }.onDeselected {
  708. $0.tintColor = DcColors.primary
  709. }.onTouchUpInside { [weak self] _ in
  710. self?.clipperButtonPressed()
  711. }
  712. ]
  713. messageInputBar.setStackViewItems(leftItems, forStack: .left, animated: false)
  714. // This just adds some more flare
  715. messageInputBar.sendButton
  716. .onEnabled { item in
  717. UIView.animate(withDuration: 0.3, animations: {
  718. item.backgroundColor = DcColors.primary
  719. })
  720. }.onDisabled { item in
  721. UIView.animate(withDuration: 0.3, animations: {
  722. item.backgroundColor = DcColors.colorDisabled
  723. })
  724. }
  725. }
  726. @objc private func chatProfilePressed() {
  727. if chatId != DC_CHAT_ID_DEADDROP {
  728. showChatDetail(chatId: chatId)
  729. }
  730. }
  731. @objc private func clipperButtonPressed() {
  732. showClipperOptions()
  733. }
  734. private func showClipperOptions() {
  735. let alert = UIAlertController(title: nil, message: nil, preferredStyle: .safeActionSheet)
  736. let galleryAction = PhotoPickerAlertAction(title: String.localized("gallery"), style: .default, handler: galleryButtonPressed(_:))
  737. let cameraAction = PhotoPickerAlertAction(title: String.localized("camera"), style: .default, handler: cameraButtonPressed(_:))
  738. let documentAction = UIAlertAction(title: String.localized("files"), style: .default, handler: documentActionPressed(_:))
  739. let voiceMessageAction = UIAlertAction(title: String.localized("voice_message"), style: .default, handler: voiceMessageButtonPressed(_:))
  740. let isLocationStreaming = dcContext.isSendingLocationsToChat(chatId: chatId)
  741. let locationStreamingAction = UIAlertAction(title: isLocationStreaming ? String.localized("stop_sharing_location") : String.localized("location"),
  742. style: isLocationStreaming ? .destructive : .default,
  743. handler: locationStreamingButtonPressed(_:))
  744. alert.addAction(cameraAction)
  745. alert.addAction(galleryAction)
  746. alert.addAction(documentAction)
  747. alert.addAction(voiceMessageAction)
  748. if UserDefaults.standard.bool(forKey: "location_streaming") {
  749. alert.addAction(locationStreamingAction)
  750. }
  751. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  752. self.present(alert, animated: true, completion: {
  753. // unfortunately, voiceMessageAction.accessibilityHint does not work,
  754. // but this hack does the trick
  755. if UIAccessibility.isVoiceOverRunning {
  756. if let view = voiceMessageAction.value(forKey: "__representer") as? UIView {
  757. view.accessibilityHint = String.localized("a11y_voice_message_hint_ios")
  758. }
  759. }
  760. })
  761. }
  762. private func confirmationAlert(title: String, actionTitle: String, actionStyle: UIAlertAction.Style = .default, actionHandler: @escaping ((UIAlertAction) -> Void), cancelHandler: ((UIAlertAction) -> Void)? = nil) {
  763. let alert = UIAlertController(title: title,
  764. message: nil,
  765. preferredStyle: .safeActionSheet)
  766. alert.addAction(UIAlertAction(title: actionTitle, style: actionStyle, handler: actionHandler))
  767. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: cancelHandler ?? { _ in
  768. self.dismiss(animated: true, completion: nil)
  769. }))
  770. present(alert, animated: true, completion: nil)
  771. }
  772. private func askToChatWith(email: String) {
  773. let contactId = self.dcContext.createContact(name: "", email: email)
  774. if dcContext.getChatIdByContactId(contactId: contactId) != 0 {
  775. self.dismiss(animated: true, completion: nil)
  776. let chatId = self.dcContext.createChatByContactId(contactId: contactId)
  777. self.showChat(chatId: chatId)
  778. } else {
  779. confirmationAlert(title: String.localizedStringWithFormat(String.localized("ask_start_chat_with"), email),
  780. actionTitle: String.localized("start_chat"),
  781. actionHandler: { _ in
  782. self.dismiss(animated: true, completion: nil)
  783. let chatId = self.dcContext.createChatByContactId(contactId: contactId)
  784. self.showChat(chatId: chatId)})
  785. }
  786. }
  787. private func askToDeleteMessage(id: Int) {
  788. self.askToDeleteMessages(ids: [id])
  789. }
  790. private func askToDeleteMessages(ids: [Int]) {
  791. let title = String.localized(stringID: "ask_delete_messages", count: ids.count)
  792. confirmationAlert(title: title, actionTitle: String.localized("delete"), actionStyle: .destructive,
  793. actionHandler: { _ in
  794. self.dcContext.deleteMessages(msgIds: ids)
  795. if self.tableView.isEditing {
  796. self.setEditing(isEditing: false)
  797. }
  798. })
  799. }
  800. private func askToForwardMessage() {
  801. let chat = dcContext.getChat(chatId: self.chatId)
  802. if chat.isSelfTalk {
  803. RelayHelper.sharedInstance.forward(to: self.chatId)
  804. } else {
  805. confirmationAlert(title: String.localizedStringWithFormat(String.localized("ask_forward"), chat.name),
  806. actionTitle: String.localized("menu_forward"),
  807. actionHandler: { _ in
  808. RelayHelper.sharedInstance.forward(to: self.chatId)
  809. self.dismiss(animated: true, completion: nil)},
  810. cancelHandler: { _ in
  811. self.dismiss(animated: false, completion: nil)
  812. self.navigationController?.popViewController(animated: true)})
  813. }
  814. }
  815. // MARK: - coordinator
  816. private func showChatDetail(chatId: Int) {
  817. let chat = dcContext.getChat(chatId: chatId)
  818. if !chat.isGroup {
  819. if let contactId = chat.contactIds.first {
  820. let contactDetailController = ContactDetailViewController(dcContext: dcContext, contactId: contactId)
  821. navigationController?.pushViewController(contactDetailController, animated: true)
  822. }
  823. } else {
  824. let groupChatDetailViewController = GroupChatDetailViewController(chatId: chatId, dcContext: dcContext)
  825. navigationController?.pushViewController(groupChatDetailViewController, animated: true)
  826. }
  827. }
  828. func showChat(chatId: Int) {
  829. if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
  830. navigationController?.popToRootViewController(animated: false)
  831. appDelegate.appCoordinator.showChat(chatId: chatId)
  832. }
  833. }
  834. private func showDocumentLibrary() {
  835. mediaPicker?.showDocumentLibrary()
  836. }
  837. private func showVoiceMessageRecorder() {
  838. mediaPicker?.showVoiceRecorder()
  839. }
  840. private func showCameraViewController() {
  841. mediaPicker?.showCamera()
  842. }
  843. private func showPhotoVideoLibrary(delegate: MediaPickerDelegate) {
  844. mediaPicker?.showPhotoVideoLibrary()
  845. }
  846. private func showMediaGallery(currentIndex: Int, msgIds: [Int]) {
  847. let betterPreviewController = PreviewController(type: .multi(msgIds, currentIndex))
  848. let nav = UINavigationController(rootViewController: betterPreviewController)
  849. nav.modalPresentationStyle = .fullScreen
  850. navigationController?.present(nav, animated: true)
  851. }
  852. private func documentActionPressed(_ action: UIAlertAction) {
  853. showDocumentLibrary()
  854. }
  855. private func voiceMessageButtonPressed(_ action: UIAlertAction) {
  856. showVoiceMessageRecorder()
  857. }
  858. private func cameraButtonPressed(_ action: UIAlertAction) {
  859. showCameraViewController()
  860. }
  861. private func galleryButtonPressed(_ action: UIAlertAction) {
  862. showPhotoVideoLibrary(delegate: self)
  863. }
  864. private func locationStreamingButtonPressed(_ action: UIAlertAction) {
  865. let isLocationStreaming = dcContext.isSendingLocationsToChat(chatId: chatId)
  866. if isLocationStreaming {
  867. locationStreamingFor(seconds: 0)
  868. } else {
  869. let alert = UIAlertController(title: String.localized("title_share_location"), message: nil, preferredStyle: .safeActionSheet)
  870. addDurationSelectionAction(to: alert, key: "share_location_for_5_minutes", duration: Time.fiveMinutes)
  871. addDurationSelectionAction(to: alert, key: "share_location_for_30_minutes", duration: Time.thirtyMinutes)
  872. addDurationSelectionAction(to: alert, key: "share_location_for_one_hour", duration: Time.oneHour)
  873. addDurationSelectionAction(to: alert, key: "share_location_for_two_hours", duration: Time.twoHours)
  874. addDurationSelectionAction(to: alert, key: "share_location_for_six_hours", duration: Time.sixHours)
  875. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  876. self.present(alert, animated: true, completion: nil)
  877. }
  878. }
  879. private func addDurationSelectionAction(to alert: UIAlertController, key: String, duration: Int) {
  880. let action = UIAlertAction(title: String.localized(key), style: .default, handler: { _ in
  881. self.locationStreamingFor(seconds: duration)
  882. })
  883. alert.addAction(action)
  884. }
  885. private func locationStreamingFor(seconds: Int) {
  886. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
  887. return
  888. }
  889. self.dcContext.sendLocationsToChat(chatId: self.chatId, seconds: seconds)
  890. appDelegate.locationManager.shareLocation(chatId: self.chatId, duration: seconds)
  891. }
  892. func updateMessage(_ messageId: Int) {
  893. if messageIds.firstIndex(where: { $0 == messageId }) != nil {
  894. DispatchQueue.global(qos: .background).async { [weak self] in
  895. self?.dcContext.markSeenMessages(messageIds: [UInt32(messageId)])
  896. }
  897. let wasLastSectionVisible = self.isLastRowVisible()
  898. reloadData()
  899. if wasLastSectionVisible {
  900. self.scrollToBottom(animated: true)
  901. }
  902. } else {
  903. let msg = DcMsg(id: messageId)
  904. if msg.chatId == chatId {
  905. insertMessage(msg)
  906. }
  907. }
  908. }
  909. func insertMessage(_ message: DcMsg) {
  910. DispatchQueue.global(qos: .background).async { [weak self] in
  911. self?.dcContext.markSeenMessages(messageIds: [UInt32(message.id)])
  912. }
  913. let wasLastSectionVisible = isLastRowVisible()
  914. messageIds.append(message.id)
  915. emptyStateView.isHidden = true
  916. reloadData()
  917. if wasLastSectionVisible || message.isFromCurrentSender {
  918. scrollToBottom(animated: true)
  919. }
  920. }
  921. private func sendTextMessage(text: String, quoteMessage: DcMsg?) {
  922. DispatchQueue.global().async {
  923. let message = DcMsg(viewType: DC_MSG_TEXT)
  924. message.text = text
  925. if let quoteMessage = quoteMessage {
  926. message.quoteMessage = quoteMessage
  927. }
  928. message.sendInChat(id: self.chatId)
  929. }
  930. }
  931. private func stageDocument(url: NSURL) {
  932. self.draft.setAttachment(viewType: DC_MSG_FILE, path: url.relativePath)
  933. self.configureDraftArea(draft: self.draft)
  934. self.messageInputBar.inputTextView.becomeFirstResponder()
  935. }
  936. private func stageVideo(url: NSURL) {
  937. DispatchQueue.main.async {
  938. self.draft.setAttachment(viewType: DC_MSG_VIDEO, path: url.relativePath)
  939. self.configureDraftArea(draft: self.draft)
  940. self.messageInputBar.inputTextView.becomeFirstResponder()
  941. }
  942. }
  943. private func stageImage(url: NSURL) {
  944. if url.pathExtension == "gif" {
  945. stageAnimatedImage(url: url)
  946. } else if let data = try? Data(contentsOf: url as URL),
  947. let image = UIImage(data: data) {
  948. stageImage(image)
  949. }
  950. }
  951. private func stageAnimatedImage(url: NSURL) {
  952. DispatchQueue.global().async {
  953. if let path = url.path,
  954. let result = SDAnimatedImage(contentsOfFile: path),
  955. let animatedImageData = result.animatedImageData,
  956. let pathInDocDir = DcUtils.saveImage(data: animatedImageData, suffix: "gif") {
  957. DispatchQueue.main.async {
  958. self.draft.setAttachment(viewType: DC_MSG_GIF, path: pathInDocDir)
  959. self.configureDraftArea(draft: self.draft)
  960. self.messageInputBar.inputTextView.becomeFirstResponder()
  961. }
  962. }
  963. }
  964. }
  965. private func stageImage(_ image: UIImage) {
  966. DispatchQueue.global().async {
  967. if let pathInDocDir = DcUtils.saveImage(image: image) {
  968. DispatchQueue.main.async {
  969. self.draft.setAttachment(viewType: DC_MSG_IMAGE, path: pathInDocDir)
  970. self.configureDraftArea(draft: self.draft)
  971. self.messageInputBar.inputTextView.becomeFirstResponder()
  972. }
  973. }
  974. }
  975. }
  976. private func sendImage(_ image: UIImage, message: String? = nil) {
  977. DispatchQueue.global().async {
  978. if let path = DcUtils.saveImage(image: image) {
  979. self.sendAttachmentMessage(viewType: DC_MSG_IMAGE, filePath: path, message: message)
  980. }
  981. }
  982. }
  983. private func sendAttachmentMessage(viewType: Int32, filePath: String, message: String? = nil, quoteMessage: DcMsg? = nil) {
  984. let msg = DcMsg(viewType: viewType)
  985. msg.setFile(filepath: filePath)
  986. msg.text = (message ?? "").isEmpty ? nil : message
  987. if quoteMessage != nil {
  988. msg.quoteMessage = quoteMessage
  989. }
  990. msg.sendInChat(id: self.chatId)
  991. }
  992. private func sendVoiceMessage(url: NSURL) {
  993. DispatchQueue.global().async {
  994. let msg = DcMsg(viewType: DC_MSG_VOICE)
  995. msg.setFile(filepath: url.relativePath, mimeType: "audio/m4a")
  996. msg.sendInChat(id: self.chatId)
  997. }
  998. }
  999. // MARK: - Context menu
  1000. private func prepareContextMenu() {
  1001. UIMenuController.shared.menuItems = contextMenu.menuItems
  1002. UIMenuController.shared.update()
  1003. }
  1004. override func tableView(_ tableView: UITableView, shouldShowMenuForRowAt indexPath: IndexPath) -> Bool {
  1005. return !DcMsg(id: messageIds[indexPath.row]).isInfo
  1006. }
  1007. override func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
  1008. return !tableView.isEditing && contextMenu.canPerformAction(action: action)
  1009. }
  1010. override func tableView(_ tableView: UITableView, performAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) {
  1011. // handle standard actions here, but custom actions never trigger this. it still needs to be present for the menu to display, though.
  1012. contextMenu.performAction(action: action, indexPath: indexPath)
  1013. }
  1014. // context menu for iOS 13+
  1015. @available(iOS 13, *)
  1016. override func tableView(_ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
  1017. if tableView.isEditing {
  1018. return nil
  1019. }
  1020. return UIContextMenuConfiguration(
  1021. identifier: nil,
  1022. previewProvider: nil,
  1023. actionProvider: { [weak self] _ in
  1024. self?.contextMenu.actionProvider(indexPath: indexPath)
  1025. }
  1026. )
  1027. }
  1028. func showMediaGalleryFor(indexPath: IndexPath) {
  1029. let messageId = messageIds[indexPath.row]
  1030. let message = DcMsg(id: messageId)
  1031. showMediaGalleryFor(message: message)
  1032. }
  1033. func showMediaGalleryFor(message: DcMsg) {
  1034. let msgIds = dcContext.getChatMedia(chatId: chatId, messageType: Int32(message.type), messageType2: 0, messageType3: 0)
  1035. let index = msgIds.firstIndex(of: message.id) ?? 0
  1036. showMediaGallery(currentIndex: index, msgIds: msgIds)
  1037. }
  1038. private func didTapAsm(msg: DcMsg, orgText: String) {
  1039. let inputDlg = UIAlertController(
  1040. title: String.localized("autocrypt_continue_transfer_title"),
  1041. message: String.localized("autocrypt_continue_transfer_please_enter_code"),
  1042. preferredStyle: .alert)
  1043. inputDlg.addTextField(configurationHandler: { (textField) in
  1044. textField.placeholder = msg.setupCodeBegin + ".."
  1045. textField.text = orgText
  1046. textField.keyboardType = UIKeyboardType.numbersAndPunctuation // allows entering spaces; decimalPad would require a mask to keep things readable
  1047. })
  1048. inputDlg.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  1049. let okAction = UIAlertAction(title: String.localized("ok"), style: .default, handler: { _ in
  1050. let textField = inputDlg.textFields![0]
  1051. let modText = textField.text ?? ""
  1052. let success = self.dcContext.continueKeyTransfer(msgId: msg.id, setupCode: modText)
  1053. let alert = UIAlertController(
  1054. title: String.localized("autocrypt_continue_transfer_title"),
  1055. message: String.localized(success ? "autocrypt_continue_transfer_succeeded" : "autocrypt_bad_setup_code"),
  1056. preferredStyle: .alert)
  1057. if success {
  1058. alert.addAction(UIAlertAction(title: String.localized("ok"), style: .default, handler: nil))
  1059. } else {
  1060. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  1061. let retryAction = UIAlertAction(title: String.localized("autocrypt_continue_transfer_retry"), style: .default, handler: { _ in
  1062. self.didTapAsm(msg: msg, orgText: modText)
  1063. })
  1064. alert.addAction(retryAction)
  1065. alert.preferredAction = retryAction
  1066. }
  1067. self.navigationController?.present(alert, animated: true, completion: nil)
  1068. })
  1069. inputDlg.addAction(okAction)
  1070. inputDlg.preferredAction = okAction // without setting preferredAction, cancel become shown *bold* as the preferred action
  1071. navigationController?.present(inputDlg, animated: true, completion: nil)
  1072. }
  1073. func handleUIMenu() -> Bool {
  1074. if UIMenuController.shared.isMenuVisible {
  1075. UIMenuController.shared.setMenuVisible(false, animated: true)
  1076. return true
  1077. }
  1078. return false
  1079. }
  1080. func handleSelection(indexPath: IndexPath) -> Bool {
  1081. if tableView.isEditing {
  1082. if tableView.indexPathsForSelectedRows?.contains(indexPath) ?? false {
  1083. tableView.deselectRow(at: indexPath, animated: false)
  1084. } else {
  1085. tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
  1086. }
  1087. handleEditingBar()
  1088. return true
  1089. }
  1090. return false
  1091. }
  1092. func handleEditingBar() {
  1093. if let rows = tableView.indexPathsForSelectedRows,
  1094. !rows.isEmpty {
  1095. editingBar.isEnabled = true
  1096. } else {
  1097. editingBar.isEnabled = false
  1098. }
  1099. }
  1100. func setEditing(isEditing: Bool, selectedAtIndexPath: IndexPath? = nil) {
  1101. self.tableView.setEditing(isEditing, animated: true)
  1102. self.draft.isEditing = isEditing
  1103. self.configureDraftArea(draft: self.draft)
  1104. if let indexPath = selectedAtIndexPath {
  1105. _ = handleSelection(indexPath: indexPath)
  1106. }
  1107. }
  1108. }
  1109. // MARK: - BaseMessageCellDelegate
  1110. extension ChatViewController: BaseMessageCellDelegate {
  1111. @objc func quoteTapped(indexPath: IndexPath) {
  1112. if handleSelection(indexPath: indexPath) { return }
  1113. _ = handleUIMenu()
  1114. let msg = DcMsg(id: messageIds[indexPath.row])
  1115. if let quoteMsg = msg.quoteMessage {
  1116. scrollToMessage(msgId: quoteMsg.id)
  1117. }
  1118. }
  1119. @objc func textTapped(indexPath: IndexPath) {
  1120. if handleUIMenu() || handleSelection(indexPath: indexPath) {
  1121. return
  1122. }
  1123. let message = DcMsg(id: messageIds[indexPath.row])
  1124. if message.isSetupMessage {
  1125. didTapAsm(msg: message, orgText: "")
  1126. }
  1127. }
  1128. @objc func phoneNumberTapped(number: String, indexPath: IndexPath) {
  1129. if handleUIMenu() || handleSelection(indexPath: indexPath) {
  1130. return
  1131. }
  1132. logger.debug("phone number tapped \(number)")
  1133. }
  1134. @objc func commandTapped(command: String, indexPath: IndexPath) {
  1135. if handleUIMenu() || handleSelection(indexPath: indexPath) {
  1136. return
  1137. }
  1138. logger.debug("command tapped \(command)")
  1139. }
  1140. @objc func urlTapped(url: URL, indexPath: IndexPath) {
  1141. if handleUIMenu() || handleSelection(indexPath: indexPath) {
  1142. return
  1143. }
  1144. if Utils.isEmail(url: url) {
  1145. logger.debug("tapped on contact")
  1146. let email = Utils.getEmailFrom(url)
  1147. self.askToChatWith(email: email)
  1148. } else {
  1149. UIApplication.shared.open(url)
  1150. }
  1151. }
  1152. @objc func imageTapped(indexPath: IndexPath) {
  1153. if handleUIMenu() || handleSelection(indexPath: indexPath) {
  1154. return
  1155. }
  1156. showMediaGalleryFor(indexPath: indexPath)
  1157. }
  1158. @objc func avatarTapped(indexPath: IndexPath) {
  1159. let message = DcMsg(id: messageIds[indexPath.row])
  1160. let contactDetailController = ContactDetailViewController(dcContext: dcContext, contactId: message.fromContactId)
  1161. navigationController?.pushViewController(contactDetailController, animated: true)
  1162. }
  1163. }
  1164. // MARK: - MediaPickerDelegate
  1165. extension ChatViewController: MediaPickerDelegate {
  1166. func onVideoSelected(url: NSURL) {
  1167. stageVideo(url: url)
  1168. }
  1169. func onImageSelected(url: NSURL) {
  1170. stageImage(url: url)
  1171. }
  1172. func onImageSelected(image: UIImage) {
  1173. stageImage(image)
  1174. }
  1175. func onVoiceMessageRecorded(url: NSURL) {
  1176. sendVoiceMessage(url: url)
  1177. }
  1178. func onDocumentSelected(url: NSURL) {
  1179. stageDocument(url: url)
  1180. }
  1181. }
  1182. // MARK: - MessageInputBarDelegate
  1183. extension ChatViewController: InputBarAccessoryViewDelegate {
  1184. func inputBar(_ inputBar: InputBarAccessoryView, didPressSendButtonWith text: String) {
  1185. let trimmedText = text.replacingOccurrences(of: "\u{FFFC}", with: "", options: .literal, range: nil)
  1186. .trimmingCharacters(in: .whitespacesAndNewlines)
  1187. if let filePath = draft.attachment, let viewType = draft.viewType {
  1188. switch viewType {
  1189. case DC_MSG_GIF, DC_MSG_IMAGE, DC_MSG_FILE, DC_MSG_VIDEO:
  1190. self.sendAttachmentMessage(viewType: viewType, filePath: filePath, message: trimmedText, quoteMessage: draft.quoteMessage)
  1191. default:
  1192. logger.warning("Unsupported viewType for drafted messages.")
  1193. }
  1194. } else if inputBar.inputTextView.images.isEmpty {
  1195. self.sendTextMessage(text: trimmedText, quoteMessage: draft.quoteMessage)
  1196. } else {
  1197. // only 1 attachment allowed for now, thus it takes the first one
  1198. self.sendImage(inputBar.inputTextView.images[0], message: trimmedText)
  1199. }
  1200. inputBar.inputTextView.text = String()
  1201. inputBar.inputTextView.attributedText = nil
  1202. draftArea.cancel()
  1203. }
  1204. func inputBar(_ inputBar: InputBarAccessoryView, textViewTextDidChangeTo text: String) {
  1205. draft.text = text
  1206. evaluateInputBar(draft: draft)
  1207. }
  1208. }
  1209. // MARK: - DraftPreviewDelegate
  1210. extension ChatViewController: DraftPreviewDelegate {
  1211. func onCancelQuote() {
  1212. draft.setQuote(quotedMsg: nil)
  1213. configureDraftArea(draft: draft)
  1214. }
  1215. func onCancelAttachment() {
  1216. draft.setAttachment(viewType: nil, path: nil, mimetype: nil)
  1217. configureDraftArea(draft: draft)
  1218. evaluateInputBar(draft: draft)
  1219. }
  1220. func onAttachmentAdded() {
  1221. evaluateInputBar(draft: draft)
  1222. }
  1223. func onAttachmentTapped() {
  1224. if let attachmentPath = draft.attachment {
  1225. let attachmentURL = URL(fileURLWithPath: attachmentPath, isDirectory: false)
  1226. let previewController = PreviewController(type: .single(attachmentURL))
  1227. if #available(iOS 13.0, *), draft.viewType == DC_MSG_IMAGE || draft.viewType == DC_MSG_VIDEO {
  1228. previewController.setEditing(true, animated: true)
  1229. previewController.delegate = self
  1230. }
  1231. let nav = UINavigationController(rootViewController: previewController)
  1232. nav.modalPresentationStyle = .fullScreen
  1233. navigationController?.present(nav, animated: true)
  1234. }
  1235. }
  1236. }
  1237. // MARK: - ChatEditingDelegate
  1238. extension ChatViewController: ChatEditingDelegate {
  1239. func onDeletePressed() {
  1240. if let rows = tableView.indexPathsForSelectedRows {
  1241. let messageIdsToDelete = rows.compactMap { messageIds[$0.row] }
  1242. askToDeleteMessages(ids: messageIdsToDelete)
  1243. }
  1244. }
  1245. func onForwardPressed() {
  1246. if let rows = tableView.indexPathsForSelectedRows {
  1247. let messageIdsToForward = rows.compactMap { messageIds[$0.row] }
  1248. RelayHelper.sharedInstance.setForwardMessages(messageIds: messageIdsToForward)
  1249. self.navigationController?.popViewController(animated: true)
  1250. }
  1251. }
  1252. func onCancelPressed() {
  1253. setEditing(isEditing: false)
  1254. }
  1255. }
  1256. // MARK: - QLPreviewControllerDelegate
  1257. extension ChatViewController: QLPreviewControllerDelegate {
  1258. @available(iOS 13.0, *)
  1259. func previewController(_ controller: QLPreviewController, editingModeFor previewItem: QLPreviewItem) -> QLPreviewItemEditingMode {
  1260. return .updateContents
  1261. }
  1262. func previewController(_ controller: QLPreviewController, didUpdateContentsOf previewItem: QLPreviewItem) {
  1263. DispatchQueue.main.async { [weak self] in
  1264. guard let self = self else { return }
  1265. self.draftArea.reload(draft: self.draft)
  1266. }
  1267. }
  1268. }