WelcomeViewController.swift 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. import UIKit
  2. import DcCore
  3. class WelcomeViewController: UIViewController, ProgressAlertHandler {
  4. private var dcContext: DcContext
  5. private let dcAccounts: DcAccounts
  6. private let accountCode: String?
  7. private var backupProgressObserver: NSObjectProtocol?
  8. var progressObserver: NSObjectProtocol?
  9. var onProgressSuccess: VoidFunction?
  10. private var securityScopedResource: NSURL?
  11. private lazy var scrollView: UIScrollView = {
  12. let scrollView = UIScrollView()
  13. scrollView.showsVerticalScrollIndicator = false
  14. return scrollView
  15. }()
  16. private lazy var welcomeView: WelcomeContentView = {
  17. let view = WelcomeContentView()
  18. view.onLogin = { [weak self] in
  19. guard let self = self else { return }
  20. self.showAccountSetupController()
  21. }
  22. view.onScanQRCode = { [weak self] in
  23. guard let self = self else { return }
  24. let qrReader = QrCodeReaderController()
  25. qrReader.delegate = self
  26. self.qrCodeReader = qrReader
  27. self.navigationController?.pushViewController(qrReader, animated: true)
  28. }
  29. view.onImportBackup = { [weak self] in
  30. guard let self = self else { return }
  31. self.restoreBackup()
  32. }
  33. view.translatesAutoresizingMaskIntoConstraints = false
  34. return view
  35. }()
  36. private lazy var canCancel: Bool = {
  37. // "cancel" removes selected unconfigured account, so there needs to be at least one other account
  38. return dcAccounts.getAll().count >= 2
  39. }()
  40. private lazy var cancelButton: UIBarButtonItem = {
  41. return UIBarButtonItem(title: String.localized("cancel"), style: .plain, target: self, action: #selector(cancelAccountCreation))
  42. }()
  43. private lazy var moreButton: UIBarButtonItem = {
  44. let image: UIImage?
  45. if #available(iOS 13.0, *) {
  46. image = UIImage(systemName: "ellipsis.circle")
  47. } else {
  48. image = UIImage(named: "ic_more")
  49. }
  50. return UIBarButtonItem(image: image,
  51. style: .plain,
  52. target: self,
  53. action: #selector(moreButtonPressed))
  54. }()
  55. private lazy var mediaPicker: MediaPicker? = {
  56. let mediaPicker = MediaPicker(navigationController: navigationController)
  57. mediaPicker.delegate = self
  58. return mediaPicker
  59. }()
  60. private var qrCodeReader: QrCodeReaderController?
  61. weak var progressAlert: UIAlertController?
  62. init(dcAccounts: DcAccounts, accountCode: String? = nil) {
  63. self.dcAccounts = dcAccounts
  64. self.dcContext = dcAccounts.getSelected()
  65. self.accountCode = accountCode
  66. super.init(nibName: nil, bundle: nil)
  67. self.navigationItem.title = String.localized(canCancel ? "add_account" : "welcome_desktop")
  68. onProgressSuccess = { [weak self] in
  69. guard let self = self else { return }
  70. let profileInfoController = ProfileInfoViewController(context: self.dcContext)
  71. profileInfoController.onClose = {
  72. if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
  73. appDelegate.reloadDcContext()
  74. }
  75. }
  76. self.navigationController?.setViewControllers([profileInfoController], animated: true)
  77. }
  78. }
  79. required init?(coder: NSCoder) {
  80. fatalError("init(coder:) has not been implemented")
  81. }
  82. // MARK: - lifecycle
  83. override func viewDidLoad() {
  84. super.viewDidLoad()
  85. setupSubviews()
  86. if canCancel {
  87. navigationItem.leftBarButtonItem = cancelButton
  88. }
  89. navigationItem.rightBarButtonItem = moreButton
  90. if let accountCode = accountCode {
  91. handleQrCode(accountCode)
  92. }
  93. }
  94. override func viewDidLayoutSubviews() {
  95. super.viewDidLayoutSubviews()
  96. welcomeView.minContainerHeight = view.frame.height - view.safeAreaInsets.top
  97. }
  98. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  99. super.viewWillTransition(to: size, with: coordinator)
  100. welcomeView.minContainerHeight = size.height - view.safeAreaInsets.top
  101. }
  102. override func viewDidDisappear(_ animated: Bool) {
  103. let nc = NotificationCenter.default
  104. if let observer = self.progressObserver {
  105. nc.removeObserver(observer)
  106. self.progressObserver = nil
  107. }
  108. removeBackupProgressObserver()
  109. }
  110. private func removeBackupProgressObserver() {
  111. if let backupProgressObserver = self.backupProgressObserver {
  112. NotificationCenter.default.removeObserver(backupProgressObserver)
  113. self.backupProgressObserver = nil
  114. }
  115. }
  116. // MARK: - setup
  117. private func setupSubviews() {
  118. view.addSubview(scrollView)
  119. scrollView.translatesAutoresizingMaskIntoConstraints = false
  120. scrollView.addSubview(welcomeView)
  121. let frameGuide = scrollView.frameLayoutGuide
  122. let contentGuide = scrollView.contentLayoutGuide
  123. frameGuide.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
  124. frameGuide.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
  125. frameGuide.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true
  126. frameGuide.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
  127. contentGuide.leadingAnchor.constraint(equalTo: welcomeView.leadingAnchor).isActive = true
  128. contentGuide.topAnchor.constraint(equalTo: welcomeView.topAnchor).isActive = true
  129. contentGuide.trailingAnchor.constraint(equalTo: welcomeView.trailingAnchor).isActive = true
  130. contentGuide.bottomAnchor.constraint(equalTo: welcomeView.bottomAnchor).isActive = true
  131. // this enables vertical scrolling
  132. frameGuide.widthAnchor.constraint(equalTo: contentGuide.widthAnchor).isActive = true
  133. }
  134. // MARK: - actions
  135. private func createAccountFromQRCode(qrCode: String) {
  136. if dcAccounts.getSelected().isConfigured() {
  137. UserDefaults.standard.setValue(dcAccounts.getSelected().id, forKey: Constants.Keys.lastSelectedAccountKey)
  138. // FIXME: what do we want to do with QR-Code created accounts? For now: adding an unencrypted account
  139. // ensure we're configuring on an empty new account
  140. _ = dcAccounts.add()
  141. }
  142. let accountId = dcAccounts.getSelected().id
  143. if accountId != 0 {
  144. dcContext = dcAccounts.get(id: accountId)
  145. addProgressAlertListener(dcAccounts: self.dcAccounts,
  146. progressName: dcNotificationConfigureProgress,
  147. onSuccess: self.handleLoginSuccess)
  148. showProgressAlert(title: String.localized("login_header"), dcContext: self.dcContext)
  149. DispatchQueue.global().async { [weak self] in
  150. guard let self = self else { return }
  151. let success = self.dcContext.setConfigFromQR(qrCode: qrCode)
  152. DispatchQueue.main.async {
  153. if success {
  154. self.dcAccounts.stopIo()
  155. self.dcContext.configure()
  156. } else {
  157. self.updateProgressAlert(error: self.dcContext.lastErrorString,
  158. completion: self.accountCode != nil ? self.cancelAccountCreation : nil)
  159. }
  160. }
  161. }
  162. }
  163. }
  164. private func handleLoginSuccess() {
  165. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  166. if !UserDefaults.standard.bool(forKey: "notifications_disabled") {
  167. appDelegate.registerForNotifications()
  168. }
  169. onProgressSuccess?()
  170. }
  171. private func handleBackupRestoreSuccess() {
  172. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  173. if !UserDefaults.standard.bool(forKey: "notifications_disabled") {
  174. appDelegate.registerForNotifications()
  175. }
  176. if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
  177. appDelegate.reloadDcContext()
  178. }
  179. }
  180. @objc private func moreButtonPressed() {
  181. let alert = UIAlertController(title: "Encrypted Account (experimental)",
  182. message: "Do you want to encrypt your account database? This cannot be undone.",
  183. preferredStyle: .safeActionSheet)
  184. let encryptedAccountAction = UIAlertAction(title: "Create encrypted account", style: .default, handler: switchToEncrypted(_:))
  185. let cancelAction = UIAlertAction(title: String.localized("cancel"), style: .destructive, handler: nil)
  186. alert.addAction(encryptedAccountAction)
  187. alert.addAction(cancelAction)
  188. self.present(alert, animated: true, completion: nil)
  189. }
  190. private func switchToEncrypted(_ action: UIAlertAction) {
  191. let lastContextId = dcAccounts.getSelected().id
  192. let newContextId = dcAccounts.addClosedAccount()
  193. _ = dcAccounts.remove(id: lastContextId)
  194. KeychainManager.deleteAccountSecret(id: lastContextId)
  195. _ = dcAccounts.select(id: newContextId)
  196. dcContext = dcAccounts.getSelected()
  197. do {
  198. let secret = try KeychainManager.getAccountSecret(accountID: dcContext.id)
  199. guard dcContext.open(passphrase: secret) else {
  200. logger.error("Failed to open account database for account \(dcContext.id)")
  201. return
  202. }
  203. self.navigationItem.title = "Add encrypted account"
  204. } catch KeychainError.unhandledError(let message, let status) {
  205. logger.error("Keychain error. Failed to create encrypted account. \(message). Error status: \(status)")
  206. } catch {
  207. logger.error("Keychain error. Failed to create encrypted account.")
  208. }
  209. }
  210. private func showAccountSetupController() {
  211. let accountSetupController = AccountSetupController(dcAccounts: self.dcAccounts, editView: false)
  212. accountSetupController.onLoginSuccess = {
  213. if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
  214. appDelegate.reloadDcContext()
  215. }
  216. }
  217. self.navigationController?.pushViewController(accountSetupController, animated: true)
  218. }
  219. @objc private func cancelAccountCreation() {
  220. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  221. // take a bit care on account removal:
  222. // remove only openend and unconfigured and make sure, there is another account
  223. // (normally, both checks are not needed, however, some resilience wrt future program-flow-changes seems to be reasonable here)
  224. let selectedAccount = dcAccounts.getSelected()
  225. if selectedAccount.isOpen() && !selectedAccount.isConfigured() {
  226. _ = dcAccounts.remove(id: selectedAccount.id)
  227. KeychainManager.deleteAccountSecret(id: selectedAccount.id)
  228. if self.dcAccounts.getAll().isEmpty {
  229. _ = self.dcAccounts.add()
  230. }
  231. }
  232. let lastSelectedAccountId = UserDefaults.standard.integer(forKey: Constants.Keys.lastSelectedAccountKey)
  233. if lastSelectedAccountId != 0 {
  234. _ = dcAccounts.select(id: lastSelectedAccountId)
  235. }
  236. appDelegate.reloadDcContext()
  237. }
  238. private func restoreBackup() {
  239. logger.info("restoring backup")
  240. if dcContext.isConfigured() {
  241. return
  242. }
  243. addProgressHudBackupListener()
  244. if let documentsDirectory = ensureDcDocFolderExists(),
  245. let filePath = dcContext.imexHasBackup(filePath: documentsDirectory.relativePath) {
  246. importBackup(at: filePath)
  247. } else {
  248. mediaPicker?.showDocumentLibrary(selectFolder: true)
  249. }
  250. }
  251. private func importBackup(at filepath: String) {
  252. logger.info("restoring backup: \(filepath)")
  253. showProgressAlert(title: String.localized("import_backup_title"), dcContext: dcContext)
  254. dcAccounts.stopIo()
  255. dcContext.imex(what: DC_IMEX_IMPORT_BACKUP, directory: filepath)
  256. }
  257. private func ensureDcDocFolderExists() -> URL? {
  258. let fileManager = FileManager.default
  259. guard let documentsDirectory = try? fileManager.url(for: .documentDirectory,
  260. in: .userDomainMask,
  261. appropriateFor: nil,
  262. create: true) else { return nil }
  263. let emptyHiddenFileURL = documentsDirectory.appendingPathComponent(".Move your backup here")
  264. if !fileManager.fileExists(atPath: emptyHiddenFileURL.relativePath) {
  265. fileManager.createFile(atPath: emptyHiddenFileURL.relativePath, contents: nil)
  266. }
  267. return documentsDirectory
  268. }
  269. private func addProgressHudBackupListener() {
  270. let nc = NotificationCenter.default
  271. backupProgressObserver = nc.addObserver(
  272. forName: dcNotificationImexProgress,
  273. object: nil,
  274. queue: nil
  275. ) { notification in
  276. if let ui = notification.userInfo {
  277. if let error = ui["error"] as? Bool, error {
  278. self.dcAccounts.startIo()
  279. self.updateProgressAlert(error: ui["errorMessage"] as? String)
  280. self.securityScopedResource?.stopAccessingSecurityScopedResource()
  281. self.securityScopedResource = nil
  282. } else if let done = ui["done"] as? Bool, done {
  283. self.dcAccounts.startIo()
  284. self.updateProgressAlertSuccess(completion: self.handleBackupRestoreSuccess)
  285. self.securityScopedResource?.stopAccessingSecurityScopedResource()
  286. self.securityScopedResource = nil
  287. } else {
  288. self.updateProgressAlertValue(value: ui["progress"] as? Int)
  289. }
  290. }
  291. }
  292. }
  293. }
  294. extension WelcomeViewController: QrCodeReaderDelegate {
  295. func handleQrCode(_ code: String) {
  296. let lot = dcContext.checkQR(qrCode: code)
  297. if let domain = lot.text1, lot.state == DC_QR_ACCOUNT {
  298. confirmAccountCreationAlert(accountDomain: domain, qrCode: code)
  299. } else {
  300. qrErrorAlert()
  301. }
  302. }
  303. private func confirmAccountCreationAlert(accountDomain domain: String, qrCode: String) {
  304. let title = String.localizedStringWithFormat(
  305. String.localized(dcAccounts.getAll().count > 1 ? "qraccount_ask_create_and_login_another" : "qraccount_ask_create_and_login"),
  306. domain)
  307. let alert = UIAlertController(title: title, message: nil, preferredStyle: .alert)
  308. let okAction = UIAlertAction(
  309. title: String.localized("ok"),
  310. style: .default,
  311. handler: { [weak self] _ in
  312. guard let self = self else { return }
  313. self.dismissQRReader()
  314. self.createAccountFromQRCode(qrCode: qrCode)
  315. }
  316. )
  317. let qrCancelAction = UIAlertAction(
  318. title: String.localized("cancel"),
  319. style: .cancel,
  320. handler: { [weak self] _ in
  321. guard let self = self else { return }
  322. self.dismissQRReader()
  323. // if an injected accountCode exists, the WelcomeViewController was only opened to handle that
  324. // cancelling the action should also dismiss the whole controller
  325. if self.accountCode != nil {
  326. self.cancelAccountCreation()
  327. }
  328. }
  329. )
  330. alert.addAction(okAction)
  331. alert.addAction(qrCancelAction)
  332. if qrCodeReader != nil {
  333. qrCodeReader?.present(alert, animated: true)
  334. } else {
  335. self.present(alert, animated: true)
  336. }
  337. }
  338. private func qrErrorAlert() {
  339. let title = String.localized("qraccount_qr_code_cannot_be_used")
  340. let alert = UIAlertController(title: title, message: nil, preferredStyle: .alert)
  341. let okAction = UIAlertAction(
  342. title: String.localized("ok"),
  343. style: .default,
  344. handler: { [weak self] _ in
  345. guard let self = self else { return }
  346. if self.accountCode != nil {
  347. // if an injected accountCode exists, the WelcomeViewController was only opened to handle that
  348. // if the action failed the whole controller should be dismissed
  349. self.cancelAccountCreation()
  350. } else {
  351. self.qrCodeReader?.startSession()
  352. }
  353. }
  354. )
  355. alert.addAction(okAction)
  356. qrCodeReader?.present(alert, animated: true, completion: nil)
  357. }
  358. private func dismissQRReader() {
  359. self.navigationController?.popViewController(animated: true)
  360. self.qrCodeReader = nil
  361. }
  362. }
  363. // MARK: - WelcomeContentView
  364. class WelcomeContentView: UIView {
  365. var onLogin: VoidFunction?
  366. var onScanQRCode: VoidFunction?
  367. var onImportBackup: VoidFunction?
  368. var minContainerHeight: CGFloat = 0 {
  369. didSet {
  370. containerMinHeightConstraint.constant = minContainerHeight
  371. logoHeightConstraint.constant = calculateLogoHeight()
  372. }
  373. }
  374. private lazy var containerMinHeightConstraint: NSLayoutConstraint = {
  375. return container.heightAnchor.constraint(greaterThanOrEqualToConstant: 0)
  376. }()
  377. private lazy var logoHeightConstraint: NSLayoutConstraint = {
  378. return logoView.heightAnchor.constraint(equalToConstant: 0)
  379. }()
  380. private var container = UIView()
  381. private var logoView: UIImageView = {
  382. let image = #imageLiteral(resourceName: "background_intro")
  383. let view = UIImageView(image: image)
  384. return view
  385. }()
  386. private lazy var titleLabel: UILabel = {
  387. let label = UILabel()
  388. label.text = String.localized("welcome_chat_over_email")
  389. label.textColor = DcColors.grayTextColor
  390. label.textAlignment = .center
  391. label.numberOfLines = 0
  392. label.font = UIFont.systemFont(ofSize: 24, weight: .bold)
  393. return label
  394. }()
  395. private lazy var buttonStack: UIStackView = {
  396. let stack = UIStackView(arrangedSubviews: [loginButton, qrCodeButton, importBackupButton])
  397. stack.axis = .vertical
  398. stack.spacing = 15
  399. return stack
  400. }()
  401. private lazy var loginButton: UIButton = {
  402. let button = UIButton(type: .roundedRect)
  403. let title = String.localized("login_header").uppercased()
  404. button.setTitle(title, for: .normal)
  405. button.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: .regular)
  406. button.setTitleColor(.white, for: .normal)
  407. button.backgroundColor = DcColors.primary
  408. let insets = button.contentEdgeInsets
  409. button.contentEdgeInsets = UIEdgeInsets(top: 8, left: 15, bottom: 8, right: 15)
  410. button.layer.cornerRadius = 5
  411. button.clipsToBounds = true
  412. button.addTarget(self, action: #selector(loginButtonPressed(_:)), for: .touchUpInside)
  413. return button
  414. }()
  415. private lazy var qrCodeButton: UIButton = {
  416. let button = UIButton()
  417. let title = String.localized("scan_invitation_code")
  418. button.setTitleColor(UIColor.systemBlue, for: .normal)
  419. button.setTitle(title, for: .normal)
  420. button.addTarget(self, action: #selector(qrCodeButtonPressed(_:)), for: .touchUpInside)
  421. return button
  422. }()
  423. private lazy var importBackupButton: UIButton = {
  424. let button = UIButton()
  425. let title = String.localized("import_backup_title")
  426. button.setTitleColor(UIColor.systemBlue, for: .normal)
  427. button.setTitle(title, for: .normal)
  428. button.addTarget(self, action: #selector(importBackupButtonPressed(_:)), for: .touchUpInside)
  429. return button
  430. }()
  431. private let defaultSpacing: CGFloat = 20
  432. init() {
  433. super.init(frame: .zero)
  434. setupSubviews()
  435. backgroundColor = DcColors.defaultBackgroundColor
  436. }
  437. required init?(coder: NSCoder) {
  438. fatalError("init(coder:) has not been implemented")
  439. }
  440. // MARK: - setup
  441. private func setupSubviews() {
  442. addSubview(container)
  443. container.translatesAutoresizingMaskIntoConstraints = false
  444. container.topAnchor.constraint(equalTo: topAnchor).isActive = true
  445. container.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
  446. container.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.75).isActive = true
  447. container.centerXAnchor.constraint(equalTo: centerXAnchor, constant: 0).isActive = true
  448. containerMinHeightConstraint.isActive = true
  449. _ = [logoView, titleLabel].map {
  450. addSubview($0)
  451. $0.translatesAutoresizingMaskIntoConstraints = false
  452. }
  453. let bottomLayoutGuide = UILayoutGuide()
  454. container.addLayoutGuide(bottomLayoutGuide)
  455. bottomLayoutGuide.bottomAnchor.constraint(equalTo: container.bottomAnchor).isActive = true
  456. bottomLayoutGuide.heightAnchor.constraint(equalTo: container.heightAnchor, multiplier: 0.45).isActive = true
  457. titleLabel.leadingAnchor.constraint(equalTo: container.leadingAnchor).isActive = true
  458. titleLabel.trailingAnchor.constraint(equalTo: container.trailingAnchor).isActive = true
  459. titleLabel.topAnchor.constraint(equalTo: bottomLayoutGuide.topAnchor).isActive = true
  460. titleLabel.setContentHuggingPriority(.defaultHigh, for: .vertical)
  461. logoView.bottomAnchor.constraint(equalTo: titleLabel.topAnchor, constant: -defaultSpacing).isActive = true
  462. logoView.centerXAnchor.constraint(equalTo: container.centerXAnchor).isActive = true
  463. logoHeightConstraint.constant = calculateLogoHeight()
  464. logoHeightConstraint.isActive = true
  465. logoView.widthAnchor.constraint(equalTo: logoView.heightAnchor).isActive = true
  466. let logoTopAnchor = logoView.topAnchor.constraint(equalTo: container.topAnchor, constant: 20) // this will allow the container to grow in height
  467. logoTopAnchor.priority = .defaultLow
  468. logoTopAnchor.isActive = true
  469. let buttonContainerGuide = UILayoutGuide()
  470. container.addLayoutGuide(buttonContainerGuide)
  471. buttonContainerGuide.topAnchor.constraint(equalTo: titleLabel.bottomAnchor).isActive = true
  472. buttonContainerGuide.bottomAnchor.constraint(equalTo: container.bottomAnchor).isActive = true
  473. loginButton.setContentHuggingPriority(.defaultHigh, for: .vertical)
  474. container.addSubview(buttonStack)
  475. buttonStack.translatesAutoresizingMaskIntoConstraints = false
  476. buttonStack.centerXAnchor.constraint(equalTo: container.centerXAnchor).isActive = true
  477. buttonStack.centerYAnchor.constraint(equalTo: buttonContainerGuide.centerYAnchor).isActive = true
  478. let buttonStackTopAnchor = buttonStack.topAnchor.constraint(equalTo: buttonContainerGuide.topAnchor, constant: defaultSpacing)
  479. // this will allow the container to grow in height
  480. let buttonStackBottomAnchor = buttonStack.bottomAnchor.constraint(equalTo: buttonContainerGuide.bottomAnchor, constant: -50)
  481. _ = [buttonStackTopAnchor, buttonStackBottomAnchor].map {
  482. $0.priority = .defaultLow
  483. $0.isActive = true
  484. }
  485. }
  486. private func calculateLogoHeight() -> CGFloat {
  487. if UIDevice.current.userInterfaceIdiom == .phone {
  488. return UIApplication.shared.statusBarOrientation.isLandscape ? UIScreen.main.bounds.height * 0.5 : UIScreen.main.bounds.width * 0.75
  489. } else {
  490. return 275
  491. }
  492. }
  493. // MARK: - actions
  494. @objc private func loginButtonPressed(_ sender: UIButton) {
  495. onLogin?()
  496. }
  497. @objc private func qrCodeButtonPressed(_ sender: UIButton) {
  498. onScanQRCode?()
  499. }
  500. @objc private func importBackupButtonPressed(_ sender: UIButton) {
  501. onImportBackup?()
  502. }
  503. }
  504. extension WelcomeViewController: MediaPickerDelegate {
  505. func onDocumentSelected(url: NSURL) {
  506. // ensure we can access folders outside of the app's sandbox
  507. let isSecurityScopedResource = url.startAccessingSecurityScopedResource()
  508. if isSecurityScopedResource {
  509. securityScopedResource = url
  510. }
  511. if let selectedBackupFilePath = url.relativePath {
  512. importBackup(at: selectedBackupFilePath)
  513. } else {
  514. onSelectionCancelled()
  515. securityScopedResource = nil
  516. }
  517. }
  518. func onSelectionCancelled() {
  519. let alert = UIAlertController(
  520. title: String.localized("import_backup_title"),
  521. message: String.localizedStringWithFormat(
  522. String.localized("import_backup_no_backup_found"),
  523. "➔ Mac-Finder or iTunes ➔ iPhone ➔ " + String.localized("files") + " ➔ Delta Chat"), // iTunes was used up to Maverick 10.4
  524. preferredStyle: .alert)
  525. alert.addAction(UIAlertAction(title: String.localized("ok"), style: .cancel))
  526. present(alert, animated: true)
  527. }
  528. }