ChatListController.swift 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  1. import UIKit
  2. import DcCore
  3. class ChatListController: UITableViewController {
  4. var viewModel: ChatListViewModel?
  5. let dcContext: DcContext
  6. internal let dcAccounts: DcAccounts
  7. var isArchive: Bool
  8. private var accountSwitchTransitioningDelegate: PartialScreenModalTransitioningDelegate!
  9. private let chatCellReuseIdentifier = "chat_cell"
  10. private let deadDropCellReuseIdentifier = "deaddrop_cell"
  11. private let contactCellReuseIdentifier = "contact_cell"
  12. private var msgChangedObserver: NSObjectProtocol?
  13. private var msgsNoticedObserver: NSObjectProtocol?
  14. private var incomingMsgObserver: NSObjectProtocol?
  15. private var incomingMsgAnyAccountObserver: NSObjectProtocol?
  16. private var chatModifiedObserver: NSObjectProtocol?
  17. private var contactsChangedObserver: NSObjectProtocol?
  18. private var connectivityChangedObserver: NSObjectProtocol?
  19. private var msgChangedSearchResultObserver: NSObjectProtocol?
  20. private weak var timer: Timer?
  21. private lazy var titleView: UILabel = {
  22. let view = UILabel()
  23. let navTapGesture = UITapGestureRecognizer(target: self, action: #selector(onNavigationTitleTapped))
  24. view.addGestureRecognizer(navTapGesture)
  25. view.isUserInteractionEnabled = true
  26. view.font = UIFont.systemFont(ofSize: 17, weight: .semibold)
  27. view.accessibilityTraits = .header
  28. return view
  29. }()
  30. private lazy var searchController: UISearchController = {
  31. let searchController = UISearchController(searchResultsController: nil)
  32. searchController.obscuresBackgroundDuringPresentation = false
  33. searchController.searchBar.placeholder = String.localized("search")
  34. return searchController
  35. }()
  36. private lazy var archiveCell: ActionCell = {
  37. let actionCell = ActionCell()
  38. return actionCell
  39. }()
  40. private lazy var newButton: UIBarButtonItem = {
  41. let button = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.compose, target: self, action: #selector(didPressNewChat))
  42. button.tintColor = DcColors.primary
  43. return button
  44. }()
  45. private lazy var cancelButton: UIBarButtonItem = {
  46. let button = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancelButtonPressed))
  47. return button
  48. }()
  49. private lazy var emptyStateLabel: EmptyStateLabel = {
  50. let label = EmptyStateLabel()
  51. label.isHidden = true
  52. return label
  53. }()
  54. private lazy var editingBar: ChatListEditingBar = {
  55. let editingBar = ChatListEditingBar()
  56. editingBar.translatesAutoresizingMaskIntoConstraints = false
  57. editingBar.delegate = self
  58. editingBar.showArchive = !isArchive
  59. return editingBar
  60. }()
  61. private lazy var accountButtonAvatar: InitialsBadge = {
  62. let badge = InitialsBadge(size: 37, accessibilityLabel: String.localized("switch_account"))
  63. badge.setLabelFont(UIFont.systemFont(ofSize: 14))
  64. badge.accessibilityTraits = .button
  65. let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(accountButtonTapped))
  66. badge.addGestureRecognizer(tapGestureRecognizer)
  67. return badge
  68. }()
  69. private lazy var accountButton: UIBarButtonItem = {
  70. return UIBarButtonItem(customView: accountButtonAvatar)
  71. }()
  72. private var editingConstraints: NSLayoutConstraintSet?
  73. init(dcContext: DcContext, dcAccounts: DcAccounts, isArchive: Bool) {
  74. self.dcContext = dcContext
  75. self.dcAccounts = dcAccounts
  76. self.isArchive = isArchive
  77. super.init(style: .grouped)
  78. DispatchQueue.global(qos: .userInteractive).async { [weak self] in
  79. guard let self = self else { return }
  80. self.viewModel = ChatListViewModel(dcContext: self.dcContext, isArchive: isArchive)
  81. self.viewModel?.onChatListUpdate = self.handleChatListUpdate
  82. DispatchQueue.main.async { [weak self] in
  83. guard let self = self else { return }
  84. if !isArchive {
  85. self.navigationItem.searchController = self.searchController
  86. self.searchController.searchResultsUpdater = self.viewModel
  87. self.searchController.searchBar.delegate = self
  88. }
  89. self.handleChatListUpdate()
  90. }
  91. }
  92. }
  93. required init?(coder _: NSCoder) {
  94. fatalError("init(coder:) has not been implemented")
  95. }
  96. // MARK: - lifecycle
  97. override func viewDidLoad() {
  98. super.viewDidLoad()
  99. configureTableView()
  100. setupSubviews()
  101. // update messages - for new messages, do not reuse or modify strings but create new ones.
  102. // it is not needed to keep all past update messages, however, when deleted, also the strings should be deleted.
  103. let msg = dcContext.newMessage(viewType: DC_MSG_TEXT)
  104. msg.text = "Some 1.34 Highlights:\n\n"
  105. + "🤗 Friendlier contact lists: Ordered by last seen and contacts seen within 10 minutes are marked by a dot 🟢\n\n"
  106. + "🔘 New account selector atop of the chat list\n\n"
  107. + "☝️ Drag'n'Drop: Eg. long tap an image in the system's gallery and navigate to the desired chat using a ✌️ second finger"
  108. dcContext.addDeviceMessage(label: "update_1_34d_ios", msg: msg)
  109. }
  110. override func willMove(toParent parent: UIViewController?) {
  111. super.willMove(toParent: parent)
  112. if parent == nil {
  113. // logger.debug("chat observer: remove")
  114. removeObservers()
  115. } else {
  116. // logger.debug("chat observer: setup")
  117. addObservers()
  118. }
  119. }
  120. override func viewWillAppear(_ animated: Bool) {
  121. super.viewWillAppear(animated)
  122. // create view
  123. navigationItem.titleView = titleView
  124. updateTitle()
  125. if RelayHelper.shared.isForwarding() {
  126. quitSearch(animated: false)
  127. tableView.scrollToTop()
  128. }
  129. }
  130. override func viewDidAppear(_ animated: Bool) {
  131. super.viewDidAppear(animated)
  132. startTimer()
  133. }
  134. override func viewDidDisappear(_ animated: Bool) {
  135. super.viewDidDisappear(animated)
  136. stopTimer()
  137. }
  138. // MARK: - setup
  139. private func addObservers() {
  140. let nc = NotificationCenter.default
  141. connectivityChangedObserver = nc.addObserver(forName: dcNotificationConnectivityChanged,
  142. object: nil,
  143. queue: nil) { [weak self] _ in
  144. self?.updateTitle()
  145. }
  146. msgChangedSearchResultObserver = nc.addObserver(
  147. forName: dcNotificationChanged,
  148. object: nil,
  149. queue: nil) { [weak self] _ in
  150. guard let self = self else { return }
  151. if let appDelegate = UIApplication.shared.delegate as? AppDelegate,
  152. let viewModel = self.viewModel,
  153. viewModel.searchActive,
  154. appDelegate.appIsInForeground() {
  155. viewModel.updateSearchResults(for: self.searchController)
  156. }
  157. }
  158. msgChangedObserver = nc.addObserver(
  159. forName: dcNotificationChanged,
  160. object: nil,
  161. queue: nil) { [weak self] _ in
  162. self?.refreshInBg()
  163. }
  164. msgsNoticedObserver = nc.addObserver(
  165. forName: dcMsgsNoticed,
  166. object: nil,
  167. queue: nil) { [weak self] _ in
  168. self?.refreshInBg()
  169. }
  170. incomingMsgObserver = nc.addObserver(
  171. forName: dcNotificationIncoming,
  172. object: nil,
  173. queue: nil) { [weak self] _ in
  174. self?.refreshInBg()
  175. }
  176. incomingMsgAnyAccountObserver = nc.addObserver(
  177. forName: dcNotificationIncomingAnyAccount,
  178. object: nil,
  179. queue: nil) { [weak self] _ in
  180. self?.updateAccountButton()
  181. }
  182. chatModifiedObserver = nc.addObserver(
  183. forName: dcNotificationChatModified,
  184. object: nil,
  185. queue: nil) { [weak self] _ in
  186. self?.refreshInBg()
  187. }
  188. contactsChangedObserver = nc.addObserver(
  189. forName: dcNotificationContactChanged,
  190. object: nil,
  191. queue: nil) { [weak self] _ in
  192. self?.refreshInBg()
  193. }
  194. nc.addObserver(
  195. self,
  196. selector: #selector(applicationDidBecomeActive(_:)),
  197. name: UIApplication.didBecomeActiveNotification,
  198. object: nil)
  199. nc.addObserver(
  200. self,
  201. selector: #selector(applicationWillResignActive(_:)),
  202. name: UIApplication.willResignActiveNotification,
  203. object: nil)
  204. }
  205. private func removeObservers() {
  206. let nc = NotificationCenter.default
  207. // remove observers with a block
  208. if let msgChangedResultObserver = self.msgChangedSearchResultObserver {
  209. nc.removeObserver(msgChangedResultObserver)
  210. }
  211. if let msgChangedObserver = self.msgChangedObserver {
  212. nc.removeObserver(msgChangedObserver)
  213. }
  214. if let incomingMsgObserver = self.incomingMsgObserver {
  215. nc.removeObserver(incomingMsgObserver)
  216. }
  217. if let incomingMsgAnyAccountObserver = self.incomingMsgAnyAccountObserver {
  218. nc.removeObserver(incomingMsgAnyAccountObserver)
  219. }
  220. if let msgsNoticedObserver = self.msgsNoticedObserver {
  221. nc.removeObserver(msgsNoticedObserver)
  222. }
  223. if let chatModifiedObserver = self.chatModifiedObserver {
  224. nc.removeObserver(chatModifiedObserver)
  225. }
  226. if let contactsChangedObserver = self.contactsChangedObserver {
  227. nc.removeObserver(contactsChangedObserver)
  228. }
  229. if let connectivityChangedObserver = self.connectivityChangedObserver {
  230. nc.removeObserver(connectivityChangedObserver)
  231. }
  232. // remove non-block observers
  233. NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil)
  234. NotificationCenter.default.removeObserver(self, name: UIApplication.willResignActiveNotification, object: nil)
  235. }
  236. private func setupSubviews() {
  237. emptyStateLabel.addCenteredTo(parentView: view)
  238. navigationItem.backButtonTitle = isArchive ? String.localized("chat_archived_chats_title") : String.localized("pref_chats")
  239. }
  240. @objc
  241. public func onNavigationTitleTapped() {
  242. logger.debug("on navigation title tapped")
  243. let connectivityViewController = ConnectivityViewController(dcContext: dcContext)
  244. navigationController?.pushViewController(connectivityViewController, animated: true)
  245. }
  246. // MARK: - configuration
  247. private func configureTableView() {
  248. tableView.register(ContactCell.self, forCellReuseIdentifier: chatCellReuseIdentifier)
  249. tableView.register(ContactCell.self, forCellReuseIdentifier: deadDropCellReuseIdentifier)
  250. tableView.register(ContactCell.self, forCellReuseIdentifier: contactCellReuseIdentifier)
  251. tableView.rowHeight = ContactCell.cellHeight
  252. tableView.allowsMultipleSelectionDuringEditing = true
  253. }
  254. private var isInitial = true
  255. @objc func applicationDidBecomeActive(_ notification: NSNotification) {
  256. if navigationController?.visibleViewController == self {
  257. if !isInitial {
  258. startTimer()
  259. handleChatListUpdate()
  260. }
  261. isInitial = false
  262. }
  263. }
  264. private var inBgRefresh = false
  265. private var needsAnotherBgRefresh = false
  266. private func refreshInBg() {
  267. if inBgRefresh {
  268. needsAnotherBgRefresh = true
  269. } else {
  270. inBgRefresh = true
  271. DispatchQueue.global(qos: .userInteractive).async { [weak self] in
  272. // do at least one refresh, without inital delay
  273. // (refreshData() calls handleChatListUpdate() on main thread when done)
  274. self?.needsAnotherBgRefresh = false
  275. self?.viewModel?.refreshData()
  276. // do subsequent refreshes with a delay of 500ms
  277. while self?.needsAnotherBgRefresh != false {
  278. usleep(500000)
  279. self?.needsAnotherBgRefresh = false
  280. self?.viewModel?.refreshData()
  281. }
  282. self?.inBgRefresh = false
  283. }
  284. }
  285. }
  286. @objc func applicationWillResignActive(_ notification: NSNotification) {
  287. if navigationController?.visibleViewController == self {
  288. stopTimer()
  289. }
  290. }
  291. // MARK: - actions
  292. @objc func didPressNewChat() {
  293. showNewChatController()
  294. }
  295. @objc func cancelButtonPressed() {
  296. if tableView.isEditing {
  297. self.setLongTapEditing(false)
  298. } else {
  299. // cancel forwarding
  300. RelayHelper.shared.cancel()
  301. updateTitle()
  302. refreshInBg()
  303. }
  304. }
  305. override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
  306. if previousTraitCollection?.preferredContentSizeCategory !=
  307. traitCollection.preferredContentSizeCategory {
  308. tableView.rowHeight = ContactCell.cellHeight
  309. }
  310. }
  311. private func quitSearch(animated: Bool) {
  312. searchController.searchBar.text = nil
  313. self.viewModel?.endSearch()
  314. searchController.dismiss(animated: animated) {
  315. self.tableView.scrollToTop()
  316. }
  317. }
  318. // MARK: - UITableViewDelegate + UITableViewDatasource
  319. override func numberOfSections(in tableView: UITableView) -> Int {
  320. return viewModel?.numberOfSections ?? 0
  321. }
  322. override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
  323. return viewModel?.numberOfRowsIn(section: section) ?? 0
  324. }
  325. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  326. guard let viewModel = viewModel else {
  327. return UITableViewCell()
  328. }
  329. let cellData = viewModel.cellDataFor(section: indexPath.section, row: indexPath.row)
  330. switch cellData.type {
  331. case .chat(let chatData):
  332. let chatId = chatData.chatId
  333. if chatId == DC_CHAT_ID_ARCHIVED_LINK {
  334. archiveCell.actionTitle = dcContext.getChat(chatId: chatId).name
  335. archiveCell.backgroundColor = DcColors.chatBackgroundColor
  336. return archiveCell
  337. } else if let chatCell = tableView.dequeueReusableCell(withIdentifier: chatCellReuseIdentifier, for: indexPath) as? ContactCell {
  338. // default chatCell
  339. chatCell.updateCell(cellViewModel: cellData)
  340. chatCell.delegate = self
  341. return chatCell
  342. }
  343. case .contact:
  344. safe_assert(viewModel.searchActive)
  345. if let contactCell = tableView.dequeueReusableCell(withIdentifier: contactCellReuseIdentifier, for: indexPath) as? ContactCell {
  346. contactCell.updateCell(cellViewModel: cellData)
  347. return contactCell
  348. }
  349. case .profile:
  350. safe_fatalError("CellData type profile not allowed")
  351. }
  352. safe_fatalError("Could not find/dequeue or recycle UITableViewCell.")
  353. return UITableViewCell()
  354. }
  355. override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
  356. return viewModel?.titleForHeaderIn(section: section)
  357. }
  358. override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
  359. if !tableView.isEditing {
  360. return indexPath
  361. }
  362. let cell = tableView.cellForRow(at: indexPath)
  363. return cell == archiveCell ? nil : indexPath
  364. }
  365. override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
  366. if tableView.isEditing,
  367. let viewModel = viewModel {
  368. editingBar.showUnpinning = viewModel.hasOnlyPinnedChatsSelected(in: tableView.indexPathsForSelectedRows)
  369. if tableView.indexPathsForSelectedRows == nil {
  370. setLongTapEditing(false)
  371. } else {
  372. updateTitle()
  373. }
  374. }
  375. }
  376. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  377. guard let viewModel = viewModel else {
  378. tableView.deselectRow(at: indexPath, animated: false)
  379. return
  380. }
  381. if tableView.isEditing {
  382. editingBar.showUnpinning = viewModel.hasOnlyPinnedChatsSelected(in: tableView.indexPathsForSelectedRows)
  383. updateTitle()
  384. return
  385. }
  386. let cellData = viewModel.cellDataFor(section: indexPath.section, row: indexPath.row)
  387. switch cellData.type {
  388. case .chat(let chatData):
  389. let chatId = chatData.chatId
  390. if chatId == DC_CHAT_ID_ARCHIVED_LINK {
  391. showArchive(animated: true)
  392. } else {
  393. showChat(chatId: chatId, highlightedMsg: chatData.highlightMsgId)
  394. }
  395. case .contact(let contactData):
  396. let contactId = contactData.contactId
  397. if let chatId = contactData.chatId {
  398. showChat(chatId: chatId)
  399. } else {
  400. self.askToChatWith(contactId: contactId)
  401. }
  402. case .profile:
  403. safe_fatalError("CellData type profile not allowed")
  404. }
  405. tableView.deselectRow(at: indexPath, animated: false)
  406. }
  407. override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
  408. guard let viewModel = viewModel else { return [] }
  409. guard let chatId = viewModel.chatIdFor(section: indexPath.section, row: indexPath.row) else {
  410. return []
  411. }
  412. if chatId==DC_CHAT_ID_ARCHIVED_LINK {
  413. return []
  414. // returning nil may result in a default delete action,
  415. // see https://forums.developer.apple.com/thread/115030
  416. }
  417. let chat = dcContext.getChat(chatId: chatId)
  418. let archived = chat.isArchived
  419. let archiveActionTitle: String = String.localized(archived ? "unarchive" : "archive")
  420. let archiveAction = UITableViewRowAction(style: .destructive, title: archiveActionTitle) { [weak self] _, _ in
  421. self?.viewModel?.archiveChatToggle(chatId: chatId)
  422. self?.setEditing(false, animated: true)
  423. }
  424. archiveAction.backgroundColor = UIColor.lightGray
  425. let pinned = chat.visibility==DC_CHAT_VISIBILITY_PINNED
  426. let pinAction = UITableViewRowAction(style: .destructive, title: String.localized(pinned ? "unpin" : "pin")) { [weak self] _, _ in
  427. self?.viewModel?.pinChatToggle(chatId: chat.id)
  428. self?.setEditing(false, animated: true)
  429. }
  430. pinAction.backgroundColor = UIColor.systemGreen
  431. let deleteAction = UITableViewRowAction(style: .normal, title: String.localized("delete")) { [weak self] _, _ in
  432. self?.showDeleteChatConfirmationAlert(chatId: chatId)
  433. }
  434. deleteAction.backgroundColor = UIColor.systemRed
  435. return [archiveAction, pinAction, deleteAction]
  436. }
  437. override func setEditing(_ editing: Bool, animated: Bool) {
  438. super.setEditing(editing, animated: animated)
  439. tableView.setEditing(editing, animated: animated)
  440. viewModel?.setEditing(editing)
  441. }
  442. func setLongTapEditing(_ editing: Bool, initialIndexPath: [IndexPath]? = nil) {
  443. setEditing(editing, animated: true)
  444. if editing {
  445. addEditingView()
  446. if let viewModel = viewModel {
  447. editingBar.showUnpinning = viewModel.hasOnlyPinnedChatsSelected(in: tableView.indexPathsForSelectedRows) ||
  448. viewModel.hasOnlyPinnedChatsSelected(in: initialIndexPath)
  449. }
  450. archiveCell.selectionStyle = .none
  451. } else {
  452. removeEditingView()
  453. archiveCell.selectionStyle = .default
  454. }
  455. updateTitle()
  456. }
  457. private func addEditingView() {
  458. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate,
  459. let tabBarController = appDelegate.window?.rootViewController as? UITabBarController
  460. else { return }
  461. if !tabBarController.view.subviews.contains(editingBar) {
  462. tabBarController.tabBar.subviews.forEach { view in
  463. view.isHidden = true
  464. }
  465. tabBarController.view.addSubview(editingBar)
  466. editingConstraints = NSLayoutConstraintSet(top: editingBar.constraintAlignTopTo(tabBarController.tabBar),
  467. bottom: editingBar.constraintAlignBottomTo(tabBarController.tabBar),
  468. left: editingBar.constraintAlignLeadingTo(tabBarController.tabBar),
  469. right: editingBar.constraintAlignTrailingTo(tabBarController.tabBar))
  470. editingConstraints?.activate()
  471. }
  472. }
  473. private func removeEditingView() {
  474. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate,
  475. let tabBarController = appDelegate.window?.rootViewController as? UITabBarController
  476. else { return }
  477. editingBar.removeFromSuperview()
  478. editingConstraints?.deactivate()
  479. editingConstraints = nil
  480. tabBarController.tabBar.subviews.forEach { view in
  481. view.isHidden = false
  482. }
  483. }
  484. private func updateAccountButton() {
  485. accountButtonAvatar.setUnreadMessageCount(getUnreadCounterOfOtherAccounts())
  486. let contact = dcContext.getContact(id: Int(DC_CONTACT_ID_SELF))
  487. let title = dcContext.displayname ?? dcContext.addr ?? ""
  488. accountButtonAvatar.setColor(contact.color)
  489. accountButtonAvatar.setName(title)
  490. if let image = contact.profileImage {
  491. accountButtonAvatar.setImage(image)
  492. }
  493. }
  494. private func getUnreadCounterOfOtherAccounts() -> Int {
  495. var unreadCount = 0
  496. let selectedAccountId = dcAccounts.getSelected().id
  497. for accountId in dcAccounts.getAll() {
  498. if accountId == selectedAccountId {
  499. continue
  500. }
  501. unreadCount += dcAccounts.get(id: accountId).getFreshMessages().count
  502. }
  503. return unreadCount
  504. }
  505. @objc private func accountButtonTapped() {
  506. let viewController = AccountSwitchViewController(dcAccounts: dcAccounts)
  507. let accountSwitchNavigationController = UINavigationController(rootViewController: viewController)
  508. if #available(iOS 15.0, *) {
  509. if let sheet = accountSwitchNavigationController.sheetPresentationController {
  510. sheet.detents = [.medium()]
  511. sheet.preferredCornerRadius = 20
  512. }
  513. } else {
  514. accountSwitchTransitioningDelegate = PartialScreenModalTransitioningDelegate(from: self, to: accountSwitchNavigationController)
  515. accountSwitchNavigationController.modalPresentationStyle = .custom
  516. accountSwitchNavigationController.transitioningDelegate = accountSwitchTransitioningDelegate
  517. }
  518. self.present(accountSwitchNavigationController, animated: true)
  519. }
  520. // MARK: updates
  521. private func updateTitle() {
  522. titleView.accessibilityHint = String.localized("a11y_connectivity_hint")
  523. if RelayHelper.shared.isForwarding() {
  524. // multi-select is not allowed during forwarding
  525. titleView.text = String.localized("forward_to")
  526. if !isArchive {
  527. navigationItem.setLeftBarButton(cancelButton, animated: true)
  528. }
  529. } else if isArchive {
  530. titleView.text = String.localized("chat_archived_chats_title")
  531. if !handleMultiSelectionTitle() {
  532. navigationItem.setLeftBarButton(nil, animated: true)
  533. }
  534. } else {
  535. titleView.text = DcUtils.getConnectivityString(dcContext: dcContext, connectedString: String.localized("pref_chats"))
  536. if !handleMultiSelectionTitle() {
  537. navigationItem.setLeftBarButton(accountButton, animated: false)
  538. updateAccountButton()
  539. navigationItem.setRightBarButton(newButton, animated: true)
  540. if dcContext.getConnectivity() >= DC_CONNECTIVITY_CONNECTED {
  541. titleView.accessibilityHint = "\(String.localized("connectivity_connected")): \(String.localized("a11y_connectivity_hint"))"
  542. }
  543. }
  544. }
  545. titleView.isUserInteractionEnabled = !tableView.isEditing
  546. titleView.sizeToFit()
  547. }
  548. func handleMultiSelectionTitle() -> Bool {
  549. if !tableView.isEditing {
  550. return false
  551. }
  552. titleView.accessibilityHint = nil
  553. let cnt = tableView.indexPathsForSelectedRows?.count ?? 1
  554. titleView.text = String.localized(stringID: "n_selected", count: cnt)
  555. navigationItem.setLeftBarButton(cancelButton, animated: true)
  556. navigationItem.setRightBarButton(nil, animated: true)
  557. return true
  558. }
  559. func handleChatListUpdate() {
  560. if let viewModel = viewModel, viewModel.isEditing {
  561. viewModel.setPendingChatListUpdate()
  562. return
  563. }
  564. if Thread.isMainThread {
  565. tableView.reloadData()
  566. handleEmptyStateLabel()
  567. } else {
  568. DispatchQueue.main.async { [weak self] in
  569. guard let self = self else { return }
  570. self.tableView.reloadData()
  571. self.handleEmptyStateLabel()
  572. }
  573. }
  574. }
  575. private func handleEmptyStateLabel() {
  576. if let emptySearchText = viewModel?.emptySearchText {
  577. let text = String.localizedStringWithFormat(
  578. String.localized("search_no_result_for_x"),
  579. emptySearchText
  580. )
  581. emptyStateLabel.text = text
  582. emptyStateLabel.isHidden = false
  583. } else if isArchive && (viewModel?.numberOfRowsIn(section: 0) ?? 0) == 0 {
  584. emptyStateLabel.text = String.localized("archive_empty_hint")
  585. emptyStateLabel.isHidden = false
  586. } else {
  587. emptyStateLabel.text = nil
  588. emptyStateLabel.isHidden = true
  589. }
  590. }
  591. private func startTimer() {
  592. // check if the timer is not yet started
  593. stopTimer()
  594. timer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { [weak self] _ in
  595. guard let self = self,
  596. let appDelegate = UIApplication.shared.delegate as? AppDelegate
  597. else { return }
  598. if appDelegate.appIsInForeground() {
  599. self.handleChatListUpdate()
  600. } else {
  601. logger.warning("startTimer() must not be executed in background")
  602. }
  603. }
  604. }
  605. private func stopTimer() {
  606. // check if the timer is not already stopped
  607. if let timer = timer {
  608. timer.invalidate()
  609. }
  610. timer = nil
  611. }
  612. public func handleMailto(askToChat: Bool = true) {
  613. if let mailtoAddress = RelayHelper.shared.mailtoAddress {
  614. // FIXME: the line below should work
  615. // var contactId = dcContext.lookupContactIdByAddress(mailtoAddress)
  616. // workaround:
  617. let contacts: [Int] = dcContext.getContacts(flags: DC_GCL_ADD_SELF, queryString: mailtoAddress)
  618. let index = contacts.firstIndex(where: { dcContext.getContact(id: $0).email == mailtoAddress }) ?? -1
  619. var contactId = 0
  620. if index >= 0 {
  621. contactId = contacts[index]
  622. }
  623. if contactId != 0 && dcContext.getChatIdByContactId(contactId: contactId) != 0 {
  624. showChat(chatId: dcContext.getChatIdByContactId(contactId: contactId), animated: false)
  625. } else if askToChat {
  626. askToChatWith(address: mailtoAddress)
  627. } else {
  628. // Attention: we should have already asked in a different view controller!
  629. createAndShowNewChat(contactId: 0, email: mailtoAddress)
  630. }
  631. }
  632. }
  633. // MARK: - alerts
  634. private func showDeleteChatConfirmationAlert(chatId: Int) {
  635. let alert = UIAlertController(
  636. title: nil,
  637. message: String.localizedStringWithFormat(String.localized("ask_delete_named_chat"), dcContext.getChat(chatId: chatId).name),
  638. preferredStyle: .safeActionSheet
  639. )
  640. alert.addAction(UIAlertAction(title: String.localized("menu_delete_chat"), style: .destructive, handler: { _ in
  641. self.deleteChat(chatId: chatId, animated: true)
  642. }))
  643. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  644. self.present(alert, animated: true, completion: nil)
  645. }
  646. private func showDeleteMultipleChatConfirmationAlert() {
  647. let selected = tableView.indexPathsForSelectedRows?.count ?? 0
  648. if selected == 0 {
  649. return
  650. }
  651. let alert = UIAlertController(
  652. title: nil,
  653. message: String.localized(stringID: "ask_delete_chat", count: selected),
  654. preferredStyle: .safeActionSheet
  655. )
  656. alert.addAction(UIAlertAction(title: String.localized("delete"), style: .destructive, handler: { [weak self] _ in
  657. guard let self = self, let viewModel = self.viewModel else { return }
  658. viewModel.deleteChats(indexPaths: self.tableView.indexPathsForSelectedRows)
  659. self.setLongTapEditing(false)
  660. }))
  661. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  662. self.present(alert, animated: true, completion: nil)
  663. }
  664. private func askToChatWith(address: String, contactId: Int = 0) {
  665. let alert = UIAlertController(title: String.localizedStringWithFormat(String.localized("ask_start_chat_with"), address),
  666. message: nil,
  667. preferredStyle: .safeActionSheet)
  668. alert.addAction(UIAlertAction(title: String.localized("start_chat"), style: .default, handler: { [weak self] _ in
  669. guard let self = self else { return }
  670. self.createAndShowNewChat(contactId: contactId, email: address)
  671. }))
  672. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: { _ in
  673. if RelayHelper.shared.isMailtoHandling() {
  674. RelayHelper.shared.finishMailto()
  675. }
  676. }))
  677. present(alert, animated: true, completion: nil)
  678. }
  679. private func createAndShowNewChat(contactId: Int, email: String) {
  680. var contactId = contactId
  681. if contactId == 0 {
  682. contactId = self.dcContext.createContact(name: nil, email: email)
  683. }
  684. self.showNewChat(contactId: contactId)
  685. }
  686. private func askToChatWith(contactId: Int) {
  687. let dcContact = dcContext.getContact(id: contactId)
  688. askToChatWith(address: dcContact.nameNAddr, contactId: contactId)
  689. }
  690. private func deleteChat(chatId: Int, animated: Bool) {
  691. guard let viewModel = viewModel else { return }
  692. if !animated {
  693. viewModel.deleteChat(chatId: chatId)
  694. refreshInBg()
  695. return
  696. }
  697. if viewModel.searchActive {
  698. viewModel.deleteChat(chatId: chatId)
  699. viewModel.refreshData()
  700. viewModel.updateSearchResults(for: searchController)
  701. return
  702. }
  703. viewModel.deleteChat(chatId: chatId)
  704. }
  705. // MARK: - coordinator
  706. private func showNewChatController() {
  707. let newChatVC = NewChatViewController(dcContext: dcContext)
  708. navigationController?.pushViewController(newChatVC, animated: true)
  709. }
  710. func showChat(chatId: Int, highlightedMsg: Int? = nil, animated: Bool = true) {
  711. if searchController.isActive {
  712. searchController.searchBar.resignFirstResponder()
  713. }
  714. let chatVC = ChatViewController(dcContext: dcContext, chatId: chatId, highlightedMsg: highlightedMsg)
  715. navigationController?.pushViewController(chatVC, animated: animated)
  716. }
  717. public func showArchive(animated: Bool) {
  718. let controller = ChatListController(dcContext: dcContext, dcAccounts: dcAccounts, isArchive: true)
  719. navigationController?.pushViewController(controller, animated: animated)
  720. }
  721. private func showNewChat(contactId: Int) {
  722. let chatId = dcContext.createChatByContactId(contactId: contactId)
  723. showChat(chatId: Int(chatId))
  724. }
  725. }
  726. // MARK: - uisearchbardelegate
  727. extension ChatListController: UISearchBarDelegate {
  728. func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
  729. viewModel?.beginSearch()
  730. setLongTapEditing(false)
  731. return true
  732. }
  733. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  734. // searchBar will be set to "" by system
  735. viewModel?.endSearch()
  736. DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
  737. self.tableView.scrollToTop()
  738. }
  739. }
  740. func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
  741. tableView.scrollToTop()
  742. return true
  743. }
  744. }
  745. extension ChatListController: ContactCellDelegate {
  746. func onLongTap(at indexPath: IndexPath) {
  747. if let searchActive = viewModel?.searchActive,
  748. !searchActive,
  749. !RelayHelper.shared.isForwarding(),
  750. !tableView.isEditing {
  751. UIImpactFeedbackGenerator(style: .medium).impactOccurred()
  752. setLongTapEditing(true, initialIndexPath: [indexPath])
  753. tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)
  754. }
  755. }
  756. }
  757. extension ChatListController: ChatListEditingBarDelegate {
  758. func onPinButtonPressed() {
  759. viewModel?.pinChatsToggle(indexPaths: tableView.indexPathsForSelectedRows)
  760. setLongTapEditing(false)
  761. }
  762. func onDeleteButtonPressed() {
  763. showDeleteMultipleChatConfirmationAlert()
  764. }
  765. func onArchiveButtonPressed() {
  766. viewModel?.archiveChatsToggle(indexPaths: tableView.indexPathsForSelectedRows)
  767. setLongTapEditing(false)
  768. }
  769. }