ChatViewController.swift 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462
  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.isMailinglist {
  543. subtitle = String.localized("mailing_list")
  544. } else if chat.isGroup {
  545. subtitle = String.localized(stringID: "n_members", count: chatContactIds.count)
  546. } else if chat.isDeviceTalk {
  547. subtitle = String.localized("device_talk_subtitle")
  548. } else if chat.isSelfTalk {
  549. subtitle = String.localized("chat_self_talk_subtitle")
  550. } else if chatContactIds.count >= 1 {
  551. subtitle = DcContact(id: chatContactIds[0]).email
  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.backgroundColor = DcColors.chatBackgroundColor
  665. messageInputBar.inputTextView.backgroundColor = DcColors.inputFieldColor
  666. messageInputBar.inputTextView.placeholderTextColor = DcColors.placeholderColor
  667. messageInputBar.inputTextView.textContainerInset = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 38)
  668. messageInputBar.inputTextView.placeholderLabelInsets = UIEdgeInsets(top: 8, left: 20, bottom: 8, right: 38)
  669. messageInputBar.inputTextView.layer.borderColor = UIColor.themeColor(light: UIColor(red: 200 / 255, green: 200 / 255, blue: 200 / 255, alpha: 1),
  670. dark: UIColor(red: 55 / 255, green: 55/255, blue: 55/255, alpha: 1)).cgColor
  671. messageInputBar.inputTextView.layer.borderWidth = 1.0
  672. messageInputBar.inputTextView.layer.cornerRadius = 13.0
  673. messageInputBar.inputTextView.layer.masksToBounds = true
  674. messageInputBar.inputTextView.scrollIndicatorInsets = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0)
  675. configureInputBarItems()
  676. }
  677. func evaluateInputBar(draft: DraftModel) {
  678. messageInputBar.sendButton.isEnabled = draft.canSend()
  679. }
  680. private func configureInputBarItems() {
  681. messageInputBar.setLeftStackViewWidthConstant(to: 40, animated: false)
  682. messageInputBar.setRightStackViewWidthConstant(to: 40, animated: false)
  683. let sendButtonImage = UIImage(named: "paper_plane")?.withRenderingMode(.alwaysTemplate)
  684. messageInputBar.sendButton.image = sendButtonImage
  685. messageInputBar.sendButton.accessibilityLabel = String.localized("menu_send")
  686. messageInputBar.sendButton.accessibilityTraits = .button
  687. messageInputBar.sendButton.title = nil
  688. messageInputBar.sendButton.tintColor = UIColor(white: 1, alpha: 1)
  689. messageInputBar.sendButton.layer.cornerRadius = 20
  690. messageInputBar.middleContentViewPadding = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 10)
  691. // this adds a padding between textinputfield and send button
  692. messageInputBar.sendButton.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
  693. messageInputBar.sendButton.setSize(CGSize(width: 40, height: 40), animated: false)
  694. messageInputBar.padding = UIEdgeInsets(top: 6, left: 6, bottom: 6, right: 12)
  695. messageInputBar.shouldManageSendButtonEnabledState = false
  696. let leftItems = [
  697. InputBarButtonItem()
  698. .configure {
  699. $0.spacing = .fixed(0)
  700. let clipperIcon = #imageLiteral(resourceName: "ic_attach_file_36pt").withRenderingMode(.alwaysTemplate)
  701. $0.image = clipperIcon
  702. $0.tintColor = DcColors.primary
  703. $0.setSize(CGSize(width: 40, height: 40), animated: false)
  704. $0.accessibilityLabel = String.localized("menu_add_attachment")
  705. $0.accessibilityTraits = .button
  706. }.onSelected {
  707. $0.tintColor = UIColor.themeColor(light: .lightGray, dark: .darkGray)
  708. }.onDeselected {
  709. $0.tintColor = DcColors.primary
  710. }.onTouchUpInside { [weak self] _ in
  711. self?.clipperButtonPressed()
  712. }
  713. ]
  714. messageInputBar.setStackViewItems(leftItems, forStack: .left, animated: false)
  715. // This just adds some more flare
  716. messageInputBar.sendButton
  717. .onEnabled { item in
  718. UIView.animate(withDuration: 0.3, animations: {
  719. item.backgroundColor = DcColors.primary
  720. })
  721. }.onDisabled { item in
  722. UIView.animate(withDuration: 0.3, animations: {
  723. item.backgroundColor = DcColors.colorDisabled
  724. })
  725. }
  726. }
  727. @objc private func chatProfilePressed() {
  728. if chatId != DC_CHAT_ID_DEADDROP {
  729. showChatDetail(chatId: chatId)
  730. }
  731. }
  732. @objc private func clipperButtonPressed() {
  733. showClipperOptions()
  734. }
  735. private func showClipperOptions() {
  736. let alert = UIAlertController(title: nil, message: nil, preferredStyle: .safeActionSheet)
  737. let galleryAction = PhotoPickerAlertAction(title: String.localized("gallery"), style: .default, handler: galleryButtonPressed(_:))
  738. let cameraAction = PhotoPickerAlertAction(title: String.localized("camera"), style: .default, handler: cameraButtonPressed(_:))
  739. let documentAction = UIAlertAction(title: String.localized("files"), style: .default, handler: documentActionPressed(_:))
  740. let voiceMessageAction = UIAlertAction(title: String.localized("voice_message"), style: .default, handler: voiceMessageButtonPressed(_:))
  741. let isLocationStreaming = dcContext.isSendingLocationsToChat(chatId: chatId)
  742. let locationStreamingAction = UIAlertAction(title: isLocationStreaming ? String.localized("stop_sharing_location") : String.localized("location"),
  743. style: isLocationStreaming ? .destructive : .default,
  744. handler: locationStreamingButtonPressed(_:))
  745. alert.addAction(cameraAction)
  746. alert.addAction(galleryAction)
  747. alert.addAction(documentAction)
  748. alert.addAction(voiceMessageAction)
  749. if UserDefaults.standard.bool(forKey: "location_streaming") {
  750. alert.addAction(locationStreamingAction)
  751. }
  752. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  753. self.present(alert, animated: true, completion: {
  754. // unfortunately, voiceMessageAction.accessibilityHint does not work,
  755. // but this hack does the trick
  756. if UIAccessibility.isVoiceOverRunning {
  757. if let view = voiceMessageAction.value(forKey: "__representer") as? UIView {
  758. view.accessibilityHint = String.localized("a11y_voice_message_hint_ios")
  759. }
  760. }
  761. })
  762. }
  763. private func confirmationAlert(title: String, actionTitle: String, actionStyle: UIAlertAction.Style = .default, actionHandler: @escaping ((UIAlertAction) -> Void), cancelHandler: ((UIAlertAction) -> Void)? = nil) {
  764. let alert = UIAlertController(title: title,
  765. message: nil,
  766. preferredStyle: .safeActionSheet)
  767. alert.addAction(UIAlertAction(title: actionTitle, style: actionStyle, handler: actionHandler))
  768. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: cancelHandler ?? { _ in
  769. self.dismiss(animated: true, completion: nil)
  770. }))
  771. present(alert, animated: true, completion: nil)
  772. }
  773. private func askToChatWith(email: String) {
  774. let contactId = self.dcContext.createContact(name: "", email: email)
  775. if dcContext.getChatIdByContactId(contactId: contactId) != 0 {
  776. self.dismiss(animated: true, completion: nil)
  777. let chatId = self.dcContext.createChatByContactId(contactId: contactId)
  778. self.showChat(chatId: chatId)
  779. } else {
  780. confirmationAlert(title: String.localizedStringWithFormat(String.localized("ask_start_chat_with"), email),
  781. actionTitle: String.localized("start_chat"),
  782. actionHandler: { _ in
  783. self.dismiss(animated: true, completion: nil)
  784. let chatId = self.dcContext.createChatByContactId(contactId: contactId)
  785. self.showChat(chatId: chatId)})
  786. }
  787. }
  788. private func askToDeleteMessage(id: Int) {
  789. self.askToDeleteMessages(ids: [id])
  790. }
  791. private func askToDeleteMessages(ids: [Int]) {
  792. let title = String.localized(stringID: "ask_delete_messages", count: ids.count)
  793. confirmationAlert(title: title, actionTitle: String.localized("delete"), actionStyle: .destructive,
  794. actionHandler: { _ in
  795. self.dcContext.deleteMessages(msgIds: ids)
  796. if self.tableView.isEditing {
  797. self.setEditing(isEditing: false)
  798. }
  799. })
  800. }
  801. private func askToForwardMessage() {
  802. let chat = dcContext.getChat(chatId: self.chatId)
  803. if chat.isSelfTalk {
  804. RelayHelper.sharedInstance.forward(to: self.chatId)
  805. } else {
  806. confirmationAlert(title: String.localizedStringWithFormat(String.localized("ask_forward"), chat.name),
  807. actionTitle: String.localized("menu_forward"),
  808. actionHandler: { _ in
  809. RelayHelper.sharedInstance.forward(to: self.chatId)
  810. self.dismiss(animated: true, completion: nil)},
  811. cancelHandler: { _ in
  812. self.dismiss(animated: false, completion: nil)
  813. self.navigationController?.popViewController(animated: true)})
  814. }
  815. }
  816. // MARK: - coordinator
  817. private func showChatDetail(chatId: Int) {
  818. let chat = dcContext.getChat(chatId: chatId)
  819. if !chat.isGroup {
  820. if let contactId = chat.contactIds.first {
  821. let contactDetailController = ContactDetailViewController(dcContext: dcContext, contactId: contactId)
  822. navigationController?.pushViewController(contactDetailController, animated: true)
  823. }
  824. } else {
  825. let groupChatDetailViewController = GroupChatDetailViewController(chatId: chatId, dcContext: dcContext)
  826. navigationController?.pushViewController(groupChatDetailViewController, animated: true)
  827. }
  828. }
  829. func showChat(chatId: Int) {
  830. if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
  831. navigationController?.popToRootViewController(animated: false)
  832. appDelegate.appCoordinator.showChat(chatId: chatId)
  833. }
  834. }
  835. private func showDocumentLibrary() {
  836. mediaPicker?.showDocumentLibrary()
  837. }
  838. private func showVoiceMessageRecorder() {
  839. mediaPicker?.showVoiceRecorder()
  840. }
  841. private func showCameraViewController() {
  842. mediaPicker?.showCamera()
  843. }
  844. private func showPhotoVideoLibrary(delegate: MediaPickerDelegate) {
  845. mediaPicker?.showPhotoVideoLibrary()
  846. }
  847. private func showMediaGallery(currentIndex: Int, msgIds: [Int]) {
  848. let betterPreviewController = PreviewController(type: .multi(msgIds, currentIndex))
  849. let nav = UINavigationController(rootViewController: betterPreviewController)
  850. nav.modalPresentationStyle = .fullScreen
  851. navigationController?.present(nav, animated: true)
  852. }
  853. private func documentActionPressed(_ action: UIAlertAction) {
  854. showDocumentLibrary()
  855. }
  856. private func voiceMessageButtonPressed(_ action: UIAlertAction) {
  857. showVoiceMessageRecorder()
  858. }
  859. private func cameraButtonPressed(_ action: UIAlertAction) {
  860. showCameraViewController()
  861. }
  862. private func galleryButtonPressed(_ action: UIAlertAction) {
  863. showPhotoVideoLibrary(delegate: self)
  864. }
  865. private func locationStreamingButtonPressed(_ action: UIAlertAction) {
  866. let isLocationStreaming = dcContext.isSendingLocationsToChat(chatId: chatId)
  867. if isLocationStreaming {
  868. locationStreamingFor(seconds: 0)
  869. } else {
  870. let alert = UIAlertController(title: String.localized("title_share_location"), message: nil, preferredStyle: .safeActionSheet)
  871. addDurationSelectionAction(to: alert, key: "share_location_for_5_minutes", duration: Time.fiveMinutes)
  872. addDurationSelectionAction(to: alert, key: "share_location_for_30_minutes", duration: Time.thirtyMinutes)
  873. addDurationSelectionAction(to: alert, key: "share_location_for_one_hour", duration: Time.oneHour)
  874. addDurationSelectionAction(to: alert, key: "share_location_for_two_hours", duration: Time.twoHours)
  875. addDurationSelectionAction(to: alert, key: "share_location_for_six_hours", duration: Time.sixHours)
  876. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  877. self.present(alert, animated: true, completion: nil)
  878. }
  879. }
  880. private func addDurationSelectionAction(to alert: UIAlertController, key: String, duration: Int) {
  881. let action = UIAlertAction(title: String.localized(key), style: .default, handler: { _ in
  882. self.locationStreamingFor(seconds: duration)
  883. })
  884. alert.addAction(action)
  885. }
  886. private func locationStreamingFor(seconds: Int) {
  887. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
  888. return
  889. }
  890. self.dcContext.sendLocationsToChat(chatId: self.chatId, seconds: seconds)
  891. appDelegate.locationManager.shareLocation(chatId: self.chatId, duration: seconds)
  892. }
  893. func updateMessage(_ messageId: Int) {
  894. if messageIds.firstIndex(where: { $0 == messageId }) != nil {
  895. DispatchQueue.global(qos: .background).async { [weak self] in
  896. self?.dcContext.markSeenMessages(messageIds: [UInt32(messageId)])
  897. }
  898. let wasLastSectionVisible = self.isLastRowVisible()
  899. reloadData()
  900. if wasLastSectionVisible {
  901. self.scrollToBottom(animated: true)
  902. }
  903. } else {
  904. let msg = DcMsg(id: messageId)
  905. if msg.chatId == chatId {
  906. insertMessage(msg)
  907. }
  908. }
  909. }
  910. func insertMessage(_ message: DcMsg) {
  911. DispatchQueue.global(qos: .background).async { [weak self] in
  912. self?.dcContext.markSeenMessages(messageIds: [UInt32(message.id)])
  913. }
  914. let wasLastSectionVisible = isLastRowVisible()
  915. messageIds.append(message.id)
  916. emptyStateView.isHidden = true
  917. reloadData()
  918. if wasLastSectionVisible || message.isFromCurrentSender {
  919. scrollToBottom(animated: true)
  920. }
  921. }
  922. private func sendTextMessage(text: String, quoteMessage: DcMsg?) {
  923. DispatchQueue.global().async {
  924. let message = DcMsg(viewType: DC_MSG_TEXT)
  925. message.text = text
  926. if let quoteMessage = quoteMessage {
  927. message.quoteMessage = quoteMessage
  928. }
  929. message.sendInChat(id: self.chatId)
  930. }
  931. }
  932. private func stageDocument(url: NSURL) {
  933. self.draft.setAttachment(viewType: DC_MSG_FILE, path: url.relativePath)
  934. self.configureDraftArea(draft: self.draft)
  935. self.messageInputBar.inputTextView.becomeFirstResponder()
  936. }
  937. private func stageVideo(url: NSURL) {
  938. DispatchQueue.main.async {
  939. self.draft.setAttachment(viewType: DC_MSG_VIDEO, path: url.relativePath)
  940. self.configureDraftArea(draft: self.draft)
  941. self.messageInputBar.inputTextView.becomeFirstResponder()
  942. }
  943. }
  944. private func stageImage(url: NSURL) {
  945. if url.pathExtension == "gif" {
  946. stageAnimatedImage(url: url)
  947. } else if let data = try? Data(contentsOf: url as URL),
  948. let image = UIImage(data: data) {
  949. stageImage(image)
  950. }
  951. }
  952. private func stageAnimatedImage(url: NSURL) {
  953. DispatchQueue.global().async {
  954. if let path = url.path,
  955. let result = SDAnimatedImage(contentsOfFile: path),
  956. let animatedImageData = result.animatedImageData,
  957. let pathInDocDir = DcUtils.saveImage(data: animatedImageData, suffix: "gif") {
  958. DispatchQueue.main.async {
  959. self.draft.setAttachment(viewType: DC_MSG_GIF, path: pathInDocDir)
  960. self.configureDraftArea(draft: self.draft)
  961. self.messageInputBar.inputTextView.becomeFirstResponder()
  962. }
  963. }
  964. }
  965. }
  966. private func stageImage(_ image: UIImage) {
  967. DispatchQueue.global().async {
  968. if let pathInDocDir = DcUtils.saveImage(image: image) {
  969. DispatchQueue.main.async {
  970. self.draft.setAttachment(viewType: DC_MSG_IMAGE, path: pathInDocDir)
  971. self.configureDraftArea(draft: self.draft)
  972. self.messageInputBar.inputTextView.becomeFirstResponder()
  973. }
  974. }
  975. }
  976. }
  977. private func sendImage(_ image: UIImage, message: String? = nil) {
  978. DispatchQueue.global().async {
  979. if let path = DcUtils.saveImage(image: image) {
  980. self.sendAttachmentMessage(viewType: DC_MSG_IMAGE, filePath: path, message: message)
  981. }
  982. }
  983. }
  984. private func sendAttachmentMessage(viewType: Int32, filePath: String, message: String? = nil, quoteMessage: DcMsg? = nil) {
  985. let msg = DcMsg(viewType: viewType)
  986. msg.setFile(filepath: filePath)
  987. msg.text = (message ?? "").isEmpty ? nil : message
  988. if quoteMessage != nil {
  989. msg.quoteMessage = quoteMessage
  990. }
  991. msg.sendInChat(id: self.chatId)
  992. }
  993. private func sendVoiceMessage(url: NSURL) {
  994. DispatchQueue.global().async {
  995. let msg = DcMsg(viewType: DC_MSG_VOICE)
  996. msg.setFile(filepath: url.relativePath, mimeType: "audio/m4a")
  997. msg.sendInChat(id: self.chatId)
  998. }
  999. }
  1000. // MARK: - Context menu
  1001. private func prepareContextMenu() {
  1002. UIMenuController.shared.menuItems = contextMenu.menuItems
  1003. UIMenuController.shared.update()
  1004. }
  1005. override func tableView(_ tableView: UITableView, shouldShowMenuForRowAt indexPath: IndexPath) -> Bool {
  1006. return !DcMsg(id: messageIds[indexPath.row]).isInfo
  1007. }
  1008. override func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
  1009. return !tableView.isEditing && contextMenu.canPerformAction(action: action)
  1010. }
  1011. override func tableView(_ tableView: UITableView, performAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) {
  1012. // handle standard actions here, but custom actions never trigger this. it still needs to be present for the menu to display, though.
  1013. contextMenu.performAction(action: action, indexPath: indexPath)
  1014. }
  1015. // context menu for iOS 13+
  1016. @available(iOS 13, *)
  1017. override func tableView(_ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
  1018. if tableView.isEditing {
  1019. return nil
  1020. }
  1021. return UIContextMenuConfiguration(
  1022. identifier: nil,
  1023. previewProvider: nil,
  1024. actionProvider: { [weak self] _ in
  1025. self?.contextMenu.actionProvider(indexPath: indexPath)
  1026. }
  1027. )
  1028. }
  1029. func showMediaGalleryFor(indexPath: IndexPath) {
  1030. let messageId = messageIds[indexPath.row]
  1031. let message = DcMsg(id: messageId)
  1032. showMediaGalleryFor(message: message)
  1033. }
  1034. func showMediaGalleryFor(message: DcMsg) {
  1035. let msgIds = dcContext.getChatMedia(chatId: chatId, messageType: Int32(message.type), messageType2: 0, messageType3: 0)
  1036. let index = msgIds.firstIndex(of: message.id) ?? 0
  1037. showMediaGallery(currentIndex: index, msgIds: msgIds)
  1038. }
  1039. private func didTapAsm(msg: DcMsg, orgText: String) {
  1040. let inputDlg = UIAlertController(
  1041. title: String.localized("autocrypt_continue_transfer_title"),
  1042. message: String.localized("autocrypt_continue_transfer_please_enter_code"),
  1043. preferredStyle: .alert)
  1044. inputDlg.addTextField(configurationHandler: { (textField) in
  1045. textField.placeholder = msg.setupCodeBegin + ".."
  1046. textField.text = orgText
  1047. textField.keyboardType = UIKeyboardType.numbersAndPunctuation // allows entering spaces; decimalPad would require a mask to keep things readable
  1048. })
  1049. inputDlg.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  1050. let okAction = UIAlertAction(title: String.localized("ok"), style: .default, handler: { _ in
  1051. let textField = inputDlg.textFields![0]
  1052. let modText = textField.text ?? ""
  1053. let success = self.dcContext.continueKeyTransfer(msgId: msg.id, setupCode: modText)
  1054. let alert = UIAlertController(
  1055. title: String.localized("autocrypt_continue_transfer_title"),
  1056. message: String.localized(success ? "autocrypt_continue_transfer_succeeded" : "autocrypt_bad_setup_code"),
  1057. preferredStyle: .alert)
  1058. if success {
  1059. alert.addAction(UIAlertAction(title: String.localized("ok"), style: .default, handler: nil))
  1060. } else {
  1061. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  1062. let retryAction = UIAlertAction(title: String.localized("autocrypt_continue_transfer_retry"), style: .default, handler: { _ in
  1063. self.didTapAsm(msg: msg, orgText: modText)
  1064. })
  1065. alert.addAction(retryAction)
  1066. alert.preferredAction = retryAction
  1067. }
  1068. self.navigationController?.present(alert, animated: true, completion: nil)
  1069. })
  1070. inputDlg.addAction(okAction)
  1071. inputDlg.preferredAction = okAction // without setting preferredAction, cancel become shown *bold* as the preferred action
  1072. navigationController?.present(inputDlg, animated: true, completion: nil)
  1073. }
  1074. func handleUIMenu() -> Bool {
  1075. if UIMenuController.shared.isMenuVisible {
  1076. UIMenuController.shared.setMenuVisible(false, animated: true)
  1077. return true
  1078. }
  1079. return false
  1080. }
  1081. func handleSelection(indexPath: IndexPath) -> Bool {
  1082. if tableView.isEditing {
  1083. if tableView.indexPathsForSelectedRows?.contains(indexPath) ?? false {
  1084. tableView.deselectRow(at: indexPath, animated: false)
  1085. } else {
  1086. tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
  1087. }
  1088. handleEditingBar()
  1089. return true
  1090. }
  1091. return false
  1092. }
  1093. func handleEditingBar() {
  1094. if let rows = tableView.indexPathsForSelectedRows,
  1095. !rows.isEmpty {
  1096. editingBar.isEnabled = true
  1097. } else {
  1098. editingBar.isEnabled = false
  1099. }
  1100. }
  1101. func setEditing(isEditing: Bool, selectedAtIndexPath: IndexPath? = nil) {
  1102. self.tableView.setEditing(isEditing, animated: true)
  1103. self.draft.isEditing = isEditing
  1104. self.configureDraftArea(draft: self.draft)
  1105. if let indexPath = selectedAtIndexPath {
  1106. _ = handleSelection(indexPath: indexPath)
  1107. }
  1108. }
  1109. }
  1110. // MARK: - BaseMessageCellDelegate
  1111. extension ChatViewController: BaseMessageCellDelegate {
  1112. @objc func fullMessageTapped(indexPath: IndexPath) {
  1113. if handleUIMenu() || handleSelection(indexPath: indexPath) {
  1114. return
  1115. }
  1116. let msg = DcMsg(id: messageIds[indexPath.row])
  1117. let fullMessageViewController = FullMessageViewController(dcContext: dcContext, messageId: msg.id)
  1118. navigationController?.pushViewController(fullMessageViewController, animated: true)
  1119. }
  1120. @objc func quoteTapped(indexPath: IndexPath) {
  1121. if handleSelection(indexPath: indexPath) { return }
  1122. _ = handleUIMenu()
  1123. let msg = DcMsg(id: messageIds[indexPath.row])
  1124. if let quoteMsg = msg.quoteMessage {
  1125. scrollToMessage(msgId: quoteMsg.id)
  1126. }
  1127. }
  1128. @objc func textTapped(indexPath: IndexPath) {
  1129. if handleUIMenu() || handleSelection(indexPath: indexPath) {
  1130. return
  1131. }
  1132. let message = DcMsg(id: messageIds[indexPath.row])
  1133. if message.isSetupMessage {
  1134. didTapAsm(msg: message, orgText: "")
  1135. }
  1136. }
  1137. @objc func phoneNumberTapped(number: String, indexPath: IndexPath) {
  1138. if handleUIMenu() || handleSelection(indexPath: indexPath) {
  1139. return
  1140. }
  1141. logger.debug("phone number tapped \(number)")
  1142. }
  1143. @objc func commandTapped(command: String, indexPath: IndexPath) {
  1144. if handleUIMenu() || handleSelection(indexPath: indexPath) {
  1145. return
  1146. }
  1147. logger.debug("command tapped \(command)")
  1148. }
  1149. @objc func urlTapped(url: URL, indexPath: IndexPath) {
  1150. if handleUIMenu() || handleSelection(indexPath: indexPath) {
  1151. return
  1152. }
  1153. if Utils.isEmail(url: url) {
  1154. logger.debug("tapped on contact")
  1155. let email = Utils.getEmailFrom(url)
  1156. self.askToChatWith(email: email)
  1157. } else {
  1158. UIApplication.shared.open(url)
  1159. }
  1160. }
  1161. @objc func imageTapped(indexPath: IndexPath) {
  1162. if handleUIMenu() || handleSelection(indexPath: indexPath) {
  1163. return
  1164. }
  1165. showMediaGalleryFor(indexPath: indexPath)
  1166. }
  1167. @objc func avatarTapped(indexPath: IndexPath) {
  1168. let message = DcMsg(id: messageIds[indexPath.row])
  1169. let contactDetailController = ContactDetailViewController(dcContext: dcContext, contactId: message.fromContactId)
  1170. navigationController?.pushViewController(contactDetailController, animated: true)
  1171. }
  1172. }
  1173. // MARK: - MediaPickerDelegate
  1174. extension ChatViewController: MediaPickerDelegate {
  1175. func onVideoSelected(url: NSURL) {
  1176. stageVideo(url: url)
  1177. }
  1178. func onImageSelected(url: NSURL) {
  1179. stageImage(url: url)
  1180. }
  1181. func onImageSelected(image: UIImage) {
  1182. stageImage(image)
  1183. }
  1184. func onVoiceMessageRecorded(url: NSURL) {
  1185. sendVoiceMessage(url: url)
  1186. }
  1187. func onDocumentSelected(url: NSURL) {
  1188. stageDocument(url: url)
  1189. }
  1190. }
  1191. // MARK: - MessageInputBarDelegate
  1192. extension ChatViewController: InputBarAccessoryViewDelegate {
  1193. func inputBar(_ inputBar: InputBarAccessoryView, didPressSendButtonWith text: String) {
  1194. let trimmedText = text.replacingOccurrences(of: "\u{FFFC}", with: "", options: .literal, range: nil)
  1195. .trimmingCharacters(in: .whitespacesAndNewlines)
  1196. if let filePath = draft.attachment, let viewType = draft.viewType {
  1197. switch viewType {
  1198. case DC_MSG_GIF, DC_MSG_IMAGE, DC_MSG_FILE, DC_MSG_VIDEO:
  1199. self.sendAttachmentMessage(viewType: viewType, filePath: filePath, message: trimmedText, quoteMessage: draft.quoteMessage)
  1200. default:
  1201. logger.warning("Unsupported viewType for drafted messages.")
  1202. }
  1203. } else if inputBar.inputTextView.images.isEmpty {
  1204. self.sendTextMessage(text: trimmedText, quoteMessage: draft.quoteMessage)
  1205. } else {
  1206. // only 1 attachment allowed for now, thus it takes the first one
  1207. self.sendImage(inputBar.inputTextView.images[0], message: trimmedText)
  1208. }
  1209. inputBar.inputTextView.text = String()
  1210. inputBar.inputTextView.attributedText = nil
  1211. draftArea.cancel()
  1212. }
  1213. func inputBar(_ inputBar: InputBarAccessoryView, textViewTextDidChangeTo text: String) {
  1214. draft.text = text
  1215. evaluateInputBar(draft: draft)
  1216. }
  1217. }
  1218. // MARK: - DraftPreviewDelegate
  1219. extension ChatViewController: DraftPreviewDelegate {
  1220. func onCancelQuote() {
  1221. draft.setQuote(quotedMsg: nil)
  1222. configureDraftArea(draft: draft)
  1223. }
  1224. func onCancelAttachment() {
  1225. draft.setAttachment(viewType: nil, path: nil, mimetype: nil)
  1226. configureDraftArea(draft: draft)
  1227. evaluateInputBar(draft: draft)
  1228. }
  1229. func onAttachmentAdded() {
  1230. evaluateInputBar(draft: draft)
  1231. }
  1232. func onAttachmentTapped() {
  1233. if let attachmentPath = draft.attachment {
  1234. let attachmentURL = URL(fileURLWithPath: attachmentPath, isDirectory: false)
  1235. let previewController = PreviewController(type: .single(attachmentURL))
  1236. if #available(iOS 13.0, *), draft.viewType == DC_MSG_IMAGE || draft.viewType == DC_MSG_VIDEO {
  1237. previewController.setEditing(true, animated: true)
  1238. previewController.delegate = self
  1239. }
  1240. let nav = UINavigationController(rootViewController: previewController)
  1241. nav.modalPresentationStyle = .fullScreen
  1242. navigationController?.present(nav, animated: true)
  1243. }
  1244. }
  1245. }
  1246. // MARK: - ChatEditingDelegate
  1247. extension ChatViewController: ChatEditingDelegate {
  1248. func onDeletePressed() {
  1249. if let rows = tableView.indexPathsForSelectedRows {
  1250. let messageIdsToDelete = rows.compactMap { messageIds[$0.row] }
  1251. askToDeleteMessages(ids: messageIdsToDelete)
  1252. }
  1253. }
  1254. func onForwardPressed() {
  1255. if let rows = tableView.indexPathsForSelectedRows {
  1256. let messageIdsToForward = rows.compactMap { messageIds[$0.row] }
  1257. RelayHelper.sharedInstance.setForwardMessages(messageIds: messageIdsToForward)
  1258. self.navigationController?.popViewController(animated: true)
  1259. }
  1260. }
  1261. func onCancelPressed() {
  1262. setEditing(isEditing: false)
  1263. }
  1264. }
  1265. // MARK: - QLPreviewControllerDelegate
  1266. extension ChatViewController: QLPreviewControllerDelegate {
  1267. @available(iOS 13.0, *)
  1268. func previewController(_ controller: QLPreviewController, editingModeFor previewItem: QLPreviewItem) -> QLPreviewItemEditingMode {
  1269. return .updateContents
  1270. }
  1271. func previewController(_ controller: QLPreviewController, didUpdateContentsOf previewItem: QLPreviewItem) {
  1272. DispatchQueue.main.async { [weak self] in
  1273. guard let self = self else { return }
  1274. self.draftArea.reload(draft: self.draft)
  1275. }
  1276. }
  1277. }