ChatViewController.swift 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479
  1. import MapKit
  2. import QuickLook
  3. import UIKit
  4. import InputBarAccessoryView
  5. import AVFoundation
  6. import DcCore
  7. protocol MediaSendHandler {
  8. func onSuccess()
  9. }
  10. extension ChatViewController: MediaSendHandler {
  11. func onSuccess() {
  12. refreshMessages()
  13. }
  14. }
  15. extension ChatViewController: MediaPickerDelegate {
  16. func onVideoSelected(url: NSURL) {
  17. sendVideo(url: url)
  18. }
  19. func onImageSelected(url: NSURL) {
  20. sendImage(url: url)
  21. }
  22. func onImageSelected(image: UIImage) {
  23. sendImage(image)
  24. }
  25. func onVoiceMessageRecorded(url: NSURL) {
  26. sendVoiceMessage(url: url)
  27. }
  28. func onDocumentSelected(url: NSURL) {
  29. sendDocumentMessage(url: url)
  30. }
  31. }
  32. class ChatViewController: MessagesViewController {
  33. var dcContext: DcContext
  34. let outgoingAvatarOverlap: CGFloat = 17.5
  35. let loadCount = 30
  36. let chatId: Int
  37. let refreshControl = UIRefreshControl()
  38. var messageList: [DcMsg] = []
  39. var msgChangedObserver: Any?
  40. var incomingMsgObserver: Any?
  41. weak var timer: Timer?
  42. lazy var navBarTap: UITapGestureRecognizer = {
  43. UITapGestureRecognizer(target: self, action: #selector(chatProfilePressed))
  44. }()
  45. private var locationStreamingItem: UIBarButtonItem = {
  46. let indicator = LocationStreamingIndicator()
  47. return UIBarButtonItem(customView: indicator)
  48. }()
  49. private lazy var badgeItem: UIBarButtonItem = {
  50. let badge: InitialsBadge
  51. let chat = dcContext.getChat(chatId: chatId)
  52. if let image = chat.profileImage {
  53. badge = InitialsBadge(image: image, size: 28, accessibilityLabel: String.localized("menu_view_profile"))
  54. } else {
  55. badge = InitialsBadge(
  56. name: chat.name,
  57. color: chat.color,
  58. size: 28,
  59. accessibilityLabel: String.localized("menu_view_profile")
  60. )
  61. badge.setLabelFont(UIFont.systemFont(ofSize: 14))
  62. }
  63. badge.setVerified(chat.isVerified)
  64. badge.accessibilityTraits = .button
  65. return UIBarButtonItem(customView: badge)
  66. }()
  67. /// The `BasicAudioController` controll the AVAudioPlayer state (play, pause, stop) and udpate audio cell UI accordingly.
  68. open lazy var audioController = BasicAudioController(messageCollectionView: messagesCollectionView)
  69. private var disableWriting: Bool
  70. private var showNamesAboveMessage: Bool
  71. var showCustomNavBar = true
  72. var previewView: UIView?
  73. private lazy var mediaPicker: MediaPicker? = {
  74. return MediaPicker(navigationController: navigationController)
  75. }()
  76. var emptyStateView: EmptyStateLabel = {
  77. let view = EmptyStateLabel()
  78. return view
  79. }()
  80. override var inputAccessoryView: UIView? {
  81. if disableWriting {
  82. return nil
  83. }
  84. return messageInputBar
  85. }
  86. init(dcContext: DcContext, chatId: Int) {
  87. let dcChat = dcContext.getChat(chatId: chatId)
  88. self.dcContext = dcContext
  89. self.chatId = chatId
  90. self.disableWriting = !dcChat.canSend
  91. self.showNamesAboveMessage = dcChat.isGroup
  92. super.init(nibName: nil, bundle: nil)
  93. hidesBottomBarWhenPushed = true
  94. }
  95. required init?(coder _: NSCoder) {
  96. fatalError("init(coder:) has not been implemented")
  97. }
  98. override func viewDidLoad() {
  99. messagesCollectionView.register(InfoMessageCell.self)
  100. super.viewDidLoad()
  101. if !dcContext.isConfigured() {
  102. // TODO: display message about nothing being configured
  103. return
  104. }
  105. configureMessageCollectionView()
  106. configureEmptyStateView()
  107. if !disableWriting {
  108. configureMessageInputBar()
  109. messageInputBar.inputTextView.text = textDraft
  110. messageInputBar.inputTextView.becomeFirstResponder()
  111. }
  112. let notificationCenter = NotificationCenter.default
  113. notificationCenter.addObserver(self,
  114. selector: #selector(setTextDraft),
  115. name: UIApplication.willResignActiveNotification,
  116. object: nil)
  117. }
  118. private func startTimer() {
  119. timer?.invalidate()
  120. timer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { [weak self] _ in
  121. //reload table
  122. DispatchQueue.main.async {
  123. guard let self = self else { return }
  124. self.messageList = self.getMessageIds(self.messageList.count)
  125. self.messagesCollectionView.reloadDataAndKeepOffset()
  126. self.refreshControl.endRefreshing()
  127. }
  128. }
  129. }
  130. private func stopTimer() {
  131. timer?.invalidate()
  132. }
  133. private func configureEmptyStateView() {
  134. view.addSubview(emptyStateView)
  135. emptyStateView.translatesAutoresizingMaskIntoConstraints = false
  136. emptyStateView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 40).isActive = true
  137. emptyStateView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -40).isActive = true
  138. emptyStateView.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor).isActive = true
  139. }
  140. override func viewWillAppear(_ animated: Bool) {
  141. super.viewWillAppear(animated)
  142. // this will be removed in viewWillDisappear
  143. navigationController?.navigationBar.addGestureRecognizer(navBarTap)
  144. if showCustomNavBar {
  145. updateTitle(chat: dcContext.getChat(chatId: chatId))
  146. }
  147. configureMessageMenu()
  148. let nc = NotificationCenter.default
  149. msgChangedObserver = nc.addObserver(
  150. forName: dcNotificationChanged,
  151. object: nil,
  152. queue: OperationQueue.main
  153. ) { [weak self] notification in
  154. guard let self = self else { return }
  155. if let ui = notification.userInfo {
  156. if self.disableWriting {
  157. // always refresh, as we can't check currently
  158. self.refreshMessages()
  159. } else if let id = ui["message_id"] as? Int {
  160. if id > 0 {
  161. self.updateMessage(id)
  162. } else {
  163. // change might be a deletion
  164. self.refreshMessages()
  165. }
  166. }
  167. if self.showCustomNavBar {
  168. self.updateTitle(chat: self.dcContext.getChat(chatId: self.chatId))
  169. }
  170. }
  171. }
  172. incomingMsgObserver = nc.addObserver(
  173. forName: dcNotificationIncoming,
  174. object: nil, queue: OperationQueue.main
  175. ) { notification in
  176. if let ui = notification.userInfo {
  177. if self.chatId == ui["chat_id"] as? Int {
  178. if let id = ui["message_id"] as? Int {
  179. if id > 0 {
  180. self.insertMessage(DcMsg(id: id))
  181. }
  182. }
  183. }
  184. }
  185. }
  186. loadFirstMessages()
  187. if RelayHelper.sharedInstance.isForwarding() {
  188. askToForwardMessage()
  189. }
  190. }
  191. override func viewDidAppear(_ animated: Bool) {
  192. super.viewDidAppear(animated)
  193. AppStateRestorer.shared.storeLastActiveChat(chatId: chatId)
  194. // things that do not affect the chatview
  195. // and are delayed after the view is displayed
  196. dcContext.marknoticedChat(chatId: chatId)
  197. let array = dcContext.getFreshMessages()
  198. UIApplication.shared.applicationIconBadgeNumber = array.count
  199. startTimer()
  200. }
  201. override func viewWillDisappear(_ animated: Bool) {
  202. super.viewWillDisappear(animated)
  203. // the navigationController will be used when chatDetail is pushed, so we have to remove that gestureRecognizer
  204. navigationController?.navigationBar.removeGestureRecognizer(navBarTap)
  205. }
  206. override func viewDidDisappear(_ animated: Bool) {
  207. super.viewDidDisappear(animated)
  208. AppStateRestorer.shared.resetLastActiveChat()
  209. setTextDraft()
  210. let nc = NotificationCenter.default
  211. if let msgChangedObserver = self.msgChangedObserver {
  212. nc.removeObserver(msgChangedObserver)
  213. }
  214. if let incomingMsgObserver = self.incomingMsgObserver {
  215. nc.removeObserver(incomingMsgObserver)
  216. }
  217. audioController.stopAnyOngoingPlaying()
  218. stopTimer()
  219. }
  220. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  221. let lastSectionVisibleBeforeTransition = self.isLastSectionVisible()
  222. coordinator.animate(
  223. alongsideTransition: { [weak self] _ in
  224. guard let self = self else { return }
  225. if self.showCustomNavBar {
  226. self.navigationItem.setRightBarButton(self.badgeItem, animated: true)
  227. }
  228. },
  229. completion: {[weak self] _ in
  230. guard let self = self else { return }
  231. self.updateTitle(chat: self.dcContext.getChat(chatId: self.chatId))
  232. self.messagesCollectionView.reloadDataAndKeepOffset()
  233. if lastSectionVisibleBeforeTransition {
  234. self.messagesCollectionView.scrollToBottom(animated: false)
  235. }
  236. }
  237. )
  238. super.viewWillTransition(to: size, with: coordinator)
  239. }
  240. private func updateTitle(chat: DcChat) {
  241. let titleView = ChatTitleView()
  242. var subtitle = "ErrSubtitle"
  243. let chatContactIds = chat.contactIds
  244. if chat.isGroup {
  245. subtitle = String.localized(stringID: "n_members", count: chatContactIds.count)
  246. } else if chatContactIds.count >= 1 {
  247. if chat.isDeviceTalk {
  248. subtitle = String.localized("device_talk_subtitle")
  249. } else if chat.isSelfTalk {
  250. subtitle = String.localized("chat_self_talk_subtitle")
  251. } else {
  252. subtitle = DcContact(id: chatContactIds[0]).email
  253. }
  254. }
  255. titleView.updateTitleView(title: chat.name, subtitle: subtitle)
  256. navigationItem.titleView = titleView
  257. if chat.isSendingLocations {
  258. navigationItem.rightBarButtonItems = [badgeItem, locationStreamingItem]
  259. } else {
  260. navigationItem.rightBarButtonItems = [badgeItem]
  261. }
  262. }
  263. @objc
  264. private func loadMoreMessages() {
  265. DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + 1) {
  266. DispatchQueue.main.async {
  267. self.messageList = self.getMessageIds(self.loadCount, from: self.messageList.count) + self.messageList
  268. self.messagesCollectionView.reloadDataAndKeepOffset()
  269. self.refreshControl.endRefreshing()
  270. }
  271. }
  272. }
  273. @objc
  274. private func refreshMessages() {
  275. DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + 1) {
  276. DispatchQueue.main.async {
  277. self.messageList = self.getMessageIds(self.messageList.count)
  278. self.messagesCollectionView.reloadDataAndKeepOffset()
  279. self.refreshControl.endRefreshing()
  280. if self.isLastSectionVisible() {
  281. self.messagesCollectionView.scrollToBottom(animated: true)
  282. }
  283. self.showEmptyStateView(self.messageList.isEmpty)
  284. }
  285. }
  286. }
  287. private func loadFirstMessages() {
  288. DispatchQueue.global(qos: .userInitiated).async {
  289. DispatchQueue.main.async {
  290. self.messageList = self.getMessageIds(self.loadCount)
  291. self.messagesCollectionView.reloadData()
  292. self.refreshControl.endRefreshing()
  293. self.messagesCollectionView.scrollToBottom(animated: false)
  294. self.showEmptyStateView(self.messageList.isEmpty)
  295. }
  296. }
  297. }
  298. private func showEmptyStateView(_ show: Bool) {
  299. if show {
  300. let dcChat = dcContext.getChat(chatId: chatId)
  301. if chatId == DC_CHAT_ID_DEADDROP {
  302. if dcContext.showEmails != DC_SHOW_EMAILS_ALL {
  303. emptyStateView.text = String.localized("chat_no_contact_requests")
  304. } else {
  305. emptyStateView.text = String.localized("chat_no_messages")
  306. }
  307. } else if dcChat.isGroup {
  308. if dcChat.isUnpromoted {
  309. emptyStateView.text = String.localized("chat_new_group_hint")
  310. } else {
  311. emptyStateView.text = String.localized("chat_no_messages")
  312. }
  313. } else if dcChat.isSelfTalk {
  314. emptyStateView.text = String.localized("saved_messages_explain")
  315. } else if dcChat.isDeviceTalk {
  316. emptyStateView.text = String.localized("device_talk_explain")
  317. } else {
  318. emptyStateView.text = String.localizedStringWithFormat(String.localized("chat_no_messages_hint"), dcChat.name, dcChat.name)
  319. }
  320. emptyStateView.isHidden = false
  321. } else {
  322. emptyStateView.isHidden = true
  323. }
  324. }
  325. private var textDraft: String? {
  326. return dcContext.getDraft(chatId: chatId)
  327. }
  328. private func getMessageIds(_ count: Int, from: Int? = nil) -> [DcMsg] {
  329. let ids = dcContext.getMessageIds(chatId: chatId, count: count, from: from)
  330. let markIds: [UInt32] = ids.map { UInt32($0) }
  331. dcContext.markSeenMessages(messageIds: markIds, count: ids.count)
  332. return ids.map {
  333. DcMsg(id: $0)
  334. }
  335. }
  336. @objc private func setTextDraft() {
  337. if let text = self.messageInputBar.inputTextView.text {
  338. dcContext.setDraft(chatId: chatId, draftText: text)
  339. }
  340. }
  341. private func configureMessageMenu() {
  342. var menuItems: [UIMenuItem]
  343. menuItems = [
  344. UIMenuItem(title: String.localized("info"), action: #selector(MessageCollectionViewCell.messageInfo(_:))),
  345. UIMenuItem(title: String.localized("delete"), action: #selector(MessageCollectionViewCell.messageDelete(_:))),
  346. UIMenuItem(title: String.localized("forward"), action: #selector(MessageCollectionViewCell.messageForward(_:)))
  347. ]
  348. UIMenuController.shared.menuItems = menuItems
  349. }
  350. private func configureMessageCollectionView() {
  351. messagesCollectionView.messagesDataSource = self
  352. messagesCollectionView.messageCellDelegate = self
  353. scrollsToBottomOnKeyboardBeginsEditing = true // default false
  354. maintainPositionOnKeyboardFrameChanged = true // default false
  355. messagesCollectionView.backgroundColor = DcColors.chatBackgroundColor
  356. messagesCollectionView.addSubview(refreshControl)
  357. refreshControl.addTarget(self, action: #selector(loadMoreMessages), for: .valueChanged)
  358. let layout = messagesCollectionView.collectionViewLayout as? MessagesCollectionViewFlowLayout
  359. layout?.sectionInset = UIEdgeInsets(top: 0, left: 8, bottom: 2, right: 8)
  360. // Hide the outgoing avatar and adjust the label alignment to line up with the messages
  361. layout?.setMessageOutgoingAvatarSize(.zero)
  362. layout?.setMessageOutgoingMessageTopLabelAlignment(LabelAlignment(textAlignment: .right,
  363. textInsets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 8)))
  364. layout?.setMessageOutgoingMessageBottomLabelAlignment(LabelAlignment(textAlignment: .right,
  365. textInsets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 8)))
  366. // Set outgoing avatar to overlap with the message bubble
  367. layout?.setMessageIncomingMessageTopLabelAlignment(LabelAlignment(textAlignment: .left,
  368. textInsets: UIEdgeInsets(top: 0, left: 18, bottom: 0, right: 0)))
  369. layout?.setMessageIncomingAvatarSize(CGSize(width: 30, height: 30))
  370. layout?.setMessageIncomingMessagePadding(UIEdgeInsets(
  371. top: 0, left: -18, bottom: 0, right: 0))
  372. layout?.setMessageIncomingMessageBottomLabelAlignment(LabelAlignment(textAlignment: .left,
  373. textInsets: UIEdgeInsets(top: 0, left: 12, bottom: 0, right: 0)))
  374. layout?.setMessageIncomingAccessoryViewSize(CGSize(width: 30, height: 30))
  375. layout?.setMessageIncomingAccessoryViewPadding(HorizontalEdgeInsets(left: 8, right: 0))
  376. layout?.setMessageOutgoingAccessoryViewSize(CGSize(width: 30, height: 30))
  377. layout?.setMessageOutgoingAccessoryViewPadding(HorizontalEdgeInsets(left: 0, right: 8))
  378. messagesCollectionView.messagesLayoutDelegate = self
  379. messagesCollectionView.messagesDisplayDelegate = self
  380. }
  381. private func configureMessageInputBar() {
  382. messageInputBar.delegate = self
  383. messageInputBar.inputTextView.tintColor = DcColors.primary
  384. messageInputBar.inputTextView.placeholder = String.localized("chat_input_placeholder")
  385. messageInputBar.separatorLine.isHidden = true
  386. messageInputBar.inputTextView.tintColor = DcColors.primary
  387. messageInputBar.inputTextView.textColor = DcColors.defaultTextColor
  388. messageInputBar.backgroundView.backgroundColor = DcColors.chatBackgroundColor
  389. scrollsToBottomOnKeyboardBeginsEditing = true
  390. messageInputBar.inputTextView.backgroundColor = DcColors.inputFieldColor
  391. messageInputBar.inputTextView.placeholderTextColor = DcColors.placeholderColor
  392. messageInputBar.inputTextView.textContainerInset = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 38)
  393. messageInputBar.inputTextView.placeholderLabelInsets = UIEdgeInsets(top: 8, left: 20, bottom: 8, right: 38)
  394. messageInputBar.inputTextView.layer.borderColor = UIColor.themeColor(light: UIColor(red: 200 / 255, green: 200 / 255, blue: 200 / 255, alpha: 1),
  395. dark: UIColor(red: 55 / 255, green: 55/255, blue: 55/255, alpha: 1)).cgColor
  396. messageInputBar.inputTextView.layer.borderWidth = 1.0
  397. messageInputBar.inputTextView.layer.cornerRadius = 13.0
  398. messageInputBar.inputTextView.layer.masksToBounds = true
  399. messageInputBar.inputTextView.scrollIndicatorInsets = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0)
  400. configureInputBarItems()
  401. }
  402. private func configureInputBarItems() {
  403. messageInputBar.setLeftStackViewWidthConstant(to: 40, animated: false)
  404. messageInputBar.setRightStackViewWidthConstant(to: 40, animated: false)
  405. let sendButtonImage = UIImage(named: "paper_plane")?.withRenderingMode(.alwaysTemplate)
  406. messageInputBar.sendButton.image = sendButtonImage
  407. messageInputBar.sendButton.accessibilityLabel = String.localized("menu_send")
  408. messageInputBar.sendButton.accessibilityTraits = .button
  409. messageInputBar.sendButton.title = nil
  410. messageInputBar.sendButton.tintColor = UIColor(white: 1, alpha: 1)
  411. messageInputBar.sendButton.layer.cornerRadius = 20
  412. messageInputBar.middleContentViewPadding = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 10)
  413. // this adds a padding between textinputfield and send button
  414. messageInputBar.sendButton.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
  415. messageInputBar.sendButton.setSize(CGSize(width: 40, height: 40), animated: false)
  416. messageInputBar.padding = UIEdgeInsets(top: 6, left: 6, bottom: 6, right: 12)
  417. let leftItems = [
  418. InputBarButtonItem()
  419. .configure {
  420. $0.spacing = .fixed(0)
  421. let clipperIcon = #imageLiteral(resourceName: "ic_attach_file_36pt").withRenderingMode(.alwaysTemplate)
  422. $0.image = clipperIcon
  423. $0.tintColor = DcColors.primary
  424. $0.setSize(CGSize(width: 40, height: 40), animated: false)
  425. $0.accessibilityLabel = String.localized("menu_add_attachment")
  426. $0.accessibilityTraits = .button
  427. }.onSelected {
  428. $0.tintColor = UIColor.themeColor(light: .lightGray, dark: .darkGray)
  429. }.onDeselected {
  430. $0.tintColor = DcColors.primary
  431. }.onTouchUpInside { _ in
  432. self.clipperButtonPressed()
  433. }
  434. ]
  435. messageInputBar.setStackViewItems(leftItems, forStack: .left, animated: false)
  436. // This just adds some more flare
  437. messageInputBar.sendButton
  438. .onEnabled { item in
  439. UIView.animate(withDuration: 0.3, animations: {
  440. item.backgroundColor = DcColors.primary
  441. })
  442. }.onDisabled { item in
  443. UIView.animate(withDuration: 0.3, animations: {
  444. item.backgroundColor = DcColors.colorDisabled
  445. })
  446. }
  447. }
  448. @objc private func chatProfilePressed() {
  449. if chatId != DC_CHAT_ID_DEADDROP {
  450. showChatDetail(chatId: chatId)
  451. }
  452. }
  453. // MARK: - UICollectionViewDataSource
  454. public override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  455. guard let messagesCollectionView = collectionView as? MessagesCollectionView else {
  456. fatalError("notMessagesCollectionView")
  457. }
  458. guard let messagesDataSource = messagesCollectionView.messagesDataSource else {
  459. fatalError("nilMessagesDataSource")
  460. }
  461. let message = messagesDataSource.messageForItem(at: indexPath, in: messagesCollectionView)
  462. switch message.kind {
  463. case .text, .attributedText, .emoji:
  464. let cell = messagesCollectionView.dequeueReusableCell(TextMessageCell.self, for: indexPath)
  465. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  466. return cell
  467. case .info:
  468. let cell = messagesCollectionView.dequeueReusableCell(InfoMessageCell.self, for: indexPath)
  469. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  470. return cell
  471. case .photo, .video:
  472. let cell = messagesCollectionView.dequeueReusableCell(MediaMessageCell.self, for: indexPath)
  473. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  474. return cell
  475. case .photoText, .videoText:
  476. let cell = messagesCollectionView.dequeueReusableCell(TextMediaMessageCell.self, for: indexPath)
  477. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  478. return cell
  479. case .animatedImageText:
  480. let cell = messagesCollectionView.dequeueReusableCell(AnimatedImageMessageCell.self, for: indexPath)
  481. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  482. return cell
  483. case .fileText:
  484. let cell = messagesCollectionView.dequeueReusableCell(FileMessageCell.self, for: indexPath)
  485. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  486. return cell
  487. case .location:
  488. let cell = messagesCollectionView.dequeueReusableCell(LocationMessageCell.self, for: indexPath)
  489. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  490. return cell
  491. case .contact:
  492. let cell = messagesCollectionView.dequeueReusableCell(ContactMessageCell.self, for: indexPath)
  493. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  494. return cell
  495. case .custom:
  496. let cell = messagesCollectionView.dequeueReusableCell(InfoMessageCell.self, for: indexPath)
  497. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  498. return cell
  499. case .audio:
  500. let cell = messagesCollectionView.dequeueReusableCell(AudioMessageCell.self, for: indexPath)
  501. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  502. return cell
  503. }
  504. }
  505. override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
  506. if action == NSSelectorFromString("messageInfo:") ||
  507. action == NSSelectorFromString("messageDelete:") ||
  508. action == NSSelectorFromString("messageForward:") {
  509. return true
  510. } else {
  511. return super.collectionView(collectionView, canPerformAction: action, forItemAt: indexPath, withSender: sender)
  512. }
  513. }
  514. override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
  515. switch action {
  516. case NSSelectorFromString("messageInfo:"):
  517. let msg = messageList[indexPath.section]
  518. logger.info("message: View info \(msg.messageId)")
  519. let msgViewController = MessageInfoViewController(dcContext: dcContext, message: msg)
  520. if let ctrl = navigationController {
  521. ctrl.pushViewController(msgViewController, animated: true)
  522. }
  523. case NSSelectorFromString("messageDelete:"):
  524. let msg = messageList[indexPath.section]
  525. logger.info("message: delete \(msg.messageId)")
  526. askToDeleteMessage(id: msg.id)
  527. case NSSelectorFromString("messageForward:"):
  528. let msg = messageList[indexPath.section]
  529. RelayHelper.sharedInstance.setForwardMessage(messageId: msg.id)
  530. navigationController?.popViewController(animated: true)
  531. default:
  532. super.collectionView(collectionView, performAction: action, forItemAt: indexPath, withSender: sender)
  533. }
  534. }
  535. private func confirmationAlert(title: String, actionTitle: String, actionStyle: UIAlertAction.Style = .default, actionHandler: @escaping ((UIAlertAction) -> Void), cancelHandler: ((UIAlertAction) -> Void)? = nil) {
  536. let alert = UIAlertController(title: title,
  537. message: nil,
  538. preferredStyle: .safeActionSheet)
  539. alert.addAction(UIAlertAction(title: actionTitle, style: actionStyle, handler: actionHandler))
  540. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: cancelHandler ?? { _ in
  541. self.dismiss(animated: true, completion: nil)
  542. }))
  543. present(alert, animated: true, completion: nil)
  544. }
  545. private func askToChatWith(email: String) {
  546. let contactId = self.dcContext.createContact(name: "", email: email)
  547. if dcContext.getChatIdByContactId(contactId: contactId) != 0 {
  548. self.dismiss(animated: true, completion: nil)
  549. let chatId = self.dcContext.createChatByContactId(contactId: contactId)
  550. self.showChat(chatId: chatId)
  551. } else {
  552. confirmationAlert(title: String.localizedStringWithFormat(String.localized("ask_start_chat_with"), email),
  553. actionTitle: String.localized("start_chat"),
  554. actionHandler: { _ in
  555. self.dismiss(animated: true, completion: nil)
  556. let chatId = self.dcContext.createChatByContactId(contactId: contactId)
  557. self.showChat(chatId: chatId)})
  558. }
  559. }
  560. private func askToDeleteMessage(id: Int) {
  561. let title = String.localized(stringID: "ask_delete_messages", count: 1)
  562. confirmationAlert(title: title, actionTitle: String.localized("delete"), actionStyle: .destructive,
  563. actionHandler: { _ in
  564. self.dcContext.deleteMessage(msgId: id)
  565. self.dismiss(animated: true, completion: nil)})
  566. }
  567. private func askToForwardMessage() {
  568. let chat = dcContext.getChat(chatId: self.chatId)
  569. if chat.isSelfTalk {
  570. RelayHelper.sharedInstance.forward(to: self.chatId)
  571. } else {
  572. confirmationAlert(title: String.localizedStringWithFormat(String.localized("ask_forward"), chat.name),
  573. actionTitle: String.localized("menu_forward"),
  574. actionHandler: { _ in
  575. RelayHelper.sharedInstance.forward(to: self.chatId)
  576. self.dismiss(animated: true, completion: nil)},
  577. cancelHandler: { _ in
  578. self.dismiss(animated: false, completion: nil)
  579. self.navigationController?.popViewController(animated: true)})
  580. }
  581. }
  582. // MARK: - coordinator
  583. private func showChatDetail(chatId: Int) {
  584. let chat = dcContext.getChat(chatId: chatId)
  585. switch chat.chatType {
  586. case .SINGLE:
  587. if let contactId = chat.contactIds.first {
  588. let contactDetailController = ContactDetailViewController(dcContext: dcContext, contactId: contactId)
  589. navigationController?.pushViewController(contactDetailController, animated: true)
  590. }
  591. case .GROUP, .VERIFIEDGROUP:
  592. let groupChatDetailViewController = GroupChatDetailViewController(chatId: chatId, dcContext: dcContext)
  593. navigationController?.pushViewController(groupChatDetailViewController, animated: true)
  594. }
  595. }
  596. private func showContactDetail(of contactId: Int, in chatOfType: ChatType, chatId: Int?) {
  597. let contactDetailController = ContactDetailViewController(dcContext: dcContext, contactId: contactId)
  598. navigationController?.pushViewController(contactDetailController, animated: true)
  599. }
  600. func showChat(chatId: Int) {
  601. if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
  602. navigationController?.popToRootViewController(animated: false)
  603. appDelegate.appCoordinator.showChat(chatId: chatId)
  604. }
  605. }
  606. private func showDocumentLibrary(delegate: MediaPickerDelegate) {
  607. mediaPicker?.showDocumentLibrary(delegate: delegate)
  608. }
  609. private func showVoiceMessageRecorder(delegate: MediaPickerDelegate) {
  610. mediaPicker?.showVoiceRecorder(delegate: delegate)
  611. }
  612. private func showCameraViewController(delegate: MediaPickerDelegate) {
  613. mediaPicker?.showCamera(delegate: delegate, allowCropping: false)
  614. }
  615. private func showPhotoVideoLibrary(delegate: MediaPickerDelegate) {
  616. mediaPicker?.showPhotoVideoLibrary(delegate: delegate)
  617. }
  618. private func showMediaGallery(currentIndex: Int, mediaUrls urls: [URL]) {
  619. let betterPreviewController = PreviewController(currentIndex: currentIndex, urls: urls)
  620. let nav = UINavigationController(rootViewController: betterPreviewController)
  621. nav.modalPresentationStyle = .fullScreen
  622. navigationController?.present(nav, animated: true)
  623. }
  624. }
  625. // MARK: - MessagesDataSource
  626. extension ChatViewController: MessagesDataSource {
  627. func numberOfSections(in _: MessagesCollectionView) -> Int {
  628. return messageList.count
  629. }
  630. func currentSender() -> SenderType {
  631. let currentSender = Sender(senderId: "1", displayName: "Alice")
  632. return currentSender
  633. }
  634. func messageForItem(at indexPath: IndexPath, in _: MessagesCollectionView) -> MessageType {
  635. return messageList[indexPath.section]
  636. }
  637. func avatar(for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> Avatar {
  638. let message = messageList[indexPath.section]
  639. let contact = message.fromContact
  640. return Avatar(image: contact.profileImage, initials: DcUtils.getInitials(inputName: contact.displayName))
  641. }
  642. func cellTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
  643. if isInfoMessage(at: indexPath) {
  644. return nil
  645. }
  646. if isTimeLabelVisible(at: indexPath) {
  647. return NSAttributedString(
  648. string: MessageKitDateFormatter.shared.string(from: message.sentDate),
  649. attributes: [
  650. NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 10),
  651. NSAttributedString.Key.foregroundColor: DcColors.grayTextColor,
  652. ]
  653. )
  654. }
  655. return nil
  656. }
  657. func messageTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
  658. var attributedString: NSMutableAttributedString?
  659. if showNamesAboveMessage && !isPreviousMessageSameSender(at: indexPath) {
  660. let name = message.sender.displayName
  661. let m = messageList[indexPath.section]
  662. attributedString = NSMutableAttributedString(string: name, attributes: [
  663. .font: UIFont.systemFont(ofSize: 14),
  664. .foregroundColor: m.fromContact.color,
  665. ])
  666. }
  667. if isMessageForwarded(at: indexPath) {
  668. let forwardedString = NSMutableAttributedString(string: String.localized("forwarded_message"), attributes: [
  669. .font: UIFont.systemFont(ofSize: 14),
  670. .foregroundColor: DcColors.grayTextColor,
  671. ])
  672. if attributedString == nil {
  673. attributedString = forwardedString
  674. } else {
  675. attributedString?.append(NSAttributedString(string: "\n", attributes: nil))
  676. attributedString?.append(forwardedString)
  677. }
  678. }
  679. return attributedString
  680. }
  681. func isMessageForwarded(at indexPath: IndexPath) -> Bool {
  682. let m = messageList[indexPath.section]
  683. return m.isForwarded
  684. }
  685. func isTimeLabelVisible(at indexPath: IndexPath) -> Bool {
  686. guard indexPath.section + 1 < messageList.count else { return false }
  687. let messageA = messageList[indexPath.section]
  688. let messageB = messageList[indexPath.section + 1]
  689. if messageA.fromContactId == messageB.fromContactId {
  690. return false
  691. }
  692. let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)
  693. let dateA = messageA.sentDate
  694. let dateB = messageB.sentDate
  695. let dayA = (calendar?.component(.day, from: dateA))
  696. let dayB = (calendar?.component(.day, from: dateB))
  697. return dayA != dayB
  698. }
  699. func isPreviousMessageSameSender(at indexPath: IndexPath) -> Bool {
  700. guard indexPath.section - 1 >= 0 else { return false }
  701. let messageA = messageList[indexPath.section - 1]
  702. let messageB = messageList[indexPath.section]
  703. if messageA.isInfo {
  704. return false
  705. }
  706. return messageA.fromContactId == messageB.fromContactId
  707. }
  708. func isInfoMessage(at indexPath: IndexPath) -> Bool {
  709. return messageList[indexPath.section].isInfo
  710. }
  711. func isImmediateNextMessageSameSender(at indexPath: IndexPath) -> Bool {
  712. guard indexPath.section + 1 < messageList.count else { return false }
  713. let messageA = messageList[indexPath.section]
  714. let messageB = messageList[indexPath.section + 1]
  715. if messageA.isInfo {
  716. return false
  717. }
  718. let dateA = messageA.sentDate
  719. let dateB = messageB.sentDate
  720. let timeinterval = dateB.timeIntervalSince(dateA)
  721. let minute = 60.0
  722. return messageA.fromContactId == messageB.fromContactId && timeinterval.isLessThanOrEqualTo(minute)
  723. }
  724. func isAvatarHidden(at indexPath: IndexPath) -> Bool {
  725. let message = messageList[indexPath.section]
  726. return isNextMessageSameSender(at: indexPath) || message.isInfo
  727. }
  728. func isNextMessageSameSender(at indexPath: IndexPath) -> Bool {
  729. guard indexPath.section + 1 < messageList.count else { return false }
  730. let messageA = messageList[indexPath.section]
  731. let messageB = messageList[indexPath.section + 1]
  732. if messageA.isInfo {
  733. return false
  734. }
  735. return messageA.fromContactId == messageB.fromContactId
  736. }
  737. func messageBottomLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
  738. guard indexPath.section < messageList.count else { return nil }
  739. let m = messageList[indexPath.section]
  740. if m.isInfo || isImmediateNextMessageSameSender(at: indexPath) {
  741. return nil
  742. }
  743. var timestampAttributes: [NSAttributedString.Key: Any] = [
  744. .font: UIFont.systemFont(ofSize: 12),
  745. .foregroundColor: DcColors.grayDateColor,
  746. .paragraphStyle: NSParagraphStyle()
  747. ]
  748. let text = NSMutableAttributedString()
  749. if isFromCurrentSender(message: message) {
  750. if let style = NSMutableParagraphStyle.default.mutableCopy() as? NSMutableParagraphStyle {
  751. style.alignment = .right
  752. timestampAttributes[.paragraphStyle] = style
  753. }
  754. text.append(NSAttributedString(string: m.formattedSentDate(), attributes: timestampAttributes))
  755. if m.showPadlock() {
  756. attachPadlock(to: text)
  757. }
  758. attachSendingState(m.state, to: text)
  759. return text
  760. }
  761. if !isAvatarHidden(at: indexPath) {
  762. if let style = NSMutableParagraphStyle.default.mutableCopy() as? NSMutableParagraphStyle {
  763. style.firstLineHeadIndent = 22
  764. timestampAttributes[.paragraphStyle] = style
  765. }
  766. }
  767. text.append(NSAttributedString(string: m.formattedSentDate(), attributes: timestampAttributes))
  768. if m.showPadlock() {
  769. attachPadlock(to: text)
  770. }
  771. return text
  772. }
  773. private func attachPadlock(to text: NSMutableAttributedString) {
  774. let imageAttachment = NSTextAttachment()
  775. imageAttachment.image = UIImage(named: "ic_lock")
  776. imageAttachment.image?.accessibilityIdentifier = String.localized("encrypted_message")
  777. let imageString = NSMutableAttributedString(attachment: imageAttachment)
  778. imageString.addAttributes([NSAttributedString.Key.baselineOffset: -1], range: NSRange(location: 0, length: 1))
  779. text.append(NSAttributedString(string: " "))
  780. text.append(imageString)
  781. }
  782. private func attachSendingState(_ state: Int, to text: NSMutableAttributedString) {
  783. let imageAttachment = NSTextAttachment()
  784. var offset = -4
  785. switch Int32(state) {
  786. case DC_STATE_OUT_PENDING, DC_STATE_OUT_PREPARING:
  787. imageAttachment.image = #imageLiteral(resourceName: "ic_hourglass_empty_36pt").scaleDownImage(toMax: 16)
  788. imageAttachment.image?.accessibilityIdentifier = String.localized("a11y_delivery_status_sending")
  789. offset = -2
  790. case DC_STATE_OUT_DELIVERED:
  791. imageAttachment.image = #imageLiteral(resourceName: "ic_done_36pt").scaleDownImage(toMax: 18)
  792. imageAttachment.image?.accessibilityIdentifier = String.localized("a11y_delivery_status_delivered")
  793. case DC_STATE_OUT_MDN_RCVD:
  794. imageAttachment.image = #imageLiteral(resourceName: "ic_done_all_36pt").scaleDownImage(toMax: 18)
  795. imageAttachment.image?.accessibilityIdentifier = String.localized("a11y_delivery_status_read")
  796. text.append(NSAttributedString(string: " "))
  797. case DC_STATE_OUT_FAILED:
  798. imageAttachment.image = #imageLiteral(resourceName: "ic_error_36pt").scaleDownImage(toMax: 16)
  799. imageAttachment.image?.accessibilityIdentifier = String.localized("a11y_delivery_status_error")
  800. offset = -2
  801. default:
  802. imageAttachment.image = nil
  803. }
  804. let imageString = NSMutableAttributedString(attachment: imageAttachment)
  805. imageString.addAttributes([.baselineOffset: offset],
  806. range: NSRange(location: 0, length: 1))
  807. text.append(imageString)
  808. }
  809. func updateMessage(_ messageId: Int) {
  810. if let index = messageList.firstIndex(where: { $0.id == messageId }) {
  811. dcContext.markSeenMessages(messageIds: [UInt32(messageId)])
  812. messageList[index] = DcMsg(id: messageId)
  813. // Reload section to update header/footer labels
  814. messagesCollectionView.performBatchUpdates({
  815. messagesCollectionView.reloadSections([index])
  816. if index > 0 {
  817. messagesCollectionView.reloadSections([index - 1])
  818. }
  819. if index < messageList.count - 1 {
  820. messagesCollectionView.reloadSections([index + 1])
  821. }
  822. }, completion: { [weak self] _ in
  823. if self?.isLastSectionVisible() == true {
  824. self?.messagesCollectionView.scrollToBottom(animated: true)
  825. }
  826. })
  827. } else {
  828. let msg = DcMsg(id: messageId)
  829. if msg.chatId == chatId {
  830. insertMessage(msg)
  831. }
  832. }
  833. }
  834. func insertMessage(_ message: DcMsg) {
  835. dcContext.markSeenMessages(messageIds: [UInt32(message.id)])
  836. messageList.append(message)
  837. emptyStateView.isHidden = true
  838. // Reload last section to update header/footer labels and insert a new one
  839. messagesCollectionView.performBatchUpdates({
  840. messagesCollectionView.insertSections([messageList.count - 1])
  841. if messageList.count >= 2 {
  842. messagesCollectionView.reloadSections([messageList.count - 2])
  843. }
  844. }, completion: { [weak self] _ in
  845. if self?.isLastSectionVisible() == true {
  846. self?.messagesCollectionView.scrollToBottom(animated: true)
  847. }
  848. })
  849. }
  850. private func sendTextMessage(message: String) {
  851. DispatchQueue.global().async {
  852. self.dcContext.sendTextInChat(id: self.chatId, message: message)
  853. }
  854. }
  855. private func sendImage(_ image: UIImage, message: String? = nil) {
  856. DispatchQueue.global().async {
  857. if let compressedImage = image.dcCompress() {
  858. // at this point image is compressed by 85% by default
  859. let pixelSize = compressedImage.imageSizeInPixel()
  860. let path = DcUtils.saveImage(image: compressedImage)
  861. let msg = DcMsg(viewType: DC_MSG_IMAGE)
  862. msg.setFile(filepath: path, mimeType: "image/jpeg")
  863. msg.setDimension(width: pixelSize.width, height: pixelSize.height)
  864. msg.text = (message ?? "").isEmpty ? nil : message
  865. msg.sendInChat(id: self.chatId)
  866. }
  867. }
  868. }
  869. private func sendDocumentMessage(url: NSURL) {
  870. DispatchQueue.global().async {
  871. let msg = DcMsg(viewType: DC_MSG_FILE)
  872. msg.setFile(filepath: url.relativePath, mimeType: nil)
  873. msg.sendInChat(id: self.chatId)
  874. }
  875. }
  876. private func sendVoiceMessage(url: NSURL) {
  877. DispatchQueue.global().async {
  878. let msg = DcMsg(viewType: DC_MSG_VOICE)
  879. msg.setFile(filepath: url.relativePath, mimeType: "audio/m4a")
  880. msg.sendInChat(id: self.chatId)
  881. }
  882. }
  883. private func sendVideo(url: NSURL) {
  884. DispatchQueue.global().async {
  885. let msg = DcMsg(viewType: DC_MSG_VIDEO)
  886. msg.setFile(filepath: url.relativePath, mimeType: "video/mp4")
  887. msg.sendInChat(id: self.chatId)
  888. }
  889. }
  890. private func sendImage(url: NSURL) {
  891. if let data = try? Data(contentsOf: url as URL) {
  892. if let image = UIImage(data: data) {
  893. sendImage(image)
  894. }
  895. }
  896. }
  897. func isLastSectionVisible() -> Bool {
  898. guard !messageList.isEmpty else { return false }
  899. let lastIndexPath = IndexPath(item: 0, section: messageList.count - 1)
  900. return messagesCollectionView.indexPathsForVisibleItems.contains(lastIndexPath)
  901. }
  902. }
  903. // MARK: - MessagesDisplayDelegate
  904. extension ChatViewController: MessagesDisplayDelegate {
  905. // MARK: - Text Messages
  906. func textColor(for _: MessageType, at _: IndexPath, in _: MessagesCollectionView) -> UIColor {
  907. return DcColors.defaultTextColor
  908. }
  909. // MARK: - All Messages
  910. func backgroundColor(for message: MessageType, at _: IndexPath, in _: MessagesCollectionView) -> UIColor {
  911. return isFromCurrentSender(message: message) ? DcColors.messagePrimaryColor : DcColors.messageSecondaryColor
  912. }
  913. func messageStyle(for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> MessageStyle {
  914. if isInfoMessage(at: indexPath) {
  915. //styling is hard-coded in info cell
  916. return .none
  917. }
  918. var corners: UIRectCorner = []
  919. if isFromCurrentSender(message: message) {
  920. corners.formUnion(.topLeft)
  921. corners.formUnion(.bottomLeft)
  922. if !isPreviousMessageSameSender(at: indexPath) {
  923. corners.formUnion(.topRight)
  924. }
  925. if !isNextMessageSameSender(at: indexPath) {
  926. corners.formUnion(.bottomRight)
  927. }
  928. } else {
  929. corners.formUnion(.topRight)
  930. corners.formUnion(.bottomRight)
  931. if !isPreviousMessageSameSender(at: indexPath) {
  932. corners.formUnion(.topLeft)
  933. }
  934. if !isNextMessageSameSender(at: indexPath) {
  935. corners.formUnion(.bottomLeft)
  936. }
  937. }
  938. return .custom { view in
  939. let radius: CGFloat = 16
  940. let path = UIBezierPath(roundedRect: view.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
  941. let mask = CAShapeLayer()
  942. mask.path = path.cgPath
  943. view.layer.mask = mask
  944. }
  945. }
  946. func configureAvatarView(_ avatarView: AvatarView, for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) {
  947. let message = messageList[indexPath.section]
  948. let contact = message.fromContact
  949. let avatar = Avatar(image: contact.profileImage, initials: DcUtils.getInitials(inputName: contact.displayName))
  950. avatarView.set(avatar: avatar)
  951. avatarView.isHidden = isAvatarHidden(at: indexPath)
  952. avatarView.backgroundColor = contact.color
  953. }
  954. func enabledDetectors(for _: MessageType, at _: IndexPath, in _: MessagesCollectionView) -> [DetectorType] {
  955. return [.url, .phoneNumber]
  956. }
  957. func detectorAttributes(for detector: DetectorType, and message: MessageType, at indexPath: IndexPath) -> [NSAttributedString.Key: Any] {
  958. return [ NSAttributedString.Key.foregroundColor: DcColors.defaultTextColor,
  959. NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue,
  960. NSAttributedString.Key.underlineColor: DcColors.defaultTextColor ]
  961. }
  962. }
  963. // MARK: - MessagesLayoutDelegate
  964. extension ChatViewController: MessagesLayoutDelegate {
  965. func cellTopLabelHeight(for _: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> CGFloat {
  966. if isTimeLabelVisible(at: indexPath) {
  967. return 18
  968. }
  969. return 0
  970. }
  971. func messageTopLabelHeight(for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> CGFloat {
  972. if isInfoMessage(at: indexPath) {
  973. return 0
  974. }
  975. if !isPreviousMessageSameSender(at: indexPath) {
  976. return 40
  977. } else if isMessageForwarded(at: indexPath) {
  978. return 20
  979. }
  980. return 0
  981. }
  982. func messageBottomLabelHeight(for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> CGFloat {
  983. if isInfoMessage(at: indexPath) {
  984. return 0
  985. }
  986. if !isImmediateNextMessageSameSender(at: indexPath) {
  987. return 16
  988. }
  989. return 0
  990. }
  991. func heightForLocation(message _: MessageType, at _: IndexPath, with _: CGFloat, in _: MessagesCollectionView) -> CGFloat {
  992. return 40
  993. }
  994. func footerViewSize(for _: MessageType, at _: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGSize {
  995. return CGSize(width: messagesCollectionView.bounds.width, height: 20)
  996. }
  997. @objc private func clipperButtonPressed() {
  998. showClipperOptions()
  999. }
  1000. private func showClipperOptions() {
  1001. let alert = UIAlertController(title: nil, message: nil, preferredStyle: .safeActionSheet)
  1002. let galleryAction = PhotoPickerAlertAction(title: String.localized("gallery"), style: .default, handler: galleryButtonPressed(_:))
  1003. let cameraAction = PhotoPickerAlertAction(title: String.localized("camera"), style: .default, handler: cameraButtonPressed(_:))
  1004. let documentAction = UIAlertAction(title: String.localized("documents"), style: .default, handler: documentActionPressed(_:))
  1005. let voiceMessageAction = UIAlertAction(title: String.localized("voice_message"), style: .default, handler: voiceMessageButtonPressed(_:))
  1006. let isLocationStreaming = dcContext.isSendingLocationsToChat(chatId: chatId)
  1007. let locationStreamingAction = UIAlertAction(title: isLocationStreaming ? String.localized("stop_sharing_location") : String.localized("location"),
  1008. style: isLocationStreaming ? .destructive : .default,
  1009. handler: locationStreamingButtonPressed(_:))
  1010. alert.addAction(cameraAction)
  1011. alert.addAction(galleryAction)
  1012. alert.addAction(documentAction)
  1013. alert.addAction(voiceMessageAction)
  1014. if UserDefaults.standard.bool(forKey: "location_streaming") {
  1015. alert.addAction(locationStreamingAction)
  1016. }
  1017. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  1018. self.present(alert, animated: true, completion: {
  1019. // unfortunately, voiceMessageAction.accessibilityHint does not work,
  1020. // but this hack does the trick
  1021. if UIAccessibility.isVoiceOverRunning {
  1022. if let view = voiceMessageAction.value(forKey: "__representer") as? UIView {
  1023. view.accessibilityHint = String.localized("a11y_voice_message_hint_ios")
  1024. }
  1025. }
  1026. })
  1027. }
  1028. private func documentActionPressed(_ action: UIAlertAction) {
  1029. showDocumentLibrary(delegate: self)
  1030. }
  1031. private func voiceMessageButtonPressed(_ action: UIAlertAction) {
  1032. showVoiceMessageRecorder(delegate: self)
  1033. }
  1034. private func cameraButtonPressed(_ action: UIAlertAction) {
  1035. showCameraViewController(delegate: self)
  1036. }
  1037. private func galleryButtonPressed(_ action: UIAlertAction) {
  1038. showPhotoVideoLibrary(delegate: self)
  1039. }
  1040. private func locationStreamingButtonPressed(_ action: UIAlertAction) {
  1041. let isLocationStreaming = dcContext.isSendingLocationsToChat(chatId: chatId)
  1042. if isLocationStreaming {
  1043. locationStreamingFor(seconds: 0)
  1044. } else {
  1045. let alert = UIAlertController(title: String.localized("title_share_location"), message: nil, preferredStyle: .safeActionSheet)
  1046. addDurationSelectionAction(to: alert, key: "share_location_for_5_minutes", duration: Time.fiveMinutes)
  1047. addDurationSelectionAction(to: alert, key: "share_location_for_30_minutes", duration: Time.thirtyMinutes)
  1048. addDurationSelectionAction(to: alert, key: "share_location_for_one_hour", duration: Time.oneHour)
  1049. addDurationSelectionAction(to: alert, key: "share_location_for_two_hours", duration: Time.twoHours)
  1050. addDurationSelectionAction(to: alert, key: "share_location_for_six_hours", duration: Time.sixHours)
  1051. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  1052. self.present(alert, animated: true, completion: nil)
  1053. }
  1054. }
  1055. private func addDurationSelectionAction(to alert: UIAlertController, key: String, duration: Int) {
  1056. let action = UIAlertAction(title: String.localized(key), style: .default, handler: { _ in
  1057. self.locationStreamingFor(seconds: duration)
  1058. })
  1059. alert.addAction(action)
  1060. }
  1061. private func locationStreamingFor(seconds: Int) {
  1062. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
  1063. return
  1064. }
  1065. self.dcContext.sendLocationsToChat(chatId: self.chatId, seconds: seconds)
  1066. appDelegate.locationManager.shareLocation(chatId: self.chatId, duration: seconds)
  1067. }
  1068. }
  1069. // MARK: - MessageCellDelegate
  1070. extension ChatViewController: MessageCellDelegate {
  1071. @objc func didTapMessage(in cell: MessageCollectionViewCell) {
  1072. if let indexPath = messagesCollectionView.indexPath(for: cell) {
  1073. let message = messageList[indexPath.section]
  1074. if message.isSetupMessage {
  1075. didTapAsm(msg: message, orgText: "")
  1076. } else if let url = message.fileURL {
  1077. // find all other messages with same message type
  1078. let previousUrls: [URL] = message.previousMediaURLs()
  1079. let nextUrls: [URL] = message.nextMediaURLs()
  1080. // these are the files user will be able to swipe trough
  1081. let mediaUrls: [URL] = previousUrls + [url] + nextUrls
  1082. showMediaGallery(currentIndex: previousUrls.count, mediaUrls: mediaUrls)
  1083. }
  1084. }
  1085. }
  1086. private func didTapAsm(msg: DcMsg, orgText: String) {
  1087. let inputDlg = UIAlertController(
  1088. title: String.localized("autocrypt_continue_transfer_title"),
  1089. message: String.localized("autocrypt_continue_transfer_please_enter_code"),
  1090. preferredStyle: .alert)
  1091. inputDlg.addTextField(configurationHandler: { (textField) in
  1092. textField.placeholder = msg.setupCodeBegin + ".."
  1093. textField.text = orgText
  1094. textField.keyboardType = UIKeyboardType.numbersAndPunctuation // allows entering spaces; decimalPad would require a mask to keep things readable
  1095. })
  1096. inputDlg.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  1097. let okAction = UIAlertAction(title: String.localized("ok"), style: .default, handler: { _ in
  1098. let textField = inputDlg.textFields![0]
  1099. let modText = textField.text ?? ""
  1100. let success = self.dcContext.continueKeyTransfer(msgId: msg.id, setupCode: modText)
  1101. let alert = UIAlertController(
  1102. title: String.localized("autocrypt_continue_transfer_title"),
  1103. message: String.localized(success ? "autocrypt_continue_transfer_succeeded" : "autocrypt_bad_setup_code"),
  1104. preferredStyle: .alert)
  1105. if success {
  1106. alert.addAction(UIAlertAction(title: String.localized("ok"), style: .default, handler: nil))
  1107. } else {
  1108. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  1109. let retryAction = UIAlertAction(title: String.localized("autocrypt_continue_transfer_retry"), style: .default, handler: { _ in
  1110. self.didTapAsm(msg: msg, orgText: modText)
  1111. })
  1112. alert.addAction(retryAction)
  1113. alert.preferredAction = retryAction
  1114. }
  1115. self.navigationController?.present(alert, animated: true, completion: nil)
  1116. })
  1117. inputDlg.addAction(okAction)
  1118. inputDlg.preferredAction = okAction // without setting preferredAction, cancel become shown *bold* as the preferred action
  1119. navigationController?.present(inputDlg, animated: true, completion: nil)
  1120. }
  1121. @objc func didTapAvatar(in cell: MessageCollectionViewCell) {
  1122. if let indexPath = messagesCollectionView.indexPath(for: cell) {
  1123. let message = messageList[indexPath.section]
  1124. let chat = dcContext.getChat(chatId: chatId)
  1125. showContactDetail(of: message.fromContact.id, in: chat.chatType, chatId: chatId)
  1126. }
  1127. }
  1128. @objc(didTapCellTopLabelIn:) func didTapCellTopLabel(in _: MessageCollectionViewCell) {
  1129. logger.info("Top label tapped")
  1130. }
  1131. @objc(didTapCellBottomLabelIn:) func didTapCellBottomLabel(in _: MessageCollectionViewCell) {
  1132. print("Bottom label tapped")
  1133. }
  1134. func didTapPlayButton(in cell: AudioMessageCell) {
  1135. guard let indexPath = messagesCollectionView.indexPath(for: cell),
  1136. let message = messagesCollectionView.messagesDataSource?.messageForItem(at: indexPath, in: messagesCollectionView) else {
  1137. print("Failed to identify message when audio cell receive tap gesture")
  1138. return
  1139. }
  1140. guard audioController.state != .stopped else {
  1141. // There is no audio sound playing - prepare to start playing for given audio message
  1142. audioController.playSound(for: message, in: cell)
  1143. return
  1144. }
  1145. if audioController.playingMessage?.messageId == message.messageId {
  1146. // tap occur in the current cell that is playing audio sound
  1147. if audioController.state == .playing {
  1148. audioController.pauseSound(for: message, in: cell)
  1149. } else {
  1150. audioController.resumeSound()
  1151. }
  1152. } else {
  1153. // tap occur in a difference cell that the one is currently playing sound. First stop currently playing and start the sound for given message
  1154. audioController.stopAnyOngoingPlaying()
  1155. audioController.playSound(for: message, in: cell)
  1156. }
  1157. }
  1158. func didStartAudio(in cell: AudioMessageCell) {
  1159. print("audio started")
  1160. }
  1161. func didStopAudio(in cell: AudioMessageCell) {
  1162. print("audio stopped")
  1163. }
  1164. func didPauseAudio(in cell: AudioMessageCell) {
  1165. print("audio paused")
  1166. }
  1167. @objc func didTapBackground(in cell: MessageCollectionViewCell) {
  1168. print("background of message tapped")
  1169. }
  1170. }
  1171. // MARK: - MessageLabelDelegate
  1172. extension ChatViewController: MessageLabelDelegate {
  1173. func didSelectPhoneNumber(_ phoneNumber: String) {
  1174. logger.info("phone open", phoneNumber)
  1175. if let escapedPhoneNumber = phoneNumber.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
  1176. if let url = NSURL(string: "tel:\(escapedPhoneNumber)") {
  1177. UIApplication.shared.open(url as URL)
  1178. }
  1179. }
  1180. }
  1181. func didSelectURL(_ url: URL) {
  1182. if Utils.isEmail(url: url) {
  1183. print("tapped on contact")
  1184. let email = Utils.getEmailFrom(url)
  1185. self.askToChatWith(email: email)
  1186. ///TODO: implement handling
  1187. } else {
  1188. UIApplication.shared.open(url)
  1189. }
  1190. }
  1191. }
  1192. // MARK: - LocationMessageDisplayDelegate
  1193. /*
  1194. extension ChatViewController: LocationMessageDisplayDelegate {
  1195. func annotationViewForLocation(message: MessageType, at indexPath: IndexPath, in messageCollectionView: MessagesCollectionView) -> MKAnnotationView? {
  1196. let annotationView = MKAnnotationView(annotation: nil, reuseIdentifier: nil)
  1197. let pinImage = #imageLiteral(resourceName: "ic_block_36pt").withRenderingMode(.alwaysTemplate)
  1198. annotationView.image = pinImage
  1199. annotationView.centerOffset = CGPoint(x: 0, y: -pinImage.size.height / 2)
  1200. return annotationView
  1201. }
  1202. func animationBlockForLocation(message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> ((UIImageView) -> Void)? {
  1203. return { view in
  1204. view.layer.transform = CATransform3DMakeScale(0, 0, 0)
  1205. view.alpha = 0.0
  1206. UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0, options: [], animations: {
  1207. view.layer.transform = CATransform3DIdentity
  1208. view.alpha = 1.0
  1209. }, completion: nil)
  1210. }
  1211. }
  1212. }
  1213. */
  1214. // MARK: - MessageInputBarDelegate
  1215. extension ChatViewController: InputBarAccessoryViewDelegate {
  1216. func inputBar(_ inputBar: InputBarAccessoryView, didPressSendButtonWith text: String) {
  1217. if inputBar.inputTextView.images.isEmpty {
  1218. self.sendTextMessage(message: text.trimmingCharacters(in: .whitespacesAndNewlines))
  1219. } else {
  1220. let trimmedText = text.replacingOccurrences(of: "\u{FFFC}", with: "", options: .literal, range: nil)
  1221. .trimmingCharacters(in: .whitespacesAndNewlines)
  1222. // only 1 attachment allowed for now, thus it takes the first one
  1223. self.sendImage(inputBar.inputTextView.images[0], message: trimmedText)
  1224. }
  1225. inputBar.inputTextView.text = String()
  1226. inputBar.inputTextView.attributedText = nil
  1227. }
  1228. }
  1229. /*
  1230. extension ChatViewController: MessageInputBarDelegate {
  1231. }
  1232. */
  1233. // MARK: - MessageCollectionViewCell
  1234. extension MessageCollectionViewCell {
  1235. @objc func messageForward(_ sender: Any?) {
  1236. // Get the collectionView
  1237. if let collectionView = self.superview as? UICollectionView {
  1238. // Get indexPath
  1239. if let indexPath = collectionView.indexPath(for: self) {
  1240. // Trigger action
  1241. collectionView.delegate?.collectionView?(collectionView,
  1242. performAction: #selector(MessageCollectionViewCell.messageForward(_:)),
  1243. forItemAt: indexPath, withSender: sender)
  1244. }
  1245. }
  1246. }
  1247. @objc func messageDelete(_ sender: Any?) {
  1248. // Get the collectionView
  1249. if let collectionView = self.superview as? UICollectionView {
  1250. // Get indexPath
  1251. if let indexPath = collectionView.indexPath(for: self) {
  1252. // Trigger action
  1253. collectionView.delegate?.collectionView?(collectionView,
  1254. performAction: #selector(MessageCollectionViewCell.messageDelete(_:)),
  1255. forItemAt: indexPath, withSender: sender)
  1256. }
  1257. }
  1258. }
  1259. @objc func messageInfo(_ sender: Any?) {
  1260. // Get the collectionView
  1261. if let collectionView = self.superview as? UICollectionView {
  1262. // Get indexPath
  1263. if let indexPath = collectionView.indexPath(for: self) {
  1264. // Trigger action
  1265. collectionView.delegate?.collectionView?(collectionView,
  1266. performAction: #selector(MessageCollectionViewCell.messageInfo(_:)),
  1267. forItemAt: indexPath, withSender: sender)
  1268. }
  1269. }
  1270. }
  1271. }