ChatViewController.swift 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437
  1. import MapKit
  2. import QuickLook
  3. import UIKit
  4. import InputBarAccessoryView
  5. import AVFoundation
  6. import DcCore
  7. import SDWebImage
  8. class ChatViewController: UITableViewController {
  9. var dcContext: DcContext
  10. private var draftMessage: DcMsg?
  11. let outgoingAvatarOverlap: CGFloat = 17.5
  12. let loadCount = 30
  13. let chatId: Int
  14. var messageIds: [Int] = []
  15. var msgChangedObserver: Any?
  16. var incomingMsgObserver: Any?
  17. var ephemeralTimerModifiedObserver: Any?
  18. var dismissCancelled = false
  19. lazy var isGroupChat: Bool = {
  20. return dcContext.getChat(chatId: chatId).isGroup
  21. }()
  22. lazy var draft: DraftModel = {
  23. let draft = DraftModel(chatId: chatId)
  24. return draft
  25. }()
  26. /// The `InputBarAccessoryView` used as the `inputAccessoryView` in the view controller.
  27. open var messageInputBar = ChatInputBar()
  28. lazy var draftArea: DraftArea = {
  29. let view = DraftArea()
  30. view.translatesAutoresizingMaskIntoConstraints = false
  31. view.delegate = self
  32. view.inputBarAccessoryView = messageInputBar
  33. return view
  34. }()
  35. public lazy var editingBar: ChatEditingBar = {
  36. let view = ChatEditingBar()
  37. view.delegate = self
  38. view.translatesAutoresizingMaskIntoConstraints = false
  39. return view
  40. }()
  41. open override var shouldAutorotate: Bool {
  42. return false
  43. }
  44. private weak var timer: Timer?
  45. lazy var navBarTap: UITapGestureRecognizer = {
  46. UITapGestureRecognizer(target: self, action: #selector(chatProfilePressed))
  47. }()
  48. private var locationStreamingItem: UIBarButtonItem = {
  49. let indicator = LocationStreamingIndicator()
  50. return UIBarButtonItem(customView: indicator)
  51. }()
  52. private lazy var muteItem: UIBarButtonItem = {
  53. let imageView = UIImageView()
  54. imageView.tintColor = DcColors.defaultTextColor
  55. imageView.image = #imageLiteral(resourceName: "volume_off").withRenderingMode(.alwaysTemplate)
  56. imageView.translatesAutoresizingMaskIntoConstraints = false
  57. imageView.heightAnchor.constraint(equalToConstant: 20).isActive = true
  58. imageView.widthAnchor.constraint(equalToConstant: 20).isActive = true
  59. return UIBarButtonItem(customView: imageView)
  60. }()
  61. private lazy var ephemeralMessageItem: UIBarButtonItem = {
  62. let imageView = UIImageView()
  63. imageView.tintColor = DcColors.defaultTextColor
  64. imageView.image = #imageLiteral(resourceName: "ephemeral_timer").withRenderingMode(.alwaysTemplate)
  65. imageView.translatesAutoresizingMaskIntoConstraints = false
  66. imageView.heightAnchor.constraint(equalToConstant: 20).isActive = true
  67. imageView.widthAnchor.constraint(equalToConstant: 20).isActive = true
  68. return UIBarButtonItem(customView: imageView)
  69. }()
  70. private lazy var badgeItem: UIBarButtonItem = {
  71. let badge: InitialsBadge
  72. let chat = dcContext.getChat(chatId: chatId)
  73. if let image = chat.profileImage {
  74. badge = InitialsBadge(image: image, size: 28, accessibilityLabel: String.localized("menu_view_profile"))
  75. } else {
  76. badge = InitialsBadge(
  77. name: chat.name,
  78. color: chat.color,
  79. size: 28,
  80. accessibilityLabel: String.localized("menu_view_profile")
  81. )
  82. badge.setLabelFont(UIFont.systemFont(ofSize: 14))
  83. }
  84. badge.setVerified(chat.isProtected)
  85. badge.accessibilityTraits = .button
  86. return UIBarButtonItem(customView: badge)
  87. }()
  88. private lazy var contextMenu: ContextMenuProvider = {
  89. let copyItem = ContextMenuProvider.ContextMenuItem(
  90. title: String.localized("global_menu_edit_copy_desktop"),
  91. imageName: "ic_content_copy_white_36pt",
  92. action: #selector(BaseMessageCell.messageCopy),
  93. onPerform: { [weak self] indexPath in
  94. guard let self = self else { return }
  95. let id = self.messageIds[indexPath.row]
  96. let msg = DcMsg(id: id)
  97. let pasteboard = UIPasteboard.general
  98. if msg.type == DC_MSG_TEXT {
  99. pasteboard.string = msg.text
  100. } else {
  101. pasteboard.string = msg.summary(chars: 10000000)
  102. }
  103. }
  104. )
  105. let infoItem = ContextMenuProvider.ContextMenuItem(
  106. title: String.localized("info"),
  107. imageName: "info",
  108. action: #selector(BaseMessageCell.messageInfo),
  109. onPerform: { [weak self] indexPath in
  110. guard let self = self else { return }
  111. let msg = DcMsg(id: self.messageIds[indexPath.row])
  112. let msgViewController = MessageInfoViewController(dcContext: self.dcContext, message: msg)
  113. if let ctrl = self.navigationController {
  114. ctrl.pushViewController(msgViewController, animated: true)
  115. }
  116. }
  117. )
  118. let deleteItem = ContextMenuProvider.ContextMenuItem(
  119. title: String.localized("delete"),
  120. imageName: "ic_delete",
  121. isDestructive: true,
  122. action: #selector(BaseMessageCell.messageDelete),
  123. onPerform: { [weak self] indexPath in
  124. DispatchQueue.main.async { [weak self] in
  125. guard let self = self else { return }
  126. self.tableView.becomeFirstResponder()
  127. let msg = DcMsg(id: self.messageIds[indexPath.row])
  128. self.askToDeleteMessage(id: msg.id)
  129. }
  130. }
  131. )
  132. let forwardItem = ContextMenuProvider.ContextMenuItem(
  133. title: String.localized("forward"),
  134. imageName: "ic_forward_white_36pt",
  135. action: #selector(BaseMessageCell.messageForward),
  136. onPerform: { [weak self] indexPath in
  137. guard let self = self else { return }
  138. let msg = DcMsg(id: self.messageIds[indexPath.row])
  139. RelayHelper.sharedInstance.setForwardMessage(messageId: msg.id)
  140. self.navigationController?.popViewController(animated: true)
  141. }
  142. )
  143. let replyItem = ContextMenuProvider.ContextMenuItem(
  144. title: String.localized("notify_reply_button"),
  145. imageName: "ic_reply",
  146. action: #selector(BaseMessageCell.messageReply),
  147. onPerform: { indexPath in
  148. DispatchQueue.main.async { [weak self] in
  149. self?.replyToMessage(at: indexPath)
  150. }
  151. }
  152. )
  153. let selectMoreItem = ContextMenuProvider.ContextMenuItem(
  154. title: String.localized("select_more"),
  155. imageName: "ic_check",
  156. action: #selector(BaseMessageCell.messageSelectMore),
  157. onPerform: { indexPath in
  158. DispatchQueue.main.async { [weak self] in
  159. guard let self = self else { return }
  160. let messageId = self.messageIds[indexPath.row]
  161. self.setEditing(isEditing: true, selectedAtIndexPath: indexPath)
  162. }
  163. }
  164. )
  165. let config = ContextMenuProvider()
  166. if #available(iOS 13.0, *), !disableWriting {
  167. config.setMenu([replyItem, forwardItem, infoItem, copyItem, selectMoreItem, deleteItem])
  168. } else {
  169. config.setMenu([forwardItem, infoItem, copyItem, deleteItem, selectMoreItem])
  170. }
  171. return config
  172. }()
  173. /// The `BasicAudioController` controll the AVAudioPlayer state (play, pause, stop) and update audio cell UI accordingly.
  174. private lazy var audioController = AudioController(dcContext: dcContext, chatId: chatId)
  175. private var disableWriting: Bool
  176. private var showNamesAboveMessage: Bool
  177. var showCustomNavBar = true
  178. var highlightedMsg: Int?
  179. private lazy var mediaPicker: MediaPicker? = {
  180. let mediaPicker = MediaPicker(navigationController: navigationController)
  181. mediaPicker.delegate = self
  182. return mediaPicker
  183. }()
  184. var emptyStateView: EmptyStateLabel = {
  185. let view = EmptyStateLabel()
  186. view.isHidden = true
  187. return view
  188. }()
  189. init(dcContext: DcContext, chatId: Int, highlightedMsg: Int? = nil) {
  190. let dcChat = dcContext.getChat(chatId: chatId)
  191. self.dcContext = dcContext
  192. self.chatId = chatId
  193. self.disableWriting = !dcChat.canSend
  194. self.showNamesAboveMessage = dcChat.isGroup
  195. self.highlightedMsg = highlightedMsg
  196. super.init(nibName: nil, bundle: nil)
  197. hidesBottomBarWhenPushed = true
  198. }
  199. required init?(coder _: NSCoder) {
  200. fatalError("init(coder:) has not been implemented")
  201. }
  202. override func loadView() {
  203. self.tableView = ChatTableView(messageInputBar: self.disableWriting ? nil : messageInputBar)
  204. self.tableView.delegate = self
  205. self.tableView.dataSource = self
  206. self.view = self.tableView
  207. }
  208. override func viewDidLoad() {
  209. super.viewDidLoad()
  210. tableView.register(TextMessageCell.self, forCellReuseIdentifier: "text")
  211. tableView.register(ImageTextCell.self, forCellReuseIdentifier: "image")
  212. tableView.register(FileTextCell.self, forCellReuseIdentifier: "file")
  213. tableView.register(InfoMessageCell.self, forCellReuseIdentifier: "info")
  214. tableView.register(AudioMessageCell.self, forCellReuseIdentifier: "audio")
  215. tableView.rowHeight = UITableView.automaticDimension
  216. tableView.separatorStyle = .none
  217. tableView.keyboardDismissMode = .interactive
  218. if !dcContext.isConfigured() {
  219. // TODO: display message about nothing being configured
  220. return
  221. }
  222. configureEmptyStateView()
  223. if !disableWriting {
  224. configureMessageInputBar()
  225. draft.parse(draftMsg: dcContext.getDraft(chatId: chatId))
  226. messageInputBar.inputTextView.text = draft.text
  227. configureDraftArea(draft: draft)
  228. editingBar.delegate = self
  229. tableView.allowsMultipleSelectionDuringEditing = true
  230. }
  231. let notificationCenter = NotificationCenter.default
  232. notificationCenter.addObserver(self,
  233. selector: #selector(saveDraft),
  234. name: UIApplication.willResignActiveNotification,
  235. object: nil)
  236. notificationCenter.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
  237. }
  238. @objc func keyboardWillShow(_ notification: Notification) {
  239. if self.isLastRowVisible() {
  240. DispatchQueue.main.async { [weak self] in
  241. if self?.messageInputBar.keyboardHeight ?? 0 > 0 {
  242. self?.scrollToBottom(animated: true)
  243. } else { // inputbar height increased, probably because of draft area changes
  244. self?.scrollToBottom(animated: false)
  245. }
  246. }
  247. }
  248. }
  249. private func startTimer() {
  250. timer?.invalidate()
  251. timer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { [weak self] _ in
  252. //reload table
  253. DispatchQueue.main.async {
  254. guard let self = self else { return }
  255. self.messageIds = self.getMessageIds()
  256. self.reloadData()
  257. }
  258. }
  259. }
  260. private func stopTimer() {
  261. timer?.invalidate()
  262. }
  263. private func configureEmptyStateView() {
  264. emptyStateView.addCenteredTo(parentView: view)
  265. }
  266. override func viewWillAppear(_ animated: Bool) {
  267. super.viewWillAppear(animated)
  268. if dismissCancelled {
  269. self.dismissCancelled = false
  270. } else {
  271. self.tableView.becomeFirstResponder()
  272. }
  273. // this will be removed in viewWillDisappear
  274. navigationController?.navigationBar.addGestureRecognizer(navBarTap)
  275. if showCustomNavBar {
  276. updateTitle(chat: dcContext.getChat(chatId: chatId))
  277. }
  278. loadMessages()
  279. if RelayHelper.sharedInstance.isForwarding() {
  280. askToForwardMessage()
  281. }
  282. prepareContextMenu()
  283. }
  284. override func viewDidAppear(_ animated: Bool) {
  285. super.viewDidAppear(animated)
  286. AppStateRestorer.shared.storeLastActiveChat(chatId: chatId)
  287. let nc = NotificationCenter.default
  288. msgChangedObserver = nc.addObserver(
  289. forName: dcNotificationChanged,
  290. object: nil,
  291. queue: OperationQueue.main
  292. ) { [weak self] notification in
  293. guard let self = self else { return }
  294. if let ui = notification.userInfo {
  295. if self.disableWriting {
  296. // always refresh, as we can't check currently
  297. self.refreshMessages()
  298. } else if let id = ui["message_id"] as? Int {
  299. if id > 0 {
  300. self.updateMessage(id)
  301. } else {
  302. // change might be a deletion
  303. self.refreshMessages()
  304. }
  305. }
  306. if self.showCustomNavBar {
  307. self.updateTitle(chat: self.dcContext.getChat(chatId: self.chatId))
  308. }
  309. }
  310. }
  311. incomingMsgObserver = nc.addObserver(
  312. forName: dcNotificationIncoming,
  313. object: nil, queue: OperationQueue.main
  314. ) { [weak self] notification in
  315. guard let self = self else { return }
  316. if let ui = notification.userInfo {
  317. if self.chatId == ui["chat_id"] as? Int {
  318. if let id = ui["message_id"] as? Int {
  319. if id > 0 {
  320. self.insertMessage(DcMsg(id: id))
  321. }
  322. }
  323. }
  324. }
  325. }
  326. ephemeralTimerModifiedObserver = nc.addObserver(
  327. forName: dcEphemeralTimerModified,
  328. object: nil, queue: OperationQueue.main
  329. ) { [weak self] _ in
  330. guard let self = self else { return }
  331. self.updateTitle(chat: self.dcContext.getChat(chatId: self.chatId))
  332. }
  333. // things that do not affect the chatview
  334. // and are delayed after the view is displayed
  335. DispatchQueue.global(qos: .background).async { [weak self] in
  336. guard let self = self else { return }
  337. self.dcContext.marknoticedChat(chatId: self.chatId)
  338. }
  339. startTimer()
  340. }
  341. override func viewWillDisappear(_ animated: Bool) {
  342. super.viewWillDisappear(animated)
  343. // the navigationController will be used when chatDetail is pushed, so we have to remove that gestureRecognizer
  344. navigationController?.navigationBar.removeGestureRecognizer(navBarTap)
  345. dismissCancelled = true
  346. }
  347. override func viewDidDisappear(_ animated: Bool) {
  348. super.viewDidDisappear(animated)
  349. dismissCancelled = false
  350. AppStateRestorer.shared.resetLastActiveChat()
  351. saveDraft()
  352. let nc = NotificationCenter.default
  353. if let msgChangedObserver = self.msgChangedObserver {
  354. nc.removeObserver(msgChangedObserver)
  355. }
  356. if let incomingMsgObserver = self.incomingMsgObserver {
  357. nc.removeObserver(incomingMsgObserver)
  358. }
  359. if let ephemeralTimerModifiedObserver = self.ephemeralTimerModifiedObserver {
  360. nc.removeObserver(ephemeralTimerModifiedObserver)
  361. }
  362. audioController.stopAnyOngoingPlaying()
  363. stopTimer()
  364. }
  365. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  366. let lastSectionVisibleBeforeTransition = self.isLastRowVisible()
  367. coordinator.animate(
  368. alongsideTransition: { [weak self] _ in
  369. guard let self = self else { return }
  370. if self.showCustomNavBar {
  371. self.navigationItem.setRightBarButton(self.badgeItem, animated: true)
  372. }
  373. if lastSectionVisibleBeforeTransition {
  374. self.scrollToBottom(animated: false)
  375. }
  376. },
  377. completion: {[weak self] _ in
  378. guard let self = self else { return }
  379. self.updateTitle(chat: self.dcContext.getChat(chatId: self.chatId))
  380. if lastSectionVisibleBeforeTransition {
  381. DispatchQueue.main.async { [weak self] in
  382. self?.reloadData()
  383. self?.scrollToBottom(animated: false)
  384. }
  385. }
  386. }
  387. )
  388. super.viewWillTransition(to: size, with: coordinator)
  389. }
  390. /// UITableView methods
  391. override func numberOfSections(in tableView: UITableView) -> Int {
  392. return 1
  393. }
  394. override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
  395. return messageIds.count
  396. }
  397. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  398. _ = handleUIMenu()
  399. let id = messageIds[indexPath.row]
  400. let message = DcMsg(id: id)
  401. if message.isInfo {
  402. let cell = tableView.dequeueReusableCell(withIdentifier: "info", for: indexPath) as? InfoMessageCell ?? InfoMessageCell()
  403. cell.update(msg: message)
  404. return cell
  405. }
  406. let cell: BaseMessageCell
  407. if message.type == DC_MSG_IMAGE || message.type == DC_MSG_GIF || message.type == DC_MSG_VIDEO {
  408. cell = tableView.dequeueReusableCell(withIdentifier: "image", for: indexPath) as? ImageTextCell ?? ImageTextCell()
  409. } else if message.type == DC_MSG_FILE {
  410. if message.isSetupMessage {
  411. cell = tableView.dequeueReusableCell(withIdentifier: "text", for: indexPath) as? TextMessageCell ?? TextMessageCell()
  412. message.text = String.localized("autocrypt_asm_click_body")
  413. } else {
  414. cell = tableView.dequeueReusableCell(withIdentifier: "file", for: indexPath) as? FileTextCell ?? FileTextCell()
  415. }
  416. } else if message.type == DC_MSG_AUDIO || message.type == DC_MSG_VOICE {
  417. let audioMessageCell: AudioMessageCell = tableView.dequeueReusableCell(withIdentifier: "audio",
  418. for: indexPath) as? AudioMessageCell ?? AudioMessageCell()
  419. audioController.update(audioMessageCell, with: message.id)
  420. cell = audioMessageCell
  421. } else {
  422. cell = tableView.dequeueReusableCell(withIdentifier: "text", for: indexPath) as? TextMessageCell ?? TextMessageCell()
  423. }
  424. cell.baseDelegate = self
  425. cell.update(msg: message,
  426. messageStyle: configureMessageStyle(for: message, at: indexPath),
  427. isAvatarVisible: configureAvatarVisibility(for: message, at: indexPath),
  428. isGroup: isGroupChat)
  429. return cell
  430. }
  431. public override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  432. if !decelerate {
  433. markSeenMessagesInVisibleArea()
  434. }
  435. }
  436. public override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  437. markSeenMessagesInVisibleArea()
  438. }
  439. private func configureDraftArea(draft: DraftModel) {
  440. draftArea.configure(draft: draft)
  441. if draft.isEditing {
  442. messageInputBar.setMiddleContentView(editingBar, animated: false)
  443. } else {
  444. messageInputBar.setMiddleContentView(messageInputBar.inputTextView, animated: false)
  445. }
  446. messageInputBar.setStackViewItems([draftArea], forStack: .top, animated: true)
  447. }
  448. override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
  449. if disableWriting {
  450. return nil
  451. }
  452. let action = UIContextualAction(style: .normal, title: nil,
  453. handler: { [weak self] (_, _, completionHandler) in
  454. self?.replyToMessage(at: indexPath)
  455. completionHandler(true)
  456. })
  457. if #available(iOS 12.0, *) {
  458. action.image = UIImage(named: traitCollection.userInterfaceStyle == .light ? "ic_reply_black" : "ic_reply")
  459. } else {
  460. action.image = UIImage(named: "ic_reply_black")
  461. }
  462. action.image?.accessibilityTraits = .button
  463. action.image?.accessibilityLabel = String.localized("menu_reply")
  464. action.backgroundColor = DcColors.chatBackgroundColor
  465. let configuration = UISwipeActionsConfiguration(actions: [action])
  466. return configuration
  467. }
  468. func replyToMessage(at indexPath: IndexPath) {
  469. let message = DcMsg(id: self.messageIds[indexPath.row])
  470. self.draft.setQuote(quotedMsg: message)
  471. self.configureDraftArea(draft: self.draft)
  472. self.messageInputBar.inputTextView.becomeFirstResponder()
  473. }
  474. func markSeenMessagesInVisibleArea() {
  475. if let indexPaths = tableView.indexPathsForVisibleRows {
  476. let visibleMessagesIds = indexPaths.map { UInt32(messageIds[$0.row]) }
  477. if !visibleMessagesIds.isEmpty {
  478. DispatchQueue.global(qos: .background).async { [weak self] in
  479. self?.dcContext.markSeenMessages(messageIds: visibleMessagesIds)
  480. }
  481. }
  482. }
  483. }
  484. override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
  485. if tableView.isEditing {
  486. handleEditingBar()
  487. }
  488. }
  489. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  490. if tableView.isEditing {
  491. handleEditingBar()
  492. return
  493. }
  494. let messageId = messageIds[indexPath.row]
  495. let message = DcMsg(id: messageId)
  496. if message.isSetupMessage {
  497. didTapAsm(msg: message, orgText: "")
  498. } else if message.type == DC_MSG_FILE ||
  499. message.type == DC_MSG_AUDIO ||
  500. message.type == DC_MSG_VOICE {
  501. showMediaGalleryFor(message: message)
  502. }
  503. _ = handleUIMenu()
  504. }
  505. func configureAvatarVisibility(for message: DcMsg, at indexPath: IndexPath) -> Bool {
  506. return isGroupChat && !message.isFromCurrentSender
  507. }
  508. func configureMessageStyle(for message: DcMsg, at indexPath: IndexPath) -> UIRectCorner {
  509. var corners: UIRectCorner = []
  510. if message.isFromCurrentSender {
  511. corners.formUnion(.topLeft)
  512. corners.formUnion(.bottomLeft)
  513. corners.formUnion(.topRight)
  514. } else {
  515. corners.formUnion(.topRight)
  516. corners.formUnion(.bottomRight)
  517. corners.formUnion(.topLeft)
  518. }
  519. return corners
  520. }
  521. private func getBackgroundColor(for currentMessage: DcMsg) -> UIColor {
  522. return currentMessage.isFromCurrentSender ? DcColors.messagePrimaryColor : DcColors.messageSecondaryColor
  523. }
  524. private func updateTitle(chat: DcChat) {
  525. let titleView = ChatTitleView()
  526. var subtitle = "ErrSubtitle"
  527. let chatContactIds = chat.contactIds
  528. if chat.isGroup {
  529. subtitle = String.localized(stringID: "n_members", count: chatContactIds.count)
  530. } else if chatContactIds.count >= 1 {
  531. if chat.isDeviceTalk {
  532. subtitle = String.localized("device_talk_subtitle")
  533. } else if chat.isSelfTalk {
  534. subtitle = String.localized("chat_self_talk_subtitle")
  535. } else {
  536. subtitle = DcContact(id: chatContactIds[0]).email
  537. }
  538. }
  539. titleView.updateTitleView(title: chat.name, subtitle: subtitle)
  540. navigationItem.titleView = titleView
  541. var rightBarButtonItems = [badgeItem]
  542. if chat.isSendingLocations {
  543. rightBarButtonItems.append(locationStreamingItem)
  544. }
  545. if chat.isMuted {
  546. rightBarButtonItems.append(muteItem)
  547. }
  548. if dcContext.getChatEphemeralTimer(chatId: chat.id) > 0 {
  549. rightBarButtonItems.append(ephemeralMessageItem)
  550. }
  551. navigationItem.rightBarButtonItems = rightBarButtonItems
  552. }
  553. @objc
  554. private func refreshMessages() {
  555. self.messageIds = self.getMessageIds()
  556. let wasLastSectionVisible = self.isLastRowVisible()
  557. self.reloadData()
  558. if wasLastSectionVisible {
  559. self.scrollToBottom(animated: true)
  560. }
  561. self.showEmptyStateView(self.messageIds.isEmpty)
  562. }
  563. func reloadData() {
  564. let selectredRows = tableView.indexPathsForSelectedRows
  565. tableView.reloadData()
  566. // There's an iOS bug, filling up the console output but which can be ignored: https://developer.apple.com/forums/thread/668295
  567. // [Assert] Attempted to call -cellForRowAtIndexPath: on the table view while it was in the process of updating its visible cells, which is not allowed.
  568. selectredRows?.forEach({ (selectedRow) in
  569. tableView.selectRow(at: selectedRow, animated: false, scrollPosition: .none)
  570. })
  571. }
  572. private func loadMessages() {
  573. DispatchQueue.global(qos: .userInitiated).async {
  574. DispatchQueue.main.async { [weak self] in
  575. guard let self = self else { return }
  576. let wasLastRowVisible = self.isLastRowVisible()
  577. let wasMessageIdsEmpty = self.messageIds.isEmpty
  578. // update message ids
  579. self.messageIds = self.getMessageIds()
  580. self.reloadData()
  581. if let msgId = self.highlightedMsg, let msgPosition = self.messageIds.firstIndex(of: msgId) {
  582. self.tableView.scrollToRow(at: IndexPath(row: msgPosition, section: 0), at: .top, animated: false)
  583. self.highlightedMsg = nil
  584. } else if wasMessageIdsEmpty ||
  585. wasLastRowVisible {
  586. self.scrollToBottom(animated: false)
  587. }
  588. self.showEmptyStateView(self.messageIds.isEmpty)
  589. }
  590. }
  591. }
  592. func isLastRowVisible() -> Bool {
  593. guard !messageIds.isEmpty else { return false }
  594. let lastIndexPath = IndexPath(item: messageIds.count - 1, section: 0)
  595. return tableView.indexPathsForVisibleRows?.contains(lastIndexPath) ?? false
  596. }
  597. func scrollToBottom(animated: Bool) {
  598. if !messageIds.isEmpty {
  599. self.tableView.scrollToRow(at: IndexPath(row: self.messageIds.count - 1, section: 0), at: .bottom, animated: animated)
  600. }
  601. }
  602. func scrollToMessage(msgId: Int, animated: Bool = true) {
  603. guard let index = messageIds.firstIndex(of: msgId) else {
  604. return
  605. }
  606. let indexPath = IndexPath(row: index, section: 0)
  607. tableView.scrollToRow(at: indexPath, at: .top, animated: animated)
  608. }
  609. private func showEmptyStateView(_ show: Bool) {
  610. if show {
  611. let dcChat = dcContext.getChat(chatId: chatId)
  612. if chatId == DC_CHAT_ID_DEADDROP {
  613. if dcContext.showEmails != DC_SHOW_EMAILS_ALL {
  614. emptyStateView.text = String.localized("chat_no_contact_requests")
  615. } else {
  616. emptyStateView.text = String.localized("chat_no_messages")
  617. }
  618. } else if dcChat.isGroup {
  619. if dcChat.isUnpromoted {
  620. emptyStateView.text = String.localized("chat_new_group_hint")
  621. } else {
  622. emptyStateView.text = String.localized("chat_no_messages")
  623. }
  624. } else if dcChat.isSelfTalk {
  625. emptyStateView.text = String.localized("saved_messages_explain")
  626. } else if dcChat.isDeviceTalk {
  627. emptyStateView.text = String.localized("device_talk_explain")
  628. } else {
  629. emptyStateView.text = String.localizedStringWithFormat(String.localized("chat_no_messages_hint"), dcChat.name, dcChat.name)
  630. }
  631. emptyStateView.isHidden = false
  632. } else {
  633. emptyStateView.isHidden = true
  634. }
  635. }
  636. private func getMessageIds() -> [Int] {
  637. return dcContext.getMessageIds(chatId: chatId)
  638. }
  639. @objc private func saveDraft() {
  640. draft.save(context: dcContext)
  641. }
  642. private func configureMessageInputBar() {
  643. messageInputBar.delegate = self
  644. messageInputBar.inputTextView.tintColor = DcColors.primary
  645. messageInputBar.inputTextView.placeholder = String.localized("chat_input_placeholder")
  646. messageInputBar.separatorLine.isHidden = true
  647. messageInputBar.inputTextView.tintColor = DcColors.primary
  648. messageInputBar.inputTextView.textColor = DcColors.defaultTextColor
  649. messageInputBar.backgroundView.backgroundColor = DcColors.chatBackgroundColor
  650. //scrollsToBottomOnKeyboardBeginsEditing = true
  651. messageInputBar.inputTextView.backgroundColor = DcColors.inputFieldColor
  652. messageInputBar.inputTextView.placeholderTextColor = DcColors.placeholderColor
  653. messageInputBar.inputTextView.textContainerInset = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 38)
  654. messageInputBar.inputTextView.placeholderLabelInsets = UIEdgeInsets(top: 8, left: 20, bottom: 8, right: 38)
  655. messageInputBar.inputTextView.layer.borderColor = UIColor.themeColor(light: UIColor(red: 200 / 255, green: 200 / 255, blue: 200 / 255, alpha: 1),
  656. dark: UIColor(red: 55 / 255, green: 55/255, blue: 55/255, alpha: 1)).cgColor
  657. messageInputBar.inputTextView.layer.borderWidth = 1.0
  658. messageInputBar.inputTextView.layer.cornerRadius = 13.0
  659. messageInputBar.inputTextView.layer.masksToBounds = true
  660. messageInputBar.inputTextView.scrollIndicatorInsets = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0)
  661. configureInputBarItems()
  662. }
  663. func evaluateInputBar(draft: DraftModel) {
  664. messageInputBar.sendButton.isEnabled = draft.canSend()
  665. }
  666. private func configureInputBarItems() {
  667. messageInputBar.setLeftStackViewWidthConstant(to: 40, animated: false)
  668. messageInputBar.setRightStackViewWidthConstant(to: 40, animated: false)
  669. let sendButtonImage = UIImage(named: "paper_plane")?.withRenderingMode(.alwaysTemplate)
  670. messageInputBar.sendButton.image = sendButtonImage
  671. messageInputBar.sendButton.accessibilityLabel = String.localized("menu_send")
  672. messageInputBar.sendButton.accessibilityTraits = .button
  673. messageInputBar.sendButton.title = nil
  674. messageInputBar.sendButton.tintColor = UIColor(white: 1, alpha: 1)
  675. messageInputBar.sendButton.layer.cornerRadius = 20
  676. messageInputBar.middleContentViewPadding = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 10)
  677. // this adds a padding between textinputfield and send button
  678. messageInputBar.sendButton.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
  679. messageInputBar.sendButton.setSize(CGSize(width: 40, height: 40), animated: false)
  680. messageInputBar.padding = UIEdgeInsets(top: 6, left: 6, bottom: 6, right: 12)
  681. messageInputBar.shouldManageSendButtonEnabledState = false
  682. let leftItems = [
  683. InputBarButtonItem()
  684. .configure {
  685. $0.spacing = .fixed(0)
  686. let clipperIcon = #imageLiteral(resourceName: "ic_attach_file_36pt").withRenderingMode(.alwaysTemplate)
  687. $0.image = clipperIcon
  688. $0.tintColor = DcColors.primary
  689. $0.setSize(CGSize(width: 40, height: 40), animated: false)
  690. $0.accessibilityLabel = String.localized("menu_add_attachment")
  691. $0.accessibilityTraits = .button
  692. }.onSelected {
  693. $0.tintColor = UIColor.themeColor(light: .lightGray, dark: .darkGray)
  694. }.onDeselected {
  695. $0.tintColor = DcColors.primary
  696. }.onTouchUpInside { [weak self] _ in
  697. self?.clipperButtonPressed()
  698. }
  699. ]
  700. messageInputBar.setStackViewItems(leftItems, forStack: .left, animated: false)
  701. // This just adds some more flare
  702. messageInputBar.sendButton
  703. .onEnabled { item in
  704. UIView.animate(withDuration: 0.3, animations: {
  705. item.backgroundColor = DcColors.primary
  706. })
  707. }.onDisabled { item in
  708. UIView.animate(withDuration: 0.3, animations: {
  709. item.backgroundColor = DcColors.colorDisabled
  710. })
  711. }
  712. }
  713. @objc private func chatProfilePressed() {
  714. if chatId != DC_CHAT_ID_DEADDROP {
  715. showChatDetail(chatId: chatId)
  716. }
  717. }
  718. @objc private func clipperButtonPressed() {
  719. showClipperOptions()
  720. }
  721. private func showClipperOptions() {
  722. let alert = UIAlertController(title: nil, message: nil, preferredStyle: .safeActionSheet)
  723. let galleryAction = PhotoPickerAlertAction(title: String.localized("gallery"), style: .default, handler: galleryButtonPressed(_:))
  724. let cameraAction = PhotoPickerAlertAction(title: String.localized("camera"), style: .default, handler: cameraButtonPressed(_:))
  725. let documentAction = UIAlertAction(title: String.localized("files"), style: .default, handler: documentActionPressed(_:))
  726. let voiceMessageAction = UIAlertAction(title: String.localized("voice_message"), style: .default, handler: voiceMessageButtonPressed(_:))
  727. let isLocationStreaming = dcContext.isSendingLocationsToChat(chatId: chatId)
  728. let locationStreamingAction = UIAlertAction(title: isLocationStreaming ? String.localized("stop_sharing_location") : String.localized("location"),
  729. style: isLocationStreaming ? .destructive : .default,
  730. handler: locationStreamingButtonPressed(_:))
  731. alert.addAction(cameraAction)
  732. alert.addAction(galleryAction)
  733. alert.addAction(documentAction)
  734. alert.addAction(voiceMessageAction)
  735. if UserDefaults.standard.bool(forKey: "location_streaming") {
  736. alert.addAction(locationStreamingAction)
  737. }
  738. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  739. self.present(alert, animated: true, completion: {
  740. // unfortunately, voiceMessageAction.accessibilityHint does not work,
  741. // but this hack does the trick
  742. if UIAccessibility.isVoiceOverRunning {
  743. if let view = voiceMessageAction.value(forKey: "__representer") as? UIView {
  744. view.accessibilityHint = String.localized("a11y_voice_message_hint_ios")
  745. }
  746. }
  747. })
  748. }
  749. private func confirmationAlert(title: String, actionTitle: String, actionStyle: UIAlertAction.Style = .default, actionHandler: @escaping ((UIAlertAction) -> Void), cancelHandler: ((UIAlertAction) -> Void)? = nil) {
  750. let alert = UIAlertController(title: title,
  751. message: nil,
  752. preferredStyle: .safeActionSheet)
  753. alert.addAction(UIAlertAction(title: actionTitle, style: actionStyle, handler: actionHandler))
  754. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: cancelHandler ?? { _ in
  755. self.dismiss(animated: true, completion: nil)
  756. }))
  757. present(alert, animated: true, completion: nil)
  758. }
  759. private func askToChatWith(email: String) {
  760. let contactId = self.dcContext.createContact(name: "", email: email)
  761. if dcContext.getChatIdByContactId(contactId: contactId) != 0 {
  762. self.dismiss(animated: true, completion: nil)
  763. let chatId = self.dcContext.createChatByContactId(contactId: contactId)
  764. self.showChat(chatId: chatId)
  765. } else {
  766. confirmationAlert(title: String.localizedStringWithFormat(String.localized("ask_start_chat_with"), email),
  767. actionTitle: String.localized("start_chat"),
  768. actionHandler: { _ in
  769. self.dismiss(animated: true, completion: nil)
  770. let chatId = self.dcContext.createChatByContactId(contactId: contactId)
  771. self.showChat(chatId: chatId)})
  772. }
  773. }
  774. private func askToDeleteMessage(id: Int) {
  775. self.askToDeleteMessages(ids: [id])
  776. }
  777. private func askToDeleteMessages(ids: [Int]) {
  778. let title = String.localized(stringID: "ask_delete_messages", count: ids.count)
  779. confirmationAlert(title: title, actionTitle: String.localized("delete"), actionStyle: .destructive,
  780. actionHandler: { _ in
  781. self.dcContext.deleteMessages(msgIds: ids)
  782. if self.tableView.isEditing {
  783. self.setEditing(isEditing: false)
  784. }
  785. })
  786. }
  787. private func askToForwardMessage() {
  788. let chat = dcContext.getChat(chatId: self.chatId)
  789. if chat.isSelfTalk {
  790. RelayHelper.sharedInstance.forward(to: self.chatId)
  791. } else {
  792. confirmationAlert(title: String.localizedStringWithFormat(String.localized("ask_forward"), chat.name),
  793. actionTitle: String.localized("menu_forward"),
  794. actionHandler: { _ in
  795. RelayHelper.sharedInstance.forward(to: self.chatId)
  796. self.dismiss(animated: true, completion: nil)},
  797. cancelHandler: { _ in
  798. self.dismiss(animated: false, completion: nil)
  799. self.navigationController?.popViewController(animated: true)})
  800. }
  801. }
  802. // MARK: - coordinator
  803. private func showChatDetail(chatId: Int) {
  804. let chat = dcContext.getChat(chatId: chatId)
  805. switch chat.chatType {
  806. case .SINGLE:
  807. if let contactId = chat.contactIds.first {
  808. let contactDetailController = ContactDetailViewController(dcContext: dcContext, contactId: contactId)
  809. navigationController?.pushViewController(contactDetailController, animated: true)
  810. }
  811. case .GROUP, .VERIFIEDGROUP:
  812. let groupChatDetailViewController = GroupChatDetailViewController(chatId: chatId, dcContext: dcContext)
  813. navigationController?.pushViewController(groupChatDetailViewController, animated: true)
  814. }
  815. }
  816. func showChat(chatId: Int) {
  817. if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
  818. navigationController?.popToRootViewController(animated: false)
  819. appDelegate.appCoordinator.showChat(chatId: chatId)
  820. }
  821. }
  822. private func showDocumentLibrary() {
  823. mediaPicker?.showDocumentLibrary()
  824. }
  825. private func showVoiceMessageRecorder() {
  826. mediaPicker?.showVoiceRecorder()
  827. }
  828. private func showCameraViewController() {
  829. mediaPicker?.showCamera()
  830. }
  831. private func showPhotoVideoLibrary(delegate: MediaPickerDelegate) {
  832. mediaPicker?.showPhotoVideoLibrary()
  833. }
  834. private func showMediaGallery(currentIndex: Int, msgIds: [Int]) {
  835. let betterPreviewController = PreviewController(type: .multi(msgIds, currentIndex))
  836. let nav = UINavigationController(rootViewController: betterPreviewController)
  837. nav.modalPresentationStyle = .fullScreen
  838. navigationController?.present(nav, animated: true)
  839. }
  840. private func documentActionPressed(_ action: UIAlertAction) {
  841. showDocumentLibrary()
  842. }
  843. private func voiceMessageButtonPressed(_ action: UIAlertAction) {
  844. showVoiceMessageRecorder()
  845. }
  846. private func cameraButtonPressed(_ action: UIAlertAction) {
  847. showCameraViewController()
  848. }
  849. private func galleryButtonPressed(_ action: UIAlertAction) {
  850. showPhotoVideoLibrary(delegate: self)
  851. }
  852. private func locationStreamingButtonPressed(_ action: UIAlertAction) {
  853. let isLocationStreaming = dcContext.isSendingLocationsToChat(chatId: chatId)
  854. if isLocationStreaming {
  855. locationStreamingFor(seconds: 0)
  856. } else {
  857. let alert = UIAlertController(title: String.localized("title_share_location"), message: nil, preferredStyle: .safeActionSheet)
  858. addDurationSelectionAction(to: alert, key: "share_location_for_5_minutes", duration: Time.fiveMinutes)
  859. addDurationSelectionAction(to: alert, key: "share_location_for_30_minutes", duration: Time.thirtyMinutes)
  860. addDurationSelectionAction(to: alert, key: "share_location_for_one_hour", duration: Time.oneHour)
  861. addDurationSelectionAction(to: alert, key: "share_location_for_two_hours", duration: Time.twoHours)
  862. addDurationSelectionAction(to: alert, key: "share_location_for_six_hours", duration: Time.sixHours)
  863. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  864. self.present(alert, animated: true, completion: nil)
  865. }
  866. }
  867. private func addDurationSelectionAction(to alert: UIAlertController, key: String, duration: Int) {
  868. let action = UIAlertAction(title: String.localized(key), style: .default, handler: { _ in
  869. self.locationStreamingFor(seconds: duration)
  870. })
  871. alert.addAction(action)
  872. }
  873. private func locationStreamingFor(seconds: Int) {
  874. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
  875. return
  876. }
  877. self.dcContext.sendLocationsToChat(chatId: self.chatId, seconds: seconds)
  878. appDelegate.locationManager.shareLocation(chatId: self.chatId, duration: seconds)
  879. }
  880. func updateMessage(_ messageId: Int) {
  881. if messageIds.firstIndex(where: { $0 == messageId }) != nil {
  882. DispatchQueue.global(qos: .background).async { [weak self] in
  883. self?.dcContext.markSeenMessages(messageIds: [UInt32(messageId)])
  884. }
  885. let wasLastSectionVisible = self.isLastRowVisible()
  886. reloadData()
  887. if wasLastSectionVisible {
  888. self.scrollToBottom(animated: true)
  889. }
  890. } else {
  891. let msg = DcMsg(id: messageId)
  892. if msg.chatId == chatId {
  893. insertMessage(msg)
  894. }
  895. }
  896. }
  897. func insertMessage(_ message: DcMsg) {
  898. DispatchQueue.global(qos: .background).async { [weak self] in
  899. self?.dcContext.markSeenMessages(messageIds: [UInt32(message.id)])
  900. }
  901. let wasLastSectionVisible = isLastRowVisible()
  902. messageIds.append(message.id)
  903. emptyStateView.isHidden = true
  904. reloadData()
  905. if wasLastSectionVisible || message.isFromCurrentSender {
  906. scrollToBottom(animated: true)
  907. }
  908. }
  909. private func sendTextMessage(text: String, quoteMessage: DcMsg?) {
  910. DispatchQueue.global().async {
  911. let message = DcMsg(viewType: DC_MSG_TEXT)
  912. message.text = text
  913. if let quoteMessage = quoteMessage {
  914. message.quoteMessage = quoteMessage
  915. }
  916. message.sendInChat(id: self.chatId)
  917. }
  918. }
  919. private func stageDocument(url: NSURL) {
  920. self.draft.setAttachment(viewType: DC_MSG_FILE, path: url.relativePath)
  921. self.configureDraftArea(draft: self.draft)
  922. self.messageInputBar.inputTextView.becomeFirstResponder()
  923. }
  924. private func stageVideo(url: NSURL) {
  925. DispatchQueue.main.async {
  926. self.draft.setAttachment(viewType: DC_MSG_VIDEO, path: url.relativePath)
  927. self.configureDraftArea(draft: self.draft)
  928. self.messageInputBar.inputTextView.becomeFirstResponder()
  929. }
  930. }
  931. private func stageImage(url: NSURL) {
  932. if url.pathExtension == "gif" {
  933. stageAnimatedImage(url: url)
  934. } else if let data = try? Data(contentsOf: url as URL),
  935. let image = UIImage(data: data) {
  936. stageImage(image)
  937. }
  938. }
  939. private func stageAnimatedImage(url: NSURL) {
  940. DispatchQueue.global().async {
  941. if let path = url.path,
  942. let result = SDAnimatedImage(contentsOfFile: path),
  943. let animatedImageData = result.animatedImageData,
  944. let pathInDocDir = DcUtils.saveImage(data: animatedImageData, suffix: "gif") {
  945. DispatchQueue.main.async {
  946. self.draft.setAttachment(viewType: DC_MSG_GIF, path: pathInDocDir)
  947. self.configureDraftArea(draft: self.draft)
  948. self.messageInputBar.inputTextView.becomeFirstResponder()
  949. }
  950. }
  951. }
  952. }
  953. private func stageImage(_ image: UIImage) {
  954. DispatchQueue.global().async {
  955. if let pathInDocDir = DcUtils.saveImage(image: image) {
  956. DispatchQueue.main.async {
  957. self.draft.setAttachment(viewType: DC_MSG_IMAGE, path: pathInDocDir)
  958. self.configureDraftArea(draft: self.draft)
  959. self.messageInputBar.inputTextView.becomeFirstResponder()
  960. }
  961. }
  962. }
  963. }
  964. private func sendImage(_ image: UIImage, message: String? = nil) {
  965. DispatchQueue.global().async {
  966. if let path = DcUtils.saveImage(image: image) {
  967. self.sendAttachmentMessage(viewType: DC_MSG_IMAGE, filePath: path, message: message)
  968. }
  969. }
  970. }
  971. private func sendAttachmentMessage(viewType: Int32, filePath: String, message: String? = nil, quoteMessage: DcMsg? = nil) {
  972. let msg = DcMsg(viewType: viewType)
  973. msg.setFile(filepath: filePath)
  974. msg.text = (message ?? "").isEmpty ? nil : message
  975. if quoteMessage != nil {
  976. msg.quoteMessage = quoteMessage
  977. }
  978. msg.sendInChat(id: self.chatId)
  979. }
  980. private func sendVoiceMessage(url: NSURL) {
  981. DispatchQueue.global().async {
  982. let msg = DcMsg(viewType: DC_MSG_VOICE)
  983. msg.setFile(filepath: url.relativePath, mimeType: "audio/m4a")
  984. msg.sendInChat(id: self.chatId)
  985. }
  986. }
  987. // MARK: - Context menu
  988. private func prepareContextMenu() {
  989. UIMenuController.shared.menuItems = contextMenu.menuItems
  990. UIMenuController.shared.update()
  991. }
  992. override func tableView(_ tableView: UITableView, shouldShowMenuForRowAt indexPath: IndexPath) -> Bool {
  993. return !DcMsg(id: messageIds[indexPath.row]).isInfo
  994. }
  995. override func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
  996. return contextMenu.canPerformAction(action: action)
  997. }
  998. override func tableView(_ tableView: UITableView, performAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) {
  999. // handle standard actions here, but custom actions never trigger this. it still needs to be present for the menu to display, though.
  1000. contextMenu.performAction(action: action, indexPath: indexPath)
  1001. }
  1002. // context menu for iOS 13+
  1003. @available(iOS 13, *)
  1004. override func tableView(_ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
  1005. return UIContextMenuConfiguration(
  1006. identifier: nil,
  1007. previewProvider: nil,
  1008. actionProvider: { [weak self] _ in
  1009. self?.contextMenu.actionProvider(indexPath: indexPath)
  1010. }
  1011. )
  1012. }
  1013. func showMediaGalleryFor(indexPath: IndexPath) {
  1014. let messageId = messageIds[indexPath.row]
  1015. let message = DcMsg(id: messageId)
  1016. showMediaGalleryFor(message: message)
  1017. }
  1018. func showMediaGalleryFor(message: DcMsg) {
  1019. let msgIds = dcContext.getChatMedia(chatId: chatId, messageType: Int32(message.type), messageType2: 0, messageType3: 0)
  1020. let index = msgIds.firstIndex(of: message.id) ?? 0
  1021. showMediaGallery(currentIndex: index, msgIds: msgIds)
  1022. }
  1023. private func didTapAsm(msg: DcMsg, orgText: String) {
  1024. let inputDlg = UIAlertController(
  1025. title: String.localized("autocrypt_continue_transfer_title"),
  1026. message: String.localized("autocrypt_continue_transfer_please_enter_code"),
  1027. preferredStyle: .alert)
  1028. inputDlg.addTextField(configurationHandler: { (textField) in
  1029. textField.placeholder = msg.setupCodeBegin + ".."
  1030. textField.text = orgText
  1031. textField.keyboardType = UIKeyboardType.numbersAndPunctuation // allows entering spaces; decimalPad would require a mask to keep things readable
  1032. })
  1033. inputDlg.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  1034. let okAction = UIAlertAction(title: String.localized("ok"), style: .default, handler: { _ in
  1035. let textField = inputDlg.textFields![0]
  1036. let modText = textField.text ?? ""
  1037. let success = self.dcContext.continueKeyTransfer(msgId: msg.id, setupCode: modText)
  1038. let alert = UIAlertController(
  1039. title: String.localized("autocrypt_continue_transfer_title"),
  1040. message: String.localized(success ? "autocrypt_continue_transfer_succeeded" : "autocrypt_bad_setup_code"),
  1041. preferredStyle: .alert)
  1042. if success {
  1043. alert.addAction(UIAlertAction(title: String.localized("ok"), style: .default, handler: nil))
  1044. } else {
  1045. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  1046. let retryAction = UIAlertAction(title: String.localized("autocrypt_continue_transfer_retry"), style: .default, handler: { _ in
  1047. self.didTapAsm(msg: msg, orgText: modText)
  1048. })
  1049. alert.addAction(retryAction)
  1050. alert.preferredAction = retryAction
  1051. }
  1052. self.navigationController?.present(alert, animated: true, completion: nil)
  1053. })
  1054. inputDlg.addAction(okAction)
  1055. inputDlg.preferredAction = okAction // without setting preferredAction, cancel become shown *bold* as the preferred action
  1056. navigationController?.present(inputDlg, animated: true, completion: nil)
  1057. }
  1058. func handleUIMenu() -> Bool {
  1059. if UIMenuController.shared.isMenuVisible {
  1060. UIMenuController.shared.setMenuVisible(false, animated: true)
  1061. return true
  1062. }
  1063. return false
  1064. }
  1065. func handleSelection(indexPath: IndexPath) -> Bool {
  1066. if tableView.isEditing {
  1067. if tableView.indexPathsForSelectedRows?.contains(indexPath) ?? false {
  1068. tableView.deselectRow(at: indexPath, animated: false)
  1069. } else {
  1070. tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
  1071. }
  1072. handleEditingBar()
  1073. return true
  1074. }
  1075. return false
  1076. }
  1077. func handleEditingBar() {
  1078. if let rows = tableView.indexPathsForSelectedRows,
  1079. !rows.isEmpty {
  1080. editingBar.isEnabled = true
  1081. } else {
  1082. editingBar.isEnabled = false
  1083. }
  1084. }
  1085. func setEditing(isEditing: Bool, selectedAtIndexPath: IndexPath? = nil) {
  1086. self.tableView.setEditing(isEditing, animated: true)
  1087. self.draft.isEditing = isEditing
  1088. self.configureDraftArea(draft: self.draft)
  1089. if let indexPath = selectedAtIndexPath {
  1090. _ = handleSelection(indexPath: indexPath)
  1091. }
  1092. }
  1093. }
  1094. // MARK: - BaseMessageCellDelegate
  1095. extension ChatViewController: BaseMessageCellDelegate {
  1096. @objc func quoteTapped(indexPath: IndexPath) {
  1097. if handleSelection(indexPath: indexPath) { return }
  1098. _ = handleUIMenu()
  1099. let msg = DcMsg(id: messageIds[indexPath.row])
  1100. if let quoteMsg = msg.quoteMessage {
  1101. scrollToMessage(msgId: quoteMsg.id)
  1102. }
  1103. }
  1104. @objc func textTapped(indexPath: IndexPath) {
  1105. if handleUIMenu() || handleSelection(indexPath: indexPath) {
  1106. return
  1107. }
  1108. let message = DcMsg(id: messageIds[indexPath.row])
  1109. if message.isSetupMessage {
  1110. didTapAsm(msg: message, orgText: "")
  1111. }
  1112. }
  1113. @objc func phoneNumberTapped(number: String, indexPath: IndexPath) {
  1114. if handleUIMenu() || handleSelection(indexPath: indexPath) {
  1115. return
  1116. }
  1117. logger.debug("phone number tapped \(number)")
  1118. }
  1119. @objc func commandTapped(command: String, indexPath: IndexPath) {
  1120. if handleUIMenu() || handleSelection(indexPath: indexPath) {
  1121. return
  1122. }
  1123. logger.debug("command tapped \(command)")
  1124. }
  1125. @objc func urlTapped(url: URL, indexPath: IndexPath) {
  1126. if handleUIMenu() || handleSelection(indexPath: indexPath) {
  1127. return
  1128. }
  1129. if Utils.isEmail(url: url) {
  1130. logger.debug("tapped on contact")
  1131. let email = Utils.getEmailFrom(url)
  1132. self.askToChatWith(email: email)
  1133. } else {
  1134. UIApplication.shared.open(url)
  1135. }
  1136. }
  1137. @objc func imageTapped(indexPath: IndexPath) {
  1138. if handleUIMenu() || handleSelection(indexPath: indexPath) {
  1139. return
  1140. }
  1141. showMediaGalleryFor(indexPath: indexPath)
  1142. }
  1143. @objc func avatarTapped(indexPath: IndexPath) {
  1144. let message = DcMsg(id: messageIds[indexPath.row])
  1145. let contactDetailController = ContactDetailViewController(dcContext: dcContext, contactId: message.fromContactId)
  1146. navigationController?.pushViewController(contactDetailController, animated: true)
  1147. }
  1148. }
  1149. // MARK: - MediaPickerDelegate
  1150. extension ChatViewController: MediaPickerDelegate {
  1151. func onVideoSelected(url: NSURL) {
  1152. stageVideo(url: url)
  1153. }
  1154. func onImageSelected(url: NSURL) {
  1155. stageImage(url: url)
  1156. }
  1157. func onImageSelected(image: UIImage) {
  1158. stageImage(image)
  1159. }
  1160. func onVoiceMessageRecorded(url: NSURL) {
  1161. sendVoiceMessage(url: url)
  1162. }
  1163. func onDocumentSelected(url: NSURL) {
  1164. stageDocument(url: url)
  1165. }
  1166. }
  1167. // MARK: - MessageInputBarDelegate
  1168. extension ChatViewController: InputBarAccessoryViewDelegate {
  1169. func inputBar(_ inputBar: InputBarAccessoryView, didPressSendButtonWith text: String) {
  1170. let trimmedText = text.replacingOccurrences(of: "\u{FFFC}", with: "", options: .literal, range: nil)
  1171. .trimmingCharacters(in: .whitespacesAndNewlines)
  1172. if let filePath = draft.attachment, let viewType = draft.viewType {
  1173. switch viewType {
  1174. case DC_MSG_GIF, DC_MSG_IMAGE, DC_MSG_FILE, DC_MSG_VIDEO:
  1175. self.sendAttachmentMessage(viewType: viewType, filePath: filePath, message: trimmedText, quoteMessage: draft.quoteMessage)
  1176. default:
  1177. logger.warning("Unsupported viewType for drafted messages.")
  1178. }
  1179. } else if inputBar.inputTextView.images.isEmpty {
  1180. self.sendTextMessage(text: trimmedText, quoteMessage: draft.quoteMessage)
  1181. } else {
  1182. // only 1 attachment allowed for now, thus it takes the first one
  1183. self.sendImage(inputBar.inputTextView.images[0], message: trimmedText)
  1184. }
  1185. inputBar.inputTextView.text = String()
  1186. inputBar.inputTextView.attributedText = nil
  1187. draftArea.cancel()
  1188. }
  1189. func inputBar(_ inputBar: InputBarAccessoryView, textViewTextDidChangeTo text: String) {
  1190. draft.text = text
  1191. evaluateInputBar(draft: draft)
  1192. }
  1193. }
  1194. // MARK: - DraftPreviewDelegate
  1195. extension ChatViewController: DraftPreviewDelegate {
  1196. func onCancelQuote() {
  1197. draft.setQuote(quotedMsg: nil)
  1198. configureDraftArea(draft: draft)
  1199. }
  1200. func onCancelAttachment() {
  1201. draft.setAttachment(viewType: nil, path: nil, mimetype: nil)
  1202. configureDraftArea(draft: draft)
  1203. evaluateInputBar(draft: draft)
  1204. }
  1205. func onAttachmentAdded() {
  1206. evaluateInputBar(draft: draft)
  1207. }
  1208. func onAttachmentTapped() {
  1209. if let attachmentPath = draft.attachment {
  1210. let attachmentURL = URL(fileURLWithPath: attachmentPath, isDirectory: false)
  1211. let previewController = PreviewController(type: .single(attachmentURL))
  1212. if #available(iOS 13.0, *), draft.viewType == DC_MSG_IMAGE || draft.viewType == DC_MSG_VIDEO {
  1213. previewController.setEditing(true, animated: true)
  1214. previewController.delegate = self
  1215. }
  1216. let nav = UINavigationController(rootViewController: previewController)
  1217. nav.modalPresentationStyle = .fullScreen
  1218. navigationController?.present(nav, animated: true)
  1219. }
  1220. }
  1221. }
  1222. // MARK: - ChatEditingDelegate
  1223. extension ChatViewController: ChatEditingDelegate {
  1224. func onDeletePressed() {
  1225. if let rows = tableView.indexPathsForSelectedRows {
  1226. let messageIdsToDelete = rows.compactMap { messageIds[$0.row] }
  1227. askToDeleteMessages(ids: messageIdsToDelete)
  1228. }
  1229. }
  1230. func onForwardPressed() {
  1231. if let rows = tableView.indexPathsForSelectedRows {
  1232. let messageIdsToForward = rows.compactMap { messageIds[$0.row] }
  1233. RelayHelper.sharedInstance.setForwardMessages(messageIds: messageIdsToForward)
  1234. self.navigationController?.popViewController(animated: true)
  1235. }
  1236. }
  1237. func onCancelPressed() {
  1238. setEditing(isEditing: false)
  1239. }
  1240. }
  1241. // MARK: - QLPreviewControllerDelegate
  1242. extension ChatViewController: QLPreviewControllerDelegate {
  1243. @available(iOS 13.0, *)
  1244. func previewController(_ controller: QLPreviewController, editingModeFor previewItem: QLPreviewItem) -> QLPreviewItemEditingMode {
  1245. return .updateContents
  1246. }
  1247. func previewController(_ controller: QLPreviewController, didUpdateContentsOf previewItem: QLPreviewItem) {
  1248. DispatchQueue.main.async { [weak self] in
  1249. guard let self = self else { return }
  1250. self.draftArea.reload(draft: self.draft)
  1251. }
  1252. }
  1253. }