ChatViewController.swift 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988
  1. import MapKit
  2. import MessageKit
  3. import QuickLook
  4. import UIKit
  5. import InputBarAccessoryView
  6. protocol MediaSendHandler {
  7. func onSuccess()
  8. }
  9. extension ChatViewController: MediaSendHandler {
  10. func onSuccess() {
  11. refreshMessages()
  12. }
  13. }
  14. class ChatViewController: MessagesViewController {
  15. var dcContext: DcContext
  16. weak var coordinator: ChatViewCoordinator?
  17. let outgoingAvatarOverlap: CGFloat = 17.5
  18. let loadCount = 30
  19. let chatId: Int
  20. let refreshControl = UIRefreshControl()
  21. var messageList: [DCMessage] = []
  22. var msgChangedObserver: Any?
  23. var incomingMsgObserver: Any?
  24. lazy var navBarTap: UITapGestureRecognizer = {
  25. UITapGestureRecognizer(target: self, action: #selector(chatProfilePressed))
  26. }()
  27. var disableWriting = false
  28. var previewView: UIView?
  29. var previewController: PreviewController?
  30. override var inputAccessoryView: UIView? {
  31. if disableWriting {
  32. return nil
  33. }
  34. return messageInputBar
  35. }
  36. private var titleView = ChatTitleView()
  37. init(dcContext: DcContext, chatId: Int, title: String? = nil) {
  38. self.dcContext = dcContext
  39. self.chatId = chatId
  40. super.init(nibName: nil, bundle: nil)
  41. if let title = title {
  42. titleView.updateTitleView(title: title, subtitle: nil)
  43. }
  44. hidesBottomBarWhenPushed = true
  45. }
  46. required init?(coder _: NSCoder) {
  47. fatalError("init(coder:) has not been implemented")
  48. }
  49. override func viewDidLoad() {
  50. messagesCollectionView.register(CustomMessageCell.self)
  51. super.viewDidLoad()
  52. navigationItem.titleView = titleView
  53. view.backgroundColor = DCColors.chatBackgroundColor
  54. if !DCConfig.configured {
  55. // TODO: display message about nothing being configured
  56. return
  57. }
  58. configureMessageCollectionView()
  59. if !disableWriting {
  60. configureMessageInputBar()
  61. messageInputBar.inputTextView.text = textDraft
  62. messageInputBar.inputTextView.becomeFirstResponder()
  63. }
  64. loadFirstMessages()
  65. }
  66. override func viewWillAppear(_ animated: Bool) {
  67. super.viewWillAppear(animated)
  68. // this will be removed in viewWillDisappear
  69. navigationController?.navigationBar.addGestureRecognizer(navBarTap)
  70. let chat = DCChat(id: chatId)
  71. titleView.updateTitleView(title: chat.name, subtitle: chat.subtitle)
  72. if let image = chat.profileImage {
  73. navigationItem.rightBarButtonItem = UIBarButtonItem(image: image, style: .done, target: self, action: #selector(chatProfilePressed))
  74. } else {
  75. let initialsLabel = InitialsBadge(name: chat.name, color: chat.color, size: 28)
  76. navigationItem.rightBarButtonItem = UIBarButtonItem(customView: initialsLabel)
  77. }
  78. configureMessageMenu()
  79. if #available(iOS 11.0, *) {
  80. if disableWriting {
  81. navigationController?.navigationBar.prefersLargeTitles = true
  82. }
  83. }
  84. let nc = NotificationCenter.default
  85. msgChangedObserver = nc.addObserver(
  86. forName: dcNotificationChanged,
  87. object: nil,
  88. queue: OperationQueue.main
  89. ) { notification in
  90. if let ui = notification.userInfo {
  91. if self.disableWriting {
  92. // always refresh, as we can't check currently
  93. self.refreshMessages()
  94. } else if let id = ui["message_id"] as? Int {
  95. if id > 0 {
  96. self.updateMessage(id)
  97. }
  98. }
  99. }
  100. }
  101. incomingMsgObserver = nc.addObserver(
  102. forName: dcNotificationIncoming,
  103. object: nil, queue: OperationQueue.main
  104. ) { notification in
  105. if let ui = notification.userInfo {
  106. if self.chatId == ui["chat_id"] as? Int {
  107. if let id = ui["message_id"] as? Int {
  108. if id > 0 {
  109. self.insertMessage(DCMessage(id: id))
  110. }
  111. }
  112. }
  113. }
  114. }
  115. }
  116. override func viewWillDisappear(_ animated: Bool) {
  117. super.viewWillDisappear(animated)
  118. // the navigationController will be used when chatDetail is pushed, so we have to remove that gestureRecognizer
  119. navigationController?.navigationBar.removeGestureRecognizer(navBarTap)
  120. let cnt = Int(dc_get_fresh_msg_cnt(mailboxPointer, UInt32(chatId)))
  121. logger.info("updating count for chat \(cnt)")
  122. UIApplication.shared.applicationIconBadgeNumber = cnt
  123. if #available(iOS 11.0, *) {
  124. if disableWriting {
  125. navigationController?.navigationBar.prefersLargeTitles = false
  126. }
  127. }
  128. }
  129. override func viewDidDisappear(_ animated: Bool) {
  130. super.viewDidDisappear(animated)
  131. setTextDraft()
  132. let nc = NotificationCenter.default
  133. if let msgChangedObserver = self.msgChangedObserver {
  134. nc.removeObserver(msgChangedObserver)
  135. }
  136. if let incomingMsgObserver = self.incomingMsgObserver {
  137. nc.removeObserver(incomingMsgObserver)
  138. }
  139. }
  140. @objc
  141. private func loadMoreMessages() {
  142. DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + 1) {
  143. DispatchQueue.main.async {
  144. self.messageList = self.getMessageIds(self.loadCount, from: self.messageList.count) + self.messageList
  145. self.messagesCollectionView.reloadDataAndKeepOffset()
  146. self.refreshControl.endRefreshing()
  147. }
  148. }
  149. }
  150. @objc
  151. private func refreshMessages() {
  152. DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + 1) {
  153. DispatchQueue.main.async {
  154. self.messageList = self.getMessageIds(self.messageList.count)
  155. self.messagesCollectionView.reloadDataAndKeepOffset()
  156. self.refreshControl.endRefreshing()
  157. if self.isLastSectionVisible() {
  158. self.messagesCollectionView.scrollToBottom(animated: true)
  159. }
  160. }
  161. }
  162. }
  163. private func loadFirstMessages() {
  164. DispatchQueue.global(qos: .userInitiated).async {
  165. DispatchQueue.main.async {
  166. self.messageList = self.getMessageIds(self.loadCount)
  167. self.messagesCollectionView.reloadData()
  168. self.refreshControl.endRefreshing()
  169. self.messagesCollectionView.scrollToBottom(animated: false)
  170. }
  171. }
  172. }
  173. private var textDraft: String? {
  174. // FIXME: need to free pointer
  175. if let draft = dc_get_draft(mailboxPointer, UInt32(chatId)) {
  176. if let text = dc_msg_get_text(draft) {
  177. let s = String(validatingUTF8: text)!
  178. return s
  179. }
  180. return nil
  181. }
  182. return nil
  183. }
  184. private func getMessageIds(_ count: Int, from: Int? = nil) -> [DCMessage] {
  185. let cMessageIds = dc_get_chat_msgs(mailboxPointer, UInt32(chatId), 0, 0)
  186. let ids: [Int]
  187. if let from = from {
  188. ids = Utils.copyAndFreeArrayWithOffset(inputArray: cMessageIds, len: count, skipEnd: from)
  189. } else {
  190. ids = Utils.copyAndFreeArrayWithLen(inputArray: cMessageIds, len: count)
  191. }
  192. let markIds: [UInt32] = ids.map { UInt32($0) }
  193. dc_markseen_msgs(mailboxPointer, UnsafePointer(markIds), Int32(ids.count))
  194. return ids.map {
  195. DCMessage(id: $0)
  196. }
  197. }
  198. private func setTextDraft() {
  199. if let text = self.messageInputBar.inputTextView.text {
  200. let draft = dc_msg_new(mailboxPointer, DC_MSG_TEXT)
  201. dc_msg_set_text(draft, text.cString(using: .utf8))
  202. dc_set_draft(mailboxPointer, UInt32(chatId), draft)
  203. // cleanup
  204. dc_msg_unref(draft)
  205. }
  206. }
  207. private func configureMessageMenu() {
  208. var menuItems: [UIMenuItem]
  209. if disableWriting {
  210. menuItems = [
  211. UIMenuItem(title: String.localized("start_chat"), action: #selector(MessageCollectionViewCell.messageStartChat(_:))),
  212. UIMenuItem(title: String.localized("dismiss"), action: #selector(MessageCollectionViewCell.messageDismiss(_:))),
  213. UIMenuItem(title: String.localized("menu_block_contact"), action: #selector(MessageCollectionViewCell.messageBlock(_:))),
  214. ]
  215. } else {
  216. // Configures the UIMenu which is shown when selecting a message
  217. menuItems = [
  218. UIMenuItem(title: String.localized("info"), action: #selector(MessageCollectionViewCell.messageInfo(_:))),
  219. ]
  220. }
  221. UIMenuController.shared.menuItems = menuItems
  222. }
  223. private func configureMessageCollectionView() {
  224. messagesCollectionView.messagesDataSource = self
  225. messagesCollectionView.messageCellDelegate = self
  226. scrollsToBottomOnKeyboardBeginsEditing = true // default false
  227. maintainPositionOnKeyboardFrameChanged = true // default false
  228. messagesCollectionView.addSubview(refreshControl)
  229. refreshControl.addTarget(self, action: #selector(loadMoreMessages), for: .valueChanged)
  230. let layout = messagesCollectionView.collectionViewLayout as? MessagesCollectionViewFlowLayout
  231. layout?.sectionInset = UIEdgeInsets(top: 1, left: 8, bottom: 1, right: 8)
  232. // Hide the outgoing avatar and adjust the label alignment to line up with the messages
  233. layout?.setMessageOutgoingAvatarSize(.zero)
  234. layout?.setMessageOutgoingMessageTopLabelAlignment(LabelAlignment(textAlignment: .right,
  235. textInsets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 8)))
  236. layout?.setMessageOutgoingMessageBottomLabelAlignment(LabelAlignment(textAlignment: .right,
  237. textInsets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 8)))
  238. // Set outgoing avatar to overlap with the message bubble
  239. layout?.setMessageIncomingMessageTopLabelAlignment(LabelAlignment(textAlignment: .left,
  240. textInsets: UIEdgeInsets(top: 0, left: 18, bottom: outgoingAvatarOverlap, right: 0)))
  241. layout?.setMessageIncomingAvatarSize(CGSize(width: 30, height: 30))
  242. layout?.setMessageIncomingMessagePadding(UIEdgeInsets(
  243. top: -outgoingAvatarOverlap, left: -18, bottom: outgoingAvatarOverlap / 2, right: 18))
  244. layout?.setMessageIncomingMessageBottomLabelAlignment(LabelAlignment(textAlignment: .left,
  245. textInsets: UIEdgeInsets(top: -7, left: 38, bottom: 0, right: 0)))
  246. layout?.setMessageIncomingAccessoryViewSize(CGSize(width: 30, height: 30))
  247. layout?.setMessageIncomingAccessoryViewPadding(HorizontalEdgeInsets(left: 8, right: 0))
  248. layout?.setMessageOutgoingAccessoryViewSize(CGSize(width: 30, height: 30))
  249. layout?.setMessageOutgoingAccessoryViewPadding(HorizontalEdgeInsets(left: 0, right: 8))
  250. messagesCollectionView.messagesLayoutDelegate = self
  251. messagesCollectionView.messagesDisplayDelegate = self
  252. }
  253. private func configureMessageInputBar() {
  254. messageInputBar.delegate = self
  255. messageInputBar.inputTextView.tintColor = DCColors.primary
  256. messageInputBar.inputTextView.placeholder = String.localized("chat_input_placeholder")
  257. messageInputBar.isTranslucent = true
  258. messageInputBar.separatorLine.isHidden = true
  259. messageInputBar.inputTextView.tintColor = DCColors.primary
  260. scrollsToBottomOnKeyboardBeginsEditing = true
  261. messageInputBar.inputTextView.backgroundColor = UIColor(red: 245 / 255, green: 245 / 255, blue: 245 / 255, alpha: 1)
  262. messageInputBar.inputTextView.placeholderTextColor = UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1)
  263. messageInputBar.inputTextView.textContainerInset = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 38)
  264. messageInputBar.inputTextView.placeholderLabelInsets = UIEdgeInsets(top: 8, left: 20, bottom: 8, right: 38)
  265. messageInputBar.inputTextView.layer.borderColor = UIColor(red: 200 / 255, green: 200 / 255, blue: 200 / 255, alpha: 1).cgColor
  266. messageInputBar.inputTextView.layer.borderWidth = 1.0
  267. messageInputBar.inputTextView.layer.cornerRadius = 16.0
  268. messageInputBar.inputTextView.layer.masksToBounds = true
  269. messageInputBar.inputTextView.scrollIndicatorInsets = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0)
  270. configureInputBarItems()
  271. }
  272. private func configureInputBarItems() {
  273. messageInputBar.setLeftStackViewWidthConstant(to: 30, animated: false)
  274. messageInputBar.setRightStackViewWidthConstant(to: 30, animated: false)
  275. let sendButtonImage = UIImage(named: "paper_plane")?.withRenderingMode(.alwaysTemplate)
  276. messageInputBar.sendButton.image = sendButtonImage
  277. messageInputBar.sendButton.title = nil
  278. messageInputBar.sendButton.tintColor = UIColor(white: 1, alpha: 1)
  279. messageInputBar.sendButton.layer.cornerRadius = 15
  280. messageInputBar.middleContentViewPadding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 10)
  281. // this adds a padding between textinputfield and send button
  282. messageInputBar.sendButton.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
  283. messageInputBar.sendButton.setSize(CGSize(width: 30, height: 30), animated: false)
  284. let leftItems = [
  285. InputBarButtonItem()
  286. .configure {
  287. $0.spacing = .fixed(0)
  288. let clipperIcon = #imageLiteral(resourceName: "ic_attach_file_36pt").withRenderingMode(.alwaysTemplate)
  289. $0.image = clipperIcon
  290. $0.tintColor = UIColor(white: 0.8, alpha: 1)
  291. $0.setSize(CGSize(width: 30, height: 30), animated: false)
  292. }.onSelected {
  293. $0.tintColor = DCColors.primary
  294. }.onDeselected {
  295. $0.tintColor = UIColor(white: 0.8, alpha: 1)
  296. }.onTouchUpInside { _ in
  297. self.clipperButtonPressed()
  298. }
  299. ]
  300. messageInputBar.setStackViewItems(leftItems, forStack: .left, animated: false)
  301. // This just adds some more flare
  302. messageInputBar.sendButton
  303. .onEnabled { item in
  304. UIView.animate(withDuration: 0.3, animations: {
  305. item.backgroundColor = DCColors.primary
  306. })
  307. }.onDisabled { item in
  308. UIView.animate(withDuration: 0.3, animations: {
  309. item.backgroundColor = UIColor(white: 0.9, alpha: 1)
  310. })
  311. }
  312. }
  313. @objc private func chatProfilePressed() {
  314. coordinator?.showChatDetail(chatId: chatId)
  315. }
  316. // MARK: - UICollectionViewDataSource
  317. public override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  318. guard let messagesCollectionView = collectionView as? MessagesCollectionView else {
  319. fatalError("notMessagesCollectionView")
  320. }
  321. guard let messagesDataSource = messagesCollectionView.messagesDataSource else {
  322. fatalError("nilMessagesDataSource")
  323. }
  324. let message = messagesDataSource.messageForItem(at: indexPath, in: messagesCollectionView)
  325. switch message.kind {
  326. case .text, .attributedText, .emoji:
  327. let cell = messagesCollectionView.dequeueReusableCell(TextMessageCell.self, for: indexPath)
  328. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  329. return cell
  330. case .photo, .video:
  331. let cell = messagesCollectionView.dequeueReusableCell(MediaMessageCell.self, for: indexPath)
  332. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  333. return cell
  334. case .location:
  335. let cell = messagesCollectionView.dequeueReusableCell(LocationMessageCell.self, for: indexPath)
  336. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  337. return cell
  338. case .contact:
  339. let cell = messagesCollectionView.dequeueReusableCell(ContactMessageCell.self, for: indexPath)
  340. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  341. return cell
  342. case .custom:
  343. let cell = messagesCollectionView.dequeueReusableCell(CustomMessageCell.self, for: indexPath)
  344. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  345. return cell
  346. case .audio(_):
  347. let cell = messagesCollectionView.dequeueReusableCell(AudioMessageCell.self, for: indexPath)
  348. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  349. return cell
  350. }
  351. }
  352. override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
  353. if action == NSSelectorFromString("messageInfo:") ||
  354. action == NSSelectorFromString("messageBlock:") ||
  355. action == NSSelectorFromString("messageDismiss:") ||
  356. action == NSSelectorFromString("messageStartChat:") {
  357. return true
  358. } else {
  359. return super.collectionView(collectionView, canPerformAction: action, forItemAt: indexPath, withSender: sender)
  360. }
  361. }
  362. override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
  363. switch action {
  364. case NSSelectorFromString("messageInfo:"):
  365. let msg = messageList[indexPath.section]
  366. logger.info("message: View info \(msg.messageId)")
  367. let msgViewController = MessageInfoViewController(dcContext: dcContext, message: msg)
  368. if let ctrl = navigationController {
  369. ctrl.pushViewController(msgViewController, animated: true)
  370. }
  371. case NSSelectorFromString("messageStartChat:"):
  372. let msg = messageList[indexPath.section]
  373. logger.info("message: Start Chat \(msg.messageId)")
  374. _ = msg.createChat()
  375. // TODO: figure out how to properly show the chat after creation
  376. refreshMessages()
  377. case NSSelectorFromString("messageBlock:"):
  378. let msg = messageList[indexPath.section]
  379. logger.info("message: Block \(msg.messageId)")
  380. msg.fromContact.block()
  381. refreshMessages()
  382. case NSSelectorFromString("messageDismiss:"):
  383. let msg = messageList[indexPath.section]
  384. logger.info("message: Dismiss \(msg.messageId)")
  385. msg.fromContact.marknoticed()
  386. refreshMessages()
  387. default:
  388. super.collectionView(collectionView, performAction: action, forItemAt: indexPath, withSender: sender)
  389. }
  390. }
  391. }
  392. // MARK: - MessagesDataSource
  393. extension ChatViewController: MessagesDataSource {
  394. func numberOfSections(in _: MessagesCollectionView) -> Int {
  395. return messageList.count
  396. }
  397. func currentSender() -> SenderType {
  398. let currentSender = Sender(id: "1", displayName: "Alice")
  399. return currentSender
  400. }
  401. func messageForItem(at indexPath: IndexPath, in _: MessagesCollectionView) -> MessageType {
  402. return messageList[indexPath.section]
  403. }
  404. func avatar(for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> Avatar {
  405. let message = messageList[indexPath.section]
  406. let contact = message.fromContact
  407. return Avatar(image: contact.profileImage, initials: Utils.getInitials(inputName: contact.name))
  408. }
  409. func cellTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
  410. if isInfoMessage(at: indexPath) {
  411. return nil
  412. }
  413. if isTimeLabelVisible(at: indexPath) {
  414. return NSAttributedString(
  415. string: MessageKitDateFormatter.shared.string(from: message.sentDate),
  416. attributes: [
  417. NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 10),
  418. NSAttributedString.Key.foregroundColor: UIColor.darkGray,
  419. ]
  420. )
  421. }
  422. return nil
  423. }
  424. func messageTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
  425. if !isPreviousMessageSameSender(at: indexPath) {
  426. let name = message.sender.displayName
  427. let m = messageList[indexPath.section]
  428. return NSAttributedString(string: name, attributes: [
  429. .font: UIFont.systemFont(ofSize: 14),
  430. .foregroundColor: m.fromContact.color,
  431. ])
  432. }
  433. return nil
  434. }
  435. func isTimeLabelVisible(at indexPath: IndexPath) -> Bool {
  436. guard indexPath.section + 1 < messageList.count else { return false }
  437. let messageA = messageList[indexPath.section]
  438. let messageB = messageList[indexPath.section + 1]
  439. if messageA.fromContactId == messageB.fromContactId {
  440. return false
  441. }
  442. let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)
  443. let dateA = messageA.sentDate
  444. let dateB = messageB.sentDate
  445. let dayA = (calendar?.component(.day, from: dateA))
  446. let dayB = (calendar?.component(.day, from: dateB))
  447. return dayA != dayB
  448. }
  449. func isPreviousMessageSameSender(at indexPath: IndexPath) -> Bool {
  450. guard indexPath.section - 1 >= 0 else { return false }
  451. let messageA = messageList[indexPath.section - 1]
  452. let messageB = messageList[indexPath.section]
  453. if messageA.isInfo {
  454. return false
  455. }
  456. return messageA.fromContactId == messageB.fromContactId
  457. }
  458. func isInfoMessage(at indexPath: IndexPath) -> Bool {
  459. return messageList[indexPath.section].isInfo
  460. }
  461. func isNextMessageSameSender(at indexPath: IndexPath) -> Bool {
  462. guard indexPath.section + 1 < messageList.count else { return false }
  463. let messageA = messageList[indexPath.section]
  464. let messageB = messageList[indexPath.section + 1]
  465. if messageA.isInfo {
  466. return false
  467. }
  468. return messageA.fromContactId == messageB.fromContactId
  469. }
  470. func messageBottomLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
  471. guard indexPath.section < messageList.count else { return nil }
  472. let m = messageList[indexPath.section]
  473. if m.isInfo || isNextMessageSameSender(at: indexPath) {
  474. return nil
  475. }
  476. let timestampAttributes: [NSAttributedString.Key: Any] = [
  477. .font: UIFont.systemFont(ofSize: 12),
  478. .foregroundColor: UIColor.lightGray,
  479. ]
  480. if isFromCurrentSender(message: message) {
  481. let text = NSMutableAttributedString()
  482. text.append(NSAttributedString(string: m.formattedSentDate(), attributes: timestampAttributes))
  483. text.append(NSAttributedString(
  484. string: " - " + m.stateDescription(),
  485. attributes: [
  486. .font: UIFont.systemFont(ofSize: 12),
  487. .foregroundColor: UIColor.darkText,
  488. ]
  489. ))
  490. return text
  491. }
  492. return NSAttributedString(string: m.formattedSentDate(), attributes: timestampAttributes)
  493. }
  494. func updateMessage(_ messageId: Int) {
  495. if let index = messageList.firstIndex(where: { $0.id == messageId }) {
  496. dc_markseen_msgs(mailboxPointer, UnsafePointer([UInt32(messageId)]), 1)
  497. messageList[index] = DCMessage(id: messageId)
  498. // Reload section to update header/footer labels
  499. messagesCollectionView.performBatchUpdates({
  500. messagesCollectionView.reloadSections([index])
  501. if index > 0 {
  502. messagesCollectionView.reloadSections([index - 1])
  503. }
  504. if index < messageList.count - 1 {
  505. messagesCollectionView.reloadSections([index + 1])
  506. }
  507. }, completion: { [weak self] _ in
  508. if self?.isLastSectionVisible() == true {
  509. self?.messagesCollectionView.scrollToBottom(animated: true)
  510. }
  511. })
  512. } else {
  513. let msg = DCMessage(id: messageId)
  514. if msg.chatId == chatId {
  515. insertMessage(msg)
  516. }
  517. }
  518. }
  519. func insertMessage(_ message: DCMessage) {
  520. dc_markseen_msgs(mailboxPointer, UnsafePointer([UInt32(message.id)]), 1)
  521. messageList.append(message)
  522. // Reload last section to update header/footer labels and insert a new one
  523. messagesCollectionView.performBatchUpdates({
  524. messagesCollectionView.insertSections([messageList.count - 1])
  525. if messageList.count >= 2 {
  526. messagesCollectionView.reloadSections([messageList.count - 2])
  527. }
  528. }, completion: { [weak self] _ in
  529. if self?.isLastSectionVisible() == true {
  530. self?.messagesCollectionView.scrollToBottom(animated: true)
  531. }
  532. })
  533. }
  534. func isLastSectionVisible() -> Bool {
  535. guard !messageList.isEmpty else { return false }
  536. let lastIndexPath = IndexPath(item: 0, section: messageList.count - 1)
  537. return messagesCollectionView.indexPathsForVisibleItems.contains(lastIndexPath)
  538. }
  539. }
  540. // MARK: - MessagesDisplayDelegate
  541. extension ChatViewController: MessagesDisplayDelegate {
  542. // MARK: - Text Messages
  543. func textColor(for _: MessageType, at _: IndexPath, in _: MessagesCollectionView) -> UIColor {
  544. return .darkText
  545. }
  546. // MARK: - All Messages
  547. func backgroundColor(for message: MessageType, at _: IndexPath, in _: MessagesCollectionView) -> UIColor {
  548. return isFromCurrentSender(message: message) ? DCColors.messagePrimaryColor : DCColors.messageSecondaryColor
  549. }
  550. func messageStyle(for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> MessageStyle {
  551. if isInfoMessage(at: indexPath) {
  552. return .custom { view in
  553. view.style = .none
  554. view.backgroundColor = UIColor(alpha: 10, red: 0, green: 0, blue: 0)
  555. let radius: CGFloat = 16
  556. let path = UIBezierPath(roundedRect: view.bounds,
  557. byRoundingCorners: UIRectCorner.allCorners,
  558. cornerRadii: CGSize(width: radius, height: radius))
  559. let mask = CAShapeLayer()
  560. mask.path = path.cgPath
  561. view.layer.mask = mask
  562. view.center.x = self.view.center.x
  563. }
  564. }
  565. var corners: UIRectCorner = []
  566. if isFromCurrentSender(message: message) {
  567. corners.formUnion(.topLeft)
  568. corners.formUnion(.bottomLeft)
  569. if !isPreviousMessageSameSender(at: indexPath) {
  570. corners.formUnion(.topRight)
  571. }
  572. if !isNextMessageSameSender(at: indexPath) {
  573. corners.formUnion(.bottomRight)
  574. }
  575. } else {
  576. corners.formUnion(.topRight)
  577. corners.formUnion(.bottomRight)
  578. if !isPreviousMessageSameSender(at: indexPath) {
  579. corners.formUnion(.topLeft)
  580. }
  581. if !isNextMessageSameSender(at: indexPath) {
  582. corners.formUnion(.bottomLeft)
  583. }
  584. }
  585. return .custom { view in
  586. let radius: CGFloat = 16
  587. let path = UIBezierPath(roundedRect: view.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
  588. let mask = CAShapeLayer()
  589. mask.path = path.cgPath
  590. view.layer.mask = mask
  591. }
  592. }
  593. func configureAvatarView(_ avatarView: AvatarView, for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) {
  594. let message = messageList[indexPath.section]
  595. let contact = message.fromContact
  596. let avatar = Avatar(image: contact.profileImage, initials: Utils.getInitials(inputName: contact.name))
  597. avatarView.set(avatar: avatar)
  598. avatarView.isHidden = isNextMessageSameSender(at: indexPath) || message.isInfo
  599. avatarView.backgroundColor = contact.color
  600. }
  601. func enabledDetectors(for _: MessageType, at _: IndexPath, in _: MessagesCollectionView) -> [DetectorType] {
  602. return [.url, .date, .phoneNumber, .address]
  603. }
  604. }
  605. // MARK: - MessagesLayoutDelegate
  606. extension ChatViewController: MessagesLayoutDelegate {
  607. func cellTopLabelHeight(for _: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> CGFloat {
  608. if isTimeLabelVisible(at: indexPath) {
  609. return 18
  610. }
  611. return 0
  612. }
  613. func messageTopLabelHeight(for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> CGFloat {
  614. if isInfoMessage(at: indexPath) {
  615. return 0
  616. }
  617. if isFromCurrentSender(message: message) {
  618. return !isPreviousMessageSameSender(at: indexPath) ? 40 : 0
  619. } else {
  620. return !isPreviousMessageSameSender(at: indexPath) ? (40 + outgoingAvatarOverlap) : 0
  621. }
  622. }
  623. func messageBottomLabelHeight(for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> CGFloat {
  624. if isInfoMessage(at: indexPath) {
  625. return 0
  626. }
  627. if !isNextMessageSameSender(at: indexPath) {
  628. return 16
  629. }
  630. if isFromCurrentSender(message: message) {
  631. return 0
  632. }
  633. return 9
  634. }
  635. func heightForLocation(message _: MessageType, at _: IndexPath, with _: CGFloat, in _: MessagesCollectionView) -> CGFloat {
  636. return 40
  637. }
  638. func footerViewSize(for _: MessageType, at _: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGSize {
  639. return CGSize(width: messagesCollectionView.bounds.width, height: 20)
  640. }
  641. @objc private func clipperButtonPressed() {
  642. showClipperOptions()
  643. }
  644. private func showClipperOptions() {
  645. let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
  646. let photoAction = PhotoPickerAlertAction(title: String.localized("photo"), style: .default, handler: photoButtonPressed(_:))
  647. let videoAction = PhotoPickerAlertAction(title: String.localized("video"), style: .default, handler: videoButtonPressed(_:))
  648. alert.addAction(photoAction)
  649. alert.addAction(videoAction)
  650. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  651. self.present(alert, animated: true, completion: nil)
  652. }
  653. private func photoButtonPressed(_ action: UIAlertAction) {
  654. coordinator?.showCameraViewController()
  655. }
  656. private func videoButtonPressed(_ action: UIAlertAction) {
  657. coordinator?.showVideoLibrary()
  658. }
  659. }
  660. // MARK: - MessageCellDelegate
  661. extension ChatViewController: MessageCellDelegate {
  662. func didTapMessage(in cell: MessageCollectionViewCell) {
  663. if let indexPath = messagesCollectionView.indexPath(for: cell) {
  664. let message = messageList[indexPath.section]
  665. if let url = message.fileURL {
  666. // find all other messages with same message type
  667. var previousUrls: [URL] = []
  668. var nextUrls: [URL] = []
  669. var prev: Int = Int(dc_get_next_media(mailboxPointer, UInt32(message.id), -1, Int32(message.type), 0, 0))
  670. while prev != 0 {
  671. let prevMessage = DCMessage(id: prev)
  672. if let url = prevMessage.fileURL {
  673. previousUrls.insert(url, at: 0)
  674. }
  675. prev = Int(dc_get_next_media(mailboxPointer, UInt32(prevMessage.id), -1, Int32(prevMessage.type), 0, 0))
  676. }
  677. var next: Int = Int(dc_get_next_media(mailboxPointer, UInt32(message.id), 1, Int32(message.type), 0, 0))
  678. while next != 0 {
  679. let nextMessage = DCMessage(id: next)
  680. if let url = nextMessage.fileURL {
  681. nextUrls.insert(url, at: 0)
  682. }
  683. next = Int(dc_get_next_media(mailboxPointer, UInt32(nextMessage.id), 1, Int32(nextMessage.type), 0, 0))
  684. }
  685. // these are the files user will be able to swipe trough
  686. let mediaUrls: [URL] = previousUrls + [url] + nextUrls
  687. previewController = PreviewController(currentIndex: previousUrls.count, urls: mediaUrls)
  688. present(previewController!.qlController, animated: true)
  689. }
  690. }
  691. }
  692. func didTapAvatar(in _: MessageCollectionViewCell) {
  693. logger.info("Avatar tapped")
  694. }
  695. @objc(didTapCellTopLabelIn:) func didTapCellTopLabel(in _: MessageCollectionViewCell) {
  696. logger.info("Top label tapped")
  697. }
  698. func didTapBottomLabel(in _: MessageCollectionViewCell) {
  699. print("Bottom label tapped")
  700. }
  701. }
  702. // MARK: - MessageLabelDelegate
  703. extension ChatViewController: MessageLabelDelegate {
  704. func didSelectAddress(_ addressComponents: [String: String]) {
  705. let mapAddress = Utils.formatAddressForQuery(address: addressComponents)
  706. if let escapedMapAddress = mapAddress.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
  707. // Use query, to handle malformed addresses
  708. if let url = URL(string: "http://maps.apple.com/?q=\(escapedMapAddress)") {
  709. UIApplication.shared.open(url as URL)
  710. }
  711. }
  712. }
  713. func didSelectDate(_ date: Date) {
  714. let interval = date.timeIntervalSinceReferenceDate
  715. if let url = NSURL(string: "calshow:\(interval)") {
  716. UIApplication.shared.open(url as URL)
  717. }
  718. }
  719. func didSelectPhoneNumber(_ phoneNumber: String) {
  720. logger.info("phone open", phoneNumber)
  721. if let escapedPhoneNumber = phoneNumber.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
  722. if let url = NSURL(string: "tel:\(escapedPhoneNumber)") {
  723. UIApplication.shared.open(url as URL)
  724. }
  725. }
  726. }
  727. func didSelectURL(_ url: URL) {
  728. UIApplication.shared.open(url)
  729. }
  730. }
  731. // MARK: - LocationMessageDisplayDelegate
  732. /*
  733. extension ChatViewController: LocationMessageDisplayDelegate {
  734. func annotationViewForLocation(message: MessageType, at indexPath: IndexPath, in messageCollectionView: MessagesCollectionView) -> MKAnnotationView? {
  735. let annotationView = MKAnnotationView(annotation: nil, reuseIdentifier: nil)
  736. let pinImage = #imageLiteral(resourceName: "ic_block_36pt").withRenderingMode(.alwaysTemplate)
  737. annotationView.image = pinImage
  738. annotationView.centerOffset = CGPoint(x: 0, y: -pinImage.size.height / 2)
  739. return annotationView
  740. }
  741. func animationBlockForLocation(message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> ((UIImageView) -> Void)? {
  742. return { view in
  743. view.layer.transform = CATransform3DMakeScale(0, 0, 0)
  744. view.alpha = 0.0
  745. UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0, options: [], animations: {
  746. view.layer.transform = CATransform3DIdentity
  747. view.alpha = 1.0
  748. }, completion: nil)
  749. }
  750. }
  751. }
  752. */
  753. // MARK: - MessageInputBarDelegate
  754. extension ChatViewController: InputBarAccessoryViewDelegate {
  755. func inputBar(_ inputBar: InputBarAccessoryView, didPressSendButtonWith text: String) {
  756. DispatchQueue.global().async {
  757. dc_send_text_msg(mailboxPointer, UInt32(self.chatId), text)
  758. }
  759. inputBar.inputTextView.text = String()
  760. }
  761. }
  762. /*
  763. extension ChatViewController: MessageInputBarDelegate {
  764. }
  765. */
  766. // MARK: - MessageCollectionViewCell
  767. extension MessageCollectionViewCell {
  768. @objc func messageInfo(_ sender: Any?) {
  769. // Get the collectionView
  770. if let collectionView = self.superview as? UICollectionView {
  771. // Get indexPath
  772. if let indexPath = collectionView.indexPath(for: self) {
  773. // Trigger action
  774. collectionView.delegate?.collectionView?(collectionView,
  775. performAction: #selector(MessageCollectionViewCell.messageInfo(_:)),
  776. forItemAt: indexPath, withSender: sender)
  777. }
  778. }
  779. }
  780. @objc func messageBlock(_ sender: Any?) {
  781. // Get the collectionView
  782. if let collectionView = self.superview as? UICollectionView {
  783. // Get indexPath
  784. if let indexPath = collectionView.indexPath(for: self) {
  785. // Trigger action
  786. collectionView.delegate?.collectionView?(collectionView,
  787. performAction: #selector(MessageCollectionViewCell.messageBlock(_:)),
  788. forItemAt: indexPath, withSender: sender)
  789. }
  790. }
  791. }
  792. @objc func messageDismiss(_ sender: Any?) {
  793. // Get the collectionView
  794. if let collectionView = self.superview as? UICollectionView {
  795. // Get indexPath
  796. if let indexPath = collectionView.indexPath(for: self) {
  797. // Trigger action
  798. collectionView.delegate?.collectionView?(collectionView,
  799. performAction: #selector(MessageCollectionViewCell.messageDismiss(_:)),
  800. forItemAt: indexPath, withSender: sender)
  801. }
  802. }
  803. }
  804. @objc func messageStartChat(_ sender: Any?) {
  805. // Get the collectionView
  806. if let collectionView = self.superview as? UICollectionView {
  807. // Get indexPath
  808. if let indexPath = collectionView.indexPath(for: self) {
  809. // Trigger action
  810. collectionView.delegate?.collectionView?(collectionView,
  811. performAction: #selector(MessageCollectionViewCell.messageStartChat(_:)),
  812. forItemAt: indexPath, withSender: sender)
  813. }
  814. }
  815. }
  816. }
  817. /*
  818. class ChatViewController: MessagesViewController {
  819. weak var coordinator: ChatViewCoordinator?
  820. let outgoingAvatarOverlap: CGFloat = 17.5
  821. let loadCount = 30
  822. private var isGroupChat: Bool {
  823. return MRChat(id: chatId).chatType != .SINGLE
  824. }
  825. let chatId: Int
  826. let refreshControl = UIRefreshControl()
  827. var messageList: [MRMessage] = []
  828. var msgChangedObserver: Any?
  829. var incomingMsgObserver: Any?
  830. lazy var navBarTap: UITapGestureRecognizer = {
  831. UITapGestureRecognizer(target: self, action: #selector(chatProfilePressed))
  832. }()
  833. var disableWriting = false
  834. var previewView: UIView?
  835. var previewController: PreviewController?
  836. override var inputAccessoryView: UIView? {
  837. if disableWriting {
  838. return nil
  839. }
  840. return messageInputBar
  841. }
  842. init(chatId: Int, title: String? = nil) {
  843. self.chatId = chatId
  844. super.init(nibName: nil, bundle: nil)
  845. if let title = title {
  846. updateTitleView(title: title, subtitle: nil)
  847. }
  848. hidesBottomBarWhenPushed = true
  849. }
  850. required init?(coder _: NSCoder) {
  851. fatalError("init(coder:) has not been implemented")
  852. }
  853. override func viewDidLoad() {
  854. messagesCollectionView.register(CustomCell.self)
  855. super.viewDidLoad()
  856. view.backgroundColor = DCColors.chatBackgroundColor
  857. if !MRConfig.configured {
  858. // TODO: display message about nothing being configured
  859. return
  860. }
  861. configureMessageCollectionView()
  862. if !disableWriting {
  863. configureMessageInputBar()
  864. messageInputBar.inputTextView.text = textDraft
  865. messageInputBar.inputTextView.becomeFirstResponder()
  866. }
  867. loadFirstMessages()
  868. }
  869. override func viewWillAppear(_ animated: Bool) {
  870. super.viewWillAppear(animated)
  871. // this will be removed in viewWillDisappear
  872. navigationController?.navigationBar.addGestureRecognizer(navBarTap)
  873. let chat = MRChat(id: chatId)
  874. updateTitleView(title: chat.name, subtitle: chat.subtitle)
  875. if let image = chat.profileImage {
  876. navigationItem.rightBarButtonItem = UIBarButtonItem(image: image, style: .done, target: self, action: #selector(chatProfilePressed))
  877. } else {
  878. let initialsLabel = InitialsLabel(name: chat.name, color: chat.color, size: 28)
  879. navigationItem.rightBarButtonItem = UIBarButtonItem(customView: initialsLabel)
  880. }
  881. configureMessageMenu()
  882. if #available(iOS 11.0, *) {
  883. if disableWriting {
  884. navigationController?.navigationBar.prefersLargeTitles = true
  885. }
  886. }
  887. let nc = NotificationCenter.default
  888. msgChangedObserver = nc.addObserver(
  889. forName: dcNotificationChanged,
  890. object: nil,
  891. queue: OperationQueue.main
  892. ) { notification in
  893. if let ui = notification.userInfo {
  894. if self.disableWriting {
  895. // always refresh, as we can't check currently
  896. self.refreshMessages()
  897. } else if let id = ui["message_id"] as? Int {
  898. if id > 0 {
  899. self.updateMessage(id)
  900. }
  901. }
  902. }
  903. }
  904. incomingMsgObserver = nc.addObserver(
  905. forName: dcNotificationIncoming,
  906. object: nil, queue: OperationQueue.main
  907. ) { notification in
  908. if let ui = notification.userInfo {
  909. if self.chatId == ui["chat_id"] as! Int {
  910. let id = ui["message_id"] as! Int
  911. if id > 0 {
  912. self.insertMessage(MRMessage(id: id))
  913. }
  914. }
  915. }
  916. }
  917. }
  918. override func viewWillDisappear(_ animated: Bool) {
  919. super.viewWillDisappear(animated)
  920. // the navigationController will be used when chatDetail is pushed, so we have to remove that gestureRecognizer
  921. navigationController?.navigationBar.removeGestureRecognizer(navBarTap)
  922. let cnt = Int(dc_get_fresh_msg_cnt(mailboxPointer, UInt32(chatId)))
  923. logger.info("updating count for chat \(cnt)")
  924. UIApplication.shared.applicationIconBadgeNumber = cnt
  925. if #available(iOS 11.0, *) {
  926. if disableWriting {
  927. navigationController?.navigationBar.prefersLargeTitles = false
  928. }
  929. }
  930. }
  931. override func viewDidDisappear(_ animated: Bool) {
  932. super.viewDidDisappear(animated)
  933. setTextDraft()
  934. let nc = NotificationCenter.default
  935. if let msgChangedObserver = self.msgChangedObserver {
  936. nc.removeObserver(msgChangedObserver)
  937. }
  938. if let incomingMsgObserver = self.incomingMsgObserver {
  939. nc.removeObserver(incomingMsgObserver)
  940. }
  941. }
  942. @objc
  943. private func loadMoreMessages() {
  944. DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + 1) {
  945. DispatchQueue.main.async {
  946. self.messageList = self.getMessageIds(self.loadCount, from: self.messageList.count) + self.messageList
  947. self.messagesCollectionView.reloadDataAndKeepOffset()
  948. self.refreshControl.endRefreshing()
  949. }
  950. }
  951. }
  952. @objc
  953. private func refreshMessages() {
  954. DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + 1) {
  955. DispatchQueue.main.async {
  956. self.messageList = self.getMessageIds(self.messageList.count)
  957. self.messagesCollectionView.reloadDataAndKeepOffset()
  958. self.refreshControl.endRefreshing()
  959. if self.isLastSectionVisible() {
  960. self.messagesCollectionView.scrollToBottom(animated: true)
  961. }
  962. }
  963. }
  964. }
  965. private func loadFirstMessages() {
  966. DispatchQueue.global(qos: .userInitiated).async {
  967. DispatchQueue.main.async {
  968. self.messageList = self.getMessageIds(self.loadCount)
  969. self.messagesCollectionView.reloadData()
  970. self.refreshControl.endRefreshing()
  971. self.messagesCollectionView.scrollToBottom(animated: false)
  972. }
  973. }
  974. }
  975. private var textDraft: String? {
  976. // FIXME: need to free pointer
  977. if let draft = dc_get_draft(mailboxPointer, UInt32(chatId)) {
  978. if let text = dc_msg_get_text(draft) {
  979. let s = String(validatingUTF8: text)!
  980. return s
  981. }
  982. return nil
  983. }
  984. return nil
  985. }
  986. private func getMessageIds(_ count: Int, from: Int? = nil) -> [MRMessage] {
  987. let cMessageIds = dc_get_chat_msgs(mailboxPointer, UInt32(chatId), 0, 0)
  988. let ids: [Int]
  989. if let from = from {
  990. ids = Utils.copyAndFreeArrayWithOffset(inputArray: cMessageIds, len: count, skipEnd: from)
  991. } else {
  992. ids = Utils.copyAndFreeArrayWithLen(inputArray: cMessageIds, len: count)
  993. }
  994. let markIds: [UInt32] = ids.map { UInt32($0) }
  995. dc_markseen_msgs(mailboxPointer, UnsafePointer(markIds), Int32(ids.count))
  996. return ids.map {
  997. MRMessage(id: $0)
  998. }
  999. }
  1000. private func setTextDraft() {
  1001. if let text = self.messageInputBar.inputTextView.text {
  1002. let draft = dc_msg_new(mailboxPointer, DC_MSG_TEXT)
  1003. dc_msg_set_text(draft, text.cString(using: .utf8))
  1004. dc_set_draft(mailboxPointer, UInt32(chatId), draft)
  1005. // cleanup
  1006. dc_msg_unref(draft)
  1007. }
  1008. }
  1009. private func configureMessageMenu() {
  1010. var menuItems: [UIMenuItem]
  1011. if disableWriting {
  1012. menuItems = [
  1013. UIMenuItem(title: "Start Chat", action: #selector(MessageCollectionViewCell.messageStartChat(_:))),
  1014. UIMenuItem(title: "Dismiss", action: #selector(MessageCollectionViewCell.messageDismiss(_:))),
  1015. UIMenuItem(title: "Block", action: #selector(MessageCollectionViewCell.messageBlock(_:))),
  1016. ]
  1017. } else {
  1018. // Configures the UIMenu which is shown when selecting a message
  1019. menuItems = [
  1020. UIMenuItem(title: "Info", action: #selector(MessageCollectionViewCell.messageInfo(_:))),
  1021. ]
  1022. }
  1023. UIMenuController.shared.menuItems = menuItems
  1024. }
  1025. private func configureMessageCollectionView() {
  1026. messagesCollectionView.messagesDataSource = self
  1027. messagesCollectionView.messageCellDelegate = self
  1028. scrollsToBottomOnKeyboardBeginsEditing = true // default false
  1029. maintainPositionOnKeyboardFrameChanged = true // default false
  1030. messagesCollectionView.addSubview(refreshControl)
  1031. refreshControl.addTarget(self, action: #selector(loadMoreMessages), for: .valueChanged)
  1032. let layout = messagesCollectionView.collectionViewLayout as? MessagesCollectionViewFlowLayout
  1033. messagesCollectionView.messagesLayoutDelegate = self
  1034. messagesCollectionView.messagesDisplayDelegate = self
  1035. /*
  1036. let layout = messagesCollectionView.collectionViewLayout as? MessagesCollectionViewFlowLayout
  1037. layout?.sectionInset = UIEdgeInsets(top: 1, left: 8, bottom: 1, right: 8)
  1038. // Hide the outgoing avatar and adjust the label alignment to line up with the messages
  1039. layout?.setMessageOutgoingAvatarSize(.zero)
  1040. layout?.setMessageOutgoingMessageTopLabelAlignment(LabelAlignment(textAlignment: .right, textInsets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 8)))
  1041. layout?.setMessageOutgoingMessageBottomLabelAlignment(LabelAlignment(textAlignment: .right, textInsets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 8)))
  1042. // Set outgoing avatar to overlap with the message bubble
  1043. if isGroupChat {
  1044. layout?.setMessageIncomingMessageTopLabelAlignment(LabelAlignment(textAlignment: .left, textInsets: UIEdgeInsets(top: 0, left: 18, bottom: outgoingAvatarOverlap, right: 0)))
  1045. layout?.setMessageIncomingAvatarSize(CGSize(width: 30, height: 30))
  1046. layout?.setMessageIncomingMessagePadding(UIEdgeInsets(top: -outgoingAvatarOverlap, left: -18, bottom: outgoingAvatarOverlap / 2, right: 18))
  1047. layout?.setMessageIncomingMessageBottomLabelAlignment(LabelAlignment(textAlignment: .left, textInsets: UIEdgeInsets(top: -7, left: 38, bottom: 0, right: 0)))
  1048. } else {
  1049. layout?.setMessageIncomingMessageTopLabelAlignment(LabelAlignment(textAlignment: .left, textInsets: UIEdgeInsets(top: 0, left: 0, bottom: 5, right: 0)))
  1050. layout?.setMessageIncomingAvatarSize(CGSize.zero) // no batch displayed in singleChats
  1051. layout?.setMessageIncomingMessagePadding(UIEdgeInsets(top: -outgoingAvatarOverlap, left: 0, bottom: outgoingAvatarOverlap / 2, right: 18))
  1052. layout?.setMessageIncomingMessageBottomLabelAlignment(LabelAlignment(textAlignment: .left, textInsets: UIEdgeInsets(top: -7, left: 12, bottom: 0, right: 0)))
  1053. }
  1054. layout?.setMessageIncomingAccessoryViewSize(CGSize(width: 30, height: 30))
  1055. layout?.setMessageIncomingAccessoryViewPadding(HorizontalEdgeInsets(left: 8, right: 0))
  1056. layout?.setMessageOutgoingAccessoryViewSize(CGSize(width: 30, height: 30))
  1057. layout?.setMessageOutgoingAccessoryViewPadding(HorizontalEdgeInsets(left: 0, right: 8))
  1058. messagesCollectionView.messagesLayoutDelegate = self
  1059. messagesCollectionView.messagesDisplayDelegate = self
  1060. */
  1061. }
  1062. private func configureMessageInputBar() {
  1063. messageInputBar.delegate = self
  1064. messageInputBar.inputTextView.tintColor = DCColors.primary
  1065. messageInputBar.isTranslucent = true
  1066. messageInputBar.separatorLine.isHidden = true
  1067. messageInputBar.inputTextView.tintColor = DCColors.primary
  1068. scrollsToBottomOnKeyboardBeginsEditing = true
  1069. messageInputBar.inputTextView.backgroundColor = UIColor(red: 245 / 255, green: 245 / 255, blue: 245 / 255, alpha: 1)
  1070. messageInputBar.inputTextView.placeholderTextColor = UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1)
  1071. messageInputBar.inputTextView.textContainerInset = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 38)
  1072. messageInputBar.inputTextView.placeholderLabelInsets = UIEdgeInsets(top: 8, left: 20, bottom: 8, right: 38)
  1073. messageInputBar.inputTextView.layer.borderColor = UIColor(red: 200 / 255, green: 200 / 255, blue: 200 / 255, alpha: 1).cgColor
  1074. messageInputBar.inputTextView.layer.borderWidth = 1.0
  1075. messageInputBar.inputTextView.layer.cornerRadius = 16.0
  1076. messageInputBar.inputTextView.layer.masksToBounds = true
  1077. messageInputBar.inputTextView.scrollIndicatorInsets = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0)
  1078. configureInputBarItems()
  1079. }
  1080. private func configureInputBarItems() {
  1081. messageInputBar.setLeftStackViewWidthConstant(to: 30, animated: false)
  1082. messageInputBar.setRightStackViewWidthConstant(to: 30, animated: false)
  1083. let sendButtonImage = UIImage(named: "paper_plane")?.withRenderingMode(.alwaysTemplate)
  1084. messageInputBar.sendButton.image = sendButtonImage
  1085. messageInputBar.sendButton.title = nil
  1086. messageInputBar.sendButton.tintColor = UIColor(white: 1, alpha: 1)
  1087. messageInputBar.sendButton.layer.cornerRadius = 15
  1088. messageInputBar.middleContentViewPadding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 10) // this adds a padding between textinputfield and send button
  1089. messageInputBar.sendButton.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
  1090. messageInputBar.sendButton.setSize(CGSize(width: 30, height: 30), animated: false)
  1091. let leftItems = [
  1092. InputBarButtonItem()
  1093. .configure {
  1094. $0.spacing = .fixed(0)
  1095. let clipperIcon = #imageLiteral(resourceName: "ic_attach_file_36pt").withRenderingMode(.alwaysTemplate)
  1096. $0.image = clipperIcon
  1097. $0.tintColor = UIColor(white: 0.8, alpha: 1)
  1098. $0.setSize(CGSize(width: 30, height: 30), animated: false)
  1099. }.onSelected {
  1100. $0.tintColor = DCColors.primary
  1101. }.onDeselected {
  1102. $0.tintColor = UIColor(white: 0.8, alpha: 1)
  1103. }.onTouchUpInside { _ in
  1104. self.clipperButtonPressed()
  1105. }
  1106. /*
  1107. InputBarButtonItem()
  1108. .configure {
  1109. $0.spacing = .fixed(0)
  1110. $0.image = UIImage(named: "camera")?.withRenderingMode(.alwaysTemplate)
  1111. $0.setSize(CGSize(width: 36, height: 36), animated: false)
  1112. $0.tintColor = UIColor(white: 0.8, alpha: 1)
  1113. }.onSelected {
  1114. $0.tintColor = DCColors.primary
  1115. }.onDeselected {
  1116. $0.tintColor = UIColor(white: 0.8, alpha: 1)
  1117. }.onTouchUpInside { _ in
  1118. self.didPressPhotoButton()
  1119. },
  1120. */
  1121. ]
  1122. messageInputBar.setStackViewItems(leftItems, forStack: .left, animated: false)
  1123. // This just adds some more flare
  1124. messageInputBar.sendButton
  1125. .onEnabled { item in
  1126. UIView.animate(withDuration: 0.3, animations: {
  1127. item.backgroundColor = DCColors.primary
  1128. })
  1129. }.onDisabled { item in
  1130. UIView.animate(withDuration: 0.3, animations: {
  1131. item.backgroundColor = UIColor(white: 0.9, alpha: 1)
  1132. })
  1133. }
  1134. }
  1135. @objc private func chatProfilePressed() {
  1136. coordinator?.showChatDetail(chatId: chatId)
  1137. }
  1138. // MARK: - UICollectionViewDataSource
  1139. public override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  1140. guard let messagesCollectionView = collectionView as? MessagesCollectionView else {
  1141. fatalError("notMessagesCollectionView")
  1142. }
  1143. guard let messagesDataSource = messagesCollectionView.messagesDataSource else {
  1144. fatalError("nilMessagesDataSource")
  1145. }
  1146. let message = messagesDataSource.messageForItem(at: indexPath, in: messagesCollectionView)
  1147. switch message.kind {
  1148. case .text, .attributedText, .emoji:
  1149. let cell = messagesCollectionView.dequeueReusableCell(TextMessageCell.self, for: indexPath)
  1150. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  1151. return cell
  1152. case .photo, .video:
  1153. let cell = messagesCollectionView.dequeueReusableCell(MediaMessageCell.self, for: indexPath)
  1154. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  1155. return cell
  1156. case .location:
  1157. let cell = messagesCollectionView.dequeueReusableCell(LocationMessageCell.self, for: indexPath)
  1158. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  1159. return cell
  1160. case .contact:
  1161. let cell = messagesCollectionView.dequeueReusableCell(ContactMessageCell.self, for: indexPath)
  1162. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  1163. return cell
  1164. case .custom:
  1165. let cell = messagesCollectionView.dequeueReusableCell(CustomCell.self, for: indexPath)
  1166. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  1167. return cell
  1168. case .audio(_):
  1169. let cell = messagesCollectionView.dequeueReusableCell(AudioMessageCell.self, for: indexPath)
  1170. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  1171. return cell
  1172. }
  1173. }
  1174. override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
  1175. if action == NSSelectorFromString("messageInfo:") ||
  1176. action == NSSelectorFromString("messageBlock:") ||
  1177. action == NSSelectorFromString("messageDismiss:") ||
  1178. action == NSSelectorFromString("messageStartChat:") {
  1179. return true
  1180. } else {
  1181. return super.collectionView(collectionView, canPerformAction: action, forItemAt: indexPath, withSender: sender)
  1182. }
  1183. }
  1184. override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
  1185. switch action {
  1186. case NSSelectorFromString("messageInfo:"):
  1187. let msg = messageList[indexPath.section]
  1188. logger.info("message: View info \(msg.messageId)")
  1189. let msgViewController = MessageInfoViewController(message: msg)
  1190. if let ctrl = navigationController {
  1191. ctrl.pushViewController(msgViewController, animated: true)
  1192. }
  1193. case NSSelectorFromString("messageStartChat:"):
  1194. let msg = messageList[indexPath.section]
  1195. logger.info("message: Start Chat \(msg.messageId)")
  1196. _ = msg.createChat()
  1197. // TODO: figure out how to properly show the chat after creation
  1198. refreshMessages()
  1199. case NSSelectorFromString("messageBlock:"):
  1200. let msg = messageList[indexPath.section]
  1201. logger.info("message: Block \(msg.messageId)")
  1202. msg.fromContact.block()
  1203. refreshMessages()
  1204. case NSSelectorFromString("messageDismiss:"):
  1205. let msg = messageList[indexPath.section]
  1206. logger.info("message: Dismiss \(msg.messageId)")
  1207. msg.fromContact.marknoticed()
  1208. refreshMessages()
  1209. default:
  1210. super.collectionView(collectionView, performAction: action, forItemAt: indexPath, withSender: sender)
  1211. }
  1212. }
  1213. }
  1214. // MARK: - MessagesDataSource
  1215. extension ChatViewController: MessagesDataSource {
  1216. func numberOfSections(in _: MessagesCollectionView) -> Int {
  1217. return messageList.count
  1218. }
  1219. func currentSender() -> SenderType {
  1220. let currentSender = Sender(id: "1", displayName: "Alice")
  1221. return currentSender
  1222. }
  1223. func messageForItem(at indexPath: IndexPath, in _: MessagesCollectionView) -> MessageType {
  1224. return messageList[indexPath.section]
  1225. }
  1226. func avatar(for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> Avatar {
  1227. let message = messageList[indexPath.section]
  1228. let contact = message.fromContact
  1229. return Avatar(image: contact.profileImage, initials: Utils.getInitials(inputName: contact.name))
  1230. }
  1231. func cellTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
  1232. if isInfoMessage(at: indexPath) {
  1233. return nil
  1234. }
  1235. if isTimeLabelVisible(at: indexPath) {
  1236. return NSAttributedString(
  1237. string: MessageKitDateFormatter.shared.string(from: message.sentDate),
  1238. attributes: [
  1239. NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 10),
  1240. NSAttributedString.Key.foregroundColor: UIColor.darkGray,
  1241. ]
  1242. )
  1243. }
  1244. return nil
  1245. }
  1246. func messageTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
  1247. if !isGroupChat {
  1248. return nil
  1249. }
  1250. if !isPreviousMessageSameSender(at: indexPath) {
  1251. let name = message.sender.displayName
  1252. let m = messageList[indexPath.section]
  1253. return NSAttributedString(string: name, attributes: [
  1254. .font: UIFont.systemFont(ofSize: 14),
  1255. .foregroundColor: m.fromContact.color,
  1256. ])
  1257. }
  1258. return nil
  1259. }
  1260. func isTimeLabelVisible(at indexPath: IndexPath) -> Bool {
  1261. guard indexPath.section + 1 < messageList.count else { return false }
  1262. let messageA = messageList[indexPath.section]
  1263. let messageB = messageList[indexPath.section + 1]
  1264. if messageA.fromContactId == messageB.fromContactId {
  1265. return false
  1266. }
  1267. let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)
  1268. let dateA = messageA.sentDate
  1269. let dateB = messageB.sentDate
  1270. let dayA = (calendar?.component(.day, from: dateA))
  1271. let dayB = (calendar?.component(.day, from: dateB))
  1272. return dayA != dayB
  1273. }
  1274. func isPreviousMessageSameSender(at indexPath: IndexPath) -> Bool {
  1275. guard indexPath.section - 1 >= 0 else { return false }
  1276. let messageA = messageList[indexPath.section - 1]
  1277. let messageB = messageList[indexPath.section]
  1278. if messageA.isInfo {
  1279. return false
  1280. }
  1281. return messageA.fromContactId == messageB.fromContactId
  1282. }
  1283. func isInfoMessage(at indexPath: IndexPath) -> Bool {
  1284. return messageList[indexPath.section].isInfo
  1285. }
  1286. func isNextMessageSameSender(at indexPath: IndexPath) -> Bool {
  1287. guard indexPath.section + 1 < messageList.count else { return false }
  1288. let messageA = messageList[indexPath.section]
  1289. let messageB = messageList[indexPath.section + 1]
  1290. if messageA.isInfo {
  1291. return false
  1292. }
  1293. return messageA.fromContactId == messageB.fromContactId
  1294. }
  1295. func messageBottomLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
  1296. guard indexPath.section < messageList.count else { return nil }
  1297. let m = messageList[indexPath.section]
  1298. if m.isInfo || isNextMessageSameSender(at: indexPath) {
  1299. return nil
  1300. }
  1301. let timestampAttributes: [NSAttributedString.Key: Any] = [
  1302. .font: UIFont.systemFont(ofSize: 12),
  1303. .foregroundColor: UIColor.lightGray,
  1304. ]
  1305. if isFromCurrentSender(message: message) {
  1306. let text = NSMutableAttributedString()
  1307. text.append(NSAttributedString(string: m.formattedSentDate(), attributes: timestampAttributes))
  1308. text.append(NSAttributedString(
  1309. string: " - " + m.stateDescription(),
  1310. attributes: [
  1311. .font: UIFont.systemFont(ofSize: 12),
  1312. .foregroundColor: UIColor.darkText,
  1313. ]
  1314. ))
  1315. return text
  1316. }
  1317. return NSAttributedString(string: m.formattedSentDate(), attributes: timestampAttributes)
  1318. }
  1319. func updateMessage(_ messageId: Int) {
  1320. if let index = messageList.firstIndex(where: { $0.id == messageId }) {
  1321. dc_markseen_msgs(mailboxPointer, UnsafePointer([UInt32(messageId)]), 1)
  1322. messageList[index] = MRMessage(id: messageId)
  1323. // Reload section to update header/footer labels
  1324. messagesCollectionView.performBatchUpdates({
  1325. messagesCollectionView.reloadSections([index])
  1326. if index > 0 {
  1327. messagesCollectionView.reloadSections([index - 1])
  1328. }
  1329. if index < messageList.count - 1 {
  1330. messagesCollectionView.reloadSections([index + 1])
  1331. }
  1332. }, completion: { [weak self] _ in
  1333. if self?.isLastSectionVisible() == true {
  1334. self?.messagesCollectionView.scrollToBottom(animated: true)
  1335. }
  1336. })
  1337. } else {
  1338. let msg = MRMessage(id: messageId)
  1339. if msg.chatId == chatId {
  1340. insertMessage(msg)
  1341. }
  1342. }
  1343. }
  1344. func insertMessage(_ message: MRMessage) {
  1345. dc_markseen_msgs(mailboxPointer, UnsafePointer([UInt32(message.id)]), 1)
  1346. messageList.append(message)
  1347. // Reload last section to update header/footer labels and insert a new one
  1348. messagesCollectionView.performBatchUpdates({
  1349. messagesCollectionView.insertSections([messageList.count - 1])
  1350. if messageList.count >= 2 {
  1351. messagesCollectionView.reloadSections([messageList.count - 2])
  1352. }
  1353. }, completion: { [weak self] _ in
  1354. if self?.isLastSectionVisible() == true {
  1355. self?.messagesCollectionView.scrollToBottom(animated: true)
  1356. }
  1357. })
  1358. }
  1359. func isLastSectionVisible() -> Bool {
  1360. guard !messageList.isEmpty else { return false }
  1361. let lastIndexPath = IndexPath(item: 0, section: messageList.count - 1)
  1362. return messagesCollectionView.indexPathsForVisibleItems.contains(lastIndexPath)
  1363. }
  1364. }
  1365. // MARK: - MessagesDisplayDelegate
  1366. extension ChatViewController: MessagesDisplayDelegate {
  1367. func configureAvatarView(_ avatarView: AvatarView, for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) {
  1368. let message = messageList[indexPath.section]
  1369. let contact = message.fromContact
  1370. let avatar = Avatar(image: contact.profileImage, initials: Utils.getInitials(inputName: contact.name))
  1371. avatarView.set(avatar: avatar)
  1372. avatarView.isHidden = isNextMessageSameSender(at: indexPath) || message.isInfo
  1373. avatarView.backgroundColor = contact.color
  1374. }
  1375. func messageStyle(for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> MessageStyle {
  1376. if isInfoMessage(at: indexPath) {
  1377. return .custom { view in
  1378. view.style = .none
  1379. view.backgroundColor = UIColor(alpha: 10, red: 0, green: 0, blue: 0)
  1380. let radius: CGFloat = 16
  1381. let path = UIBezierPath(roundedRect: view.bounds, byRoundingCorners: UIRectCorner.allCorners, cornerRadii: CGSize(width: radius, height: radius))
  1382. let mask = CAShapeLayer()
  1383. mask.path = path.cgPath
  1384. view.layer.mask = mask
  1385. view.center.x = self.view.center.x
  1386. }
  1387. }
  1388. var corners: UIRectCorner = []
  1389. if isFromCurrentSender(message: message) {
  1390. corners.formUnion(.topLeft)
  1391. corners.formUnion(.bottomLeft)
  1392. if !isPreviousMessageSameSender(at: indexPath) {
  1393. corners.formUnion(.topRight)
  1394. }
  1395. if !isNextMessageSameSender(at: indexPath) {
  1396. corners.formUnion(.bottomRight)
  1397. }
  1398. } else {
  1399. corners.formUnion(.topRight)
  1400. corners.formUnion(.bottomRight)
  1401. if !isPreviousMessageSameSender(at: indexPath) {
  1402. corners.formUnion(.topLeft)
  1403. }
  1404. if !isNextMessageSameSender(at: indexPath) {
  1405. corners.formUnion(.bottomLeft)
  1406. }
  1407. }
  1408. return .custom { view in
  1409. let radius: CGFloat = 16
  1410. let path = UIBezierPath(roundedRect: view.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
  1411. let mask = CAShapeLayer()
  1412. mask.path = path.cgPath
  1413. view.layer.mask = mask
  1414. }
  1415. }
  1416. }
  1417. /*
  1418. extension ChatViewController: MessagesDisplayDelegate {
  1419. // MARK: - Text Messages
  1420. func textColor(for _: MessageType, at _: IndexPath, in _: MessagesCollectionView) -> UIColor {
  1421. return .darkText
  1422. }
  1423. // MARK: - All Messages
  1424. func backgroundColor(for message: MessageType, at _: IndexPath, in _: MessagesCollectionView) -> UIColor {
  1425. return isFromCurrentSender(message: message) ? DCColors.messagePrimaryColor : DCColors.messageSecondaryColor
  1426. }
  1427. func enabledDetectors(for _: MessageType, at _: IndexPath, in _: MessagesCollectionView) -> [DetectorType] {
  1428. return [.url, .date, .phoneNumber, .address]
  1429. }
  1430. }
  1431. */
  1432. // MARK: - MessagesLayoutDelegate
  1433. extension ChatViewController: MessagesLayoutDelegate {
  1434. func cellTopLabelHeight(for _: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> CGFloat {
  1435. if isTimeLabelVisible(at: indexPath) {
  1436. return 18
  1437. }
  1438. if !isPreviousMessageSameSender(at: indexPath) {
  1439. return 18
  1440. }
  1441. return 0
  1442. }
  1443. }
  1444. /*
  1445. extension ChatViewController: MessagesLayoutDelegate {
  1446. func cellTopLabelHeight(for _: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> CGFloat {
  1447. if isTimeLabelVisible(at: indexPath) {
  1448. return 18
  1449. }
  1450. return !isPreviousMessageSameSender(at: indexPath) ? 18 : 0
  1451. }
  1452. func messageTopLabelHeight(for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> CGFloat {
  1453. if isInfoMessage(at: indexPath) {
  1454. return 0
  1455. }
  1456. if isFromCurrentSender(message: message) {
  1457. if !isGroupChat {
  1458. return !isPreviousMessageSameSender(at: indexPath) ? 20 : 0
  1459. } else {
  1460. return !isPreviousMessageSameSender(at: indexPath) ? 20 : 0
  1461. }
  1462. } else {
  1463. if !isGroupChat {
  1464. return !isPreviousMessageSameSender(at: indexPath) ? 20 : 0
  1465. } else {
  1466. return !isPreviousMessageSameSender(at: indexPath) ? (20 + outgoingAvatarOverlap) : 0
  1467. }
  1468. }
  1469. }
  1470. func messageBottomLabelHeight(for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> CGFloat {
  1471. if isInfoMessage(at: indexPath) {
  1472. return 0
  1473. }
  1474. if !isNextMessageSameSender(at: indexPath) {
  1475. return 16
  1476. }
  1477. if isFromCurrentSender(message: message) {
  1478. return 0
  1479. }
  1480. return 0
  1481. }
  1482. func heightForLocation(message _: MessageType, at _: IndexPath, with _: CGFloat, in _: MessagesCollectionView) -> CGFloat {
  1483. return 40
  1484. }
  1485. func footerViewSize(for _: MessageType, at _: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGSize {
  1486. return CGSize(width: messagesCollectionView.bounds.width, height: 10)
  1487. }
  1488. */
  1489. extension ChatViewController {
  1490. @objc private func clipperButtonPressed() {
  1491. showClipperOptions()
  1492. }
  1493. private func photoButtonPressed() {
  1494. if UIImagePickerController.isSourceTypeAvailable(.camera) {
  1495. let cameraViewController = CameraViewController { [weak self] image, _ in
  1496. self?.dismiss(animated: true, completion: nil)
  1497. DispatchQueue.global().async {
  1498. if let pickedImage = image {
  1499. let width = Int32(exactly: pickedImage.size.width)!
  1500. let height = Int32(exactly: pickedImage.size.height)!
  1501. let path = Utils.saveImage(image: pickedImage)
  1502. let msg = dc_msg_new(mailboxPointer, DC_MSG_IMAGE)
  1503. dc_msg_set_file(msg, path, "image/jpeg")
  1504. dc_msg_set_dimension(msg, width, height)
  1505. dc_send_msg(mailboxPointer, UInt32(self!.chatId), msg)
  1506. // cleanup
  1507. dc_msg_unref(msg)
  1508. }
  1509. }
  1510. }
  1511. present(cameraViewController, animated: true, completion: nil)
  1512. } else {
  1513. let alert = UIAlertController(title: "Camera is not available", message: nil, preferredStyle: .alert)
  1514. alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: { _ in
  1515. self.dismiss(animated: true, completion: nil)
  1516. }))
  1517. present(alert, animated: true, completion: nil)
  1518. }
  1519. }
  1520. private func showClipperOptions() {
  1521. let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
  1522. let photoAction = PhotoPickerAlertAction(title: "Photo", style: .default, handler: photoActionPressed(_:))
  1523. alert.addAction(photoAction)
  1524. alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
  1525. self.present(alert, animated: true, completion: nil)
  1526. }
  1527. private func photoActionPressed(_ action: UIAlertAction) {
  1528. photoButtonPressed()
  1529. }
  1530. }
  1531. // MARK: - MessageCellDelegate
  1532. extension ChatViewController: MessageCellDelegate {
  1533. func didTapMessage(in cell: MessageCollectionViewCell) {
  1534. if let indexPath = messagesCollectionView.indexPath(for: cell) {
  1535. let message = messageList[indexPath.section]
  1536. if let url = message.fileURL {
  1537. previewController = PreviewController(urls: [url])
  1538. present(previewController!.qlController, animated: true)
  1539. }
  1540. }
  1541. }
  1542. func didTapAvatar(in cell: MessageCollectionViewCell) {
  1543. logger.info("Avatar tapped")
  1544. if let indexPath = super.messagesCollectionView.indexPath(for: cell) {
  1545. let contactId = messageList[indexPath.row].fromContact.id
  1546. coordinator?.showContactDetail(of: contactId)
  1547. }
  1548. }
  1549. @objc(didTapCellTopLabelIn:) func didTapCellTopLabel(in _: MessageCollectionViewCell) {
  1550. logger.info("Top label tapped")
  1551. }
  1552. func didTapBottomLabel(in _: MessageCollectionViewCell) {
  1553. print("Bottom label tapped")
  1554. }
  1555. }
  1556. class PreviewController: QLPreviewControllerDataSource {
  1557. var urls: [URL]
  1558. var qlController: QLPreviewController
  1559. init(urls: [URL]) {
  1560. self.urls = urls
  1561. qlController = QLPreviewController()
  1562. qlController.dataSource = self
  1563. }
  1564. func numberOfPreviewItems(in _: QLPreviewController) -> Int {
  1565. return urls.count
  1566. }
  1567. func previewController(_: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
  1568. return urls[index] as QLPreviewItem
  1569. }
  1570. }
  1571. // MARK: - MessageLabelDelegate
  1572. extension ChatViewController: MessageLabelDelegate {
  1573. func didSelectAddress(_ addressComponents: [String: String]) {
  1574. let mapAddress = Utils.formatAddressForQuery(address: addressComponents)
  1575. if let escapedMapAddress = mapAddress.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
  1576. // Use query, to handle malformed addresses
  1577. if let url = URL(string: "http://maps.apple.com/?q=\(escapedMapAddress)") {
  1578. UIApplication.shared.open(url as URL)
  1579. }
  1580. }
  1581. }
  1582. func didSelectDate(_ date: Date) {
  1583. let interval = date.timeIntervalSinceReferenceDate
  1584. if let url = NSURL(string: "calshow:\(interval)") {
  1585. UIApplication.shared.open(url as URL)
  1586. }
  1587. }
  1588. func didSelectPhoneNumber(_ phoneNumber: String) {
  1589. logger.info("phone open", phoneNumber)
  1590. if let escapedPhoneNumber = phoneNumber.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
  1591. if let url = NSURL(string: "tel:\(escapedPhoneNumber)") {
  1592. UIApplication.shared.open(url as URL)
  1593. }
  1594. }
  1595. }
  1596. func didSelectURL(_ url: URL) {
  1597. UIApplication.shared.open(url)
  1598. }
  1599. }
  1600. // MARK: - LocationMessageDisplayDelegate
  1601. /*
  1602. extension ChatViewController: LocationMessageDisplayDelegate {
  1603. func annotationViewForLocation(message: MessageType, at indexPath: IndexPath, in messageCollectionView: MessagesCollectionView) -> MKAnnotationView? {
  1604. let annotationView = MKAnnotationView(annotation: nil, reuseIdentifier: nil)
  1605. let pinImage = #imageLiteral(resourceName: "ic_block_36pt").withRenderingMode(.alwaysTemplate)
  1606. annotationView.image = pinImage
  1607. annotationView.centerOffset = CGPoint(x: 0, y: -pinImage.size.height / 2)
  1608. return annotationView
  1609. }
  1610. func animationBlockForLocation(message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> ((UIImageView) -> Void)? {
  1611. return { view in
  1612. view.layer.transform = CATransform3DMakeScale(0, 0, 0)
  1613. view.alpha = 0.0
  1614. UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0, options: [], animations: {
  1615. view.layer.transform = CATransform3DIdentity
  1616. view.alpha = 1.0
  1617. }, completion: nil)
  1618. }
  1619. }
  1620. }
  1621. */
  1622. // MARK: - MessageInputBarDelegate
  1623. extension ChatViewController: InputBarAccessoryViewDelegate {
  1624. func inputBar(_ inputBar: InputBarAccessoryView, didPressSendButtonWith text: String) {
  1625. DispatchQueue.global().async {
  1626. dc_send_text_msg(mailboxPointer, UInt32(self.chatId), text)
  1627. }
  1628. inputBar.inputTextView.text = String()
  1629. }
  1630. }
  1631. /*
  1632. extension ChatViewController: MessageInputBarDelegate {
  1633. }
  1634. */
  1635. // MARK: - MessageCollectionViewCell
  1636. extension MessageCollectionViewCell {
  1637. @objc func messageInfo(_ sender: Any?) {
  1638. // Get the collectionView
  1639. if let collectionView = self.superview as? UICollectionView {
  1640. // Get indexPath
  1641. if let indexPath = collectionView.indexPath(for: self) {
  1642. // Trigger action
  1643. collectionView.delegate?.collectionView?(collectionView, performAction: #selector(MessageCollectionViewCell.messageInfo(_:)), forItemAt: indexPath, withSender: sender)
  1644. }
  1645. }
  1646. }
  1647. @objc func messageBlock(_ sender: Any?) {
  1648. // Get the collectionView
  1649. if let collectionView = self.superview as? UICollectionView {
  1650. // Get indexPath
  1651. if let indexPath = collectionView.indexPath(for: self) {
  1652. // Trigger action
  1653. collectionView.delegate?.collectionView?(collectionView, performAction: #selector(MessageCollectionViewCell.messageBlock(_:)), forItemAt: indexPath, withSender: sender)
  1654. }
  1655. }
  1656. }
  1657. @objc func messageDismiss(_ sender: Any?) {
  1658. // Get the collectionView
  1659. if let collectionView = self.superview as? UICollectionView {
  1660. // Get indexPath
  1661. if let indexPath = collectionView.indexPath(for: self) {
  1662. // Trigger action
  1663. collectionView.delegate?.collectionView?(collectionView, performAction: #selector(MessageCollectionViewCell.messageDismiss(_:)), forItemAt: indexPath, withSender: sender)
  1664. }
  1665. }
  1666. }
  1667. @objc func messageStartChat(_ sender: Any?) {
  1668. // Get the collectionView
  1669. if let collectionView = self.superview as? UICollectionView {
  1670. // Get indexPath
  1671. if let indexPath = collectionView.indexPath(for: self) {
  1672. // Trigger action
  1673. collectionView.delegate?.collectionView?(collectionView, performAction: #selector(MessageCollectionViewCell.messageStartChat(_:)), forItemAt: indexPath, withSender: sender)
  1674. }
  1675. }
  1676. }
  1677. }
  1678. */