ChatViewController.swift 72 KB

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