content stringlengths 1 103k ⌀ | path stringlengths 8 216 | filename stringlengths 2 179 | language stringclasses 15
values | size_bytes int64 2 189k | quality_score float64 0.5 0.95 | complexity float64 0 1 | documentation_ratio float64 0 1 | repository stringclasses 5
values | stars int64 0 1k | created_date stringdate 2023-07-10 19:21:08 2025-07-09 19:11:45 | license stringclasses 4
values | is_test bool 2
classes | file_hash stringlengths 32 32 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
//\n// AccountDeletionViewModel.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2023-07-13.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nstruct AccountDeletionViewModel {\n let accountNumber: String\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\AccountDeletion\AccountDeletionViewModel.swift | AccountDeletionViewModel.swift | Swift | 241 | 0.95 | 0 | 0.636364 | awesome-app | 438 | 2024-03-25T18:46:05.806361 | BSD-3-Clause | false | 8f5c1547c210a2c4edf56651f7f33999 |
//\n// AlertPresentation.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-08-23.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport Routing\n\nstruct AlertMetadata {\n let presentation: AlertPresentation\n let context: Presenting\n}\n\nstruct AlertAction {\n let title: String\n let style: AlertActionStyle\n var accessibilityId: AccessibilityIdentifier?\n var handler: (() -> Void)?\n}\n\nstruct AlertPresentation: Identifiable, CustomDebugStringConvertible {\n let id: String\n\n var accessibilityIdentifier: AccessibilityIdentifier?\n var header: String?\n var icon: AlertIcon?\n var title: String?\n var message: String?\n var attributedMessage: NSAttributedString?\n let buttons: [AlertAction]\n\n var debugDescription: String {\n return id\n }\n}\n\nextension AlertPresentation: Equatable, Hashable {\n func hash(into hasher: inout Hasher) {\n hasher.combine(id)\n }\n\n static func == (lhs: AlertPresentation, rhs: AlertPresentation) -> Bool {\n return lhs.id == rhs.id\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Alert\AlertPresentation.swift | AlertPresentation.swift | Swift | 1,076 | 0.95 | 0 | 0.175 | vue-tools | 341 | 2025-04-07T02:47:58.719017 | MIT | false | 2cafdd86dd06444cd135bb94f7fe0838 |
//\n// AlertPresenter.swift\n// MullvadVPN\n//\n// Created by pronebird on 04/06/2020.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Routing\n\n@MainActor\nstruct AlertPresenter {\n weak var context: (any Presenting)?\n\n func showAlert(presentation: AlertPresentation, animated: Bool) {\n guard let context else { return }\n\n context.applicationRouter?.presentAlert(\n route: .alert(presentation.id),\n animated: animated,\n metadata: AlertMetadata(presentation: presentation, context: context)\n )\n }\n\n func dismissAlert(presentation: AlertPresentation, animated: Bool) {\n context?.applicationRouter?.dismiss(.alert(presentation.id), animated: animated)\n }\n}\n\nextension ApplicationRouter {\n func presentAlert(route: RouteType, animated: Bool, metadata: AlertMetadata) {\n present(route, animated: animated, metadata: metadata)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Alert\AlertPresenter.swift | AlertPresenter.swift | Swift | 933 | 0.95 | 0 | 0.25 | awesome-app | 498 | 2025-06-11T17:49:51.987100 | GPL-3.0 | false | 9718f61bfdf086cff6f9791988cf65da |
//\n// AlertViewController.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-05-19.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nenum AlertActionStyle {\n case `default`\n case destructive\n\n fileprivate var buttonStyle: AppButton.Style {\n switch self {\n case .default:\n return .default\n case .destructive:\n return .danger\n }\n }\n}\n\nenum AlertIcon {\n case alert\n case warning\n case info\n case spinner\n\n fileprivate var image: UIImage? {\n switch self {\n case .alert:\n return UIImage.Buttons.alert.withTintColor(.dangerColor)\n case .warning:\n return UIImage.Buttons.alert.withTintColor(.white)\n case .info:\n return UIImage.Buttons.info.withTintColor(.white)\n default:\n return nil\n }\n }\n}\n\nclass AlertViewController: UIViewController {\n typealias Handler = () -> Void\n var onDismiss: Handler?\n\n private let scrollView = UIScrollView()\n private var scrollViewHeightConstraint: NSLayoutConstraint!\n private let presentation: AlertPresentation\n\n private let viewContainer: UIView = {\n let view = UIView()\n\n view.backgroundColor = .secondaryColor\n view.layer.cornerRadius = 11\n\n return view\n }()\n\n private let buttonView: UIStackView = {\n let view = UIStackView()\n\n view.axis = .vertical\n view.spacing = UIMetrics.CustomAlert.containerSpacing\n view.isLayoutMarginsRelativeArrangement = true\n view.directionalLayoutMargins = UIMetrics.CustomAlert.containerMargins\n\n return view\n }()\n\n private let contentView: UIStackView = {\n let view = UIStackView()\n\n view.axis = .vertical\n view.spacing = UIMetrics.CustomAlert.containerSpacing\n view.isLayoutMarginsRelativeArrangement = true\n view.directionalLayoutMargins = UIMetrics.CustomAlert.containerMargins\n\n return view\n }()\n\n private var handlers = [UIButton: Handler]()\n\n init(presentation: AlertPresentation) {\n self.presentation = presentation\n\n super.init(nibName: nil, bundle: nil)\n\n modalPresentationStyle = .overFullScreen\n modalTransitionStyle = .crossDissolve\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n override func viewDidLayoutSubviews() {\n super.viewDidLayoutSubviews()\n\n view.layoutIfNeeded()\n scrollViewHeightConstraint.constant = scrollView.contentSize.height\n\n adjustButtonMargins()\n }\n\n override func viewDidLoad() {\n super.viewDidLoad()\n\n view.setAccessibilityIdentifier(presentation.accessibilityIdentifier ?? .alertContainerView)\n view.backgroundColor = .black.withAlphaComponent(0.5)\n\n setContent()\n setConstraints()\n }\n\n private func setContent() {\n presentation.icon.flatMap { addIcon($0) }\n presentation.header.flatMap { addHeader($0) }\n presentation.title.flatMap { addTitle($0) }\n\n if let message = presentation.attributedMessage {\n addMessage(message)\n } else if let message = presentation.message {\n addMessage(message)\n }\n\n presentation.buttons.forEach { action in\n addAction(\n title: action.title,\n style: action.style,\n accessibilityId: action.accessibilityId,\n handler: action.handler\n )\n }\n\n // Icon only spinner alerts should have no background and equal top and bottom margins.\n if presentation.icon == .spinner, contentView.arrangedSubviews.count == 1 {\n viewContainer.backgroundColor = .clear\n contentView.directionalLayoutMargins.bottom = UIMetrics.CustomAlert.containerMargins.top\n }\n }\n\n private func setConstraints() {\n viewContainer.addConstrainedSubviews([scrollView, buttonView]) {\n scrollView.pinEdgesToSuperview(.all().excluding(.bottom))\n buttonView.pinEdgesToSuperview(.all().excluding(.top))\n buttonView.topAnchor.constraint(equalTo: scrollView.bottomAnchor)\n }\n\n scrollView.addConstrainedSubviews([contentView]) {\n contentView.pinEdgesToSuperview(.all())\n contentView.widthAnchor.constraint(equalTo: scrollView.widthAnchor)\n }\n\n scrollViewHeightConstraint = scrollView.heightAnchor.constraint(equalToConstant: 0).withPriority(.defaultLow)\n scrollViewHeightConstraint.isActive = true\n\n view.addConstrainedSubviews([viewContainer]) {\n viewContainer.centerXAnchor.constraint(equalTo: view.centerXAnchor)\n viewContainer.centerYAnchor.constraint(equalTo: view.centerYAnchor)\n\n viewContainer.topAnchor\n .constraint(greaterThanOrEqualTo: view.layoutMarginsGuide.topAnchor)\n .withPriority(.defaultHigh)\n\n view.layoutMarginsGuide.bottomAnchor\n .constraint(greaterThanOrEqualTo: viewContainer.bottomAnchor)\n .withPriority(.defaultHigh)\n\n let leadingConstraint = viewContainer.leadingAnchor\n .constraint(equalTo: view.layoutMarginsGuide.leadingAnchor)\n let trailingConstraint = view.layoutMarginsGuide.trailingAnchor\n .constraint(equalTo: viewContainer.trailingAnchor)\n\n if traitCollection.userInterfaceIdiom == .pad {\n viewContainer.widthAnchor\n .constraint(lessThanOrEqualToConstant: UIMetrics.preferredFormSheetContentSize.width)\n leadingConstraint.withPriority(.defaultHigh)\n trailingConstraint.withPriority(.defaultHigh)\n } else {\n leadingConstraint\n trailingConstraint\n }\n }\n }\n\n private func adjustButtonMargins() {\n if !buttonView.arrangedSubviews.isEmpty {\n // The presence of a button should yield a custom top margin.\n buttonView.directionalLayoutMargins.top = UIMetrics.CustomAlert.interContainerSpacing\n\n // Buttons below scrollable content should have more margin.\n if scrollView.contentSize.height > scrollView.bounds.size.height {\n buttonView.directionalLayoutMargins.top = UIMetrics.CustomAlert.containerSpacing\n }\n }\n }\n\n private func addHeader(_ title: String) {\n let label = UILabel()\n\n label.text = title\n label.font = .preferredFont(forTextStyle: .largeTitle, weight: .bold)\n label.textColor = .white\n label.adjustsFontForContentSizeCategory = true\n label.textAlignment = .center\n label.numberOfLines = 0\n label.setAccessibilityIdentifier(.alertTitle)\n\n contentView.addArrangedSubview(label)\n contentView.setCustomSpacing(16, after: label)\n }\n\n private func addTitle(_ title: String) {\n let label = UILabel()\n\n label.text = title\n label.font = .preferredFont(forTextStyle: .title3, weight: .semibold)\n label.textColor = .white.withAlphaComponent(0.9)\n label.adjustsFontForContentSizeCategory = true\n label.numberOfLines = 0\n\n contentView.addArrangedSubview(label)\n contentView.setCustomSpacing(8, after: label)\n }\n\n private func addMessage(_ message: String) {\n let label = UILabel()\n\n let message = NSMutableAttributedString(string: message)\n message.apply(paragraphStyle: .alert)\n\n label.attributedText = message\n label.font = .preferredFont(forTextStyle: .body)\n label.textColor = .white.withAlphaComponent(0.8)\n label.adjustsFontForContentSizeCategory = true\n label.numberOfLines = 0\n\n contentView.addArrangedSubview(label)\n }\n\n private func addMessage(_ message: NSAttributedString) {\n let label = UILabel()\n\n let message = NSMutableAttributedString(attributedString: message)\n message.removeAttribute(.paragraphStyle, range: NSRange(location: 0, length: message.length))\n message.apply(paragraphStyle: .alert)\n\n label.attributedText = message\n label.textColor = .white.withAlphaComponent(0.8)\n label.adjustsFontForContentSizeCategory = true\n label.numberOfLines = 0\n\n contentView.addArrangedSubview(label)\n }\n\n private func addIcon(_ icon: AlertIcon) {\n let iconView = icon == .spinner ? getSpinnerView() : getImageView(for: icon)\n contentView.addArrangedSubview(iconView)\n }\n\n private func addAction(\n title: String,\n style: AlertActionStyle,\n accessibilityId: AccessibilityIdentifier?,\n handler: (() -> Void)? = nil\n ) {\n let button = AppButton(style: style.buttonStyle)\n\n button.setTitle(title, for: .normal)\n button.setAccessibilityIdentifier(accessibilityId)\n button.addTarget(self, action: #selector(didTapButton), for: .touchUpInside)\n\n buttonView.addArrangedSubview(button)\n handler.flatMap { handlers[button] = $0 }\n }\n\n private func getImageView(for icon: AlertIcon) -> UIView {\n let imageView = UIImageView()\n let imageContainerView = UIView()\n\n imageContainerView.addConstrainedSubviews([imageView]) {\n imageView.pinEdges(.init([.top(0), .bottom(0)]), to: imageContainerView)\n imageView.centerXAnchor.constraint(equalTo: imageContainerView.centerXAnchor, constant: 0)\n imageView.heightAnchor.constraint(equalToConstant: 48)\n imageView.widthAnchor.constraint(equalTo: imageView.heightAnchor, multiplier: 1)\n }\n\n imageView.image = icon.image?.withRenderingMode(.alwaysOriginal)\n imageView.contentMode = .scaleAspectFit\n\n return imageContainerView\n }\n\n private func getSpinnerView() -> UIView {\n let spinnerView = SpinnerActivityIndicatorView(style: .large)\n let spinnerContainerView = UIView()\n\n spinnerContainerView.addConstrainedSubviews([spinnerView]) {\n spinnerView.pinEdges(.init([.top(0), .bottom(0)]), to: spinnerContainerView)\n spinnerView.centerXAnchor.constraint(equalTo: spinnerContainerView.centerXAnchor, constant: 0)\n }\n\n spinnerView.startAnimating()\n\n return spinnerContainerView\n }\n\n @objc private func didTapButton(_ button: AppButton) {\n onDismiss?()\n if let handler = handlers.removeValue(forKey: button) {\n handler()\n }\n handlers.removeAll()\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Alert\AlertViewController.swift | AlertViewController.swift | Swift | 10,599 | 0.95 | 0.044025 | 0.04 | python-kit | 751 | 2024-10-04T12:56:49.398931 | Apache-2.0 | false | 08c15d743d31cc01056fe7cc4f93d941 |
//\n// BulletPointText.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2025-01-10.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\nimport SwiftUI\n\nstruct BulletPointText: View {\n let text: String\n let bullet = "•"\n\n var body: some View {\n HStack(alignment: .firstTextBaseline) {\n Text(bullet)\n .font(.body)\n .foregroundColor(UIColor.secondaryTextColor.color)\n Text(text)\n .font(.body)\n .foregroundColor(UIColor.secondaryTextColor.color)\n .lineLimit(nil)\n .multilineTextAlignment(.leading)\n }\n .frame(maxWidth: .infinity, alignment: .leading)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\ChangeLog\BulletPointText.swift | BulletPointText.swift | Swift | 709 | 0.95 | 0 | 0.28 | python-kit | 30 | 2024-01-24T10:15:32.692597 | GPL-3.0 | false | a93908624178fe52f8bbd27b30ade31a |
//\n// ChangeLogModel.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2025-01-10.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nstruct ChangeLogModel {\n let title: String\n let changes: [String]\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\ChangeLog\ChangeLogModel.swift | ChangeLogModel.swift | Swift | 220 | 0.8 | 0 | 0.636364 | python-kit | 597 | 2023-09-26T16:24:04.697826 | MIT | false | 043ed29e8b83d0ed93ce55a49f51100b |
//\n// ChangeLogReader.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2025-01-10.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\nimport Foundation\n\nprotocol ChangeLogReaderProtocol {\n func read() throws -> [String]\n}\n\nstruct ChangeLogReader: ChangeLogReaderProtocol {\n /**\n Reads change log file from bundle and returns its contents as a string.\n */\n func read() throws -> [String] {\n try String(contentsOfFile: try getPathToChangesFile())\n .split(whereSeparator: { $0.isNewline })\n .compactMap { line in\n let trimmedString = line.trimmingCharacters(in: .whitespaces)\n\n return trimmedString.isEmpty ? nil : trimmedString\n }\n }\n\n /**\n Returns path to change log file in bundle.\n */\n private func getPathToChangesFile() throws -> String {\n if let filePath = Bundle.main.path(forResource: "changes", ofType: "txt") {\n return filePath\n } else {\n throw CocoaError(.fileNoSuchFile)\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\ChangeLog\ChangeLogReader.swift | ChangeLogReader.swift | Swift | 1,051 | 0.95 | 0.078947 | 0.323529 | vue-tools | 794 | 2025-05-05T06:26:24.367548 | BSD-3-Clause | false | f2c63547b5b68693eccabcee9ef438f3 |
//\n// ChangeLogView.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2025-01-10.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\nimport SwiftUI\n\nstruct ChangeLogView<ViewModel>: View where ViewModel: ChangeLogViewModelProtocol {\n @ObservedObject var viewModel: ViewModel\n\n init(viewModel: ViewModel) {\n self.viewModel = viewModel\n }\n\n var body: some View {\n ZStack {\n UIColor.secondaryColor.color.ignoresSafeArea()\n VStack {\n Text(viewModel.changeLog?.title ?? "")\n .font(.title)\n .fontWeight(.semibold)\n .foregroundColor(UIColor.primaryTextColor.color)\n .frame(maxWidth: .infinity, alignment: .leading)\n List {\n ForEach(viewModel.changeLog?.changes ?? [], id: \.self) { item in\n BulletPointText(text: item)\n .listRowSeparator(.hidden)\n .listRowBackground(Color.clear)\n }\n }\n .listStyle(.plain)\n .frame(maxHeight: .infinity)\n }\n .padding(.horizontal, 24.0)\n }\n .onAppear {\n viewModel.getLatestChanges()\n }\n }\n}\n\n#Preview {\n ChangeLogView(viewModel: MockChangeLogViewModel())\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\ChangeLog\ChangeLogView.swift | ChangeLogView.swift | Swift | 1,366 | 0.95 | 0 | 0.190476 | react-lib | 329 | 2025-07-01T15:24:55.180542 | BSD-3-Clause | false | f4145f5cfdcd8bbe3a878ff88b9fb950 |
//\n// ChangeLogViewModel.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2023-08-22.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadLogging\nimport SwiftUI\n\nprotocol ChangeLogViewModelProtocol: ObservableObject {\n var changeLog: ChangeLogModel? { get }\n func getLatestChanges()\n}\n\nclass ChangeLogViewModel: ChangeLogViewModelProtocol {\n private let logger = Logger(label: "ChangeLogViewModel")\n private let changeLogReader: ChangeLogReaderProtocol\n\n @Published var changeLog: ChangeLogModel?\n\n init(changeLogReader: ChangeLogReaderProtocol) {\n self.changeLogReader = changeLogReader\n }\n\n func getLatestChanges() {\n do {\n changeLog = ChangeLogModel(title: Bundle.main.productVersion, changes: try changeLogReader.read())\n } catch {\n logger.error(error: error, message: "Cannot read change log from bundle.")\n }\n }\n}\n\nclass MockChangeLogViewModel: ChangeLogViewModelProtocol {\n @Published var changeLog: ChangeLogModel?\n func getLatestChanges() {\n changeLog = ChangeLogModel(title: "2025.1", changes: [\n "Introduced a dark mode for better accessibility and user experience.",\n "Added two-factor authentication (2FA) for all user accounts.",\n ])\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\ChangeLog\ChangeLogViewModel.swift | ChangeLogViewModel.swift | Swift | 1,319 | 0.95 | 0.133333 | 0.184211 | react-lib | 922 | 2024-03-05T21:57:14.119831 | BSD-3-Clause | false | b4669b2aec82ec6c25edf71648fe4233 |
//\n// InAppPurchaseInteractor.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2023-07-21.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport StoreKit\n\nprotocol InAppPurchaseViewControllerDelegate: AnyObject {\n func didBeginPayment()\n func didEndPayment()\n}\n\nclass InAppPurchaseInteractor: @unchecked Sendable {\n let storePaymentManager: StorePaymentManager\n var didFinishPayment: ((InAppPurchaseInteractor, StorePaymentEvent) -> Void)?\n weak var viewControllerDelegate: InAppPurchaseViewControllerDelegate?\n\n private var paymentObserver: StorePaymentObserver?\n\n init(storePaymentManager: StorePaymentManager) {\n self.storePaymentManager = storePaymentManager\n self.addObservers()\n }\n\n private func addObservers() {\n let paymentObserver = StorePaymentBlockObserver { [weak self] _, event in\n guard let self else { return }\n viewControllerDelegate?.didEndPayment()\n didFinishPayment?(self, event)\n }\n\n storePaymentManager.addPaymentObserver(paymentObserver)\n\n self.paymentObserver = paymentObserver\n }\n\n func purchase(accountNumber: String, product: SKProduct) {\n let payment = SKPayment(product: product)\n storePaymentManager.addPayment(payment, for: accountNumber)\n viewControllerDelegate?.didBeginPayment()\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\CreationAccount\InAppPurchaseInteractor.swift | InAppPurchaseInteractor.swift | Swift | 1,384 | 0.95 | 0.043478 | 0.189189 | vue-tools | 881 | 2023-10-12T07:03:41.111531 | BSD-3-Clause | false | d7cca5852856027010592daa05027246 |
//\n// SetupAccountCompletedContentView.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2023-06-30.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nprotocol SetupAccountCompletedContentViewDelegate: AnyObject {\n func didTapPrivacyButton(view: SetupAccountCompletedContentView, button: AppButton)\n func didTapStartingAppButton(view: SetupAccountCompletedContentView, button: AppButton)\n}\n\nclass SetupAccountCompletedContentView: UIView {\n private let titleLabel: UILabel = {\n let label = UILabel()\n label.font = .preferredFont(forTextStyle: .largeTitle, weight: .bold)\n label.textColor = .white\n label.adjustsFontForContentSizeCategory = true\n label.lineBreakMode = .byWordWrapping\n label.numberOfLines = .zero\n label.text = NSLocalizedString(\n "CREATED_ACCOUNT_CONFIRMATION_PAGE_TITLE",\n tableName: "CreatedAccountConfirmation",\n value: "You’re all set!!",\n comment: ""\n )\n return label\n }()\n\n private let commentLabel: UILabel = {\n let label = UILabel()\n\n let message = NSMutableAttributedString(string: NSLocalizedString(\n "CREATED_ACCOUNT_CONFIRMATION_PAGE_BODY",\n tableName: "CreatedAccountConfirmation",\n value: """\n Go ahead and start using the app to begin reclaiming your online privacy.\n To continue your journey as a privacy ninja, \\n visit our website to pick up other privacy-friendly habits and tools.\n """,\n comment: ""\n ))\n message.apply(paragraphStyle: .alert)\n\n label.attributedText = message\n label.font = .preferredFont(forTextStyle: .body)\n label.textColor = .white\n label.adjustsFontForContentSizeCategory = true\n label.numberOfLines = .zero\n\n return label\n }()\n\n private let privacyButton: AppButton = {\n let button = AppButton(style: .success)\n button.setAccessibilityIdentifier(.learnAboutPrivacyButton)\n let localizedString = NSLocalizedString(\n "LEARN_ABOUT_PRIVACY_BUTTON",\n tableName: "CreatedAccountConfirmation",\n value: "Learn about privacy",\n comment: ""\n )\n button.setTitle(localizedString, for: .normal)\n button.setImage(UIImage(named: "IconExtlink")?.imageFlippedForRightToLeftLayoutDirection(), for: .normal)\n return button\n }()\n\n private let startButton: AppButton = {\n let button = AppButton(style: .success)\n button.setAccessibilityIdentifier(.startUsingTheAppButton)\n button.setTitle(NSLocalizedString(\n "START_USING_THE_APP_BUTTON",\n tableName: "CreatedAccountConfirmation",\n value: "Start using the app",\n comment: ""\n ), for: .normal)\n return button\n }()\n\n private let textsStackView: UIStackView = {\n let stackView = UIStackView()\n stackView.axis = .vertical\n return stackView\n }()\n\n private let buttonsStackView: UIStackView = {\n let stackView = UIStackView()\n stackView.axis = .vertical\n stackView.spacing = UIMetrics.interButtonSpacing\n return stackView\n }()\n\n weak var delegate: SetupAccountCompletedContentViewDelegate?\n\n override init(frame: CGRect) {\n super.init(frame: frame)\n\n backgroundColor = .primaryColor\n directionalLayoutMargins = UIMetrics.contentLayoutMargins\n backgroundColor = .secondaryColor\n\n configureUI()\n addActions()\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n private func configureUI() {\n textsStackView.addArrangedSubview(titleLabel)\n textsStackView.setCustomSpacing(UIMetrics.padding8, after: titleLabel)\n textsStackView.addArrangedSubview(commentLabel)\n textsStackView.setCustomSpacing(UIMetrics.padding16, after: commentLabel)\n\n buttonsStackView.addArrangedSubview(privacyButton)\n buttonsStackView.addArrangedSubview(startButton)\n\n addSubview(textsStackView)\n addSubview(buttonsStackView)\n addConstraints()\n }\n\n private func addConstraints() {\n addConstrainedSubviews([textsStackView, buttonsStackView]) {\n textsStackView\n .pinEdgesToSuperviewMargins(.all().excluding(.bottom))\n\n buttonsStackView\n .pinEdgesToSuperviewMargins(.all().excluding(.top))\n }\n }\n\n private func addActions() {\n [privacyButton, startButton].forEach {\n $0.addTarget(self, action: #selector(tapped(button:)), for: .touchUpInside)\n }\n }\n\n @objc private func tapped(button: AppButton) {\n switch button.accessibilityIdentifier {\n case AccessibilityIdentifier.learnAboutPrivacyButton.asString:\n delegate?.didTapPrivacyButton(view: self, button: button)\n case AccessibilityIdentifier.startUsingTheAppButton.asString:\n delegate?.didTapStartingAppButton(view: self, button: button)\n default: return\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\CreationAccount\Completed\SetupAccountCompletedContentView.swift | SetupAccountCompletedContentView.swift | Swift | 5,159 | 0.95 | 0.039474 | 0.054264 | vue-tools | 201 | 2024-01-21T14:45:39.728102 | Apache-2.0 | false | fafba714a44016714bcff23125edc9a0 |
//\n// SetupAccountCompletedController.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2023-06-30.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nprotocol SetupAccountCompletedControllerDelegate: AnyObject, Sendable {\n func didRequestToSeePrivacy(controller: SetupAccountCompletedController)\n func didRequestToStartTheApp(controller: SetupAccountCompletedController)\n}\n\nclass SetupAccountCompletedController: UIViewController, RootContainment {\n private lazy var contentView: SetupAccountCompletedContentView = {\n let view = SetupAccountCompletedContentView()\n view.delegate = self\n return view\n }()\n\n var preferredHeaderBarPresentation: HeaderBarPresentation {\n HeaderBarPresentation(style: .default, showsDivider: true)\n }\n\n var prefersHeaderBarHidden: Bool {\n false\n }\n\n var prefersDeviceInfoBarHidden: Bool {\n true\n }\n\n weak var delegate: SetupAccountCompletedControllerDelegate?\n\n override func viewDidLoad() {\n super.viewDidLoad()\n configureUI()\n }\n\n private func configureUI() {\n view.addSubview(contentView)\n view.addConstrainedSubviews([contentView]) {\n contentView.pinEdgesToSuperview()\n }\n }\n}\n\nextension SetupAccountCompletedController: @preconcurrency SetupAccountCompletedContentViewDelegate {\n func didTapPrivacyButton(view: SetupAccountCompletedContentView, button: AppButton) {\n delegate?.didRequestToSeePrivacy(controller: self)\n }\n\n func didTapStartingAppButton(view: SetupAccountCompletedContentView, button: AppButton) {\n delegate?.didRequestToStartTheApp(controller: self)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\CreationAccount\Completed\SetupAccountCompletedController.swift | SetupAccountCompletedController.swift | Swift | 1,690 | 0.95 | 0.017241 | 0.148936 | node-utils | 365 | 2024-06-25T23:15:05.965539 | BSD-3-Clause | false | fa08b76a169313db7a8843598709c6b7 |
//\n// WelcomeContentView.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2023-06-27.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nprotocol WelcomeContentViewDelegate: AnyObject, Sendable {\n func didTapPurchaseButton(welcomeContentView: WelcomeContentView, button: AppButton)\n func didTapInfoButton(welcomeContentView: WelcomeContentView, button: UIButton)\n func didTapCopyButton(welcomeContentView: WelcomeContentView, button: UIButton)\n}\n\nstruct WelcomeViewModel: Sendable {\n let deviceName: String\n let accountNumber: String\n}\n\nfinal class WelcomeContentView: UIView, Sendable {\n private var revertCopyImageWorkItem: DispatchWorkItem?\n\n private let titleLabel: UILabel = {\n let label = UILabel()\n label.font = .preferredFont(forTextStyle: .largeTitle, weight: .bold)\n label.textColor = .white\n label.adjustsFontForContentSizeCategory = true\n label.lineBreakMode = .byWordWrapping\n label.numberOfLines = .zero\n label.text = NSLocalizedString(\n "WELCOME_PAGE_TITLE",\n tableName: "Welcome",\n value: "Congrats!",\n comment: ""\n )\n return label\n }()\n\n private let subtitleLabel: UILabel = {\n let label = UILabel()\n label.font = .preferredFont(forTextStyle: .body)\n label.textColor = .white\n label.adjustsFontForContentSizeCategory = true\n label.lineBreakMode = .byWordWrapping\n label.numberOfLines = .zero\n label.text = NSLocalizedString(\n "WELCOME_PAGE_SUBTITLE",\n tableName: "Welcome",\n value: "Here’s your account number. Save it!",\n comment: ""\n )\n return label\n }()\n\n private let accountNumberLabel: UILabel = {\n let label = UILabel()\n label.setAccessibilityIdentifier(.welcomeAccountNumberLabel)\n label.adjustsFontForContentSizeCategory = true\n label.lineBreakMode = .byWordWrapping\n label.numberOfLines = .zero\n label.font = .preferredFont(forTextStyle: .title2, weight: .bold)\n label.textColor = .white\n return label\n }()\n\n private let copyButton: UIButton = {\n let button = UIButton(type: .system)\n button.setAccessibilityIdentifier(.copyButton)\n button.tintColor = .white\n button.setContentHuggingPriority(.defaultHigh, for: .horizontal)\n return button\n }()\n\n private let deviceNameLabel: UILabel = {\n let label = UILabel()\n label.adjustsFontForContentSizeCategory = true\n label.translatesAutoresizingMaskIntoConstraints = false\n label.font = .preferredFont(forTextStyle: .body)\n label.textColor = .white\n label.setContentHuggingPriority(.defaultLow, for: .horizontal)\n label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)\n return label\n }()\n\n private let infoButton: UIButton = {\n let button = IncreasedHitButton(type: .system)\n button.setAccessibilityIdentifier(.infoButton)\n button.tintColor = .white\n button.translatesAutoresizingMaskIntoConstraints = false\n button.setImage(UIImage.Buttons.info, for: .normal)\n button.setContentHuggingPriority(.defaultHigh, for: .horizontal)\n button.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)\n return button\n }()\n\n private let descriptionLabel: UILabel = {\n let label = UILabel()\n label.font = .preferredFont(forTextStyle: .body)\n label.adjustsFontForContentSizeCategory = true\n label.textColor = .white\n label.numberOfLines = .zero\n label.lineBreakMode = .byWordWrapping\n label.lineBreakStrategy = []\n label.text = NSLocalizedString(\n "WELCOME_PAGE_DESCRIPTION",\n tableName: "Welcome",\n value: """\n To start using the app, you first need to \\n add time to your account. Either buy credit \\n on our website or redeem a voucher.\n """,\n comment: ""\n )\n return label\n }()\n\n private let purchaseButton: InAppPurchaseButton = {\n let button = InAppPurchaseButton()\n button.setAccessibilityIdentifier(.purchaseButton)\n let localizedString = NSLocalizedString(\n "ADD_TIME_BUTTON",\n tableName: "Welcome",\n value: "Add time",\n comment: ""\n )\n button.setTitle(localizedString, for: .normal)\n return button\n }()\n\n private let textsStackView: UIStackView = {\n let stackView = UIStackView()\n stackView.axis = .vertical\n return stackView\n }()\n\n private let accountRowStackView: UIStackView = {\n let stackView = UIStackView()\n stackView.axis = .horizontal\n stackView.distribution = .fill\n stackView.spacing = UIMetrics.padding8\n return stackView\n }()\n\n private let deviceRowStackView: UIStackView = {\n let stackView = UIStackView()\n stackView.axis = .horizontal\n stackView.distribution = .fill\n return stackView\n }()\n\n private let spacerView: UIView = {\n let view = UIView()\n view.setContentHuggingPriority(.required, for: .horizontal)\n view.setContentCompressionResistancePriority(.required, for: .horizontal)\n return view\n }()\n\n private let buttonsStackView: UIStackView = {\n let stackView = UIStackView()\n stackView.axis = .vertical\n stackView.spacing = UIMetrics.interButtonSpacing\n return stackView\n }()\n\n weak var delegate: WelcomeContentViewDelegate?\n var viewModel: WelcomeViewModel? {\n didSet {\n accountNumberLabel.text = viewModel?.accountNumber\n deviceNameLabel.text = String(format: NSLocalizedString(\n "DEVICE_NAME_TEXT",\n tableName: "Welcome",\n value: "Device name: %@",\n comment: ""\n ), viewModel?.deviceName ?? "")\n }\n }\n\n override init(frame: CGRect) {\n super.init(frame: frame)\n\n setAccessibilityIdentifier(.welcomeView)\n backgroundColor = .primaryColor\n directionalLayoutMargins = UIMetrics.contentLayoutMargins\n backgroundColor = .secondaryColor\n\n configureUI()\n addActions()\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n private func configureUI() {\n accountRowStackView.addArrangedSubview(accountNumberLabel)\n accountRowStackView.addArrangedSubview(copyButton)\n accountRowStackView.addArrangedSubview(UIView()) // To push content to the left.\n\n textsStackView.addArrangedSubview(titleLabel)\n textsStackView.setCustomSpacing(UIMetrics.padding8, after: titleLabel)\n textsStackView.addArrangedSubview(subtitleLabel)\n textsStackView.setCustomSpacing(UIMetrics.padding16, after: subtitleLabel)\n textsStackView.addArrangedSubview(accountRowStackView)\n textsStackView.setCustomSpacing(UIMetrics.padding16, after: accountRowStackView)\n\n deviceRowStackView.addArrangedSubview(deviceNameLabel)\n deviceRowStackView.setCustomSpacing(UIMetrics.padding8, after: deviceNameLabel)\n deviceRowStackView.addArrangedSubview(infoButton)\n deviceRowStackView.addArrangedSubview(spacerView)\n\n textsStackView.addArrangedSubview(deviceRowStackView)\n textsStackView.setCustomSpacing(UIMetrics.padding16, after: deviceRowStackView)\n textsStackView.addArrangedSubview(descriptionLabel)\n\n buttonsStackView.addArrangedSubview(purchaseButton)\n\n addSubview(textsStackView)\n addSubview(buttonsStackView)\n addConstraints()\n\n showCheckmark(false)\n }\n\n private func addConstraints() {\n addConstrainedSubviews([textsStackView, buttonsStackView]) {\n textsStackView\n .pinEdgesToSuperviewMargins(.all().excluding(.bottom))\n\n buttonsStackView\n .pinEdgesToSuperviewMargins(.all().excluding(.top))\n }\n }\n\n private func addActions() {\n [purchaseButton, infoButton, copyButton].forEach {\n $0.addTarget(self, action: #selector(tapped(button:)), for: .touchUpInside)\n }\n }\n\n @objc private func tapped(button: AppButton) {\n switch button.accessibilityIdentifier {\n case AccessibilityIdentifier.purchaseButton.asString:\n delegate?.didTapPurchaseButton(welcomeContentView: self, button: button)\n case AccessibilityIdentifier.infoButton.asString:\n delegate?.didTapInfoButton(welcomeContentView: self, button: button)\n case AccessibilityIdentifier.copyButton.asString:\n didTapCopyAccountNumber()\n default: return\n }\n }\n\n private func showCheckmark(_ showCheckmark: Bool) {\n if showCheckmark {\n let tickIcon = UIImage(named: "IconTick")\n\n copyButton.setImage(tickIcon, for: .normal)\n copyButton.tintColor = .successColor\n } else {\n let copyIcon = UIImage(named: "IconCopy")\n\n copyButton.setImage(copyIcon, for: .normal)\n copyButton.tintColor = .white\n }\n }\n\n @objc private func didTapCopyAccountNumber() {\n let delayedWorkItem = DispatchWorkItem { [weak self] in\n self?.showCheckmark(false)\n }\n\n revertCopyImageWorkItem?.cancel()\n revertCopyImageWorkItem = delayedWorkItem\n\n showCheckmark(true)\n delegate?.didTapCopyButton(welcomeContentView: self, button: copyButton)\n\n DispatchQueue.main.asyncAfter(\n deadline: .now() + .seconds(2),\n execute: delayedWorkItem\n )\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\CreationAccount\Welcome\WelcomeContentView.swift | WelcomeContentView.swift | Swift | 9,811 | 0.95 | 0.052817 | 0.028689 | python-kit | 792 | 2024-08-12T14:16:11.265711 | Apache-2.0 | false | 4a3079976627fee19f81272c29c9d8e8 |
//\n// WelcomeInteractor.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2023-06-29.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadLogging\nimport MullvadTypes\nimport StoreKit\n\nfinal class WelcomeInteractor: @unchecked Sendable {\n private let tunnelManager: TunnelManager\n\n /// Interval used for periodic polling account updates.\n private let accountUpdateTimerInterval: Duration = .minutes(1)\n private var accountUpdateTimer: DispatchSourceTimer?\n\n private let logger = Logger(label: "\(WelcomeInteractor.self)")\n private var tunnelObserver: TunnelObserver?\n private(set) var products: [SKProduct]?\n\n var didAddMoreCredit: (() -> Void)?\n\n var viewWillAppear = false {\n didSet {\n guard viewWillAppear else { return }\n startAccountUpdateTimer()\n }\n }\n\n var viewDidDisappear = false {\n didSet {\n guard viewDidDisappear else { return }\n stopAccountUpdateTimer()\n }\n }\n\n var accountNumber: String {\n tunnelManager.deviceState.accountData?.number ?? ""\n }\n\n var viewModel: WelcomeViewModel {\n WelcomeViewModel(\n deviceName: tunnelManager.deviceState.deviceData?.capitalizedName ?? "",\n accountNumber: tunnelManager.deviceState.accountData?.number.formattedAccountNumber ?? ""\n )\n }\n\n init(\n tunnelManager: TunnelManager\n ) {\n self.tunnelManager = tunnelManager\n let tunnelObserver =\n TunnelBlockObserver(didUpdateDeviceState: { [weak self] _, deviceState, previousDeviceState in\n let isInactive = previousDeviceState.accountData?.isExpired == true\n let isActive = deviceState.accountData?.isExpired == false\n if isInactive && isActive {\n self?.didAddMoreCredit?()\n }\n })\n\n tunnelManager.addObserver(tunnelObserver)\n self.tunnelObserver = tunnelObserver\n }\n\n private func startAccountUpdateTimer() {\n logger.debug(\n "Start polling account updates every \(accountUpdateTimerInterval) second(s)."\n )\n\n let timer = DispatchSource.makeTimerSource(queue: .main)\n timer.setEventHandler { [weak self] in\n self?.tunnelManager.updateAccountData()\n }\n\n accountUpdateTimer?.cancel()\n accountUpdateTimer = timer\n\n timer.schedule(\n wallDeadline: .now() + accountUpdateTimerInterval,\n repeating: accountUpdateTimerInterval.timeInterval\n )\n timer.activate()\n }\n\n private func stopAccountUpdateTimer() {\n logger.debug(\n "Stop polling account updates."\n )\n\n accountUpdateTimer?.cancel()\n accountUpdateTimer = nil\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\CreationAccount\Welcome\WelcomeInteractor.swift | WelcomeInteractor.swift | Swift | 2,817 | 0.95 | 0.030928 | 0.1 | awesome-app | 36 | 2023-10-31T20:00:15.931634 | BSD-3-Clause | false | 89b3056db8318572dc9f89887be34677 |
//\n// WelcomeViewController.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2023-06-28.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport StoreKit\nimport UIKit\n\nprotocol WelcomeViewControllerDelegate: AnyObject {\n func didRequestToShowInfo(controller: WelcomeViewController)\n func didRequestToViewPurchaseOptions(\n accountNumber: String\n )\n}\n\nclass WelcomeViewController: UIViewController, RootContainment {\n private lazy var contentView: WelcomeContentView = {\n let view = WelcomeContentView()\n view.delegate = self\n return view\n }()\n\n private let interactor: WelcomeInteractor\n\n weak var delegate: WelcomeViewControllerDelegate?\n\n var preferredHeaderBarPresentation: HeaderBarPresentation {\n HeaderBarPresentation(style: .default, showsDivider: true)\n }\n\n var prefersHeaderBarHidden: Bool {\n false\n }\n\n var prefersDeviceInfoBarHidden: Bool {\n true\n }\n\n override var preferredStatusBarStyle: UIStatusBarStyle {\n .lightContent\n }\n\n init(interactor: WelcomeInteractor) {\n self.interactor = interactor\n super.init(nibName: nil, bundle: nil)\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n override func viewDidLoad() {\n super.viewDidLoad()\n configureUI()\n contentView.viewModel = interactor.viewModel\n }\n\n override func viewWillAppear(_ animated: Bool) {\n super.viewWillAppear(animated)\n interactor.viewWillAppear = true\n }\n\n override func viewDidDisappear(_ animated: Bool) {\n super.viewDidDisappear(animated)\n interactor.viewDidDisappear = true\n }\n\n private func configureUI() {\n view.addConstrainedSubviews([contentView]) {\n contentView.pinEdgesToSuperview()\n }\n }\n}\n\nextension WelcomeViewController: @preconcurrency WelcomeContentViewDelegate {\n func didTapInfoButton(welcomeContentView: WelcomeContentView, button: UIButton) {\n delegate?.didRequestToShowInfo(controller: self)\n }\n\n func didTapPurchaseButton(welcomeContentView: WelcomeContentView, button: AppButton) {\n delegate?.didRequestToViewPurchaseOptions(accountNumber: interactor.accountNumber)\n }\n\n func didTapCopyButton(welcomeContentView: WelcomeContentView, button: UIButton) {\n UIPasteboard.general.string = interactor.accountNumber\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\CreationAccount\Welcome\WelcomeViewController.swift | WelcomeViewController.swift | Swift | 2,445 | 0.95 | 0.011111 | 0.097222 | node-utils | 432 | 2025-03-04T16:50:05.848697 | GPL-3.0 | false | f3e93efa3500eb8629da32ad96c9de1d |
//\n// DeviceManagementContentView.swift\n// MullvadVPN\n//\n// Created by pronebird on 19/07/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass DeviceManagementContentView: UIView {\n private let scrollView: UIScrollView = {\n let scrollView = UIScrollView()\n scrollView.translatesAutoresizingMaskIntoConstraints = false\n return scrollView\n }()\n\n let scrollContentView: UIView = {\n let view = UIView()\n view.directionalLayoutMargins = UIMetrics.contentLayoutMargins\n view.translatesAutoresizingMaskIntoConstraints = false\n return view\n }()\n\n let statusImageView: StatusImageView = {\n let imageView = StatusImageView(style: .failure)\n imageView.translatesAutoresizingMaskIntoConstraints = false\n return imageView\n }()\n\n let titleLabel: UILabel = {\n let textLabel = UILabel()\n textLabel.font = UIFont.systemFont(ofSize: 32)\n textLabel.textColor = .white\n textLabel.translatesAutoresizingMaskIntoConstraints = false\n return textLabel\n }()\n\n let messageLabel: UILabel = {\n let textLabel = UILabel()\n textLabel.font = UIFont.systemFont(ofSize: 17)\n textLabel.textColor = .white\n textLabel.translatesAutoresizingMaskIntoConstraints = false\n textLabel.numberOfLines = 0\n textLabel.lineBreakStrategy = []\n return textLabel\n }()\n\n let deviceStackView: UIStackView = {\n let stackView = UIStackView(arrangedSubviews: [])\n stackView.translatesAutoresizingMaskIntoConstraints = false\n stackView.axis = .vertical\n stackView.spacing = 1\n stackView.clipsToBounds = true\n stackView.distribution = .fillEqually\n return stackView\n }()\n\n let continueButton: AppButton = {\n let button = AppButton(style: .success)\n button.translatesAutoresizingMaskIntoConstraints = false\n button.setTitle(\n NSLocalizedString(\n "CONTINUE_BUTTON",\n tableName: "DeviceManagement",\n value: "Continue with login",\n comment: ""\n ),\n for: .normal\n )\n button.isEnabled = false\n button.setAccessibilityIdentifier(.continueWithLoginButton)\n return button\n }()\n\n let backButton: AppButton = {\n let button = AppButton(style: .default)\n button.translatesAutoresizingMaskIntoConstraints = false\n button.setTitle(\n NSLocalizedString(\n "BACK_BUTTON",\n tableName: "DeviceManagement",\n value: "Back",\n comment: ""\n ),\n for: .normal\n )\n return button\n }()\n\n private lazy var buttonStackView: UIStackView = {\n let stackView = UIStackView(arrangedSubviews: [continueButton, backButton])\n stackView.translatesAutoresizingMaskIntoConstraints = false\n stackView.axis = .vertical\n stackView.distribution = .fillEqually\n stackView.spacing = UIMetrics.interButtonSpacing\n return stackView\n }()\n\n var handleDeviceDeletion: (@Sendable (DeviceViewModel, @escaping @Sendable () -> Void) -> Void)?\n\n private var currentDeviceModels = [DeviceViewModel]()\n\n var canContinue = false {\n didSet {\n updateView()\n }\n }\n\n override init(frame: CGRect) {\n super.init(frame: frame)\n\n addViews()\n constraintViews()\n updateView()\n\n setAccessibilityIdentifier(.deviceManagementView)\n }\n\n private func addViews() {\n try? [scrollView, buttonStackView].forEach(addSubview)\n\n scrollView.addSubview(scrollContentView)\n\n try? [statusImageView, titleLabel, messageLabel, deviceStackView]\n .forEach(scrollContentView.addSubview)\n }\n\n private func constraintViews() {\n NSLayoutConstraint.activate([\n scrollView.topAnchor.constraint(equalTo: topAnchor),\n scrollView.leadingAnchor.constraint(equalTo: leadingAnchor),\n scrollView.trailingAnchor.constraint(equalTo: trailingAnchor),\n\n buttonStackView.topAnchor.constraint(\n equalTo: scrollView.bottomAnchor,\n constant: UIMetrics.contentLayoutMargins.top\n ),\n buttonStackView.leadingAnchor.constraint(\n equalTo: leadingAnchor,\n constant: UIMetrics.contentLayoutMargins.leading\n ),\n buttonStackView.trailingAnchor.constraint(\n equalTo: trailingAnchor,\n constant: -UIMetrics.contentLayoutMargins.trailing\n ),\n buttonStackView.bottomAnchor.constraint(\n equalTo: safeAreaLayoutGuide.bottomAnchor,\n constant: -UIMetrics.contentLayoutMargins.bottom\n ),\n\n scrollContentView.topAnchor.constraint(equalTo: scrollView.topAnchor),\n scrollContentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),\n scrollContentView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),\n scrollContentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),\n scrollContentView.widthAnchor.constraint(equalTo: scrollView.widthAnchor),\n\n statusImageView.topAnchor\n .constraint(equalTo: scrollContentView.layoutMarginsGuide.topAnchor),\n statusImageView.centerXAnchor.constraint(equalTo: scrollContentView.centerXAnchor),\n\n titleLabel.topAnchor.constraint(equalTo: statusImageView.bottomAnchor, constant: 22),\n titleLabel.leadingAnchor\n .constraint(equalTo: scrollContentView.layoutMarginsGuide.leadingAnchor),\n titleLabel.trailingAnchor\n .constraint(equalTo: scrollContentView.layoutMarginsGuide.trailingAnchor),\n\n messageLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 8),\n messageLabel.leadingAnchor\n .constraint(equalTo: scrollContentView.layoutMarginsGuide.leadingAnchor),\n messageLabel.trailingAnchor\n .constraint(equalTo: scrollContentView.layoutMarginsGuide.trailingAnchor),\n\n deviceStackView.topAnchor.constraint(\n equalTo: messageLabel.bottomAnchor,\n constant: UIMetrics.TableView.sectionSpacing\n ),\n deviceStackView.leadingAnchor.constraint(equalTo: scrollContentView.leadingAnchor),\n deviceStackView.trailingAnchor.constraint(equalTo: scrollContentView.trailingAnchor),\n deviceStackView.bottomAnchor.constraint(equalTo: scrollContentView.bottomAnchor),\n ])\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n func setDeviceViewModels(_ newModels: [DeviceViewModel], animated: Bool) {\n let difference = newModels.difference(from: currentDeviceModels) { newModel, model in\n newModel.id == model.id\n }\n\n currentDeviceModels = newModels\n\n var viewsToAdd: [(view: UIView, offset: Int)] = []\n var viewsToRemove: [UIView] = []\n\n difference.forEach { change in\n switch change {\n case let .insert(offset, model, _):\n viewsToAdd.append((createDeviceRowView(from: model), offset))\n case let .remove(offset, _, _):\n viewsToRemove.append(deviceStackView.arrangedSubviews[offset])\n }\n }\n\n viewsToAdd.forEach { item in\n deviceStackView.insertArrangedSubview(item.view, at: item.offset)\n }\n\n // Layout inserted subviews before running animations to achieve a folding effect.\n if animated {\n UIView.performWithoutAnimation {\n deviceStackView.layoutIfNeeded()\n }\n }\n\n if animated {\n UIView.animate(\n withDuration: 0.25,\n delay: 0,\n options: [.curveEaseInOut],\n animations: { [weak self] in\n self?.showHideViews(viewsToAdd: viewsToAdd, viewsToRemove: viewsToRemove)\n self?.deviceStackView.layoutIfNeeded()\n },\n completion: { [weak self] _ in\n self?.removeViews(viewsToRemove: viewsToRemove)\n }\n )\n } else {\n showHideViews(viewsToAdd: viewsToAdd, viewsToRemove: viewsToRemove)\n removeViews(viewsToRemove: viewsToRemove)\n }\n }\n\n private func showHideViews(viewsToAdd: [(view: UIView, offset: Int)], viewsToRemove: [UIView]) {\n viewsToRemove.forEach { view in\n view.alpha = 0\n view.isHidden = true\n }\n\n viewsToAdd.forEach { item in\n item.view.alpha = 1\n item.view.isHidden = false\n }\n }\n\n private func removeViews(viewsToRemove: [UIView]) {\n viewsToRemove.forEach { view in\n view.removeFromSuperview()\n }\n }\n\n private func createDeviceRowView(from model: DeviceViewModel) -> DeviceRowView {\n let view = DeviceRowView(viewModel: model)\n\n view.isHidden = true\n view.alpha = 0\n\n view.deleteHandler = { [weak self] _ in\n view.showsActivityIndicator = true\n\n self?.handleDeviceDeletion?(view.viewModel) {\n Task { @MainActor in\n view.showsActivityIndicator = false\n }\n }\n }\n\n return view\n }\n\n private func updateView() {\n titleLabel.text = titleText\n messageLabel.text = messageText\n continueButton.isEnabled = canContinue\n statusImageView.style = canContinue ? .success : .failure\n }\n\n private var titleText: String {\n if canContinue {\n return NSLocalizedString(\n "CONTINUE_LOGIN_TITLE",\n tableName: "DeviceManagement",\n value: "Super!",\n comment: ""\n )\n } else {\n return NSLocalizedString(\n "LOGOUT_DEVICES_TITLE",\n tableName: "DeviceManagement",\n value: "Too many devices",\n comment: ""\n )\n }\n }\n\n private var messageText: String {\n if canContinue {\n return NSLocalizedString(\n "CONTINUE_LOGIN_MESSAGE",\n tableName: "DeviceManagement",\n value: "You can now continue logging in on this device.",\n comment: ""\n )\n } else {\n return NSLocalizedString(\n "LOGOUT_DEVICES_MESSAGE",\n tableName: "DeviceManagement",\n value: """\n Please log out of at least one by removing it from the list below. You can find \\n the corresponding device name under the device’s Account settings.\n """,\n comment: ""\n )\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\DeviceList\DeviceManagementContentView.swift | DeviceManagementContentView.swift | Swift | 11,055 | 0.95 | 0.031348 | 0.029197 | vue-tools | 897 | 2024-10-08T22:58:12.858498 | GPL-3.0 | false | 31260464bccd95f8b0f224d07944435e |
//\n// DeviceManagementInteractor.swift\n// MullvadVPN\n//\n// Created by pronebird on 26/07/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\nimport MullvadTypes\nimport Operations\n\nclass DeviceManagementInteractor: @unchecked Sendable {\n private let devicesProxy: DeviceHandling\n private let accountNumber: String\n\n init(accountNumber: String, devicesProxy: DeviceHandling) {\n self.accountNumber = accountNumber\n self.devicesProxy = devicesProxy\n }\n\n @discardableResult\n func getDevices(_ completionHandler: @escaping @Sendable (Result<[Device], Error>) -> Void) -> Cancellable {\n devicesProxy.getDevices(\n accountNumber: accountNumber,\n retryStrategy: .default,\n completion: completionHandler\n )\n }\n\n @discardableResult\n func deleteDevice(\n _ identifier: String,\n completionHandler: @escaping @Sendable (Result<Bool, Error>) -> Void\n ) -> Cancellable {\n devicesProxy.deleteDevice(\n accountNumber: accountNumber,\n identifier: identifier,\n retryStrategy: .default,\n completion: completionHandler\n )\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\DeviceList\DeviceManagementInteractor.swift | DeviceManagementInteractor.swift | Swift | 1,225 | 0.95 | 0.022727 | 0.179487 | python-kit | 915 | 2023-12-11T18:36:31.267120 | BSD-3-Clause | false | 9fe2e2b22aba327ce98d585bae537bb5 |
//\n// DeviceManagementViewController.swift\n// MullvadVPN\n//\n// Created by pronebird on 15/07/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\n@preconcurrency import MullvadLogging\nimport MullvadREST\nimport MullvadTypes\nimport Operations\nimport UIKit\n\nprotocol DeviceManagementViewControllerDelegate: AnyObject, Sendable {\n func deviceManagementViewControllerDidFinish(_ controller: DeviceManagementViewController)\n func deviceManagementViewControllerDidCancel(_ controller: DeviceManagementViewController)\n}\n\nclass DeviceManagementViewController: UIViewController, RootContainment {\n weak var delegate: DeviceManagementViewControllerDelegate?\n\n var preferredHeaderBarPresentation: HeaderBarPresentation {\n .default\n }\n\n var prefersHeaderBarHidden: Bool {\n false\n }\n\n override var preferredStatusBarStyle: UIStatusBarStyle {\n .lightContent\n }\n\n private let contentView: DeviceManagementContentView = {\n let contentView = DeviceManagementContentView()\n contentView.translatesAutoresizingMaskIntoConstraints = false\n return contentView\n }()\n\n nonisolated(unsafe) private let logger = Logger(label: "DeviceManagementViewController")\n let interactor: DeviceManagementInteractor\n private let alertPresenter: AlertPresenter\n\n init(interactor: DeviceManagementInteractor, alertPresenter: AlertPresenter) {\n self.interactor = interactor\n self.alertPresenter = alertPresenter\n\n super.init(nibName: nil, bundle: nil)\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n override func viewDidLoad() {\n super.viewDidLoad()\n\n view.backgroundColor = .secondaryColor\n\n view.addSubview(contentView)\n\n contentView.backButton.addTarget(\n self,\n action: #selector(didTapBackButton(_:)),\n for: .touchUpInside\n )\n\n contentView.continueButton.addTarget(\n self,\n action: #selector(didTapContinueButton(_:)),\n for: .touchUpInside\n )\n\n contentView.handleDeviceDeletion = { [weak self] viewModel, finish in\n Task { @MainActor in\n self?.handleDeviceDeletion(viewModel, completionHandler: finish)\n }\n }\n\n NSLayoutConstraint.activate([\n contentView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),\n contentView.leadingAnchor.constraint(equalTo: view.leadingAnchor),\n contentView.trailingAnchor.constraint(equalTo: view.trailingAnchor),\n contentView.bottomAnchor.constraint(equalTo: view.bottomAnchor),\n ])\n }\n\n func fetchDevices(\n animateUpdates: Bool,\n completionHandler: (@Sendable (Result<Void, Error>) -> Void)? = nil\n ) {\n interactor.getDevices { [weak self] result in\n guard let self = self else { return }\n\n if let devices = result.value {\n setDevices(devices, animated: animateUpdates)\n }\n\n completionHandler?(result.map { _ in () })\n }\n }\n\n // MARK: - Private\n\n nonisolated private func setDevices(_ devices: [Device], animated: Bool) {\n let viewModels = devices.map { restDevice -> DeviceViewModel in\n DeviceViewModel(\n id: restDevice.id,\n name: restDevice.name.capitalized,\n creationDate: DateFormatter.localizedString(\n from: restDevice.created,\n dateStyle: .short,\n timeStyle: .none\n )\n )\n }\n\n Task { @MainActor in\n contentView.canContinue = viewModels.count < ApplicationConfiguration.maxAllowedDevices\n contentView.setDeviceViewModels(viewModels, animated: animated)\n }\n }\n\n private func handleDeviceDeletion(\n _ device: DeviceViewModel,\n completionHandler: @escaping @Sendable () -> Void\n ) {\n showLogoutConfirmation(deviceName: device.name) { [weak self] shouldDelete in\n guard let self else { return }\n\n guard shouldDelete else {\n completionHandler()\n return\n }\n\n deleteDevice(identifier: device.id) { [weak self] error in\n guard let self = self else { return }\n\n if let error {\n Task { @MainActor in\n self.showErrorAlert(\n title: NSLocalizedString(\n "LOGOUT_DEVICE_ERROR_ALERT_TITLE",\n tableName: "DeviceManagement",\n value: "Failed to log out device",\n comment: ""\n ),\n error: error\n )\n }\n }\n\n completionHandler()\n }\n }\n }\n\n private func getErrorDescription(_ error: Error) -> String {\n if case let .network(urlError) = error as? REST.Error {\n return urlError.localizedDescription\n } else {\n return error.localizedDescription\n }\n }\n\n private func showErrorAlert(title: String, error: Error) {\n let presentation = AlertPresentation(\n id: "delete-device-error-alert",\n title: title,\n message: getErrorDescription(error),\n buttons: [\n AlertAction(\n title: NSLocalizedString(\n "ERROR_ALERT_OK_ACTION",\n tableName: "DeviceManagement",\n value: "Got it!",\n comment: ""\n ),\n style: .default\n ),\n ]\n )\n\n alertPresenter.showAlert(presentation: presentation, animated: true)\n }\n\n private func showLogoutConfirmation(\n deviceName: String,\n completion: @escaping (_ shouldDelete: Bool) -> Void\n ) {\n let text = String(\n format: NSLocalizedString(\n "DELETE_ALERT_TITLE",\n tableName: "DeviceManagement",\n value: "Are you sure you want to log **\(deviceName)** out?",\n comment: ""\n )\n )\n\n let attributedText = NSAttributedString(\n markdownString: text,\n options: MarkdownStylingOptions(\n font: .preferredFont(forTextStyle: .body)\n )\n )\n\n let presentation = AlertPresentation(\n id: "logout-confirmation-alert",\n icon: .alert,\n attributedMessage: attributedText,\n buttons: [\n AlertAction(\n title: NSLocalizedString(\n "DELETE_ALERT_CONFIRM_ACTION",\n tableName: "DeviceManagement",\n value: "Yes, log out device",\n comment: ""\n ),\n style: .destructive,\n accessibilityId: .logOutDeviceConfirmButton,\n handler: {\n completion(true)\n }\n ),\n AlertAction(\n title: NSLocalizedString(\n "DELETE_ALERT_CANCEL_ACTION",\n tableName: "DeviceManagement",\n value: "Back",\n comment: ""\n ),\n style: .default,\n accessibilityId: .logOutDeviceCancelButton,\n handler: {\n completion(false)\n }\n ),\n ]\n )\n\n alertPresenter.showAlert(presentation: presentation, animated: true)\n }\n\n private func deleteDevice(identifier: String, completionHandler: @escaping @Sendable (Error?) -> Void) {\n interactor.deleteDevice(identifier) { [weak self] completion in\n guard let self = self else { return }\n\n switch completion {\n case .success:\n Task { @MainActor in\n fetchDevices(animateUpdates: true) { completion in\n completionHandler(completion.error)\n }\n }\n\n case let .failure(error):\n if error.isOperationCancellationError {\n completionHandler(nil)\n } else {\n logger.error(\n error: error,\n message: "Failed to delete device."\n )\n completionHandler(error)\n }\n }\n }\n }\n\n // MARK: - Actions\n\n @objc private func didTapBackButton(_ sender: Any?) {\n delegate?.deviceManagementViewControllerDidCancel(self)\n }\n\n @objc private func didTapContinueButton(_ sender: Any?) {\n delegate?.deviceManagementViewControllerDidFinish(self)\n }\n}\n\nstruct DeviceViewModel: Sendable {\n let id: String\n let name: String\n let creationDate: String\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\DeviceList\DeviceManagementViewController.swift | DeviceManagementViewController.swift | Swift | 9,216 | 0.95 | 0.027972 | 0.037037 | vue-tools | 86 | 2025-03-19T08:42:07.345175 | BSD-3-Clause | false | 92d8da2b47df38d3d54c328d6d12ce5a |
//\n// DeviceRowView.swift\n// MullvadVPN\n//\n// Created by pronebird on 26/07/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass DeviceRowView: UIView {\n let viewModel: DeviceViewModel\n var deleteHandler: ((DeviceRowView) -> Void)?\n\n let textLabel: UILabel = {\n let textLabel = UILabel()\n textLabel.translatesAutoresizingMaskIntoConstraints = false\n textLabel.font = UIFont.systemFont(ofSize: 17)\n textLabel.textColor = .white\n return textLabel\n }()\n\n let activityIndicator: SpinnerActivityIndicatorView = {\n let activityIndicator = SpinnerActivityIndicatorView(style: .custom)\n activityIndicator.translatesAutoresizingMaskIntoConstraints = false\n return activityIndicator\n }()\n\n let creationDateLabel: UILabel = {\n let creationDateLabel = UILabel()\n creationDateLabel.translatesAutoresizingMaskIntoConstraints = false\n creationDateLabel.font = UIFont.systemFont(ofSize: 14)\n creationDateLabel.textColor = .white.withAlphaComponent(0.6)\n return creationDateLabel\n }()\n\n let removeButton: UIButton = {\n let image = UIImage.Buttons.close\n .withTintColor(\n .white.withAlphaComponent(0.4),\n renderingMode: .alwaysOriginal\n )\n\n let button = IncreasedHitButton(type: .custom)\n button.translatesAutoresizingMaskIntoConstraints = false\n button.setImage(image, for: .normal)\n button.accessibilityLabel = NSLocalizedString(\n "REMOVE_DEVICE_ACCESSIBILITY_LABEL",\n tableName: "DeviceManagement",\n value: "Remove device",\n comment: ""\n )\n return button\n }()\n\n var showsActivityIndicator = false {\n didSet {\n removeButton.isHidden = showsActivityIndicator\n\n if showsActivityIndicator {\n activityIndicator.startAnimating()\n } else {\n activityIndicator.stopAnimating()\n }\n }\n }\n\n init(viewModel: DeviceViewModel) {\n self.viewModel = viewModel\n\n super.init(frame: .zero)\n\n setAccessibilityIdentifier(.deviceCell)\n backgroundColor = .primaryColor\n directionalLayoutMargins = UIMetrics.TableView.rowViewLayoutMargins\n\n for subview in [textLabel, removeButton, activityIndicator, creationDateLabel] {\n addSubview(subview)\n }\n\n textLabel.text = viewModel.name\n creationDateLabel.text = .init(\n format:\n NSLocalizedString(\n "CREATED_DEVICE_LABEL",\n tableName: "DeviceManagement",\n value: "Created: %@",\n comment: ""\n ),\n viewModel.creationDate\n )\n\n removeButton.addTarget(self, action: #selector(handleButtonTap(_:)), for: .touchUpInside)\n removeButton.setAccessibilityIdentifier(.deviceCellRemoveButton)\n\n NSLayoutConstraint.activate([\n textLabel.topAnchor.constraint(equalTo: layoutMarginsGuide.topAnchor),\n textLabel.leadingAnchor.constraint(equalTo: layoutMarginsGuide.leadingAnchor),\n\n creationDateLabel.leadingAnchor.constraint(equalTo: textLabel.leadingAnchor),\n creationDateLabel.topAnchor.constraint(equalTo: textLabel.bottomAnchor, constant: 4.0),\n creationDateLabel.bottomAnchor.constraint(equalTo: layoutMarginsGuide.bottomAnchor)\n .withPriority(.defaultLow),\n creationDateLabel.trailingAnchor.constraint(equalTo: textLabel.trailingAnchor),\n\n removeButton.centerYAnchor.constraint(equalTo: layoutMarginsGuide.centerYAnchor),\n removeButton.leadingAnchor.constraint(\n greaterThanOrEqualTo: textLabel.trailingAnchor,\n constant: 8\n ),\n removeButton.trailingAnchor.constraint(equalTo: layoutMarginsGuide.trailingAnchor),\n\n activityIndicator.centerXAnchor.constraint(equalTo: removeButton.centerXAnchor),\n activityIndicator.centerYAnchor.constraint(equalTo: removeButton.centerYAnchor),\n\n // Bump dimensions by 6pt to account for transparent pixels around spinner image.\n activityIndicator.widthAnchor.constraint(\n equalTo: removeButton.widthAnchor,\n constant: 6\n ),\n activityIndicator.heightAnchor.constraint(\n equalTo: removeButton.heightAnchor,\n constant: 6\n ),\n ])\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n @objc private func handleButtonTap(_ sender: Any?) {\n deleteHandler?(self)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\DeviceList\DeviceRowView.swift | DeviceRowView.swift | Swift | 4,765 | 0.95 | 0.044444 | 0.070796 | python-kit | 342 | 2024-08-27T02:42:10.929197 | MIT | false | e321c9e7468e2b32559e99963f90f7ba |
//\n// SheetViewController.swift\n// MullvadVPN\n//\n// Created by Steffen Ernst on 2025-01-29.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport StoreKit\nimport UIKit\n\nclass InAppPurchaseViewController: UIViewController, StorePaymentObserver {\n private let storePaymentManager: StorePaymentManager\n private let accountNumber: String\n private let paymentAction: PaymentAction\n private let errorPresenter: PaymentAlertPresenter\n\n private let spinnerView = {\n SpinnerActivityIndicatorView(style: .large)\n }()\n\n var didFinish: (() -> Void)?\n\n init(\n storePaymentManager: StorePaymentManager,\n accountNumber: String,\n errorPresenter: PaymentAlertPresenter,\n paymentAction: PaymentAction\n ) {\n self.storePaymentManager = storePaymentManager\n self.accountNumber = accountNumber\n self.errorPresenter = errorPresenter\n self.paymentAction = paymentAction\n super.init(nibName: nil, bundle: nil)\n self.storePaymentManager.addPaymentObserver(self)\n modalPresentationStyle = .overFullScreen\n modalTransitionStyle = .crossDissolve\n view.addConstrainedSubviews([spinnerView]) {\n spinnerView.centerXAnchor.constraint(equalTo: view.centerXAnchor)\n spinnerView.centerYAnchor.constraint(equalTo: view.centerYAnchor)\n }\n view.backgroundColor = .black.withAlphaComponent(0.5)\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n override func viewDidLoad() {\n spinnerView.startAnimating()\n let productIdentifiers = Set(StoreSubscription.allCases)\n switch paymentAction {\n case .purchase:\n _ = storePaymentManager.requestProducts(\n with: productIdentifiers\n ) { result in\n Task { @MainActor [weak self] in\n guard let self else { return }\n self.spinnerView.stopAnimating()\n switch result {\n case let .success(success):\n let products = success.products\n guard !products.isEmpty else {\n return\n }\n self.showPurchaseOptions(for: products)\n case let .failure(failure as StorePaymentManagerError):\n self.errorPresenter.showAlertForError(failure, context: .purchase) {\n self.didFinish?()\n }\n case let .failure(failure):\n self.didFinish?()\n }\n }\n }\n case .restorePurchase:\n _ = storePaymentManager.restorePurchases(for: accountNumber) { result in\n Task { @MainActor [weak self] in\n guard let self else { return }\n self.spinnerView.stopAnimating()\n switch result {\n case let .success(success):\n self.errorPresenter.showAlertForResponse(success, context: .restoration) {\n self.didFinish?()\n }\n case let .failure(failure as StorePaymentManagerError):\n self.errorPresenter.showAlertForError(failure, context: .restoration) {\n self.didFinish?()\n }\n case let .failure(failure):\n self.didFinish?()\n }\n }\n }\n }\n }\n\n func purchase(product: SKProduct) {\n let payment = SKPayment(product: product)\n storePaymentManager.addPayment(payment, for: accountNumber)\n }\n\n func showPurchaseOptions(for products: [SKProduct]) {\n let localizedString = NSLocalizedString(\n "ADD_TIME_BUTTON",\n tableName: "Welcome",\n value: "Add Time",\n comment: ""\n )\n let sheetController = UIAlertController(\n title: localizedString,\n message: nil,\n preferredStyle: UIDevice.current.userInterfaceIdiom == .pad ? .alert : .actionSheet\n )\n sheetController.overrideUserInterfaceStyle = .dark\n sheetController.view.tintColor = .AlertController.tintColor\n products.sortedByPrice().forEach { product in\n guard let title = product.customLocalizedTitle else { return }\n let action = UIAlertAction(title: title, style: .default, handler: { _ in\n sheetController.dismiss(animated: true, completion: {\n self.purchase(product: product)\n self.spinnerView.startAnimating()\n })\n })\n action\n .accessibilityIdentifier = action.accessibilityIdentifier\n sheetController.addAction(action)\n }\n\n let cancelAction = UIAlertAction(title: NSLocalizedString(\n "SHEET_CANCEL_BUTTON",\n tableName: "ActionSheet",\n value: "Cancel",\n comment: ""\n ), style: .cancel) { _ in\n self.didFinish?()\n }\n cancelAction.accessibilityIdentifier = "actoin-sheet-cancel-button"\n sheetController.addAction(cancelAction)\n present(sheetController, animated: true)\n }\n\n nonisolated func storePaymentManager(_ manager: StorePaymentManager, didReceiveEvent event: StorePaymentEvent) {\n Task { @MainActor in\n spinnerView.stopAnimating()\n switch event {\n case let .finished(completion):\n errorPresenter.showAlertForResponse(completion.serverResponse, context: .purchase) {\n self.didFinish?()\n }\n\n case let .failure(paymentFailure):\n switch paymentFailure.error {\n case .storePayment(SKError.paymentCancelled):\n self.didFinish?()\n default:\n errorPresenter.showAlertForError(paymentFailure.error, context: .purchase) {\n self.didFinish?()\n }\n }\n }\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\InAppPurchase\InAppPurchaseViewController.swift | InAppPurchaseViewController.swift | Swift | 6,256 | 0.95 | 0.060976 | 0.046053 | python-kit | 72 | 2023-10-27T07:09:44.394189 | Apache-2.0 | false | 39aa557736967844df3d39fecafc083c |
//\n// LaunchViewController.swift\n// MullvadVPN\n//\n// Created by pronebird on 18/11/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass LaunchViewController: UIViewController {\n override var preferredStatusBarStyle: UIStatusBarStyle {\n .lightContent\n }\n\n init() {\n super.init(nibName: nil, bundle: nil)\n\n let storyboard = UIStoryboard(name: "LaunchScreen", bundle: nil)\n\n guard let initialController = storyboard.instantiateInitialViewController() else { return }\n\n initialController.view.translatesAutoresizingMaskIntoConstraints = false\n\n addChild(initialController)\n view.addSubview(initialController.view)\n initialController.didMove(toParent: self)\n\n NSLayoutConstraint.activate([\n initialController.view.topAnchor.constraint(equalTo: view.topAnchor),\n initialController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor),\n initialController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),\n initialController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),\n ])\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Launch\LaunchViewController.swift | LaunchViewController.swift | Swift | 1,271 | 0.95 | 0.025 | 0.225806 | node-utils | 176 | 2024-02-12T00:15:35.579356 | MIT | false | 11475349cc7644f699963c2bf598da98 |
//\n// AccountInputGroupView.swift\n// MullvadVPN\n//\n// Created by pronebird on 22/03/2019.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadTypes\nimport UIKit\n\nprivate let animationDuration: Duration = .milliseconds(250)\n\nfinal class AccountInputGroupView: UIView {\n private let minimumAccountTokenLength = 10\n private var showsLastUsedAccountRow = false\n\n enum Style {\n case normal, error, authenticating\n }\n\n let sendButton: UIButton = {\n let button = UIButton(type: .custom)\n button.translatesAutoresizingMaskIntoConstraints = false\n button.setImage(UIImage.Buttons.rightArrow, for: .normal)\n button.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)\n button.setAccessibilityIdentifier(.loginTextFieldButton)\n button.accessibilityLabel = NSLocalizedString(\n "ACCOUNT_INPUT_LOGIN_BUTTON_ACCESSIBILITY_LABEL",\n tableName: "AccountInput",\n value: "Log in",\n comment: ""\n )\n return button\n }()\n\n var textField: UITextField {\n privateTextField\n }\n\n var parsedToken: String {\n privateTextField.parsedToken\n }\n\n var satisfiesMinimumTokenLengthRequirement: Bool {\n privateTextField.parsedToken.count > minimumAccountTokenLength\n }\n\n var didRemoveLastUsedAccount: (() -> Void)?\n var didEnterAccount: (() -> Void)?\n\n private let privateTextField: AccountTextField = {\n let textField = AccountTextField()\n textField.font = accountNumberFont()\n textField.translatesAutoresizingMaskIntoConstraints = false\n textField.placeholder = "0000 0000 0000 0000"\n textField.placeholderTextColor = .lightGray\n textField.textContentType = .username\n textField.clearButtonMode = .never\n textField.autocapitalizationType = .none\n textField.autocorrectionType = .no\n textField.smartDashesType = .no\n textField.smartInsertDeleteType = .no\n textField.smartQuotesType = .no\n textField.spellCheckingType = .no\n textField.keyboardType = .numberPad\n textField.returnKeyType = .done\n textField.enablesReturnKeyAutomatically = false\n textField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)\n return textField\n }()\n\n private let separator: UIView = {\n let separator = UIView()\n separator.translatesAutoresizingMaskIntoConstraints = false\n return separator\n }()\n\n private let topRowView: UIView = {\n let view = UIView()\n view.translatesAutoresizingMaskIntoConstraints = false\n view.backgroundColor = .white\n return view\n }()\n\n private let bottomRowView: UIView = {\n let view = UIView()\n view.translatesAutoresizingMaskIntoConstraints = false\n view.backgroundColor = .white.withAlphaComponent(0.8)\n view.accessibilityElementsHidden = true\n return view\n }()\n\n private let lastUsedAccountButton: UIButton = {\n let button = UIButton(configuration: .plain())\n button.translatesAutoresizingMaskIntoConstraints = false\n button.contentHorizontalAlignment = .leading\n button.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)\n button.accessibilityLabel = NSLocalizedString(\n "LAST_USED_ACCOUNT_ACCESSIBILITY_LABEL",\n tableName: "AccountInput",\n value: "Last used account",\n comment: ""\n )\n button.configuration?.contentInsets = UIMetrics.textFieldMargins.toDirectionalInsets\n button.configuration?.title = " "\n button.configuration?\n .titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { attributeContainer in\n var updatedAttributeContainer = attributeContainer\n updatedAttributeContainer.font = AccountInputGroupView.accountNumberFont()\n updatedAttributeContainer.foregroundColor = .AccountTextField.NormalState.textColor\n return updatedAttributeContainer\n }\n\n return button\n }()\n\n private let removeLastUsedAccountButton: CustomButton = {\n let button = CustomButton()\n button.translatesAutoresizingMaskIntoConstraints = false\n button.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)\n button.accessibilityLabel = NSLocalizedString(\n "REMOVE_LAST_USED_ACCOUNT_ACCESSIBILITY_LABEL",\n tableName: "AccountInput",\n value: "Remove last used account",\n comment: ""\n )\n button.configuration?.image = UIImage.Buttons.closeSmall.withTintColor(.primaryColor)\n button.configuration?.title = " "\n return button\n }()\n\n let contentView: UIView = {\n let view = UIView()\n view.backgroundColor = .clear\n return view\n }()\n\n private(set) var loginState = LoginState.default\n private let borderRadius = CGFloat(8)\n private let borderWidth = CGFloat(2)\n private var lastUsedAccount: String?\n\n private var borderColor: UIColor {\n switch loginState {\n case .default:\n return privateTextField.isEditing\n ? UIColor.AccountTextField.NormalState.borderColor\n : UIColor.clear\n\n case .failure:\n return UIColor.AccountTextField.ErrorState.borderColor\n\n case .authenticating, .success:\n return UIColor.AccountTextField.AuthenticatingState.borderColor\n }\n }\n\n private var textColor: UIColor {\n switch loginState {\n case .default:\n return UIColor.AccountTextField.NormalState.textColor\n\n case .failure:\n return UIColor.AccountTextField.ErrorState.textColor\n\n case .authenticating, .success:\n return UIColor.AccountTextField.AuthenticatingState.textColor\n }\n }\n\n private var backgroundLayerColor: UIColor {\n switch loginState {\n case .default:\n return UIColor.AccountTextField.NormalState.backgroundColor\n\n case .failure:\n return UIColor.AccountTextField.ErrorState.backgroundColor\n\n case .authenticating, .success:\n return UIColor.AccountTextField.AuthenticatingState.backgroundColor\n }\n }\n\n private let borderLayer = AccountInputBorderLayer()\n private let contentLayerMask = CALayer()\n private var lastUsedAccountVisibleConstraint: NSLayoutConstraint!\n private var lastUsedAccountHiddenConstraint: NSLayoutConstraint!\n\n // MARK: - View lifecycle\n\n override init(frame: CGRect) {\n super.init(frame: frame)\n configUI()\n setAppearance()\n addActions()\n updateAppearance()\n updateTextFieldEnabled()\n updateSendButtonAppearance(animated: false)\n updateKeyboardReturnKeyEnabled()\n addTextFieldNotificationObservers()\n addAccessibilityNotificationObservers()\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n private func configUI() {\n addConstrainedSubviews([contentView]) {\n contentView.pinEdgesToSuperview(.all().excluding(.bottom))\n }\n\n contentView.addConstrainedSubviews([topRowView, separator, bottomRowView]) {\n topRowView.pinEdgesToSuperview(.all().excluding(.bottom))\n topRowView.bottomAnchor.constraint(equalTo: separator.topAnchor)\n\n separator.pinEdgesToSuperview(.all().excluding([.bottom, .top]))\n separator.topAnchor.constraint(equalTo: topRowView.bottomAnchor)\n separator.heightAnchor.constraint(equalToConstant: borderWidth)\n\n bottomRowView.topAnchor.constraint(equalTo: separator.bottomAnchor)\n bottomRowView.pinEdgesToSuperview(.all().excluding(.top))\n }\n\n topRowView.addConstrainedSubviews([privateTextField, sendButton]) {\n privateTextField.trailingAnchor.constraint(equalTo: sendButton.leadingAnchor)\n privateTextField.pinEdgesToSuperview(.all().excluding(.trailing))\n\n sendButton.pinEdgesToSuperview(.all().excluding(.leading))\n sendButton.widthAnchor.constraint(equalTo: sendButton.heightAnchor)\n }\n\n bottomRowView.addConstrainedSubviews([lastUsedAccountButton, removeLastUsedAccountButton]) {\n lastUsedAccountButton.pinEdgesToSuperview(.all().excluding(.trailing))\n lastUsedAccountButton.trailingAnchor.constraint(equalTo: removeLastUsedAccountButton.leadingAnchor)\n\n removeLastUsedAccountButton.pinEdgesToSuperview(.all().excluding(.leading))\n removeLastUsedAccountButton.widthAnchor.constraint(equalTo: sendButton.widthAnchor)\n }\n\n lastUsedAccountVisibleConstraint = heightAnchor.constraint(equalTo: contentView.heightAnchor)\n lastUsedAccountHiddenConstraint = heightAnchor.constraint(equalTo: topRowView.heightAnchor)\n lastUsedAccountHiddenConstraint.isActive = true\n }\n\n private func setAppearance() {\n backgroundColor = UIColor.clear\n borderLayer.lineWidth = borderWidth\n borderLayer.fillColor = UIColor.clear.cgColor\n contentView.layer.mask = contentLayerMask\n layer.insertSublayer(borderLayer, at: 0)\n }\n\n private func addActions() {\n lastUsedAccountButton.addTarget(\n self,\n action: #selector(didTapLastUsedAccount),\n for: .touchUpInside\n )\n\n removeLastUsedAccountButton.addTarget(\n self,\n action: #selector(didTapRemoveLastUsedAccount),\n for: .touchUpInside\n )\n\n sendButton.addTarget(self, action: #selector(handleSendButton(_:)), for: .touchUpInside)\n }\n\n func setLoginState(_ state: LoginState, animated: Bool) {\n loginState = state\n\n updateAppearance()\n updateTextFieldEnabled()\n updateSendButtonAppearance(animated: animated)\n updateLastUsedAccountConstraints(animated: animated)\n }\n\n func setOnReturnKey(_ onReturnKey: ((AccountInputGroupView) -> Bool)?) {\n if let onReturnKey {\n privateTextField.onReturnKey = { [weak self] _ -> Bool in\n guard let self else { return true }\n\n return onReturnKey(self)\n }\n } else {\n privateTextField.onReturnKey = nil\n }\n }\n\n func setAccount(_ account: String) {\n privateTextField.autoformattingText = account\n updateSendButtonAppearance(animated: false)\n }\n\n func clearAccount() {\n privateTextField.autoformattingText = ""\n updateSendButtonAppearance(animated: false)\n }\n\n func setLastUsedAccount(_ accountNumber: String?, animated: Bool) {\n if let accountNumber {\n let formattedNumber = accountNumber.formattedAccountNumber\n\n lastUsedAccountButton.accessibilityAttributedValue = NSAttributedString(\n string: accountNumber,\n attributes: [.accessibilitySpeechSpellOut: true]\n )\n\n UIView.performWithoutAnimation {\n self.lastUsedAccountButton.configuration?.title = formattedNumber\n self.lastUsedAccountButton.layoutIfNeeded()\n }\n }\n\n lastUsedAccount = accountNumber\n updateLastUsedAccountConstraints(animated: animated)\n }\n\n // MARK: - CALayerDelegate\n\n override func layoutSublayers(of layer: CALayer) {\n super.layoutSublayers(of: layer)\n\n guard layer == self.layer else { return }\n\n // extend the border frame outside of the content area\n let borderFrame = layer.bounds.insetBy(dx: -borderWidth * 0.5, dy: -borderWidth * 0.5)\n\n // create a bezier path for border\n let borderPath = borderBezierPath(size: borderFrame.size)\n\n // update the background layer mask\n contentLayerMask.frame = borderFrame\n contentLayerMask.contents = backgroundMaskImage(borderPath: borderPath).cgImage\n\n borderLayer.path = borderPath.cgPath\n borderLayer.frame = borderFrame\n }\n\n // MARK: - Actions\n\n @objc private func textDidBeginEditing() {\n updateAppearance()\n }\n\n @objc private func textDidChange() {\n updateSendButtonAppearance(animated: true)\n updateKeyboardReturnKeyEnabled()\n }\n\n @objc private func textDidEndEditing() {\n updateAppearance()\n }\n\n @objc private func handleSendButton(_ sender: Any) {\n didEnterAccount?()\n }\n\n @objc private func didTapLastUsedAccount() {\n guard let lastUsedAccount else { return }\n\n setAccount(lastUsedAccount)\n privateTextField.resignFirstResponder()\n\n updateLastUsedAccountConstraints(animated: true)\n didEnterAccount?()\n }\n\n @objc private func didTapRemoveLastUsedAccount() {\n didRemoveLastUsedAccount?()\n setLastUsedAccount(nil, animated: true)\n }\n\n // MARK: - Private\n\n private static func accountNumberFont() -> UIFont {\n UIFont.monospacedSystemFont(ofSize: 20, weight: .regular)\n }\n\n private func addTextFieldNotificationObservers() {\n let notificationCenter = NotificationCenter.default\n\n notificationCenter.addObserver(\n self,\n selector: #selector(textDidBeginEditing),\n name: UITextField.textDidBeginEditingNotification,\n object: privateTextField\n )\n notificationCenter.addObserver(\n self,\n selector: #selector(textDidChange),\n name: UITextField.textDidChangeNotification,\n object: privateTextField\n )\n notificationCenter.addObserver(\n self,\n selector: #selector(textDidEndEditing),\n name: UITextField.textDidEndEditingNotification,\n object: privateTextField\n )\n }\n\n private func updateAppearance() {\n borderLayer.strokeColor = borderColor.cgColor\n separator.backgroundColor = borderColor\n topRowView.backgroundColor = backgroundLayerColor\n privateTextField.textColor = textColor\n }\n\n private func updateTextFieldEnabled() {\n switch loginState {\n case .authenticating, .success:\n privateTextField.isEnabled = false\n\n case .default, .failure:\n privateTextField.isEnabled = true\n }\n }\n\n private func shouldShowLastUsedAccountRow() -> Bool {\n guard lastUsedAccount != nil else {\n return false\n }\n\n switch loginState {\n case .authenticating, .success:\n return false\n case .default, .failure:\n return true\n }\n }\n\n private func updateLastUsedAccountConstraints(animated: Bool) {\n let shouldShow = shouldShowLastUsedAccountRow()\n\n guard showsLastUsedAccountRow != shouldShow else {\n return\n }\n\n let actions = {\n let constraintToDeactivate: NSLayoutConstraint\n let constraintToActivate: NSLayoutConstraint\n\n if shouldShow {\n constraintToActivate = self.lastUsedAccountVisibleConstraint\n constraintToDeactivate = self.lastUsedAccountHiddenConstraint\n } else {\n constraintToActivate = self.lastUsedAccountHiddenConstraint\n constraintToDeactivate = self.lastUsedAccountVisibleConstraint\n }\n\n constraintToDeactivate.isActive = false\n constraintToActivate.isActive = true\n }\n\n if animated {\n actions()\n UIView.animate(withDuration: animationDuration.timeInterval) {\n self.layoutIfNeeded()\n }\n } else {\n actions()\n setNeedsLayout()\n }\n\n showsLastUsedAccountRow = shouldShow\n\n bottomRowView.accessibilityElementsHidden = !shouldShow\n\n if lastUsedAccountButton.accessibilityElementIsFocused() ||\n removeLastUsedAccountButton.accessibilityElementIsFocused() {\n UIAccessibility.post(notification: .layoutChanged, argument: textField)\n }\n }\n\n private func updateSendButtonAppearance(animated: Bool) {\n let actions = {\n switch self.loginState {\n case .authenticating, .success:\n // Always show the send button when voice over is running to make it discoverable\n self.sendButton.alpha = UIAccessibility.isVoiceOverRunning ? 1 : 0\n\n self.sendButton.isEnabled = false\n self.sendButton.backgroundColor = .lightGray\n\n case .default, .failure:\n let isEnabled = self.satisfiesMinimumTokenLengthRequirement\n\n // Always show the send button when voice over is running to make it discoverable\n if UIAccessibility.isVoiceOverRunning {\n self.sendButton.alpha = 1\n } else {\n self.sendButton.alpha = isEnabled ? 1 : 0\n }\n\n self.sendButton.isEnabled = isEnabled\n self.sendButton.backgroundColor = isEnabled ? .successColor : .lightGray\n }\n }\n\n if animated {\n UIView.animate(withDuration: animationDuration.timeInterval) {\n actions()\n }\n } else {\n actions()\n }\n }\n\n private func updateKeyboardReturnKeyEnabled() {\n privateTextField.enableReturnKey = satisfiesMinimumTokenLengthRequirement\n }\n\n private func borderBezierPath(size: CGSize) -> UIBezierPath {\n let borderPath = UIBezierPath(\n roundedRect: CGRect(origin: .zero, size: size),\n cornerRadius: borderRadius\n )\n borderPath.lineWidth = borderWidth\n\n return borderPath\n }\n\n private func backgroundMaskImage(borderPath: UIBezierPath) -> UIImage {\n let renderer = UIGraphicsImageRenderer(bounds: borderPath.bounds)\n return renderer.image { _ in\n borderPath.fill()\n // strip out any overlapping pixels between the border and the background\n borderPath.stroke(with: .clear, alpha: 0)\n }\n }\n\n // MARK: - Accessibility\n\n private func addAccessibilityNotificationObservers() {\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(voiceOverStatusDidChange(_:)),\n name: UIAccessibility.voiceOverStatusDidChangeNotification,\n object: nil\n )\n }\n\n @objc private func voiceOverStatusDidChange(_ notification: Notification) {\n updateSendButtonAppearance(animated: true)\n }\n}\n\nprivate class AccountInputBorderLayer: CAShapeLayer {\n override class func defaultAction(forKey event: String) -> CAAction? {\n if event == "path" {\n let action = CABasicAnimation(keyPath: event)\n action.duration = animationDuration.timeInterval\n action.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)\n\n return action\n }\n return super.defaultAction(forKey: event)\n }\n\n // swiftlint:disable:next file_length\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Login\AccountInputGroupView.swift | AccountInputGroupView.swift | Swift | 19,185 | 0.95 | 0.046099 | 0.041304 | react-lib | 371 | 2024-02-06T19:02:32.127587 | Apache-2.0 | false | 2398edfd0ab9e611aeab5300ed650f67 |
//\n// AccountTextField.swift\n// MullvadVPN\n//\n// Created by pronebird on 20/03/2019.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass AccountTextField: CustomTextField, UITextFieldDelegate {\n enum GroupingStyle: Int {\n case full\n case lastPart\n\n var size: UInt8 {\n switch self {\n case .full:\n return 4\n case .lastPart:\n return 1\n }\n }\n }\n\n private var groupSize: GroupingStyle = .full\n private lazy var inputFormatter = InputTextFormatter(configuration: InputTextFormatter.Configuration(\n allowedInput: .numeric,\n groupSeparator: " ",\n groupSize: 4,\n maxGroups: groupSize.size\n ))\n\n var onReturnKey: ((AccountTextField) -> Bool)?\n\n init(groupingStyle: GroupingStyle = .full) {\n self.groupSize = groupingStyle\n super.init(frame: .zero)\n commonInit()\n }\n\n override init(frame: CGRect) {\n super.init(frame: frame)\n commonInit()\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n private func commonInit() {\n backgroundColor = .clear\n cornerRadius = 0\n\n delegate = self\n pasteDelegate = inputFormatter\n\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(keyboardWillShow(_:)),\n name: UIWindow.keyboardWillShowNotification,\n object: nil\n )\n }\n\n var autoformattingText: String {\n get {\n inputFormatter.formattedString\n }\n set {\n inputFormatter.replace(with: newValue)\n inputFormatter.updateTextField(self)\n }\n }\n\n var parsedToken: String {\n inputFormatter.string\n }\n\n var enableReturnKey = true {\n didSet {\n updateKeyboardReturnKey()\n }\n }\n\n override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {\n if action == #selector(captureTextFromCamera(_:)) {\n return false\n }\n return super.canPerformAction(action, withSender: sender)\n }\n\n // MARK: - UITextFieldDelegate\n\n func textField(\n _ textField: UITextField,\n shouldChangeCharactersIn range: NSRange,\n replacementString string: String\n ) -> Bool {\n inputFormatter.textField(\n textField,\n shouldChangeCharactersIn: range,\n replacementString: string\n )\n }\n\n func textFieldShouldReturn(_ textField: UITextField) -> Bool {\n onReturnKey?(self) ?? true\n }\n\n // MARK: - Notifications\n\n @objc private func keyboardWillShow(_ notification: Notification) {\n if isFirstResponder {\n updateKeyboardReturnKey()\n }\n }\n\n // MARK: - Keyboard\n\n private func updateKeyboardReturnKey() {\n setEnableKeyboardReturnKey(enableReturnKey)\n }\n\n private func setEnableKeyboardReturnKey(_ enableReturnKey: Bool) {\n let selector = NSSelectorFromString("setReturnKeyEnabled:")\n if let inputDelegate = inputDelegate as? NSObject, inputDelegate.responds(to: selector) {\n inputDelegate.setValue(enableReturnKey, forKey: "returnKeyEnabled")\n }\n }\n\n // MARK: - Accessibility\n\n override var accessibilityValue: String? {\n get {\n if text?.isEmpty ?? true {\n return ""\n } else {\n return super.accessibilityValue\n }\n }\n set {\n super.accessibilityValue = newValue\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Login\AccountTextField.swift | AccountTextField.swift | Swift | 3,645 | 0.95 | 0.041096 | 0.090909 | awesome-app | 500 | 2025-03-20T18:20:43.915931 | GPL-3.0 | false | 1d77a010ff0403cf7986bbdc8f311f99 |
//\n// LoginContentView.swift\n// MullvadVPN\n//\n// Created by pronebird on 22/03/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass LoginContentView: UIView {\n private var keyboardResponder: AutomaticKeyboardResponder?\n\n let titleLabel: UILabel = {\n let textLabel = UILabel()\n textLabel.font = UIFont.systemFont(ofSize: 32)\n textLabel.textColor = .white\n textLabel.translatesAutoresizingMaskIntoConstraints = false\n return textLabel\n }()\n\n let messageLabel: UILabel = {\n let textLabel = UILabel()\n textLabel.font = UIFont.systemFont(ofSize: 17)\n textLabel.textColor = UIColor.white.withAlphaComponent(0.6)\n textLabel.translatesAutoresizingMaskIntoConstraints = false\n textLabel.numberOfLines = 0\n return textLabel\n }()\n\n let accountInputGroup: AccountInputGroupView = {\n let inputGroup = AccountInputGroupView()\n inputGroup.translatesAutoresizingMaskIntoConstraints = false\n return inputGroup\n }()\n\n let accountInputGroupWrapper: UIView = {\n let wrapperView = UIView()\n wrapperView.translatesAutoresizingMaskIntoConstraints = false\n return wrapperView\n }()\n\n let statusActivityView: StatusActivityView = {\n let statusActivityView = StatusActivityView(state: .hidden)\n statusActivityView.translatesAutoresizingMaskIntoConstraints = false\n statusActivityView.clipsToBounds = true\n return statusActivityView\n }()\n\n let contentContainer: UIView = {\n let view = UIView()\n view.translatesAutoresizingMaskIntoConstraints = false\n view.directionalLayoutMargins = UIMetrics.contentLayoutMargins\n return view\n }()\n\n let formContainer: UIView = {\n let view = UIView()\n view.translatesAutoresizingMaskIntoConstraints = false\n view.directionalLayoutMargins = UIMetrics.contentLayoutMargins\n return view\n }()\n\n let footerContainer: UIView = {\n let view = UIView()\n view.translatesAutoresizingMaskIntoConstraints = false\n view.directionalLayoutMargins = UIMetrics.contentLayoutMargins\n view.backgroundColor = .secondaryColor\n return view\n }()\n\n let footerLabel: UILabel = {\n let textLabel = UILabel()\n textLabel.font = UIFont.systemFont(ofSize: 17)\n textLabel.textColor = UIColor.white.withAlphaComponent(0.6)\n textLabel.translatesAutoresizingMaskIntoConstraints = false\n textLabel.text = NSLocalizedString(\n "CREATE_BUTTON_HEADER_LABEL",\n tableName: "Login",\n value: "Don’t have an account number?",\n comment: ""\n )\n return textLabel\n }()\n\n let createAccountButton: AppButton = {\n let button = AppButton(style: .default)\n button.setAccessibilityIdentifier(.createAccountButton)\n button.translatesAutoresizingMaskIntoConstraints = false\n button.setTitle(NSLocalizedString(\n "CREATE_ACCOUNT_BUTTON_LABEL",\n tableName: "Login",\n value: "Create account",\n comment: ""\n ), for: .normal)\n return button\n }()\n\n private var isStatusImageVisible = false\n private var contentContainerBottomConstraint: NSLayoutConstraint?\n\n override init(frame: CGRect) {\n super.init(frame: frame)\n\n backgroundColor = .primaryColor\n directionalLayoutMargins = UIMetrics.contentLayoutMargins\n setAccessibilityIdentifier(.loginView)\n\n accountInputGroup.textField.setAccessibilityIdentifier(.loginTextField)\n\n keyboardResponder = AutomaticKeyboardResponder(\n targetView: self,\n handler: { [weak self] _, adjustment in\n self?.contentContainerBottomConstraint?.constant = adjustment\n\n self?.layoutIfNeeded()\n }\n )\n\n addSubviews()\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n private func addSubviews() {\n formContainer.addSubview(titleLabel)\n formContainer.addSubview(messageLabel)\n formContainer.addSubview(accountInputGroupWrapper)\n accountInputGroupWrapper.addSubview(accountInputGroup)\n\n contentContainer.addSubview(statusActivityView)\n contentContainer.addSubview(formContainer)\n\n footerContainer.addSubview(footerLabel)\n footerContainer.addSubview(createAccountButton)\n\n let contentContainerBottomConstraint = bottomAnchor\n .constraint(equalTo: contentContainer.bottomAnchor)\n self.contentContainerBottomConstraint = contentContainerBottomConstraint\n\n addConstrainedSubviews([contentContainer, footerContainer]) {\n contentContainer.pinEdges(PinnableEdges([.top(0)]), to: safeAreaLayoutGuide)\n contentContainer.pinEdgesToSuperview(PinnableEdges([.leading(0), .trailing(0)]))\n contentContainerBottomConstraint\n\n footerContainer.pinEdgesToSuperview(.all().excluding(.top))\n footerLabel.pinEdges(.all().excluding(.bottom), to: footerContainer.layoutMarginsGuide)\n\n createAccountButton.topAnchor.constraint(equalToSystemSpacingBelow: footerLabel.bottomAnchor, multiplier: 1)\n createAccountButton.pinEdges(.all().excluding(.top), to: footerContainer.layoutMarginsGuide)\n\n statusActivityView.centerXAnchor.constraint(equalTo: contentContainer.centerXAnchor)\n statusActivityView.widthAnchor.constraint(equalToConstant: 60.0)\n statusActivityView.heightAnchor.constraint(equalTo: statusActivityView.widthAnchor, multiplier: 1.0)\n\n formContainer.topAnchor.constraint(equalTo: statusActivityView.bottomAnchor, constant: 30)\n formContainer.centerYAnchor.constraint(equalTo: contentContainer.centerYAnchor, constant: -20)\n formContainer.pinEdges(PinnableEdges([.leading(0), .trailing(0)]), to: contentContainer)\n formContainer.pinEdges(PinnableEdges([.bottom(0)]), to: accountInputGroupWrapper)\n\n titleLabel.pinEdges(.all().excluding(.bottom), to: formContainer.layoutMarginsGuide)\n\n messageLabel.topAnchor.constraint(equalToSystemSpacingBelow: titleLabel.bottomAnchor, multiplier: 1)\n messageLabel.pinEdges(PinnableEdges([.leading(0), .trailing(0)]), to: formContainer.layoutMarginsGuide)\n\n accountInputGroupWrapper.topAnchor.constraint(\n equalToSystemSpacingBelow: messageLabel.bottomAnchor,\n multiplier: 1\n )\n accountInputGroupWrapper.pinEdges(\n PinnableEdges([.leading(0), .trailing(0)]),\n to: formContainer.layoutMarginsGuide\n )\n accountInputGroupWrapper.heightAnchor.constraint(equalTo: accountInputGroup.contentView.heightAnchor)\n accountInputGroup.pinEdges(.all().excluding(.bottom), to: accountInputGroupWrapper)\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Login\LoginContentView.swift | LoginContentView.swift | Swift | 7,006 | 0.95 | 0.011111 | 0.047297 | node-utils | 460 | 2024-12-10T06:21:20.892366 | BSD-3-Clause | false | cca95bfd080038fab404d0a58d274d04 |
//\n// LoginInteractor.swift\n// MullvadVPN\n//\n// Created by pronebird on 27/01/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n@preconcurrency import MullvadLogging\nimport MullvadSettings\n\nfinal class LoginInteractor: @unchecked Sendable {\n private let tunnelManager: TunnelManager\n private let logger = Logger(label: "LoginInteractor")\n private var tunnelObserver: TunnelObserver?\n var didCreateAccount: (@MainActor @Sendable () -> Void)?\n var suggestPreferredAccountNumber: (@Sendable (String) -> Void)?\n\n init(tunnelManager: TunnelManager) {\n self.tunnelManager = tunnelManager\n }\n\n func setAccount(accountNumber: String) async throws {\n _ = try await tunnelManager.setExistingAccount(accountNumber: accountNumber)\n }\n\n func createAccount() async throws -> String {\n let accountNumber = try await tunnelManager.setNewAccount().number\n await didCreateAccount?()\n\n return accountNumber\n }\n\n func getLastUsedAccount() -> String? {\n do {\n return try SettingsManager.getLastUsedAccount()\n } catch {\n logger.error(\n error: error,\n message: "Failed to get last used account."\n )\n return nil\n }\n }\n\n func removeLastUsedAccount() {\n do {\n try SettingsManager.setLastUsedAccount(nil)\n } catch {\n logger.error(\n error: error,\n message: "Failed to remove last used account."\n )\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Login\LoginInteractor.swift | LoginInteractor.swift | Swift | 1,577 | 0.95 | 0.122807 | 0.142857 | vue-tools | 672 | 2025-03-18T03:18:29.640930 | Apache-2.0 | false | ed2381b5a80e0c4a15c11724ddffb94c |
//\n// LoginViewController.swift\n// MullvadVPN\n//\n// Created by pronebird on 19/03/2019.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadLogging\nimport MullvadTypes\nimport Operations\nimport UIKit\n\nenum LoginState {\n case `default`\n case authenticating(LoginAction)\n case failure(LoginAction, Error)\n case success(LoginAction)\n}\n\nenum LoginAction {\n case useExistingAccount(String)\n case createAccount\n}\n\nenum EndLoginAction {\n /// Do nothing.\n case nothing\n\n /// Set focus on account text field.\n case activateTextField\n\n /// Wait for promise before showing login error.\n case wait(Promise<Void, Error>)\n}\n\nclass LoginViewController: UIViewController, RootContainment {\n private lazy var contentView: LoginContentView = {\n let view = LoginContentView(frame: self.view.bounds)\n view.translatesAutoresizingMaskIntoConstraints = false\n return view\n }()\n\n private lazy var accountInputAccessoryCancelButton = UIBarButtonItem(\n barButtonSystemItem: .cancel,\n target: self,\n action: #selector(cancelLogin)\n )\n\n private lazy var accountInputAccessoryLoginButton: UIBarButtonItem = {\n let barButtonItem = UIBarButtonItem(\n title: NSLocalizedString(\n "LOGIN_ACCESSORY_TOOLBAR_BUTTON_TITLE",\n tableName: "Login",\n value: "Log in",\n comment: ""\n ),\n style: .done,\n target: self,\n action: #selector(doLogin)\n )\n barButtonItem.setAccessibilityIdentifier(.loginBarButton)\n\n return barButtonItem\n }()\n\n private lazy var accountInputAccessoryToolbar: UIToolbar = {\n let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: 320, height: 44))\n toolbar.items = [\n self.accountInputAccessoryCancelButton,\n UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),\n self.accountInputAccessoryLoginButton,\n ]\n toolbar.sizeToFit()\n return toolbar\n }()\n\n private let logger = Logger(label: "LoginViewController")\n\n private var loginState = LoginState.default {\n didSet {\n loginStateDidChange()\n }\n }\n\n private var canBeginLogin: Bool {\n contentView.accountInputGroup.satisfiesMinimumTokenLengthRequirement\n }\n\n var prefersDeviceInfoBarHidden: Bool {\n true\n }\n\n private let interactor: LoginInteractor\n\n var didFinishLogin: ((LoginAction, Error?) -> EndLoginAction)?\n\n override var preferredStatusBarStyle: UIStatusBarStyle {\n .lightContent\n }\n\n var preferredHeaderBarPresentation: HeaderBarPresentation {\n HeaderBarPresentation(style: .transparent, showsDivider: false)\n }\n\n var prefersHeaderBarHidden: Bool {\n false\n }\n\n init(interactor: LoginInteractor) {\n self.interactor = interactor\n super.init(nibName: nil, bundle: nil)\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n override func viewDidLoad() {\n super.viewDidLoad()\n\n view.addSubview(contentView)\n NSLayoutConstraint.activate([\n contentView.topAnchor.constraint(equalTo: view.topAnchor),\n contentView.leadingAnchor.constraint(equalTo: view.leadingAnchor),\n contentView.trailingAnchor.constraint(equalTo: view.trailingAnchor),\n contentView.bottomAnchor.constraint(equalTo: view.bottomAnchor),\n ])\n updateLastUsedAccount()\n\n contentView.accountInputGroup.didRemoveLastUsedAccount = { [weak self] in\n self?.interactor.removeLastUsedAccount()\n }\n\n contentView.accountInputGroup.didEnterAccount = { [weak self] in\n self?.attemptLogin()\n }\n\n interactor.suggestPreferredAccountNumber = { [weak self] value in\n Task { @MainActor in\n self?.contentView.accountInputGroup.setAccount(value)\n }\n }\n\n contentView.accountInputGroup.setOnReturnKey { [weak self] _ in\n guard let self else { return true }\n\n return attemptLogin()\n }\n\n // There is no need to set the input accessory toolbar on iPad since it has a dedicated\n // button to dismiss the keyboard.\n if case .phone = UIDevice.current.userInterfaceIdiom {\n contentView.accountInputGroup.textField.inputAccessoryView = accountInputAccessoryToolbar\n } else {\n contentView.accountInputGroup.textField.inputAccessoryView = nil\n }\n\n updateDisplayedMessage()\n updateStatusIcon()\n updateKeyboardToolbar()\n\n let notificationCenter = NotificationCenter.default\n\n contentView.createAccountButton.addTarget(\n self,\n action: #selector(createNewAccount),\n for: .touchUpInside\n )\n\n notificationCenter.addObserver(\n self,\n selector: #selector(textDidChange(_:)),\n name: UITextField.textDidChangeNotification,\n object: contentView.accountInputGroup.textField\n )\n }\n\n // MARK: - Public\n\n func start(action: LoginAction) {\n beginLogin(action)\n Task { [weak self] in\n guard let self else { return }\n do {\n switch action {\n case .createAccount:\n self.contentView.accountInputGroup.setAccount(try await interactor.createAccount())\n\n case let .useExistingAccount(accountNumber):\n try await interactor.setAccount(accountNumber: accountNumber)\n }\n self.endLogin(action: action, error: nil)\n } catch {\n self.endLogin(action: action, error: error)\n }\n }\n }\n\n func reset() {\n contentView.accountInputGroup.clearAccount()\n loginState = .default\n updateKeyboardToolbar()\n updateLastUsedAccount()\n }\n\n // MARK: - UITextField notifications\n\n @objc func textDidChange(_ notification: Notification) {\n // Reset the text style as user start typing\n if case .failure = loginState {\n loginState = .default\n }\n\n // Enable the log in button in the keyboard toolbar.\n updateKeyboardToolbar()\n\n // Update "create account" button state.\n updateCreateButtonEnabled()\n }\n\n // MARK: - Actions\n\n @objc private func cancelLogin() {\n view.endEditing(true)\n }\n\n @objc private func doLogin() {\n let accountNumber = contentView.accountInputGroup.parsedToken\n\n start(action: .useExistingAccount(accountNumber))\n }\n\n @objc private func createNewAccount() {\n start(action: .createAccount)\n }\n\n // MARK: - Private\n\n private func updateLastUsedAccount() {\n contentView.accountInputGroup.setLastUsedAccount(\n interactor.getLastUsedAccount(),\n animated: false\n )\n }\n\n private func loginStateDidChange() {\n contentView.accountInputGroup.setLoginState(loginState, animated: true)\n\n updateDisplayedMessage()\n updateStatusIcon()\n updateCreateButtonEnabled()\n }\n\n private func updateStatusIcon() {\n contentView.statusActivityView.state = loginState.statusActivityState\n }\n\n private func beginLogin(_ action: LoginAction) {\n loginState = .authenticating(action)\n\n view.endEditing(true)\n }\n\n private func endLogin(action: LoginAction, error: Error?) {\n let nextLoginState: LoginState = error.map { .failure(action, $0) } ?? .success(action)\n\n let endAction = didFinishLogin?(action, error) ?? .nothing\n\n switch endAction {\n case .activateTextField:\n contentView.accountInputGroup.textField.becomeFirstResponder()\n loginState = nextLoginState\n\n case .nothing:\n loginState = nextLoginState\n\n case let .wait(promise):\n promise.observe { result in\n self.loginState = result.error.map { .failure(action, $0) } ?? nextLoginState\n }\n }\n }\n\n private func updateDisplayedMessage() {\n contentView.titleLabel.text = loginState.localizedTitle\n contentView.messageLabel.text = loginState.localizedMessage\n }\n\n private func updateKeyboardToolbar() {\n accountInputAccessoryLoginButton.isEnabled = canBeginLogin\n }\n\n private func updateCreateButtonEnabled() {\n let isEnabled: Bool\n\n switch loginState {\n case .failure, .default:\n isEnabled = true\n\n case .success, .authenticating:\n isEnabled = false\n }\n\n contentView.createAccountButton.isEnabled = isEnabled\n }\n\n @discardableResult private func attemptLogin() -> Bool {\n if canBeginLogin {\n doLogin()\n return true\n } else {\n return false\n }\n }\n}\n\n/// Private extension that brings localizable messages displayed in the Login view controller\nprivate extension LoginState {\n var localizedTitle: String {\n switch self {\n case .default:\n return NSLocalizedString(\n "HEADING_TITLE_DEFAULT",\n tableName: "Login",\n value: "Login",\n comment: ""\n )\n\n case .authenticating:\n return NSLocalizedString(\n "HEADING_TITLE_AUTHENTICATING",\n tableName: "Login",\n value: "Logging in...",\n comment: ""\n )\n\n case .failure:\n return NSLocalizedString(\n "HEADING_TITLE_FAILURE",\n tableName: "Login",\n value: "Login failed",\n comment: ""\n )\n\n case .success:\n return NSLocalizedString(\n "HEADING_TITLE_SUCCESS",\n tableName: "Login",\n value: "Logged in",\n comment: ""\n )\n }\n }\n\n var localizedMessage: String {\n switch self {\n case .default:\n return NSLocalizedString(\n "SUBHEAD_TITLE_DEFAULT",\n tableName: "Login",\n value: "Enter your account number",\n comment: ""\n )\n\n case let .authenticating(method):\n switch method {\n case .useExistingAccount:\n return NSLocalizedString(\n "SUBHEAD_TITLE_AUTHENTICATING",\n tableName: "Login",\n value: "Checking account number",\n comment: ""\n )\n case .createAccount:\n return NSLocalizedString(\n "SUBHEAD_TITLE_CREATING_ACCOUNT",\n tableName: "Login",\n value: "Creating new account",\n comment: ""\n )\n }\n\n case let .failure(_, error):\n return (error as? DisplayError)?.displayErrorDescription ?? error.localizedDescription\n\n case let .success(method):\n switch method {\n case .useExistingAccount:\n return NSLocalizedString(\n "SUBHEAD_TITLE_SUCCESS",\n tableName: "Login",\n value: "Correct account number",\n comment: ""\n )\n case .createAccount:\n return NSLocalizedString(\n "SUBHEAD_TITLE_CREATED_ACCOUNT",\n tableName: "Login",\n value: "Account created",\n comment: ""\n )\n }\n }\n }\n\n var statusActivityState: StatusActivityView.State {\n switch self {\n case .failure:\n return .failure\n case .success:\n return .success\n case .authenticating:\n return .activity\n case .default:\n return .hidden\n }\n }\n\n // swiftlint:disable:next file_length\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Login\LoginViewController.swift | LoginViewController.swift | Swift | 12,128 | 0.95 | 0.04038 | 0.06087 | node-utils | 501 | 2024-11-03T09:28:29.183483 | Apache-2.0 | false | 1180805f8b96b6ce4357a63e747c0dd8 |
//\n// OutOfTimeContentView.swift\n// MullvadVPN\n//\n// Created by Andreas Lif on 2022-07-26.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport UIKit\n\nclass OutOfTimeContentView: UIView {\n let statusActivityView: StatusActivityView = {\n let statusActivityView = StatusActivityView(state: .failure)\n statusActivityView.translatesAutoresizingMaskIntoConstraints = false\n return statusActivityView\n }()\n\n private lazy var titleLabel: UILabel = {\n let label = UILabel()\n label.text = NSLocalizedString(\n "OUT_OF_TIME_TITLE",\n tableName: "OutOfTime",\n value: "Out of time",\n comment: ""\n )\n label.font = UIFont.systemFont(ofSize: 32)\n label.textColor = .white\n return label\n }()\n\n private lazy var bodyLabel: UILabel = {\n let label = UILabel()\n label.textColor = .white\n label.numberOfLines = 0\n return label\n }()\n\n lazy var disconnectButton: AppButton = {\n let button = AppButton(style: .danger)\n button.translatesAutoresizingMaskIntoConstraints = false\n button.alpha = 0\n let localizedString = NSLocalizedString(\n "OUT_OF_TIME_DISCONNECT_BUTTON",\n tableName: "OutOfTime",\n value: "Disconnect",\n comment: ""\n )\n button.setTitle(localizedString, for: .normal)\n return button\n }()\n\n lazy var purchaseButton: InAppPurchaseButton = {\n let button = InAppPurchaseButton()\n button.translatesAutoresizingMaskIntoConstraints = false\n let localizedString = NSLocalizedString(\n "OUT_OF_TIME_PURCHASE_BUTTON",\n tableName: "OutOfTime",\n value: "Add time",\n comment: ""\n )\n button.setTitle(localizedString, for: .normal)\n return button\n }()\n\n lazy var restoreButton: AppButton = {\n let button = AppButton(style: .default)\n button.translatesAutoresizingMaskIntoConstraints = false\n button.setTitle(NSLocalizedString(\n "RESTORE_PURCHASES_BUTTON_TITLE",\n tableName: "OutOfTime",\n value: "Restore purchases",\n comment: ""\n ), for: .normal)\n return button\n }()\n\n private lazy var topStackView: UIStackView = {\n let stackView = UIStackView(arrangedSubviews: [statusActivityView, titleLabel, bodyLabel])\n stackView.translatesAutoresizingMaskIntoConstraints = false\n stackView.axis = .vertical\n stackView.spacing = UIMetrics.TableView.sectionSpacing\n return stackView\n }()\n\n private lazy var bottomStackView: UIStackView = {\n let stackView = UIStackView(\n arrangedSubviews: [disconnectButton, purchaseButton, restoreButton]\n )\n stackView.translatesAutoresizingMaskIntoConstraints = false\n stackView.axis = .vertical\n stackView.spacing = UIMetrics.TableView.sectionSpacing\n return stackView\n }()\n\n override init(frame: CGRect) {\n super.init(frame: frame)\n setAccessibilityIdentifier(.outOfTimeView)\n translatesAutoresizingMaskIntoConstraints = false\n backgroundColor = .secondaryColor\n directionalLayoutMargins = UIMetrics.contentLayoutMargins\n setUpSubviews()\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n func enableDisconnectButton(_ enabled: Bool, animated: Bool) {\n disconnectButton.isEnabled = enabled\n UIView.animate(withDuration: animated ? 0.25 : 0) {\n self.disconnectButton.alpha = enabled ? 1 : 0\n }\n }\n\n // MARK: - Private Functions\n\n func setUpSubviews() {\n addSubview(topStackView)\n addSubview(bottomStackView)\n configureConstraints()\n }\n\n func configureConstraints() {\n NSLayoutConstraint.activate([\n topStackView.centerYAnchor.constraint(equalTo: centerYAnchor, constant: -20),\n\n topStackView.leadingAnchor.constraint(\n equalTo: layoutMarginsGuide.leadingAnchor\n ),\n topStackView.trailingAnchor.constraint(\n equalTo: layoutMarginsGuide.trailingAnchor\n ),\n\n bottomStackView.leadingAnchor.constraint(\n equalTo: layoutMarginsGuide.leadingAnchor\n ),\n bottomStackView.trailingAnchor.constraint(\n equalTo: layoutMarginsGuide.trailingAnchor\n ),\n bottomStackView.bottomAnchor.constraint(\n equalTo: layoutMarginsGuide.bottomAnchor\n ),\n ])\n }\n\n func setBodyLabelText(_ text: String) {\n bodyLabel.attributedText = NSAttributedString(\n markdownString: text,\n options: MarkdownStylingOptions(font: .systemFont(ofSize: 17))\n )\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\OutOfTime\OutOfTimeContentView.swift | OutOfTimeContentView.swift | Swift | 4,911 | 0.95 | 0.026144 | 0.059259 | python-kit | 719 | 2023-08-01T17:18:49.877082 | GPL-3.0 | false | bb01dc7ea8378c2c5aa7b5fcec7fb873 |
//\n// OutOfTimeInteractor.swift\n// MullvadVPN\n//\n// Created by pronebird on 26/10/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadLogging\nimport MullvadREST\nimport MullvadSettings\nimport MullvadTypes\nimport Operations\n@preconcurrency import StoreKit\n\nfinal class OutOfTimeInteractor: Sendable {\n private let tunnelManager: TunnelManager\n\n nonisolated(unsafe) private var tunnelObserver: TunnelObserver?\n\n nonisolated(unsafe) private let logger = Logger(label: "OutOfTimeInteractor")\n\n private let accountUpdateTimerInterval: Duration = .minutes(1)\n nonisolated(unsafe) private var accountUpdateTimer: DispatchSourceTimer?\n\n nonisolated(unsafe) var didReceiveTunnelStatus: (@Sendable (TunnelStatus) -> Void)?\n nonisolated(unsafe) var didAddMoreCredit: (@Sendable () -> Void)?\n\n init(tunnelManager: TunnelManager) {\n self.tunnelManager = tunnelManager\n\n let tunnelObserver = TunnelBlockObserver(\n didUpdateTunnelStatus: { [weak self] _, tunnelStatus in\n self?.didReceiveTunnelStatus?(tunnelStatus)\n },\n didUpdateDeviceState: { [weak self] _, deviceState, previousDeviceState in\n let isInactive = previousDeviceState.accountData?.isExpired == true\n let isActive = deviceState.accountData?.isExpired == false\n if isInactive && isActive {\n self?.didAddMoreCredit?()\n }\n }\n )\n\n tunnelManager.addObserver(tunnelObserver)\n\n self.tunnelObserver = tunnelObserver\n }\n\n var tunnelStatus: TunnelStatus {\n tunnelManager.tunnelStatus\n }\n\n var deviceState: DeviceState {\n tunnelManager.deviceState\n }\n\n func stopTunnel() {\n tunnelManager.stopTunnel()\n }\n\n func startAccountUpdateTimer() {\n logger.debug(\n "Start polling account updates every \(accountUpdateTimerInterval) second(s)."\n )\n let timer = DispatchSource.makeTimerSource(queue: .main)\n timer.setEventHandler { [weak self] in\n self?.tunnelManager.updateAccountData()\n }\n\n accountUpdateTimer?.cancel()\n accountUpdateTimer = timer\n\n timer.schedule(\n wallDeadline: .now() + accountUpdateTimerInterval,\n repeating: accountUpdateTimerInterval.timeInterval\n )\n timer.activate()\n }\n\n func stopAccountUpdateTimer() {\n logger.debug(\n "Stop polling account updates."\n )\n\n accountUpdateTimer?.cancel()\n accountUpdateTimer = nil\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\OutOfTime\OutOfTimeInteractor.swift | OutOfTimeInteractor.swift | Swift | 2,625 | 0.95 | 0.022222 | 0.097222 | python-kit | 207 | 2024-12-17T00:09:24.638617 | GPL-3.0 | false | 68687b142ec52ee695eb06e08b22aafd |
//\n// OutOfTimeViewController.swift\n// MullvadVPN\n//\n// Created by Andreas Lif on 2022-07-25.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\nimport Operations\n@preconcurrency import StoreKit\nimport UIKit\n\nprotocol OutOfTimeViewControllerDelegate: AnyObject, Sendable {\n func didRequestShowInAppPurchase(\n accountNumber: String,\n paymentAction: PaymentAction\n )\n}\n\n@MainActor\nclass OutOfTimeViewController: UIViewController, RootContainment {\n weak var delegate: OutOfTimeViewControllerDelegate?\n\n private let interactor: OutOfTimeInteractor\n\n private lazy var contentView = OutOfTimeContentView()\n\n override var preferredStatusBarStyle: UIStatusBarStyle {\n .lightContent\n }\n\n nonisolated(unsafe) var preferredHeaderBarPresentation: HeaderBarPresentation {\n let tunnelState = interactor.tunnelStatus.state\n\n return HeaderBarPresentation(\n style: tunnelState.isSecured ? .secured : .unsecured,\n showsDivider: false\n )\n }\n\n var prefersHeaderBarHidden: Bool {\n false\n }\n\n init(interactor: OutOfTimeInteractor, errorPresenter: PaymentAlertPresenter) {\n self.interactor = interactor\n\n super.init(nibName: nil, bundle: nil)\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n override func viewDidLoad() {\n super.viewDidLoad()\n\n view.addSubview(contentView)\n\n NSLayoutConstraint.activate([\n contentView.topAnchor.constraint(equalTo: view.topAnchor),\n contentView.leadingAnchor.constraint(equalTo: view.leadingAnchor),\n contentView.trailingAnchor.constraint(equalTo: view.trailingAnchor),\n contentView.bottomAnchor.constraint(equalTo: view.bottomAnchor),\n ])\n\n contentView.disconnectButton.addTarget(\n self,\n action: #selector(handleDisconnect(_:)),\n for: .touchUpInside\n )\n contentView.purchaseButton.addTarget(\n self,\n action: #selector(requestStoreProducts),\n for: .touchUpInside\n )\n contentView.restoreButton.addTarget(\n self,\n action: #selector(restorePurchases),\n for: .touchUpInside\n )\n\n interactor.didReceiveTunnelStatus = { [weak self] _ in\n Task { @MainActor in\n self?.setNeedsHeaderBarStyleAppearanceUpdate()\n self?.applyViewState()\n }\n }\n applyViewState()\n }\n\n override func viewDidAppear(_ animated: Bool) {\n super.viewDidAppear(animated)\n interactor.startAccountUpdateTimer()\n }\n\n override func viewDidDisappear(_ animated: Bool) {\n super.viewDidDisappear(animated)\n interactor.stopAccountUpdateTimer()\n }\n\n // MARK: - Private\n\n private func applyViewState() {\n let tunnelState = interactor.tunnelStatus.state\n contentView.enableDisconnectButton(tunnelState.isSecured, animated: true)\n\n if tunnelState.isSecured {\n contentView.setBodyLabelText(\n NSLocalizedString(\n "OUT_OF_TIME_BODY_CONNECTED",\n tableName: "OutOfTime",\n value: """\n You have no more VPN time left on this account. To add more, you will need to \\n disconnect and access the Internet with an unsecure connection.\n """,\n comment: ""\n )\n )\n } else {\n contentView.setBodyLabelText(\n NSLocalizedString(\n "OUT_OF_TIME_BODY_DISCONNECTED",\n tableName: "OutOfTime",\n value: """\n You have no more VPN time left on this account. Either buy credit on our website \\n or make an in-app purchase via the **Add time** button below.\n """,\n comment: ""\n )\n )\n }\n }\n\n // MARK: - Actions\n\n @objc private func requestStoreProducts() {\n guard let accountNumber = interactor.deviceState.accountData?.number else {\n return\n }\n delegate?.didRequestShowInAppPurchase(\n accountNumber: accountNumber,\n paymentAction: .purchase\n )\n }\n\n @objc func restorePurchases() {\n guard let accountNumber = interactor.deviceState.accountData?.number else {\n return\n }\n delegate?.didRequestShowInAppPurchase(\n accountNumber: accountNumber,\n paymentAction: .restorePurchase\n )\n }\n\n @objc private func handleDisconnect(_ sender: Any) {\n contentView.disconnectButton.isEnabled = false\n interactor.stopTunnel()\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\OutOfTime\OutOfTimeViewController.swift | OutOfTimeViewController.swift | Swift | 4,883 | 0.95 | 0.030675 | 0.065693 | python-kit | 384 | 2025-06-24T06:18:23.239454 | Apache-2.0 | false | bef80442c43e823f48a1406806dd132e |
//\n// ProblemReportInteractor.swift\n// MullvadVPN\n//\n// Created by pronebird on 25/10/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\nimport MullvadTypes\nimport Operations\n\nfinal class ProblemReportInteractor: @unchecked Sendable {\n private let apiProxy: APIQuerying\n private let tunnelManager: TunnelManager\n private let consolidatedLog: ConsolidatedApplicationLog\n private var reportedString = ""\n\n init(apiProxy: APIQuerying, tunnelManager: TunnelManager) {\n self.apiProxy = apiProxy\n self.tunnelManager = tunnelManager\n let redactCustomStrings = [tunnelManager.deviceState.accountData?.number].compactMap { $0 }\n self.consolidatedLog = ConsolidatedApplicationLog(\n redactCustomStrings: redactCustomStrings.isEmpty ? nil : redactCustomStrings,\n redactContainerPathsForSecurityGroupIdentifiers: [ApplicationConfiguration.securityGroupIdentifier],\n bufferSize: ApplicationConfiguration.logMaximumFileSize\n )\n }\n\n func fetchReportString(completion: @escaping @Sendable (String) -> Void) {\n consolidatedLog.addLogFiles(fileURLs: ApplicationTarget.allCases.flatMap {\n ApplicationConfiguration.logFileURLs(for: $0, in: ApplicationConfiguration.containerURL)\n }) { [weak self] in\n guard let self else { return }\n completion(consolidatedLog.string)\n }\n }\n\n func sendReport(\n email: String,\n message: String,\n completion: @escaping @Sendable (Result<Void, Error>) -> Void\n ) {\n let logString = self.consolidatedLog.string\n\n if logString.isEmpty {\n fetchReportString { [weak self] updatedLogString in\n self?.sendProblemReport(\n email: email,\n message: message,\n logString: updatedLogString,\n completion: completion\n )\n }\n } else {\n sendProblemReport(\n email: email,\n message: message,\n logString: logString,\n completion: completion\n )\n }\n }\n\n private func sendProblemReport(\n email: String,\n message: String,\n logString: String,\n completion: @escaping @Sendable (Result<Void, Error>) -> Void\n ) {\n let metadataDict = self.consolidatedLog.metadata.reduce(into: [:]) { output, entry in\n output[entry.key.rawValue] = entry.value\n }\n\n let request = ProblemReportRequest(\n address: email,\n message: message,\n log: logString,\n metadata: metadataDict\n )\n\n _ = self.apiProxy.sendProblemReport(request, retryStrategy: .default, completionHandler: { result in\n DispatchQueue.main.async {\n completion(result)\n }\n })\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\ProblemReport\ProblemReportInteractor.swift | ProblemReportInteractor.swift | Swift | 2,949 | 0.95 | 0.033708 | 0.0875 | node-utils | 115 | 2025-02-07T14:23:22.941003 | Apache-2.0 | false | d88602be0d076647b0ffaa68378c3482 |
//\n// ProblemReportReviewViewController.swift\n// MullvadVPN\n//\n// Created by pronebird on 10/02/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass ProblemReportReviewViewController: UIViewController {\n private let spinnerView = SpinnerActivityIndicatorView(style: .large)\n private var textView = UITextView()\n private let interactor: ProblemReportInteractor\n private lazy var spinnerContainerView: UIView = {\n let view = UIView()\n view.backgroundColor = .black.withAlphaComponent(0.5)\n return view\n }()\n\n init(interactor: ProblemReportInteractor) {\n self.interactor = interactor\n super.init(nibName: nil, bundle: nil)\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n override func viewDidLoad() {\n super.viewDidLoad()\n view.backgroundColor = .secondaryColor\n view.setAccessibilityIdentifier(.appLogsView)\n\n navigationItem.title = NSLocalizedString(\n "NAVIGATION_TITLE",\n tableName: "ProblemReportReview",\n value: "App logs",\n comment: ""\n )\n\n navigationItem.rightBarButtonItem = UIBarButtonItem(\n systemItem: .done,\n primaryAction: UIAction(handler: { [weak self] _ in\n self?.dismiss(animated: true)\n })\n )\n navigationItem.rightBarButtonItem?.setAccessibilityIdentifier(.appLogsDoneButton)\n\n #if DEBUG\n navigationItem.leftBarButtonItem = UIBarButtonItem(\n systemItem: .action,\n primaryAction: UIAction(handler: { [weak self] _ in\n self?.share()\n })\n )\n navigationItem.leftBarButtonItem?.setAccessibilityIdentifier(.appLogsShareButton)\n #endif\n\n textView.setAccessibilityIdentifier(.problemReportAppLogsTextView)\n textView.translatesAutoresizingMaskIntoConstraints = false\n textView.isEditable = false\n textView.font = UIFont.monospacedSystemFont(\n ofSize: UIFont.systemFontSize,\n weight: .regular\n )\n textView.backgroundColor = .systemBackground\n\n view.addConstrainedSubviews([textView]) {\n textView.pinEdgesToSuperview(.all().excluding(.top))\n textView.pinEdgeToSuperviewMargin(.top(0))\n }\n\n textView.addConstrainedSubviews([spinnerContainerView]) {\n spinnerContainerView.pinEdgesToSuperview()\n spinnerContainerView.widthAnchor.constraint(equalTo: textView.widthAnchor)\n spinnerContainerView.heightAnchor.constraint(equalTo: textView.heightAnchor)\n }\n\n spinnerContainerView.addConstrainedSubviews([spinnerView]) {\n spinnerView.centerXAnchor.constraint(equalTo: view.centerXAnchor)\n spinnerView.centerYAnchor.constraint(equalTo: view.centerYAnchor)\n }\n\n // Used to layout constraints so that navigation controller could properly adjust the text\n // view insets.\n view.layoutIfNeeded()\n\n loadLogs()\n }\n\n override func selectAll(_ sender: Any?) {\n textView.selectAll(sender)\n }\n\n private func loadLogs() {\n spinnerView.startAnimating()\n interactor.fetchReportString { [weak self] reportString in\n guard let self else { return }\n Task { @MainActor in\n textView.text = reportString\n spinnerView.stopAnimating()\n spinnerContainerView.isHidden = true\n }\n }\n }\n\n #if DEBUG\n private func share() {\n interactor.fetchReportString { [weak self] reportString in\n guard let self,!reportString.isEmpty else { return }\n Task { @MainActor in\n let activityController = UIActivityViewController(\n activityItems: [reportString],\n applicationActivities: nil\n )\n\n activityController.popoverPresentationController?.barButtonItem = navigationItem.leftBarButtonItem\n\n present(activityController, animated: true)\n }\n }\n }\n #endif\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\ProblemReport\ProblemReportReviewViewController.swift | ProblemReportReviewViewController.swift | Swift | 4,187 | 0.95 | 0.024 | 0.122642 | node-utils | 276 | 2024-12-14T22:44:55.368550 | MIT | false | 8368da42c60e1c76e65675dea891f833 |
//\n// ProblemReportSubmissionOverlayView.swift\n// MullvadVPN\n//\n// Created by pronebird on 12/02/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\nimport UIKit\n\nclass ProblemReportSubmissionOverlayView: UIView {\n var editButtonAction: (() -> Void)?\n var retryButtonAction: (() -> Void)?\n\n enum State {\n case sending\n case sent(_ email: String)\n case failure(Error)\n\n var title: String? {\n switch self {\n case .sending:\n return NSLocalizedString(\n "SUBMISSION_STATUS_SENDING",\n tableName: "ProblemReport",\n value: "Sending...",\n comment: ""\n )\n case .sent:\n return NSLocalizedString(\n "SUBMISSION_STATUS_SENT",\n tableName: "ProblemReport",\n value: "Sent",\n comment: ""\n )\n case .failure:\n return NSLocalizedString(\n "SUBMISSION_STATUS_FAILURE",\n tableName: "ProblemReport",\n value: "Failed to send",\n comment: ""\n )\n }\n }\n\n var body: NSAttributedString? {\n switch self {\n case .sending:\n return nil\n case let .sent(email):\n let combinedAttributedString = NSMutableAttributedString(\n string: NSLocalizedString(\n "THANKS_MESSAGE",\n tableName: "ProblemReport",\n value: "Thanks!",\n comment: ""\n ),\n attributes: [.foregroundColor: UIColor.successColor]\n )\n\n if email.isEmpty {\n combinedAttributedString.append(NSAttributedString(string: " "))\n combinedAttributedString.append(\n NSAttributedString(\n string: NSLocalizedString(\n "WE_WILL_LOOK_INTO_THIS_MESSAGE",\n tableName: "ProblemReport",\n value: "We will look into this.",\n comment: ""\n )\n )\n )\n } else {\n let emailText = String(\n format: NSLocalizedString(\n "CONTACT_BACK_EMAIL_MESSAGE_FORMAT",\n tableName: "ProblemReport",\n value: "If needed we will contact you at %@",\n comment: ""\n ), email\n )\n let emailAttributedString = NSMutableAttributedString(string: emailText)\n if let emailRange = emailText.range(of: email) {\n let font = UIFont.systemFont(ofSize: 17, weight: .bold)\n let nsRange = NSRange(emailRange, in: emailText)\n\n emailAttributedString.addAttribute(.font, value: font, range: nsRange)\n }\n\n combinedAttributedString.append(NSAttributedString(string: " "))\n combinedAttributedString.append(emailAttributedString)\n }\n\n return combinedAttributedString\n\n case let .failure(error):\n if let error = error as? REST.Error {\n return error.displayErrorDescription.flatMap { NSAttributedString(string: $0) }\n } else {\n return NSAttributedString(string: error.localizedDescription)\n }\n }\n }\n }\n\n var state: State = .sending {\n didSet {\n transitionToState(state)\n }\n }\n\n let activityIndicator: SpinnerActivityIndicatorView = {\n let indicator = SpinnerActivityIndicatorView(style: .large)\n indicator.tintColor = .white\n return indicator\n }()\n\n let statusImageView = StatusImageView(style: .success)\n\n let titleLabel: UILabel = {\n let textLabel = UILabel()\n textLabel.font = UIFont.systemFont(ofSize: 32)\n textLabel.textColor = .white\n textLabel.numberOfLines = 0\n return textLabel\n }()\n\n let bodyLabel: UILabel = {\n let textLabel = UILabel()\n textLabel.font = UIFont.systemFont(ofSize: 17)\n textLabel.textColor = .white\n textLabel.numberOfLines = 0\n return textLabel\n }()\n\n /// Footer stack view that contains action buttons\n private lazy var buttonsStackView: UIStackView = {\n let stackView = UIStackView(arrangedSubviews: [self.editMessageButton, self.tryAgainButton])\n stackView.translatesAutoresizingMaskIntoConstraints = false\n stackView.axis = .vertical\n stackView.spacing = 18\n\n return stackView\n }()\n\n private lazy var editMessageButton: AppButton = {\n let button = AppButton(style: .default)\n button.translatesAutoresizingMaskIntoConstraints = false\n button.setTitle(NSLocalizedString(\n "EDIT_MESSAGE_BUTTON",\n tableName: "ProblemReport",\n value: "Edit message",\n comment: ""\n ), for: .normal)\n button.addTarget(self, action: #selector(handleEditButton), for: .touchUpInside)\n return button\n }()\n\n private lazy var tryAgainButton: AppButton = {\n let button = AppButton(style: .success)\n button.translatesAutoresizingMaskIntoConstraints = false\n button.setTitle(NSLocalizedString(\n "TRY_AGAIN_BUTTON",\n tableName: "ProblemReport",\n value: "Try again",\n comment: ""\n ), for: .normal)\n button.addTarget(self, action: #selector(handleRetryButton), for: .touchUpInside)\n return button\n }()\n\n override init(frame: CGRect) {\n super.init(frame: frame)\n\n setAccessibilityIdentifier(.problemReportSubmittedView)\n\n addSubviews()\n transitionToState(state)\n\n directionalLayoutMargins = UIMetrics.contentLayoutMargins\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n private func addSubviews() {\n for subview in [\n titleLabel,\n bodyLabel,\n activityIndicator,\n statusImageView,\n buttonsStackView,\n ] {\n subview.translatesAutoresizingMaskIntoConstraints = false\n addSubview(subview)\n }\n\n NSLayoutConstraint.activate([\n statusImageView.topAnchor.constraint(\n equalTo: layoutMarginsGuide.topAnchor,\n constant: 32\n ),\n statusImageView.centerXAnchor.constraint(equalTo: centerXAnchor),\n\n activityIndicator.centerXAnchor.constraint(equalTo: statusImageView.centerXAnchor),\n activityIndicator.centerYAnchor.constraint(equalTo: statusImageView.centerYAnchor),\n\n titleLabel.topAnchor.constraint(equalTo: statusImageView.bottomAnchor, constant: 60),\n titleLabel.leadingAnchor.constraint(equalTo: layoutMarginsGuide.leadingAnchor),\n titleLabel.trailingAnchor.constraint(equalTo: layoutMarginsGuide.trailingAnchor),\n\n bodyLabel.topAnchor.constraint(\n equalToSystemSpacingBelow: titleLabel.bottomAnchor,\n multiplier: 1\n ),\n bodyLabel.leadingAnchor.constraint(equalTo: layoutMarginsGuide.leadingAnchor),\n bodyLabel.trailingAnchor.constraint(equalTo: layoutMarginsGuide.trailingAnchor),\n buttonsStackView.topAnchor.constraint(\n greaterThanOrEqualTo: bodyLabel.bottomAnchor,\n constant: 18\n ),\n\n buttonsStackView.leadingAnchor.constraint(equalTo: layoutMarginsGuide.leadingAnchor),\n buttonsStackView.trailingAnchor.constraint(equalTo: layoutMarginsGuide.trailingAnchor),\n buttonsStackView.bottomAnchor.constraint(equalTo: layoutMarginsGuide.bottomAnchor),\n ])\n }\n\n private func transitionToState(_ state: State) {\n titleLabel.text = state.title\n bodyLabel.attributedText = state.body\n\n switch state {\n case .sending:\n activityIndicator.startAnimating()\n statusImageView.isHidden = true\n buttonsStackView.isHidden = true\n\n case .sent:\n activityIndicator.stopAnimating()\n statusImageView.style = .success\n statusImageView.isHidden = false\n buttonsStackView.isHidden = true\n\n case .failure:\n activityIndicator.stopAnimating()\n statusImageView.style = .failure\n statusImageView.isHidden = false\n buttonsStackView.isHidden = false\n }\n }\n\n // MARK: - Actions\n\n @objc private func handleEditButton() {\n editButtonAction?()\n }\n\n @objc private func handleRetryButton() {\n retryButtonAction?()\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\ProblemReport\ProblemReportSubmissionOverlayView.swift | ProblemReportSubmissionOverlayView.swift | Swift | 9,208 | 0.95 | 0.045283 | 0.039474 | vue-tools | 952 | 2023-09-23T18:06:46.529258 | Apache-2.0 | false | a1a47af84f32ce7042169a81e6f77e18 |
//\n// ProblemReportViewController+ViewManagement.swift\n// MullvadVPN\n//\n// Created by Marco Nikic on 2024-02-09.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport UIKit\n\nextension ProblemReportViewController {\n func makeScrollView() -> UIScrollView {\n let scrollView = UIScrollView()\n scrollView.translatesAutoresizingMaskIntoConstraints = false\n scrollView.backgroundColor = .clear\n return scrollView\n }\n\n func makeContainerView() -> UIView {\n let containerView = UIView()\n containerView.translatesAutoresizingMaskIntoConstraints = false\n containerView.directionalLayoutMargins = UIMetrics.contentLayoutMargins\n containerView.backgroundColor = .clear\n return containerView\n }\n\n func makeSubheaderLabel() -> UILabel {\n let textLabel = UILabel()\n textLabel.translatesAutoresizingMaskIntoConstraints = false\n textLabel.numberOfLines = 0\n textLabel.textColor = .white\n textLabel.text = Self.persistentViewModel.subheadLabelText\n return textLabel\n }\n\n func makeEmailTextField() -> CustomTextField {\n let textField = CustomTextField()\n textField.translatesAutoresizingMaskIntoConstraints = false\n textField.delegate = self\n textField.keyboardType = .emailAddress\n textField.textContentType = .emailAddress\n textField.autocorrectionType = .no\n textField.autocapitalizationType = .none\n textField.smartInsertDeleteType = .no\n textField.returnKeyType = .next\n textField.borderStyle = .none\n textField.backgroundColor = .white\n textField.inputAccessoryView = emailAccessoryToolbar\n textField.font = UIFont.systemFont(ofSize: 17)\n textField.placeholder = Self.persistentViewModel.emailPlaceholderText\n return textField\n }\n\n func makeMessageTextView() -> CustomTextView {\n let textView = CustomTextView()\n textView.translatesAutoresizingMaskIntoConstraints = false\n textView.backgroundColor = .white\n textView.inputAccessoryView = messageAccessoryToolbar\n textView.font = UIFont.systemFont(ofSize: 17)\n textView.placeholder = Self.persistentViewModel.messageTextViewPlaceholder\n textView.contentInsetAdjustmentBehavior = .never\n\n return textView\n }\n\n func makeTextFieldsHolder() -> UIView {\n let view = UIView()\n view.translatesAutoresizingMaskIntoConstraints = false\n return view\n }\n\n func makeMessagePlaceholderView() -> UIView {\n let view = UIView()\n view.translatesAutoresizingMaskIntoConstraints = false\n view.backgroundColor = .clear\n return view\n }\n\n func makeButtonsStackView() -> UIStackView {\n let stackView = UIStackView(arrangedSubviews: [self.viewLogsButton, self.sendButton])\n stackView.translatesAutoresizingMaskIntoConstraints = false\n stackView.axis = .vertical\n stackView.spacing = 18\n\n return stackView\n }\n\n func makeViewLogsButton() -> AppButton {\n let button = AppButton(style: .default)\n button.setAccessibilityIdentifier(.problemReportAppLogsButton)\n button.translatesAutoresizingMaskIntoConstraints = false\n button.setTitle(Self.persistentViewModel.viewLogsButtonTitle, for: .normal)\n button.addTarget(self, action: #selector(handleViewLogsButtonTap), for: .touchUpInside)\n return button\n }\n\n func makeSendButton() -> AppButton {\n let button = AppButton(style: .success)\n button.setAccessibilityIdentifier(.problemReportSendButton)\n button.translatesAutoresizingMaskIntoConstraints = false\n button.setTitle(Self.persistentViewModel.sendLogsButtonTitle, for: .normal)\n button.addTarget(self, action: #selector(handleSendButtonTap), for: .touchUpInside)\n return button\n }\n\n func makeSubmissionOverlayView() -> ProblemReportSubmissionOverlayView {\n let overlay = ProblemReportSubmissionOverlayView()\n overlay.translatesAutoresizingMaskIntoConstraints = false\n\n overlay.editButtonAction = { [weak self] in\n self?.hideSubmissionOverlay()\n }\n\n overlay.retryButtonAction = { [weak self] in\n self?.sendProblemReport()\n }\n\n return overlay\n }\n\n func addConstraints() {\n activeMessageTextViewConstraints =\n messageTextView.pinEdges(.all().excluding(.top), to: view) +\n messageTextView.pinEdges(PinnableEdges([.top(0)]), to: view.safeAreaLayoutGuide)\n\n inactiveMessageTextViewConstraints =\n messageTextView.pinEdges(.all().excluding(.top), to: textFieldsHolder) +\n [messageTextView.topAnchor.constraint(equalTo: emailTextField.bottomAnchor, constant: 12)]\n\n textFieldsHolder.addSubview(emailTextField)\n textFieldsHolder.addSubview(messagePlaceholder)\n textFieldsHolder.addSubview(messageTextView)\n\n scrollView.addSubview(containerView)\n containerView.addSubview(subheaderLabel)\n containerView.addSubview(textFieldsHolder)\n containerView.addSubview(buttonsStackView)\n\n view.addConstrainedSubviews([scrollView]) {\n inactiveMessageTextViewConstraints\n\n subheaderLabel.pinEdges(.all().excluding(.bottom), to: containerView.layoutMarginsGuide)\n\n textFieldsHolder.pinEdges(PinnableEdges([.leading(0), .trailing(0)]), to: containerView.layoutMarginsGuide)\n textFieldsHolder.topAnchor.constraint(equalTo: subheaderLabel.bottomAnchor, constant: 24)\n\n buttonsStackView.pinEdges(.all().excluding(.top), to: containerView.layoutMarginsGuide)\n buttonsStackView.topAnchor.constraint(equalTo: textFieldsHolder.bottomAnchor, constant: 18)\n\n emailTextField.pinEdges(.all().excluding(.bottom), to: textFieldsHolder)\n\n messagePlaceholder.pinEdges(.all().excluding(.top), to: textFieldsHolder)\n messagePlaceholder.topAnchor.constraint(equalTo: emailTextField.bottomAnchor, constant: 12)\n messagePlaceholder.heightAnchor.constraint(equalTo: messageTextView.heightAnchor)\n\n scrollView.frameLayoutGuide.topAnchor.constraint(equalTo: view.topAnchor)\n scrollView.frameLayoutGuide.bottomAnchor.constraint(equalTo: view.bottomAnchor)\n scrollView.frameLayoutGuide.leadingAnchor.constraint(equalTo: view.leadingAnchor)\n scrollView.frameLayoutGuide.trailingAnchor.constraint(equalTo: view.trailingAnchor)\n\n scrollView.contentLayoutGuide.topAnchor.constraint(equalTo: containerView.topAnchor)\n scrollView.contentLayoutGuide.bottomAnchor.constraint(equalTo: containerView.bottomAnchor)\n scrollView.contentLayoutGuide.leadingAnchor.constraint(equalTo: containerView.leadingAnchor)\n scrollView.contentLayoutGuide.trailingAnchor.constraint(equalTo: containerView.trailingAnchor)\n scrollView.contentLayoutGuide.widthAnchor.constraint(equalTo: scrollView.frameLayoutGuide.widthAnchor)\n scrollView.contentLayoutGuide.heightAnchor\n .constraint(greaterThanOrEqualTo: scrollView.safeAreaLayoutGuide.heightAnchor)\n\n messageTextView.heightAnchor.constraint(greaterThanOrEqualToConstant: 150)\n }\n }\n\n override func viewSafeAreaInsetsDidChange() {\n super.viewSafeAreaInsetsDidChange()\n\n scrollViewKeyboardResponder?.updateContentInsets()\n textViewKeyboardResponder?.updateContentInsets()\n }\n\n func makeKeyboardToolbar(canGoBackward: Bool, canGoForward: Bool) -> UIToolbar {\n var toolbarItems = UIBarButtonItem.makeKeyboardNavigationItems { prevButton, nextButton in\n prevButton.target = self\n prevButton.action = #selector(focusEmailTextField)\n prevButton.isEnabled = canGoBackward\n\n nextButton.target = self\n nextButton.action = #selector(focusDescriptionTextView)\n nextButton.isEnabled = canGoForward\n }\n\n toolbarItems.append(contentsOf: [\n UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),\n UIBarButtonItem(\n barButtonSystemItem: .done,\n target: self,\n action: #selector(dismissKeyboard)\n ),\n ])\n\n let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: 100, height: 44))\n toolbar.items = toolbarItems\n return toolbar\n }\n\n func setDescriptionFieldExpanded(_ isExpanded: Bool) {\n // Make voice over ignore siblings when expanded\n messageTextView.accessibilityViewIsModal = isExpanded\n\n if isExpanded {\n // Disable the large title\n navigationItem.largeTitleDisplayMode = .never\n\n // Move the text view above scroll view\n view.addSubview(messageTextView)\n\n // Re-add old constraints\n NSLayoutConstraint.activate(inactiveMessageTextViewConstraints)\n\n // Do a layout pass\n view.layoutIfNeeded()\n\n // Swap constraints\n NSLayoutConstraint.deactivate(inactiveMessageTextViewConstraints)\n NSLayoutConstraint.activate(activeMessageTextViewConstraints)\n\n // Enable content inset adjustment on text view\n messageTextView.contentInsetAdjustmentBehavior = .always\n\n // Animate constraints & rounded corners on the text view\n animateDescriptionTextView(animations: {\n // Turn off rounded corners as the text view fills in the entire view\n self.messageTextView.roundCorners = false\n\n self.view.layoutIfNeeded()\n }, completion: { _ in\n self.isMessageTextViewExpanded = true\n\n self.textViewKeyboardResponder?.updateContentInsets()\n\n // Tell accessibility engine to scan the new layout\n UIAccessibility.post(notification: .layoutChanged, argument: nil)\n })\n\n } else {\n // Re-enable the large title\n navigationItem.largeTitleDisplayMode = .automatic\n\n // Swap constraints\n NSLayoutConstraint.deactivate(activeMessageTextViewConstraints)\n NSLayoutConstraint.activate(inactiveMessageTextViewConstraints)\n\n // Animate constraints & rounded corners on the text view\n animateDescriptionTextView(animations: {\n // Turn on rounded corners as the text view returns back to where it was\n self.messageTextView.roundCorners = true\n\n self.view.layoutIfNeeded()\n }, completion: { _ in\n // Revert the content adjustment behavior\n self.messageTextView.contentInsetAdjustmentBehavior = .never\n\n // Add the text view inside of the scroll view\n self.textFieldsHolder.addSubview(self.messageTextView)\n\n self.isMessageTextViewExpanded = false\n\n // Tell accessibility engine to scan the new layout\n UIAccessibility.post(notification: .layoutChanged, argument: nil)\n })\n }\n }\n\n func animateDescriptionTextView(\n animations: @escaping () -> Void,\n completion: @escaping (Bool) -> Void\n ) {\n UIView.animate(withDuration: 0.25, animations: animations) { completed in\n completion(completed)\n }\n }\n\n func showSubmissionOverlay() {\n guard !showsSubmissionOverlay else { return }\n\n showsSubmissionOverlay = true\n\n view.addSubview(submissionOverlayView)\n\n NSLayoutConstraint.activate([\n submissionOverlayView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),\n submissionOverlayView.leadingAnchor\n .constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),\n submissionOverlayView.trailingAnchor\n .constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor),\n submissionOverlayView.bottomAnchor\n .constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),\n ])\n\n UIView.transition(\n from: scrollView,\n to: submissionOverlayView,\n duration: 0.25,\n options: [.showHideTransitionViews, .transitionCrossDissolve]\n ) { _ in\n // success\n }\n }\n\n func hideSubmissionOverlay() {\n guard showsSubmissionOverlay else { return }\n\n showsSubmissionOverlay = false\n\n UIView.transition(\n from: submissionOverlayView,\n to: scrollView,\n duration: 0.25,\n options: [.showHideTransitionViews, .transitionCrossDissolve]\n ) { _ in\n // success\n self.submissionOverlayView.removeFromSuperview()\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\ProblemReport\ProblemReportViewController+ViewManagement.swift | ProblemReportViewController+ViewManagement.swift | Swift | 12,890 | 0.95 | 0.015385 | 0.099237 | python-kit | 382 | 2024-07-12T23:09:53.525998 | MIT | false | cef24566cff248864a3ac2fe4326d545 |
//\n// ProblemReportViewController.swift\n// MullvadVPN\n//\n// Created by pronebird on 15/09/2020.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadREST\nimport MullvadTypes\nimport Operations\nimport UIKit\n\nfinal class ProblemReportViewController: UIViewController, UITextFieldDelegate {\n private let interactor: ProblemReportInteractor\n private let alertPresenter: AlertPresenter\n\n var textViewKeyboardResponder: AutomaticKeyboardResponder?\n var scrollViewKeyboardResponder: AutomaticKeyboardResponder?\n var showsSubmissionOverlay = false\n\n /// Constraints used when description text view is active\n var activeMessageTextViewConstraints = [NSLayoutConstraint]()\n /// Constraints used when description text view is inactive\n var inactiveMessageTextViewConstraints = [NSLayoutConstraint]()\n /// Flag indicating when the text view is expanded to fill the entire view\n var isMessageTextViewExpanded = false\n\n static var persistentViewModel = ProblemReportViewModel()\n\n /// Scroll view\n lazy var scrollView: UIScrollView = { makeScrollView() }()\n /// Scroll view content container\n lazy var containerView: UIView = { makeContainerView() }()\n /// Subheading label displayed below navigation bar\n lazy var subheaderLabel: UILabel = { makeSubheaderLabel() }()\n lazy var emailTextField: CustomTextField = { makeEmailTextField() }()\n lazy var messageTextView: CustomTextView = { makeMessageTextView() }()\n /// Container view for text input fields\n lazy var textFieldsHolder: UIView = { makeTextFieldsHolder() }()\n /// Placeholder view used to fill the space within the scroll view when the text view is\n /// expanded to fill the entire view\n lazy var messagePlaceholder: UIView = { makeMessagePlaceholderView() }()\n /// Footer stack view that contains action buttons\n lazy var buttonsStackView: UIStackView = { makeButtonsStackView() }()\n lazy var viewLogsButton: AppButton = { makeViewLogsButton() }()\n lazy var sendButton: AppButton = { makeSendButton() }()\n lazy var emailAccessoryToolbar: UIToolbar = makeKeyboardToolbar(\n canGoBackward: false,\n canGoForward: true\n )\n lazy var messageAccessoryToolbar: UIToolbar = makeKeyboardToolbar(\n canGoBackward: true,\n canGoForward: false\n )\n\n lazy var submissionOverlayView: ProblemReportSubmissionOverlayView = { makeSubmissionOverlayView() }()\n\n // MARK: - View lifecycle\n\n override var preferredStatusBarStyle: UIStatusBarStyle { .lightContent }\n // Allow dismissing the keyboard in .formSheet presentation style\n override var disablesAutomaticKeyboardDismissal: Bool { false }\n\n init(interactor: ProblemReportInteractor, alertPresenter: AlertPresenter) {\n self.interactor = interactor\n self.alertPresenter = alertPresenter\n\n super.init(nibName: nil, bundle: nil)\n }\n\n required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }\n\n override func viewDidLoad() {\n super.viewDidLoad()\n\n view.backgroundColor = .secondaryColor\n view.setAccessibilityIdentifier(.problemReportView)\n\n navigationItem.title = Self.persistentViewModel.navigationTitle\n\n textViewKeyboardResponder = AutomaticKeyboardResponder(targetView: messageTextView)\n scrollViewKeyboardResponder = AutomaticKeyboardResponder(targetView: scrollView)\n\n // Make sure that the user can't easily dismiss the controller on iOS 13 and above\n isModalInPresentation = true\n\n // Set hugging & compression priorities so that description text view wants to grow\n emailTextField.setContentHuggingPriority(.defaultHigh, for: .vertical)\n emailTextField.setContentCompressionResistancePriority(.defaultHigh, for: .vertical)\n messageTextView.setContentHuggingPriority(.defaultLow, for: .vertical)\n messageTextView.setContentCompressionResistancePriority(.defaultLow, for: .vertical)\n\n emailTextField.setAccessibilityIdentifier(.problemReportEmailTextField)\n messageTextView.setAccessibilityIdentifier(.problemReportMessageTextView)\n\n addConstraints()\n registerForNotifications()\n loadPersistentViewModel()\n }\n\n // MARK: - Actions\n\n @objc func focusEmailTextField() {\n emailTextField.becomeFirstResponder()\n }\n\n @objc func focusDescriptionTextView() {\n messageTextView.becomeFirstResponder()\n }\n\n @objc func dismissKeyboard() {\n view.endEditing(false)\n }\n\n @objc func handleSendButtonTap() {\n let proceedWithSubmission = {\n self.sendProblemReport()\n }\n\n if Self.persistentViewModel.email.isEmpty {\n presentEmptyEmailConfirmationAlert { shouldSend in\n if shouldSend {\n proceedWithSubmission()\n }\n }\n } else {\n proceedWithSubmission()\n }\n }\n\n @objc func handleViewLogsButtonTap() {\n let reviewController = ProblemReportReviewViewController(interactor: interactor)\n let navigationController = CustomNavigationController(rootViewController: reviewController)\n\n present(navigationController, animated: true)\n }\n\n // MARK: - Private\n\n private func registerForNotifications() {\n let notificationCenter = NotificationCenter.default\n notificationCenter.addObserver(\n self,\n selector: #selector(emailTextFieldDidChange),\n name: UITextField.textDidChangeNotification,\n object: emailTextField\n )\n notificationCenter.addObserver(\n self,\n selector: #selector(messageTextViewDidBeginEditing),\n name: UITextView.textDidBeginEditingNotification,\n object: messageTextView\n )\n notificationCenter.addObserver(\n self,\n selector: #selector(messageTextViewDidEndEditing),\n name: UITextView.textDidEndEditingNotification,\n object: messageTextView\n )\n notificationCenter.addObserver(\n self,\n selector: #selector(messageTextViewDidChange),\n name: UITextView.textDidChangeNotification,\n object: messageTextView\n )\n }\n\n private func presentEmptyEmailConfirmationAlert(completion: @escaping (Bool) -> Void) {\n let presentation = AlertPresentation(\n id: "problem-report-alert",\n icon: .alert,\n message: Self.persistentViewModel.emptyEmailAlertWarning,\n buttons: [\n AlertAction(\n title: Self.persistentViewModel.confirmEmptyEmailTitle,\n style: .destructive,\n handler: {\n completion(true)\n }\n ),\n AlertAction(\n title: Self.persistentViewModel.cancelEmptyEmailTitle,\n style: .default,\n handler: {\n completion(false)\n }\n ),\n ]\n )\n\n alertPresenter.showAlert(presentation: presentation, animated: true)\n }\n\n // MARK: - Data model\n\n private func loadPersistentViewModel() {\n emailTextField.text = Self.persistentViewModel.email\n messageTextView.text = Self.persistentViewModel.message\n\n validateForm()\n }\n\n private func updatePersistentViewModel() {\n Self.persistentViewModel = ProblemReportViewModel(\n email: emailTextField.text ?? "",\n message: messageTextView.text\n )\n\n validateForm()\n }\n\n private func setPopGestureEnabled(_ isEnabled: Bool) {\n navigationController?.interactivePopGestureRecognizer?.isEnabled = isEnabled\n }\n\n private func clearPersistentViewModel() {\n Self.persistentViewModel = ProblemReportViewModel()\n }\n\n // MARK: - Form validation\n\n private func validateForm() {\n sendButton.isEnabled = Self.persistentViewModel.isValid\n }\n\n // MARK: - Problem submission progress handling\n\n private func willSendProblemReport() {\n showSubmissionOverlay()\n\n submissionOverlayView.state = .sending\n navigationItem.setHidesBackButton(true, animated: true)\n }\n\n private func didSendProblemReport(\n viewModel: ProblemReportViewModel,\n completion: Result<Void, Error>\n ) {\n switch completion {\n case .success:\n submissionOverlayView.state = .sent(viewModel.email)\n\n // Clear persistent view model upon successful submission\n clearPersistentViewModel()\n\n case let .failure(error):\n submissionOverlayView.state = .failure(error)\n }\n\n navigationItem.setHidesBackButton(false, animated: true)\n }\n\n // MARK: - Problem report submission helpers\n\n func sendProblemReport() {\n let viewModel = Self.persistentViewModel\n\n willSendProblemReport()\n\n interactor.sendReport(\n email: viewModel.email,\n message: viewModel.message\n ) { completion in\n Task { @MainActor in\n self.didSendProblemReport(viewModel: viewModel, completion: completion)\n }\n }\n }\n\n // MARK: - Input fields notifications\n\n @objc private func messageTextViewDidBeginEditing() {\n setDescriptionFieldExpanded(true)\n setPopGestureEnabled(false)\n }\n\n @objc private func messageTextViewDidEndEditing() {\n setDescriptionFieldExpanded(false)\n setPopGestureEnabled(true)\n }\n\n @objc private func messageTextViewDidChange() {\n updatePersistentViewModel()\n }\n\n @objc private func emailTextFieldDidChange() {\n updatePersistentViewModel()\n }\n\n // MARK: - UITextFieldDelegate\n\n func textFieldDidBeginEditing(_ textField: UITextField) {\n setPopGestureEnabled(false)\n }\n\n func textFieldDidEndEditing(_ textField: UITextField) {\n setPopGestureEnabled(true)\n }\n\n func textFieldShouldReturn(_ textField: UITextField) -> Bool {\n messageTextView.becomeFirstResponder()\n return false\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\ProblemReport\ProblemReportViewController.swift | ProblemReportViewController.swift | Swift | 10,194 | 0.95 | 0.029508 | 0.122951 | react-lib | 985 | 2025-02-15T07:04:21.621406 | GPL-3.0 | false | c0a9d854f8c493ab6e7fc9f1e32b8ee3 |
//\n// ProblemReportViewModel.swift\n// MullvadVPN\n//\n// Created by Marco Nikic on 2024-02-09.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nstruct ProblemReportViewModel {\n let email: String\n let message: String\n\n let navigationTitle = NSLocalizedString(\n "NAVIGATION_TITLE",\n tableName: "ProblemReport",\n value: "Report a problem",\n comment: ""\n )\n\n let subheadLabelText = NSLocalizedString(\n "SUBHEAD_LABEL",\n tableName: "ProblemReport",\n value: """\n To help you more effectively, your app’s log file will be attached to \\n this message. Your data will remain secure and private, as it is anonymised \\n before being sent over an encrypted channel.\n """,\n comment: ""\n )\n\n let emailPlaceholderText = NSLocalizedString(\n "EMAIL_TEXTFIELD_PLACEHOLDER",\n tableName: "ProblemReport",\n value: "Your email (optional)",\n comment: ""\n )\n\n let messageTextViewPlaceholder = NSLocalizedString(\n "DESCRIPTION_TEXTVIEW_PLACEHOLDER",\n tableName: "ProblemReport",\n value: """\n To assist you better, please write in English or Swedish and \\n include which country you are connecting from.\n """,\n comment: ""\n )\n\n let viewLogsButtonTitle = NSLocalizedString(\n "VIEW_APP_LOGS_BUTTON_TITLE",\n tableName: "ProblemReport",\n value: "View app logs",\n comment: ""\n )\n\n let sendLogsButtonTitle = NSLocalizedString(\n "SEND_BUTTON_TITLE",\n tableName: "ProblemReport",\n value: "Send",\n comment: ""\n )\n\n let emptyEmailAlertWarning = NSLocalizedString(\n "EMPTY_EMAIL_ALERT_MESSAGE",\n tableName: "ProblemReport",\n value: """\n You are about to send the problem report without a way for us to get back to you. \\n If you want an answer to your report you will have to enter an email address.\n """,\n comment: ""\n )\n\n let confirmEmptyEmailTitle = NSLocalizedString(\n "EMPTY_EMAIL_ALERT_SEND_ANYWAY_ACTION",\n tableName: "ProblemReport",\n value: "Send anyway",\n comment: ""\n )\n\n let cancelEmptyEmailTitle = NSLocalizedString(\n "EMPTY_EMAIL_ALERT_CANCEL_ACTION",\n tableName: "ProblemReport",\n value: "Cancel",\n comment: ""\n )\n\n init() {\n email = ""\n message = ""\n }\n\n init(email: String, message: String) {\n self.email = email.trimmingCharacters(in: .whitespacesAndNewlines)\n self.message = message.trimmingCharacters(in: .whitespacesAndNewlines)\n }\n\n var isValid: Bool {\n !message.isEmpty\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\ProblemReport\ProblemReportViewModel.swift | ProblemReportViewModel.swift | Swift | 2,732 | 0.95 | 0.009901 | 0.08046 | react-lib | 10 | 2023-11-23T16:20:41.783295 | Apache-2.0 | false | 9e8a345cb081072ba901f57076ad3f30 |
//\n// AddCreditSucceededViewController.swift\n// MullvadVPN\n//\n// Created by Sajad Vishkai on 2022-09-23.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nprotocol AddCreditSucceededViewControllerDelegate: AnyObject {\n func header(in controller: AddCreditSucceededViewController) -> String\n\n func titleForAction(in controller: AddCreditSucceededViewController) -> String\n\n func addCreditSucceededViewControllerDidFinish(in controller: AddCreditSucceededViewController)\n}\n\nclass AddCreditSucceededViewController: UIViewController, RootContainment {\n private let statusImageView: StatusImageView = {\n let statusImageView = StatusImageView(style: .success)\n statusImageView.translatesAutoresizingMaskIntoConstraints = false\n return statusImageView\n }()\n\n private let titleLabel: UILabel = {\n let label = UILabel()\n label.font = UIFont.boldSystemFont(ofSize: 20)\n label.textColor = .white\n label.numberOfLines = 0\n label.translatesAutoresizingMaskIntoConstraints = false\n return label\n }()\n\n private let messageLabel: UILabel = {\n let label = UILabel()\n label.font = UIFont.systemFont(ofSize: 17)\n label.textColor = UIColor.white.withAlphaComponent(0.6)\n label.numberOfLines = 0\n label.translatesAutoresizingMaskIntoConstraints = false\n return label\n }()\n\n private let dismissButton: AppButton = {\n let button = AppButton(style: .default)\n button.translatesAutoresizingMaskIntoConstraints = false\n return button\n }()\n\n override var preferredStatusBarStyle: UIStatusBarStyle {\n .lightContent\n }\n\n var preferredHeaderBarPresentation: HeaderBarPresentation {\n HeaderBarPresentation(style: .default, showsDivider: true)\n }\n\n var prefersHeaderBarHidden: Bool {\n false\n }\n\n var prefersDeviceInfoBarHidden: Bool {\n true\n }\n\n weak var delegate: AddCreditSucceededViewControllerDelegate? {\n didSet {\n dismissButton.setTitle(delegate?.titleForAction(in: self), for: .normal)\n titleLabel.text = delegate?.header(in: self)\n }\n }\n\n init(timeAddedComponents: DateComponents) {\n super.init(nibName: nil, bundle: nil)\n\n view.backgroundColor = .secondaryColor\n view.directionalLayoutMargins = UIMetrics.contentLayoutMargins\n\n messageLabel.text = String(\n format: NSLocalizedString(\n "ADDED_TIME_SUCCESS_MESSAGE",\n tableName: "AddedTime",\n value: "%@ were added to your account.",\n comment: ""\n ),\n timeAddedComponents.formattedAddedDay\n )\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n override func viewDidLoad() {\n super.viewDidLoad()\n configureUI()\n addDismissButtonHandler()\n }\n\n private func configureUI() {\n let contentHolderView = UIView(frame: .zero)\n\n view.addConstrainedSubviews([contentHolderView]) {\n contentHolderView.pinEdgesToSuperview(.all(UIMetrics.SettingsRedeemVoucher.successfulRedeemMargins))\n }\n\n contentHolderView.addConstrainedSubviews([statusImageView, titleLabel, messageLabel, dismissButton]) {\n statusImageView.pinEdgesToSuperviewMargins(PinnableEdges([.top(0)]))\n statusImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor)\n\n titleLabel.pinEdgesToSuperviewMargins(PinnableEdges([.leading(0), .trailing(0)]))\n titleLabel.topAnchor.constraint(\n equalTo: statusImageView.bottomAnchor,\n constant: UIMetrics.TableView.sectionSpacing\n )\n\n messageLabel.topAnchor.constraint(\n equalTo: titleLabel.layoutMarginsGuide.bottomAnchor,\n constant: UIMetrics.interButtonSpacing\n )\n messageLabel.pinEdgesToSuperviewMargins(PinnableEdges([.leading(0), .trailing(0)]))\n\n dismissButton.pinEdgesToSuperviewMargins(.all().excluding(.top))\n }\n }\n\n private func addDismissButtonHandler() {\n dismissButton.addTarget(\n self,\n action: #selector(handleDismissTap),\n for: .touchUpInside\n )\n }\n\n @objc private func handleDismissTap() {\n delegate?.addCreditSucceededViewControllerDidFinish(in: self)\n }\n}\n\nprivate extension DateComponents {\n var formattedAddedDay: String {\n let formatter = DateComponentsFormatter()\n formatter.allowedUnits = [.day]\n formatter.unitsStyle = .full\n return formatter.string(from: self) ?? ""\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\RedeemVoucher\AddCreditSucceededViewController.swift | AddCreditSucceededViewController.swift | Swift | 4,732 | 0.95 | 0.020408 | 0.058333 | awesome-app | 545 | 2023-12-30T23:02:52.585263 | MIT | false | 4c61b0e598f9f576ee5ed3278d58648b |
//\n// LogoutDialogueView.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2023-08-29.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass LogoutDialogueView: UIView {\n private let containerView: UIView = {\n let view = UIView()\n view.backgroundColor = .secondaryColor\n view.layer.cornerRadius = 11\n view.directionalLayoutMargins = UIMetrics.CustomAlert.containerMargins\n view.clipsToBounds = true\n return view\n }()\n\n private let messageLabel: UILabel = {\n let label = UILabel()\n\n let message = NSMutableAttributedString(string: NSLocalizedString(\n "ACCOUNT_NUMBER_AS_VOUCHER_INPUT_ERROR_BODY",\n tableName: "CreateAccountRedeemingVoucher",\n value: """\n It looks like you have entered a Mullvad account number instead of a voucher code. \\n Do you want to log in to an existing account?\n If so, click log out below to log in with the other account number.\n """,\n comment: ""\n ))\n message.apply(paragraphStyle: .alert)\n\n label.attributedText = message\n label.font = .preferredFont(forTextStyle: .callout, weight: .semibold)\n label.numberOfLines = .zero\n label.textColor = .white\n\n return label\n }()\n\n private let logoutButton: AppButton = {\n let button = AppButton(style: .danger)\n button.setTitle(NSLocalizedString(\n "LOGOUT_BUTTON_TITLE",\n tableName: "CreateAccountRedeemingVoucher",\n value: "Log out",\n comment: ""\n ), for: .normal)\n return button\n }()\n\n private var showConstraint: NSLayoutConstraint?\n private var hideConstraint: NSLayoutConstraint?\n private var didRequestToLogOut: (LogoutDialogueView) -> Void\n\n var isLoading = true {\n didSet {\n logoutButton.isEnabled = !isLoading\n }\n }\n\n override var isHidden: Bool {\n willSet {\n if newValue == true {\n fadeOut()\n } else {\n fadeIn()\n }\n }\n }\n\n init(didRequestToLogOut: @escaping (LogoutDialogueView) -> Void) {\n self.didRequestToLogOut = didRequestToLogOut\n super.init(frame: .zero)\n setupAppearance()\n configureUI()\n addActions()\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n private func setupAppearance() {\n containerView.layer.cornerRadius = 11\n containerView.backgroundColor = .primaryColor\n }\n\n private func configureUI() {\n addConstrainedSubviews([containerView]) {\n containerView.pinEdgesToSuperview(.all().excluding(.bottom))\n }\n\n containerView.addConstrainedSubviews([messageLabel, logoutButton]) {\n messageLabel.pinEdgesToSuperviewMargins(.all().excluding(.bottom))\n logoutButton.pinEdgesToSuperviewMargins(.all().excluding(.top))\n logoutButton.topAnchor.constraint(\n equalTo: messageLabel.bottomAnchor,\n constant: UIMetrics.padding16\n ).withPriority(.defaultHigh)\n }\n\n showConstraint = containerView.bottomAnchor.constraint(equalTo: bottomAnchor)\n hideConstraint = containerView.bottomAnchor.constraint(equalTo: topAnchor)\n hideConstraint?.isActive = true\n }\n\n private func addActions() {\n logoutButton.addTarget(self, action: #selector(logout), for: .touchUpInside)\n }\n\n @objc private func logout() {\n didRequestToLogOut(self)\n }\n\n private func fadeIn() {\n guard hideConstraint?.isActive == true else { return }\n showConstraint?.isActive = true\n hideConstraint?.isActive = false\n animateWith(animations: {\n self.containerView.alpha = 1.0\n }, duration: 0.3, delay: 0.2)\n }\n\n private func fadeOut() {\n guard showConstraint?.isActive == true else { return }\n showConstraint?.isActive = false\n hideConstraint?.isActive = true\n animateWith(animations: {\n self.containerView.alpha = 0.0\n }, duration: 0.0, delay: 0.0)\n }\n\n private func animateWith(\n animations: @escaping () -> Void,\n duration: TimeInterval,\n delay: TimeInterval\n ) {\n UIView.animate(\n withDuration: duration,\n delay: delay,\n options: .curveEaseInOut,\n animations: {\n animations()\n self.layoutIfNeeded()\n },\n completion: nil\n )\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\RedeemVoucher\LogoutDialogueView.swift | LogoutDialogueView.swift | Swift | 4,633 | 0.95 | 0.026144 | 0.05303 | react-lib | 206 | 2024-01-24T07:08:21.691281 | MIT | false | 44b029f9d901d3d9a2be313abe3918f7 |
//\n// RedeemVoucherContentView.swift\n// MullvadVPN\n//\n// Created by Andreas Lif on 2022-08-05.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadREST\nimport UIKit\n\nenum RedeemVoucherState {\n case initial\n case success\n case verifying\n case failure(Error)\n case logout\n}\n\nfinal class RedeemVoucherContentView: UIView {\n // MARK: - private\n\n private let scrollView: UIScrollView = {\n let scrollView = UIScrollView()\n return scrollView\n }()\n\n private let contentHolderView: UIView = {\n let contentHolderView = UIView()\n return contentHolderView\n }()\n\n private let voucherTextFieldHeight: CGFloat = 54\n\n private let title: UILabel = {\n let label = UILabel()\n label.font = .preferredFont(forTextStyle: .title1, weight: .bold).withSize(32)\n label.text = NSLocalizedString(\n "REDEEM_VOUCHER_TITLE",\n tableName: "RedeemVoucher",\n value: "Redeem voucher",\n comment: ""\n )\n label.textColor = .white\n label.numberOfLines = 0\n return label\n }()\n\n private let enterVoucherLabel: UILabel = {\n let label = UILabel()\n label.font = .preferredFont(forTextStyle: .body, weight: .semibold).withSize(15)\n\n label.text = NSLocalizedString(\n "REDEEM_VOUCHER_INSTRUCTION",\n tableName: "RedeemVoucher",\n value: "Enter voucher code",\n comment: ""\n )\n label.textColor = .white\n label.numberOfLines = 0\n return label\n }()\n\n private let textField: VoucherTextField = {\n let textField = VoucherTextField()\n textField.font = UIFont.monospacedSystemFont(ofSize: 15, weight: .regular)\n textField.placeholder = Array(repeating: "XXXX", count: 4).joined(separator: "-")\n textField.placeholderTextColor = .lightGray\n textField.backgroundColor = .white\n textField.cornerRadius = UIMetrics.SettingsRedeemVoucher.cornerRadius\n textField.keyboardType = .asciiCapable\n textField.autocapitalizationType = .allCharacters\n textField.returnKeyType = .done\n textField.autocorrectionType = .no\n return textField\n }()\n\n private let activityIndicator: SpinnerActivityIndicatorView = {\n let activityIndicator = SpinnerActivityIndicatorView(style: .medium)\n activityIndicator.tintColor = .white\n activityIndicator.setContentHuggingPriority(.defaultHigh, for: .horizontal)\n activityIndicator.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)\n return activityIndicator\n }()\n\n private let statusLabel: UILabel = {\n let label = UILabel()\n label.font = .systemFont(ofSize: 13, weight: .semibold)\n label.numberOfLines = 2\n label.lineBreakMode = .byWordWrapping\n label.textColor = .red\n label.setContentHuggingPriority(.defaultLow, for: .horizontal)\n label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)\n label.lineBreakStrategy = []\n return label\n }()\n\n private lazy var logoutViewForAccountNumberIsEntered: LogoutDialogueView = {\n LogoutDialogueView { verifiedAccountView in\n verifiedAccountView.isLoading = true\n self.logoutAction?()\n }\n }()\n\n private let redeemButton: AppButton = {\n let button = AppButton(style: .success)\n button.setTitle(NSLocalizedString(\n "REDEEM_VOUCHER_REDEEM_BUTTON",\n tableName: "RedeemVoucher",\n value: "Redeem",\n comment: ""\n ), for: .normal)\n return button\n }()\n\n private let cancelButton: AppButton = {\n let button = AppButton(style: .default)\n button.setTitle(NSLocalizedString(\n "REDEEM_VOUCHER_CANCEL_BUTTON",\n tableName: "RedeemVoucher",\n value: "Cancel",\n comment: ""\n ), for: .normal)\n return button\n }()\n\n private lazy var statusStack: UIStackView = {\n let stackView = UIStackView(arrangedSubviews: [activityIndicator, statusLabel])\n stackView.spacing = UIMetrics.padding8\n return stackView\n }()\n\n private lazy var voucherCodeStackView: UIStackView = {\n var arrangedSubviews = [\n enterVoucherLabel,\n textField,\n statusStack,\n logoutViewForAccountNumberIsEntered,\n ]\n\n if configuration.shouldUseCompactStyle == false {\n arrangedSubviews.insert(title, at: 0)\n }\n\n let stackView = UIStackView(arrangedSubviews: arrangedSubviews)\n stackView.axis = .vertical\n stackView.setCustomSpacing(UIMetrics.padding8, after: title)\n stackView.setCustomSpacing(UIMetrics.padding16, after: enterVoucherLabel)\n stackView.setCustomSpacing(UIMetrics.padding8, after: textField)\n stackView.setCustomSpacing(UIMetrics.padding16, after: statusLabel)\n stackView.setCustomSpacing(UIMetrics.padding10, after: statusStack)\n stackView.setContentHuggingPriority(.defaultLow, for: .vertical)\n\n return stackView\n }()\n\n private lazy var buttonsStackView: UIStackView = {\n let stackView = UIStackView(arrangedSubviews: [redeemButton, cancelButton])\n stackView.axis = .vertical\n stackView.spacing = UIMetrics.padding16\n stackView.setContentCompressionResistancePriority(.required, for: .vertical)\n return stackView\n }()\n\n private var text: String {\n switch state {\n case let .failure(error):\n guard let restError = error as? REST.Error else {\n return error.localizedDescription\n }\n return restError.description\n case .verifying:\n return NSLocalizedString(\n "REDEEM_VOUCHER_STATUS_WAITING",\n tableName: "RedeemVoucher",\n value: "Verifying voucher...",\n comment: ""\n )\n case .logout:\n return NSLocalizedString(\n "REDEEM_VOUCHER_STATUS_WAITING",\n tableName: "RedeemVoucher",\n value: "Logging out...",\n comment: ""\n )\n default: return ""\n }\n }\n\n private var isRedeemButtonEnabled: Bool {\n switch state {\n case .initial, .failure:\n return true\n case .success, .verifying, .logout:\n return false\n }\n }\n\n private var textColor: UIColor {\n switch state {\n case .failure:\n return .dangerColor\n default:\n return .white\n }\n }\n\n private var isLoading: Bool {\n switch state {\n case .verifying, .logout:\n return true\n default:\n return false\n }\n }\n\n private var keyboardResponder: AutomaticKeyboardResponder?\n private var bottomsOfButtonsConstraint: NSLayoutConstraint?\n private let configuration: RedeemVoucherViewConfiguration\n\n // MARK: - public\n\n var redeemAction: ((String) -> Void)?\n var cancelAction: (() -> Void)?\n var logoutAction: (() -> Void)?\n\n var state: RedeemVoucherState = .initial {\n didSet {\n updateUI()\n }\n }\n\n var isEditing: Bool {\n get {\n textField.isEditing\n }\n set {\n guard textField.isFirstResponder != newValue else { return }\n if newValue {\n textField.becomeFirstResponder()\n } else {\n textField.resignFirstResponder()\n }\n }\n }\n\n var isLogoutDialogHidden = true {\n didSet {\n logoutViewForAccountNumberIsEntered.isHidden = isLogoutDialogHidden\n }\n }\n\n init(configuration: RedeemVoucherViewConfiguration) {\n self.configuration = configuration\n super.init(frame: .zero)\n commonInit()\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n private func commonInit() {\n setupAppearance()\n configureUI()\n addButtonHandlers()\n updateUI()\n addKeyboardResponderIfNeeded()\n addObservers()\n }\n\n private func setupAppearance() {\n translatesAutoresizingMaskIntoConstraints = false\n backgroundColor = .secondaryColor\n directionalLayoutMargins = UIMetrics.contentLayoutMargins\n }\n\n private func configureUI() {\n addConstrainedSubviews([scrollView]) {\n scrollView.pinEdgesToSuperview(.all(configuration.layoutMargins))\n }\n\n scrollView.addConstrainedSubviews([contentHolderView]) {\n contentHolderView.pinEdgesToSuperview()\n contentHolderView.widthAnchor.constraint(equalTo: scrollView.widthAnchor)\n contentHolderView.heightAnchor.constraint(greaterThanOrEqualTo: scrollView.heightAnchor)\n }\n contentHolderView.addConstrainedSubviews([voucherCodeStackView, buttonsStackView]) {\n voucherCodeStackView.pinEdgesToSuperview(.all().excluding(.bottom))\n buttonsStackView.pinEdgesToSuperview(PinnableEdges([.leading(.zero), .trailing(.zero)]))\n voucherCodeStackView.bottomAnchor.constraint(\n lessThanOrEqualTo: buttonsStackView.topAnchor,\n constant: -UIMetrics.padding16\n )\n }\n bottomsOfButtonsConstraint = buttonsStackView.pinEdgesToSuperview(PinnableEdges([.bottom(.zero)])).first\n bottomsOfButtonsConstraint?.isActive = true\n }\n\n private func addButtonHandlers() {\n cancelButton.addTarget(\n self,\n action: #selector(cancelButtonTapped),\n for: .touchUpInside\n )\n\n redeemButton.addTarget(\n self,\n action: #selector(redeemButtonTapped),\n for: .touchUpInside\n )\n }\n\n private func updateUI() {\n if isLoading {\n activityIndicator.startAnimating()\n } else {\n activityIndicator.stopAnimating()\n }\n redeemButton.isEnabled = isRedeemButtonEnabled && textField.isVoucherLengthSatisfied\n statusLabel.text = text\n statusLabel.textColor = textColor\n logoutViewForAccountNumberIsEntered.isLoading = isLoading\n }\n\n private func addObservers() {\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(textDidChange),\n name: UITextField.textDidChangeNotification,\n object: textField\n )\n }\n\n @objc private func cancelButtonTapped(_ sender: AppButton) {\n cancelAction?()\n }\n\n @objc private func redeemButtonTapped(_ sender: AppButton) {\n let code = textField.parsedToken\n guard !code.isEmpty else {\n return\n }\n redeemAction?(code)\n }\n\n @objc private func textDidChange() {\n if textField.parsedToken.isEmpty {\n isLogoutDialogHidden = true\n }\n updateUI()\n }\n\n private func addKeyboardResponderIfNeeded() {\n guard configuration.adjustViewWhenKeyboardAppears else { return }\n keyboardResponder = AutomaticKeyboardResponder(\n targetView: self,\n handler: { [weak self] _, offset in\n guard let self else { return }\n self.bottomsOfButtonsConstraint?.constant = isEditing ? -offset : 0\n self.layoutIfNeeded()\n }\n )\n }\n}\n\nprivate extension REST.Error {\n var description: String {\n if compareErrorCode(.invalidVoucher) {\n return NSLocalizedString(\n "REDEEM_VOUCHER_STATUS_FAILURE",\n tableName: "RedeemVoucher",\n value: "Voucher code is invalid.",\n comment: ""\n )\n } else if compareErrorCode(.usedVoucher) {\n return NSLocalizedString(\n "REDEEM_VOUCHER_STATUS_FAILURE",\n tableName: "RedeemVoucher",\n value: "This voucher code has already been used.",\n comment: ""\n )\n }\n return displayErrorDescription ?? ""\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\RedeemVoucher\RedeemVoucherContentView.swift | RedeemVoucherContentView.swift | Swift | 12,182 | 0.95 | 0.054404 | 0.026471 | python-kit | 68 | 2024-07-13T10:06:48.762106 | MIT | false | a1fa393a29a2f8891deb122987372f44 |
//\n// RedeemVoucherInteractor.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2023-08-30.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\nimport MullvadTypes\n\nfinal class RedeemVoucherInteractor: @unchecked Sendable {\n private let tunnelManager: TunnelManager\n private let accountsProxy: RESTAccountHandling\n private let shouldVerifyVoucherAsAccount: Bool\n\n private var tasks: [Cancellable] = []\n private var preferredAccountNumber: String?\n\n var showLogoutDialog: (() -> Void)?\n var didLogout: ((String) -> Void)?\n\n init(\n tunnelManager: TunnelManager,\n accountsProxy: RESTAccountHandling,\n verifyVoucherAsAccount: Bool\n ) {\n self.tunnelManager = tunnelManager\n self.accountsProxy = accountsProxy\n self.shouldVerifyVoucherAsAccount = verifyVoucherAsAccount\n }\n\n func redeemVoucher(\n code: String,\n completion: @escaping (@Sendable (Result<REST.SubmitVoucherResponse, Error>) -> Void)\n ) {\n tasks.append(tunnelManager.redeemVoucher(code) { [weak self] result in\n guard let self else { return }\n completion(result)\n guard shouldVerifyVoucherAsAccount,\n result.error?.isInvalidVoucher ?? false else {\n return\n }\n verifyVoucherAsAccount(code: code)\n })\n }\n\n func logout() async {\n guard let accountNumber = preferredAccountNumber else { return }\n await tunnelManager.unsetAccount()\n didLogout?(accountNumber)\n }\n\n func cancelAll() {\n tasks.forEach { $0.cancel() }\n }\n\n private func verifyVoucherAsAccount(code: String) {\n let task = accountsProxy.getAccountData(\n accountNumber: code,\n retryStrategy: .noRetry\n ) { [weak self] result in\n guard let self,\n case .success = result else {\n return\n }\n showLogoutDialog?()\n preferredAccountNumber = code\n }\n\n tasks.append(task)\n }\n}\n\nfileprivate extension Error {\n var isInvalidVoucher: Bool {\n (self as? REST.Error)?.compareErrorCode(.invalidVoucher) ?? false\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\RedeemVoucher\RedeemVoucherInteractor.swift | RedeemVoucherInteractor.swift | Swift | 2,242 | 0.95 | 0.0125 | 0.101449 | react-lib | 61 | 2024-01-08T06:53:49.557630 | MIT | false | efa85d3bab9a7d0b22e3f3cb83d76d0e |
//\n// RedeemVoucherViewConfiguration.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2023-09-12.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport UIKit\n\nstruct RedeemVoucherViewConfiguration {\n let adjustViewWhenKeyboardAppears: Bool\n /// Hides the title when set to `true`.\n let shouldUseCompactStyle: Bool\n /// Custom margins to use for the compact style.\n let layoutMargins: NSDirectionalEdgeInsets\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\RedeemVoucher\RedeemVoucherViewConfiguration.swift | RedeemVoucherViewConfiguration.swift | Swift | 461 | 0.95 | 0.055556 | 0.5625 | react-lib | 660 | 2023-11-21T09:50:56.178785 | Apache-2.0 | false | 1c2f1276a85b4f2829c95abd8a2c529f |
//\n// RedeemVoucherViewController.swift\n// MullvadVPN\n//\n// Created by Andreas Lif on 2022-08-05.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadREST\nimport MullvadTypes\nimport UIKit\n\nprotocol RedeemVoucherViewControllerDelegate: AnyObject, Sendable {\n func redeemVoucherDidSucceed(\n _ controller: RedeemVoucherViewController,\n with response: REST.SubmitVoucherResponse\n )\n func redeemVoucherDidCancel(_ controller: RedeemVoucherViewController)\n}\n\n@MainActor\nclass RedeemVoucherViewController: UIViewController, UINavigationControllerDelegate, RootContainment {\n private let contentView: RedeemVoucherContentView\n nonisolated(unsafe) private var interactor: RedeemVoucherInteractor\n\n weak var delegate: RedeemVoucherViewControllerDelegate?\n\n init(\n configuration: RedeemVoucherViewConfiguration,\n interactor: RedeemVoucherInteractor\n ) {\n self.contentView = RedeemVoucherContentView(configuration: configuration)\n self.interactor = interactor\n self.contentView.isUserInteractionEnabled = false\n\n super.init(nibName: nil, bundle: nil)\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n override var preferredStatusBarStyle: UIStatusBarStyle {\n .lightContent\n }\n\n var preferredHeaderBarPresentation: HeaderBarPresentation {\n HeaderBarPresentation(style: .default, showsDivider: true)\n }\n\n var prefersHeaderBarHidden: Bool {\n false\n }\n\n var prefersDeviceInfoBarHidden: Bool {\n true\n }\n\n // MARK: - Life Cycle\n\n override func viewDidLoad() {\n super.viewDidLoad()\n configureUI()\n addActions()\n }\n\n override func viewDidAppear(_ animated: Bool) {\n super.viewDidAppear(animated)\n\n contentView.isUserInteractionEnabled = true\n contentView.isEditing = true\n }\n\n override func viewWillDisappear(_ animated: Bool) {\n super.viewWillDisappear(animated)\n contentView.isEditing = false\n }\n\n override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {\n contentView.isEditing = false\n super.viewWillTransition(to: size, with: coordinator)\n }\n\n // MARK: - private functions\n\n private func addActions() {\n contentView.redeemAction = { [weak self] code in\n self?.submit(code: code)\n }\n\n contentView.cancelAction = { [weak self] in\n self?.cancel()\n }\n\n contentView.logoutAction = { [weak self] in\n self?.logout()\n }\n\n interactor.showLogoutDialog = { [weak self] in\n self?.contentView.isLogoutDialogHidden = false\n }\n }\n\n private func configureUI() {\n view.addConstrainedSubviews([contentView]) {\n contentView.pinEdgesToSuperview(.all())\n }\n }\n\n private func submit(code: String) {\n contentView.state = .verifying\n contentView.isEditing = false\n interactor.redeemVoucher(code: code, completion: { [weak self] result in\n guard let self else { return }\n /// Safe to assume `@MainActor` isolation because\n /// `TunnelManager.redeemVoucher` sets the `RedeemVoucherOperation`'s `completionQueue` to `.main`\n MainActor.assumeIsolated {\n switch result {\n case let .success(value):\n contentView.state = .success\n delegate?.redeemVoucherDidSucceed(self, with: value)\n case let .failure(error):\n contentView.state = .failure(error)\n }\n }\n })\n }\n\n private func cancel() {\n contentView.isEditing = false\n\n interactor.cancelAll()\n\n delegate?.redeemVoucherDidCancel(self)\n }\n\n private func logout() {\n contentView.isEditing = false\n\n contentView.state = .logout\n\n Task { [weak self] in\n guard let self else { return }\n await interactor.logout()\n contentView.state = .initial\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\RedeemVoucher\RedeemVoucherViewController.swift | RedeemVoucherViewController.swift | Swift | 4,159 | 0.95 | 0.013514 | 0.09322 | react-lib | 612 | 2023-12-06T16:09:13.127308 | MIT | false | 67441610f11f16b6b98847c03443bd73 |
//\n// VoucherTextField.swift\n// MullvadVPN\n//\n// Created by Andreas Lif on 2022-08-05.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport UIKit\n\nclass VoucherTextField: CustomTextField, UITextFieldDelegate {\n private let inputFormatter = InputTextFormatter(configuration: InputTextFormatter.Configuration(\n allowedInput: .alphanumeric(isUpperCase: true),\n groupSeparator: "-",\n groupSize: 4,\n maxGroups: 4\n ))\n\n private var voucherLength: UInt8 {\n let maxGroups = inputFormatter.configuration.maxGroups\n let groupSize = inputFormatter.configuration.groupSize\n return maxGroups * groupSize + (maxGroups - 1)\n }\n\n var parsedToken: String {\n inputFormatter.string\n }\n\n var isVoucherLengthSatisfied: Bool {\n let length = text?.count ?? 0\n return length >= voucherLength\n }\n\n override init(frame: CGRect) {\n super.init(frame: frame)\n delegate = self\n autocorrectionType = .no\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {\n if action == #selector(captureTextFromCamera(_:)) { return false }\n return super.canPerformAction(action, withSender: sender)\n }\n\n // MARK: - UITextFieldDelegate\n\n func textField(\n _ textField: UITextField,\n shouldChangeCharactersIn range: NSRange,\n replacementString string: String\n ) -> Bool {\n inputFormatter.textField(\n textField,\n shouldChangeCharactersIn: range,\n replacementString: string\n )\n }\n\n func textFieldShouldReturn(_ textField: UITextField) -> Bool {\n textField.resignFirstResponder()\n return true\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\RedeemVoucher\VoucherTextField.swift | VoucherTextField.swift | Swift | 1,867 | 0.95 | 0.029412 | 0.140351 | vue-tools | 939 | 2024-07-22T02:09:13.286202 | BSD-3-Clause | false | cafc17b1884aa4b22c12061f403fa9a2 |
//\n// ChipCollectionView.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2024-10-31.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport UIKit\n\nclass ChipCollectionView: UIView {\n private var chips: [ChipConfiguration] = []\n private let cellReuseIdentifier = String(describing: ChipViewCell.self)\n\n private(set) lazy var collectionView: UICollectionView = {\n let collectionView = UICollectionView(frame: .zero, collectionViewLayout: ChipFlowLayout())\n collectionView.contentInset = .zero\n collectionView.backgroundColor = .clear\n collectionView.translatesAutoresizingMaskIntoConstraints = false\n return collectionView\n }()\n\n init() {\n super.init(frame: .zero)\n setupCollectionView()\n }\n\n required init?(coder: NSCoder) {\n super.init(coder: coder)\n setupCollectionView()\n }\n\n private func setupCollectionView() {\n collectionView.dataSource = self\n collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellReuseIdentifier)\n addConstrainedSubviews([collectionView]) {\n collectionView.pinEdgesToSuperview()\n }\n }\n\n func setChips(_ values: [ChipConfiguration]) {\n chips = values\n collectionView.reloadData()\n }\n}\n\nextension ChipCollectionView: UICollectionViewDataSource {\n func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {\n return chips.count\n }\n\n func collectionView(\n _ collectionView: UICollectionView,\n cellForItemAt indexPath: IndexPath\n ) -> UICollectionViewCell {\n let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellReuseIdentifier, for: indexPath)\n cell.contentConfiguration = chips[indexPath.row]\n return cell\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\RelayFilter\ChipCollectionView.swift | ChipCollectionView.swift | Swift | 1,865 | 0.95 | 0.032787 | 0.134615 | vue-tools | 771 | 2024-04-07T07:32:37.567463 | GPL-3.0 | false | 7cf0af7ecc52078474493bb8d686ce5f |
//\n// ChipFlowLayout.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2024-10-31.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass ChipFlowLayout: UICollectionViewCompositionalLayout {\n init() {\n super.init { _, _ -> NSCollectionLayoutSection? in\n // Create an item with flexible size\n let itemSize = NSCollectionLayoutSize(widthDimension: .estimated(50), heightDimension: .estimated(20))\n let item = NSCollectionLayoutItem(layoutSize: itemSize)\n item.edgeSpacing = NSCollectionLayoutEdgeSpacing(\n leading: .fixed(0),\n top: .fixed(0),\n trailing: .fixed(0),\n bottom: .fixed(0)\n )\n\n // Create a group that fills the available width and wraps items with proper spacing\n let groupSize = NSCollectionLayoutSize(\n widthDimension: .fractionalWidth(1.0),\n heightDimension: .estimated(20)\n )\n let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item])\n group.interItemSpacing = .fixed(UIMetrics.FilterView.interChipViewSpacing)\n group.contentInsets = .zero\n\n // Create a section with zero inter-group spacing and no content insets\n let section = NSCollectionLayoutSection(group: group)\n section.interGroupSpacing = UIMetrics.FilterView.interChipViewSpacing\n section.contentInsets = .zero\n\n return section\n }\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\RelayFilter\ChipFlowLayout.swift | ChipFlowLayout.swift | Swift | 1,658 | 0.95 | 0.022222 | 0.25641 | node-utils | 10 | 2024-06-05T22:58:57.986592 | MIT | false | 91fa9ce78a3f5314f781c3f1db9f4542 |
//\n// ChipViewCell.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-06-20.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass ChipViewCell: UIView, UIContentView {\n var configuration: UIContentConfiguration {\n didSet {\n set(configuration: configuration)\n }\n }\n\n private let container = {\n let container = UIView()\n container.backgroundColor = .primaryColor\n container.layer.cornerRadius = UIMetrics.FilterView.chipViewCornerRadius\n container.layoutMargins = UIMetrics.FilterView.chipViewLayoutMargins\n return container\n }()\n\n private let titleLabel: UILabel = {\n let label = UILabel()\n label.setAccessibilityIdentifier(.relayFilterChipLabel)\n label.adjustsFontForContentSizeCategory = true\n label.translatesAutoresizingMaskIntoConstraints = false\n label.numberOfLines = 1\n label.setContentCompressionResistancePriority(.required, for: .horizontal)\n label.setContentHuggingPriority(.required, for: .horizontal)\n return label\n }()\n\n private let closeButton: IncreasedHitButton = {\n let button = IncreasedHitButton()\n var buttonConfiguration = UIButton.Configuration.plain()\n buttonConfiguration.image = UIImage.Buttons.closeSmall.withTintColor(.white.withAlphaComponent(0.6))\n buttonConfiguration.contentInsets = .zero\n button.setAccessibilityIdentifier(.relayFilterChipCloseButton)\n button.configuration = buttonConfiguration\n return button\n }()\n\n private lazy var closeButtonActionHandler: UIAction = {\n return UIAction { [weak self] action in\n guard let self,\n let chipConfiguration = configuration as? ChipConfiguration,\n let action = chipConfiguration.didTapButton else {\n return\n }\n action()\n }\n }()\n\n init(configuration: UIContentConfiguration) {\n self.configuration = configuration\n super.init(frame: .zero)\n addSubviews()\n set(configuration: configuration)\n }\n\n override init(frame: CGRect) {\n self.configuration = ChipConfiguration(group: .filter, title: "", didTapButton: nil)\n super.init(frame: .zero)\n addSubviews()\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n func addSubviews() {\n self.setAccessibilityIdentifier(.relayFilterChipView)\n\n let stackView = UIStackView(arrangedSubviews: [titleLabel, closeButton])\n stackView.spacing = UIMetrics.FilterView.chipViewLabelSpacing\n\n container.addConstrainedSubviews([stackView]) {\n stackView.pinEdgesToSuperviewMargins()\n }\n addConstrainedSubviews([container]) {\n container.pinEdgesToSuperview()\n }\n }\n\n private func set(configuration: UIContentConfiguration) {\n guard let chipConfiguration = configuration as? ChipConfiguration else { return }\n container.backgroundColor = chipConfiguration.backgroundColor\n titleLabel.text = chipConfiguration.title\n titleLabel.textColor = chipConfiguration.textColor\n titleLabel.font = chipConfiguration.font\n closeButton.isHidden = chipConfiguration.didTapButton == nil\n titleLabel.accessibilityIdentifier = chipConfiguration.accessibilityId?.asString\n if chipConfiguration.didTapButton != nil {\n closeButton.addAction(closeButtonActionHandler, for: .touchUpInside)\n } else {\n closeButton.removeAction(closeButtonActionHandler, for: .touchUpInside)\n }\n }\n}\n\n// Custom content configuration\nstruct ChipConfiguration: UIContentConfiguration {\n enum Group: Hashable {\n case filter, settings\n }\n\n var group: Group\n var title: String\n var accessibilityId: AccessibilityIdentifier? = nil\n var textColor: UIColor = .white\n var font = UIFont.preferredFont(forTextStyle: .caption1)\n var backgroundColor: UIColor = .primaryColor\n let didTapButton: (() -> Void)?\n\n func makeContentView() -> UIView & UIContentView {\n return ChipViewCell(configuration: self)\n }\n\n func updated(for state: UIConfigurationState) -> ChipConfiguration {\n return self\n }\n}\n\nextension ChipConfiguration: Equatable {\n static func == (lhs: ChipConfiguration, rhs: ChipConfiguration) -> Bool {\n lhs.title == rhs.title\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\RelayFilter\ChipViewCell.swift | ChipViewCell.swift | Swift | 4,486 | 0.95 | 0.05303 | 0.070175 | vue-tools | 788 | 2025-06-28T15:06:38.168995 | GPL-3.0 | false | 2dc879d5c28f50e295f645794633cd69 |
//\n// FilterDescriptor.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2025-02-25.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\nimport MullvadREST\nimport MullvadSettings\n\nstruct FilterDescriptor {\n let relayFilterResult: RelayCandidates\n let settings: LatestTunnelSettings\n\n var isEnabled: Bool {\n // Check if multihop is enabled via settings\n let isMultihopEnabled = settings.tunnelMultihopState.isEnabled\n let isSmartRoutingEnabled = settings.daita.isAutomaticRouting\n\n /// Closure to check if there are enough relays available for multihoping\n let hasSufficientRelays: () -> Bool = {\n (relayFilterResult.entryRelays ?? []).count >= 1 &&\n relayFilterResult.exitRelays.count >= 1 &&\n numberOfServers > 1\n }\n\n if isMultihopEnabled {\n // Multihop mode requires at least one entry relay, one exit relay,\n // and more than one unique server.\n return hasSufficientRelays()\n } else if isSmartRoutingEnabled {\n // Smart Routing mode: Enabled only if there is NO daita server in the exit relays\n let isSmartRoutingNeeded = !relayFilterResult.exitRelays.contains { $0.relay.daita == true }\n return isSmartRoutingNeeded ? hasSufficientRelays() : true\n } else {\n // Single-hop mode: The filter is enabled if at least one available exit relay exists.\n return !relayFilterResult.exitRelays.isEmpty\n }\n }\n\n var title: String {\n guard isEnabled else {\n return NSLocalizedString(\n "RELAY_FILTER_BUTTON_TITLE",\n tableName: "RelayFilter",\n value: "No matching servers",\n comment: ""\n )\n }\n return createTitleForAvailableServers()\n }\n\n var description: String {\n guard settings.daita.daitaState.isEnabled else {\n return ""\n }\n return NSLocalizedString(\n "RELAY_FILTER_BUTTON_DESCRIPTION",\n tableName: "RelayFilter",\n value: "When using DAITA, one provider with DAITA-enabled servers is required.",\n comment: ""\n )\n }\n\n init(relayFilterResult: RelayCandidates, settings: LatestTunnelSettings) {\n self.settings = settings\n self.relayFilterResult = relayFilterResult\n }\n\n private var numberOfServers: Int {\n Set(relayFilterResult.entryRelays ?? []).union(relayFilterResult.exitRelays).count\n }\n\n private func createTitleForAvailableServers() -> String {\n let displayNumber: (Int) -> String = { number in\n number >= 100 ? "99+" : "\(number)"\n }\n return String(format: "Show %@ servers", displayNumber(numberOfServers))\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\RelayFilter\FilterDescriptor.swift | FilterDescriptor.swift | Swift | 2,801 | 0.95 | 0.0875 | 0.183099 | vue-tools | 261 | 2025-01-28T12:47:56.402664 | GPL-3.0 | false | a4c904da55d4bb9e58760564446f9571 |
//\n// RelayFilterCellFactory.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-06-02.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\n@MainActor\nstruct RelayFilterCellFactory: @preconcurrency CellFactoryProtocol {\n let tableView: UITableView\n\n func makeCell(for item: RelayFilterDataSourceItem, indexPath: IndexPath) -> UITableViewCell {\n let cell = tableView.dequeueReusableCell(\n withIdentifier: RelayFilterDataSource.CellReuseIdentifiers.allCases[indexPath.section].rawValue,\n for: indexPath\n )\n configureCell(cell, item: item, indexPath: indexPath)\n\n return cell\n }\n\n func configureCell(\n _ cell: UITableViewCell,\n item: RelayFilterDataSourceItem,\n indexPath: IndexPath\n ) {\n switch item.type {\n case .ownershipAny, .ownershipOwned, .ownershipRented:\n configureOwnershipCell(cell as? SelectableSettingsCell, item: item)\n case .allProviders, .provider:\n configureProviderCell(cell as? CheckableSettingsCell, item: item)\n }\n }\n\n private func configureOwnershipCell(_ cell: SelectableSettingsCell?, item: RelayFilterDataSourceItem) {\n guard let cell = cell else { return }\n\n cell.titleLabel.text = NSLocalizedString(\n "RELAY_FILTER_CELL_LABEL",\n tableName: "Relay filter ownership cell",\n value: item.name,\n comment: ""\n )\n\n let accessibilityIdentifier: AccessibilityIdentifier\n switch item.type {\n case .ownershipAny:\n accessibilityIdentifier = .ownershipAnyCell\n case .ownershipOwned:\n accessibilityIdentifier = .ownershipMullvadOwnedCell\n case .ownershipRented:\n accessibilityIdentifier = .ownershipRentedCell\n default:\n assertionFailure("Unexpected ownership item: \(item)")\n return\n }\n\n cell.setAccessibilityIdentifier(accessibilityIdentifier)\n cell.applySubCellStyling()\n }\n\n private func configureProviderCell(_ cell: CheckableSettingsCell?, item: RelayFilterDataSourceItem) {\n guard let cell = cell else { return }\n let alpha = item.isEnabled ? 1.0 : 0.2\n\n cell.titleLabel.text = NSLocalizedString(\n "RELAY_FILTER_CELL_LABEL",\n tableName: "Relay filter provider cell",\n value: item.name,\n comment: ""\n )\n cell.detailTitleLabel.text = item.description\n\n if item.type == .allProviders {\n setFontWeight(.semibold, to: cell.titleLabel)\n } else {\n setFontWeight(.regular, to: cell.titleLabel)\n }\n\n cell.applySubCellStyling()\n cell.setAccessibilityIdentifier(.relayFilterProviderCell)\n cell.titleLabel.alpha = alpha\n cell.detailTitleLabel.alpha = alpha\n }\n\n private func setFontWeight(_ weight: UIFont.Weight, to label: UILabel) {\n label.font = UIFont.systemFont(ofSize: label.font.pointSize, weight: weight)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\RelayFilter\RelayFilterCellFactory.swift | RelayFilterCellFactory.swift | Swift | 3,055 | 0.95 | 0.054348 | 0.089744 | node-utils | 512 | 2024-01-13T16:03:23.784106 | Apache-2.0 | false | ba168805b7e6302651632bda4737d9cb |
//\n// RelayFilterDataSource.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-06-02.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport MullvadREST\nimport MullvadTypes\nimport UIKit\nfinal class RelayFilterDataSource: UITableViewDiffableDataSource<\n RelayFilterDataSource.Section,\n RelayFilterDataSourceItem\n> {\n private weak var tableView: UITableView?\n private var viewModel: RelayFilterViewModel\n private let relayFilterCellFactory: RelayFilterCellFactory\n private var disposeBag = Set<Combine.AnyCancellable>()\n\n init(tableView: UITableView, viewModel: RelayFilterViewModel) {\n self.tableView = tableView\n self.viewModel = viewModel\n\n let relayFilterCellFactory = RelayFilterCellFactory(tableView: tableView)\n self.relayFilterCellFactory = relayFilterCellFactory\n\n super.init(tableView: tableView) { _, indexPath, itemIdentifier in\n relayFilterCellFactory.makeCell(for: itemIdentifier, indexPath: indexPath)\n }\n\n registerCells()\n createDataSnapshot()\n tableView.delegate = self\n setupBindings()\n }\n\n private func registerCells() {\n CellReuseIdentifiers.allCases.forEach { tableView?.register(\n $0.reusableViewClass,\n forCellReuseIdentifier: $0.rawValue\n ) }\n HeaderFooterReuseIdentifiers.allCases.forEach { tableView?.register(\n $0.reusableViewClass,\n forHeaderFooterViewReuseIdentifier: $0.rawValue\n ) }\n }\n\n private func setupBindings() {\n viewModel\n .$relayFilter\n .dropFirst()\n .removeDuplicates()\n .receive(on: DispatchQueue.main)\n .sink { [weak self] filter in\n self?.updateDataSnapshot(filter: filter)\n }\n .store(in: &disposeBag)\n }\n\n private func createDataSnapshot() {\n var snapshot = NSDiffableDataSourceSnapshot<Section, RelayFilterDataSourceItem>()\n snapshot.appendSections(Section.allCases)\n apply(snapshot, animatingDifferences: false)\n }\n\n private func updateDataSnapshot(filter: RelayFilter) {\n let oldSnapshot = snapshot()\n var newSnapshot = NSDiffableDataSourceSnapshot<Section, RelayFilterDataSourceItem>()\n newSnapshot.appendSections(Section.allCases)\n\n Section.allCases.forEach { section in\n switch section {\n case .ownership:\n if !oldSnapshot.itemIdentifiers(inSection: section).isEmpty {\n newSnapshot.appendItems(RelayFilterDataSourceItem.ownerships, toSection: .ownership)\n }\n case .providers:\n if !oldSnapshot.itemIdentifiers(inSection: section).isEmpty {\n newSnapshot.appendItems(\n [RelayFilterDataSourceItem.allProviders] + viewModel.availableProviders(for: filter.ownership),\n toSection: .providers\n )\n applySnapshot(newSnapshot, animated: false)\n }\n }\n }\n }\n\n private func applySnapshot(\n _ snapshot: NSDiffableDataSourceSnapshot<Section, RelayFilterDataSourceItem>,\n animated: Bool,\n completion: (() -> Void)? = nil\n ) {\n apply(snapshot, animatingDifferences: animated) { [weak self] in\n guard let self else { return }\n updateSelection(from: viewModel.relayFilter)\n completion?()\n }\n }\n\n private func updateSelection(from filter: RelayFilter) {\n tableView?.indexPathsForSelectedRows?.forEach { selectRow(false, at: $0) }\n\n if let ownership = viewModel.ownershipItem(for: filter.ownership),\n let ownershipIndexPath = indexPath(for: ownership) {\n selectRow(true, at: ownershipIndexPath)\n }\n\n switch filter.providers {\n case .any:\n selectAllProviders(true)\n case let .only(providers):\n selectAllProviders(false)\n providers.forEach { providerName in\n selectRow(true, at: indexPath(for: viewModel.providerItem(for: providerName)))\n }\n updateAllProvidersSelection()\n }\n }\n\n private func isItemSelected(_ item: RelayFilterDataSourceItem, for filter: RelayFilter) -> Bool {\n switch item.type {\n case .ownershipAny, .ownershipOwned, .ownershipRented:\n return viewModel.ownership(for: item) == filter.ownership\n case .allProviders:\n return filter.providers == .any\n case .provider:\n return switch filter.providers {\n case .any:\n true\n case let .only(providers):\n providers.contains(item.name)\n }\n }\n }\n\n private func updateAllProvidersSelection() {\n let selectedCount = getSelectedIndexPaths(in: .providers).count\n let providerCount = viewModel.availableProviders(for: viewModel.relayFilter.ownership).count\n selectRow(selectedCount == providerCount, at: indexPath(for: .allProviders))\n }\n\n private func handleCollapseOwnership(isExpanded: Bool) {\n var newSnapshot = snapshot()\n if isExpanded {\n newSnapshot.deleteItems(RelayFilterDataSourceItem.ownerships)\n } else {\n newSnapshot.appendItems(RelayFilterDataSourceItem.ownerships, toSection: .ownership)\n }\n applySnapshot(newSnapshot, animated: !isExpanded)\n }\n\n private func handleCollapseProviders(isExpanded: Bool) {\n let currentSnapshot = snapshot()\n var newSnapshot = currentSnapshot\n\n if isExpanded {\n let items = newSnapshot.itemIdentifiers(inSection: .providers)\n newSnapshot.deleteItems(items)\n } else {\n newSnapshot.appendItems(\n [RelayFilterDataSourceItem.allProviders] + viewModel\n .availableProviders(for: viewModel.relayFilter.ownership),\n toSection: .providers\n )\n }\n applySnapshot(newSnapshot, animated: !isExpanded)\n }\n\n private func selectRow(_ select: Bool, at indexPath: IndexPath?) {\n guard let indexPath else { return }\n\n if select {\n tableView?.selectRow(at: indexPath, animated: false, scrollPosition: .none)\n } else {\n tableView?.deselectRow(at: indexPath, animated: false)\n }\n }\n\n private func selectAllProviders(_ select: Bool) {\n let providerItems = snapshot().itemIdentifiers(inSection: .providers)\n\n providerItems.forEach { providerItem in\n selectRow(select, at: indexPath(for: providerItem))\n }\n }\n\n private func getSelectedIndexPaths(in section: Section) -> [IndexPath] {\n let sectionIndex = snapshot().indexOfSection(section)\n\n return tableView?.indexPathsForSelectedRows?.filter { indexPath in\n indexPath.section == sectionIndex\n } ?? []\n }\n\n private func getSection(for indexPath: IndexPath) -> Section {\n return snapshot().sectionIdentifiers[indexPath.section]\n }\n}\n\n// MARK: - UITableViewDelegate\n\nextension RelayFilterDataSource: UITableViewDelegate {\n func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {\n switch getSection(for: indexPath) {\n case .ownership:\n selectRow(false, at: getSelectedIndexPaths(in: .ownership).first)\n case .providers:\n break\n }\n\n return indexPath\n }\n\n func tableView(_ tableView: UITableView, willDeselectRowAt indexPath: IndexPath) -> IndexPath? {\n switch getSection(for: indexPath) {\n case .ownership:\n return nil\n case .providers:\n return indexPath\n }\n }\n\n func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {\n guard let item = itemIdentifier(for: indexPath) else { return }\n viewModel.toggleItem(item)\n }\n\n func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {\n guard let item = itemIdentifier(for: indexPath) else { return }\n viewModel.toggleItem(item)\n }\n\n func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {\n guard let item = itemIdentifier(for: indexPath) else { return }\n cell.setSelected(isItemSelected(item, for: viewModel.relayFilter), animated: false)\n }\n\n func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {\n guard let view = tableView.dequeueReusableHeaderFooterView(\n withIdentifier: HeaderFooterReuseIdentifiers.section.rawValue\n ) as? SettingsHeaderView else { return nil }\n\n let sectionId = snapshot().sectionIdentifiers[section]\n let title: String\n let accessibilityIdentifier: AccessibilityIdentifier\n\n switch sectionId {\n case .ownership:\n accessibilityIdentifier = .locationFilterOwnershipHeaderCell\n title = "Ownership"\n case .providers:\n accessibilityIdentifier = .locationFilterProvidersHeaderCell\n title = "Providers"\n }\n\n view.setAccessibilityIdentifier(accessibilityIdentifier)\n view.titleLabel.text = NSLocalizedString(\n "RELAY_FILTER_HEADER_LABEL",\n tableName: "Relay filter header",\n value: title,\n comment: ""\n )\n\n view.didCollapseHandler = { [weak self] headerView in\n guard let self else { return }\n switch sectionId {\n case .ownership:\n handleCollapseOwnership(isExpanded: headerView.isExpanded)\n case .providers:\n handleCollapseProviders(isExpanded: headerView.isExpanded)\n }\n\n headerView.isExpanded.toggle()\n }\n\n return view\n }\n\n func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {\n return nil\n }\n\n func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {\n return UIMetrics.TableView.separatorHeight\n }\n}\n\n// MARK: - Cell Identifiers\n\nextension RelayFilterDataSource {\n enum Section: CaseIterable { case ownership, providers }\n\n enum CellReuseIdentifiers: String, CaseIterable {\n case ownershipCell, providerCell\n\n var reusableViewClass: AnyClass {\n switch self {\n case .ownershipCell: return SelectableSettingsCell.self\n case .providerCell: return CheckableSettingsCell.self\n }\n }\n }\n\n enum HeaderFooterReuseIdentifiers: String, CaseIterable {\n case section\n\n var reusableViewClass: AnyClass { SettingsHeaderView.self }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\RelayFilter\RelayFilterDataSource.swift | RelayFilterDataSource.swift | Swift | 10,839 | 0.95 | 0.112179 | 0.034091 | python-kit | 340 | 2024-11-10T09:01:03.168547 | MIT | false | 3489f5dc0a2299e4b319d2eba5b8fadd |
//\n// RelayFilterDataSourceItem.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2025-03-05.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nstruct RelayFilterDataSourceItem: Hashable, Comparable {\n let name: String\n var description = ""\n let type: ItemType\n let isEnabled: Bool\n\n enum ItemType: Hashable {\n case ownershipAny, ownershipOwned, ownershipRented, allProviders, provider\n }\n\n static let anyOwnershipItem = RelayFilterDataSourceItem(name: NSLocalizedString(\n "RELAY_FILTER_ANY_LABEL",\n tableName: "RelayFilter",\n value: "Any",\n comment: ""\n ), type: .ownershipAny, isEnabled: true)\n\n static let ownedOwnershipItem = RelayFilterDataSourceItem(name: NSLocalizedString(\n "RELAY_FILTER_OWNED_LABEL",\n tableName: "RelayFilter",\n value: "Owned",\n comment: ""\n ), type: .ownershipOwned, isEnabled: true)\n\n static let rentedOwnershipItem = RelayFilterDataSourceItem(name: NSLocalizedString(\n "RELAY_FILTER_RENTED_LABEL",\n tableName: "RelayFilter",\n value: "Rented",\n comment: ""\n ), type: .ownershipRented, isEnabled: true)\n\n static let ownerships: [RelayFilterDataSourceItem] = [anyOwnershipItem, ownedOwnershipItem, rentedOwnershipItem]\n\n static var allProviders: RelayFilterDataSourceItem {\n RelayFilterDataSourceItem(name: NSLocalizedString(\n "RELAY_FILTER_ALL_PROVIDERS_LABEL",\n tableName: "RelayFilter",\n value: "All Providers",\n comment: ""\n ), type: .allProviders, isEnabled: true)\n }\n\n static func < (lhs: RelayFilterDataSourceItem, rhs: RelayFilterDataSourceItem) -> Bool {\n let nameComparison = lhs.name.caseInsensitiveCompare(rhs.name)\n return nameComparison == .orderedAscending\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\RelayFilter\RelayFilterDataSourceItem.swift | RelayFilterDataSourceItem.swift | Swift | 1,849 | 0.95 | 0 | 0.145833 | react-lib | 587 | 2025-01-24T18:05:34.229480 | MIT | false | b2b9bc65e3273001f4834e22cc166cde |
//\n// RelayFilterAppliedView.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-06-19.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadTypes\nimport UIKit\n\nclass RelayFilterView: UIView {\n enum Filter {\n case ownership\n case providers\n }\n\n private let titleLabel: UILabel = {\n let label = UILabel()\n label.text = NSLocalizedString(\n "RELAY_FILTER_APPLIED_TITLE",\n tableName: "RelayFilter",\n value: "Filtered:",\n comment: ""\n )\n label.font = UIFont.preferredFont(forTextStyle: .caption1)\n label.adjustsFontForContentSizeCategory = true\n label.textColor = .white\n return label\n }()\n\n private var chips: [ChipConfiguration] = []\n private var chipsView = ChipCollectionView()\n private var collectionViewHeightConstraint: NSLayoutConstraint!\n private var filter: RelayFilter?\n private var contentSizeObservation: NSKeyValueObservation?\n\n var didUpdateFilter: ((RelayFilter) -> Void)?\n\n init() {\n super.init(frame: .zero)\n\n setUpViews()\n }\n\n required init?(coder aDecoder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n func setFilter(_ filter: RelayFilter) {\n let filterChips = createFilterChips(for: filter)\n self.filter = filter\n chips.removeAll(where: { $0.group == .filter })\n chips += filterChips\n chipsView.setChips(chips)\n hideIfNeeded()\n }\n\n func setDaita(_ enabled: Bool) {\n let chip = ChipConfiguration(\n group: .settings,\n title: NSLocalizedString(\n "RELAY_FILTER_APPLIED_DAITA",\n tableName: "RelayFilter",\n value: "Setting: DAITA",\n comment: ""\n ),\n accessibilityId: .daitaFilterPill,\n didTapButton: nil\n )\n\n setChip(chip, enabled: enabled)\n }\n\n func setObfuscation(_ enabled: Bool) {\n let chip = ChipConfiguration(\n group: .settings,\n title: NSLocalizedString(\n "RELAY_FILTER_APPLIED_OBFUSCATION",\n tableName: "RelayFilter",\n value: "Setting: Obfuscation",\n comment: ""\n ),\n accessibilityId: .obfuscationFilterPill,\n didTapButton: nil\n )\n\n setChip(chip, enabled: enabled)\n }\n\n // MARK: - Private\n\n private func setChip(_ chip: ChipConfiguration, enabled: Bool) {\n if enabled {\n if !chips.contains(chip) {\n chips.insert(chip, at: 0)\n }\n } else {\n chips.removeAll { $0 == chip }\n }\n\n chipsView.setChips(chips)\n }\n\n private func setUpViews() {\n let dummyView = UIView()\n dummyView.layoutMargins = UIMetrics.FilterView.chipViewLayoutMargins\n\n let contentContainer = UIStackView(arrangedSubviews: [dummyView, chipsView])\n contentContainer.distribution = .fill\n\n collectionViewHeightConstraint = chipsView.collectionView.heightAnchor\n .constraint(equalToConstant: 8)\n collectionViewHeightConstraint.isActive = true\n\n dummyView.addConstrainedSubviews([titleLabel]) {\n titleLabel.pinEdgesToSuperviewMargins()\n }\n\n addConstrainedSubviews([contentContainer]) {\n contentContainer.pinEdgesToSuperview(PinnableEdges([.top(8), .bottom(8), .leading(4), .trailing(4)]))\n }\n\n // Add KVO for observing collectionView's contentSize changes\n observeContentSize()\n }\n\n private func hideIfNeeded() {\n isHidden = chips.isEmpty\n }\n\n private func createFilterChips(for filter: RelayFilter) -> [ChipConfiguration] {\n var filterChips: [ChipConfiguration] = []\n\n // Ownership Chip\n if let ownershipChip = createOwnershipChip(for: filter.ownership) {\n filterChips.append(ownershipChip)\n }\n\n // Providers Chip\n if let providersChip = createProvidersChip(for: filter.providers) {\n filterChips.append(providersChip)\n }\n\n return filterChips\n }\n\n private func createOwnershipChip(for ownership: RelayFilter.Ownership) -> ChipConfiguration? {\n switch ownership {\n case .any:\n return nil\n case .owned, .rented:\n let title = NSLocalizedString(\n "RELAY_FILTER_APPLIED_OWNERSHIP",\n tableName: "RelayFilter",\n value: ownership == .owned ? "Owned" : "Rented",\n comment: ""\n )\n return ChipConfiguration(group: .filter, title: title, didTapButton: { [weak self] in\n guard var filter = self?.filter else { return }\n filter.ownership = .any\n self?.didUpdateFilter?(filter)\n })\n }\n }\n\n private func createProvidersChip(for providers: RelayConstraint<[String]>) -> ChipConfiguration? {\n switch providers {\n case .any:\n return nil\n case let .only(providerList):\n let title = String(\n format: NSLocalizedString(\n "RELAY_FILTER_APPLIED_PROVIDERS",\n tableName: "RelayFilter",\n value: "Providers: %d",\n comment: ""\n ),\n providerList.count\n )\n return ChipConfiguration(group: .filter, title: title, didTapButton: { [weak self] in\n guard var filter = self?.filter else { return }\n filter.providers = .any\n self?.didUpdateFilter?(filter)\n })\n }\n }\n\n private func observeContentSize() {\n contentSizeObservation = chipsView.collectionView.observe(\.contentSize, options: [\n .new,\n .old,\n ]) { [weak self] _, change in\n guard let self, let newSize = change.newValue else { return }\n Task { @MainActor in\n let height = newSize.height == .zero ? 8 : newSize.height\n collectionViewHeightConstraint.constant = height > 80 ? 80 : height\n layoutIfNeeded() // Update the layout\n }\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\RelayFilter\RelayFilterView.swift | RelayFilterView.swift | Swift | 6,276 | 0.95 | 0.069307 | 0.063953 | react-lib | 916 | 2024-03-22T09:02:24.697365 | Apache-2.0 | false | e96ab2be779b7cc9e507ac617e94dfbd |
//\n// RelayFilterViewController.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-06-02.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport MullvadREST\nimport MullvadSettings\nimport MullvadTypes\nimport UIKit\n\nclass RelayFilterViewController: UIViewController {\n private let tableView = UITableView(frame: .zero, style: .grouped)\n private var viewModel: RelayFilterViewModel\n private var dataSource: RelayFilterDataSource?\n private var disposeBag = Set<Combine.AnyCancellable>()\n\n private let buttonContainerView: UIStackView = {\n let containerView = UIStackView()\n containerView.axis = .vertical\n containerView.spacing = 8\n containerView.isLayoutMarginsRelativeArrangement = true\n return containerView\n }()\n\n private let descriptionLabel: UILabel = {\n let label = UILabel()\n label.numberOfLines = 0\n label.lineBreakMode = .byWordWrapping\n label.font = .preferredFont(forTextStyle: .body)\n label.textColor = .secondaryTextColor\n label.textAlignment = .center\n return label\n }()\n\n private let applyButton: AppButton = {\n let button = AppButton(style: .success)\n button.setAccessibilityIdentifier(.applyButton)\n return button\n }()\n\n var onApplyFilter: ((RelayFilter) -> Void)?\n var didFinish: (() -> Void)?\n\n init(\n settings: LatestTunnelSettings,\n relaySelectorWrapper: RelaySelectorWrapper\n ) {\n self.viewModel = RelayFilterViewModel(settings: settings, relaySelectorWrapper: relaySelectorWrapper)\n super.init(nibName: nil, bundle: nil)\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n override func viewDidLoad() {\n super.viewDidLoad()\n\n view.directionalLayoutMargins = UIMetrics.contentLayoutMargins\n view.backgroundColor = .secondaryColor\n\n navigationItem.title = NSLocalizedString(\n "RELAY_FILTER_NAVIGATION_TITLE",\n tableName: "RelayFilter",\n value: "Filter",\n comment: ""\n )\n\n navigationItem.rightBarButtonItem = UIBarButtonItem(\n systemItem: .cancel,\n primaryAction: UIAction(handler: { [weak self] _ in\n self?.didFinish?()\n })\n )\n\n applyButton.addTarget(self, action: #selector(applyFilter), for: .touchUpInside)\n\n tableView.backgroundColor = view.backgroundColor\n tableView.separatorColor = view.backgroundColor\n tableView.rowHeight = UITableView.automaticDimension\n tableView.estimatedRowHeight = 60\n tableView.estimatedSectionHeaderHeight = tableView.estimatedRowHeight\n tableView.allowsMultipleSelection = true\n tableView.isMultipleTouchEnabled = false\n\n view.addSubview(tableView)\n buttonContainerView.addArrangedSubview(descriptionLabel)\n buttonContainerView.addArrangedSubview(applyButton)\n\n view.addConstrainedSubviews([tableView, buttonContainerView]) {\n tableView.pinEdgesToSuperview(.all().excluding(.bottom))\n buttonContainerView.pinEdgesToSuperviewMargins(.all().excluding(.top))\n buttonContainerView.topAnchor.constraint(\n equalTo: tableView.bottomAnchor,\n constant: UIMetrics.contentLayoutMargins.top\n )\n }\n\n setupDataSource()\n }\n\n private func setupDataSource() {\n viewModel\n .$relayFilter\n .removeDuplicates()\n .sink { [weak self] filter in\n guard let self else { return }\n let filterDescriptor = viewModel.getFilteredRelays(filter)\n applyButton.isEnabled = filterDescriptor.isEnabled\n applyButton.setTitle(filterDescriptor.title, for: .normal)\n descriptionLabel.text = filterDescriptor.description\n }\n .store(in: &disposeBag)\n dataSource = RelayFilterDataSource(tableView: tableView, viewModel: viewModel)\n }\n\n @objc private func applyFilter() {\n var relayFilter = viewModel.relayFilter\n\n switch viewModel.relayFilter.ownership {\n case .any:\n break\n case .owned:\n switch relayFilter.providers {\n case .any:\n break\n case let .only(providers):\n let ownedProviders = viewModel.ownedProviders.filter { providers.contains($0) }\n relayFilter.providers = .only(ownedProviders)\n }\n case .rented:\n switch relayFilter.providers {\n case .any:\n break\n case let .only(providers):\n let rentedProviders = viewModel.rentedProviders.filter { providers.contains($0) }\n relayFilter.providers = .only(rentedProviders)\n }\n }\n\n onApplyFilter?(relayFilter)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\RelayFilter\RelayFilterViewController.swift | RelayFilterViewController.swift | Swift | 4,961 | 0.95 | 0.040816 | 0.055556 | react-lib | 832 | 2024-04-23T13:33:00.843022 | MIT | false | d5f0eb1a6716ea6269667e08e3b21ebb |
//\n// RelayFilterViewModel.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-06-09.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport MullvadREST\nimport MullvadSettings\nimport MullvadTypes\n\nfinal class RelayFilterViewModel {\n @Published var relayFilter: RelayFilter\n\n private var settings: LatestTunnelSettings\n private let relaySelectorWrapper: RelaySelectorProtocol\n private let relaysWithLocation: LocationRelays\n private var relayCandidatesForAny: RelayCandidates\n\n init(settings: LatestTunnelSettings, relaySelectorWrapper: RelaySelectorProtocol) {\n self.settings = settings\n self.relaySelectorWrapper = relaySelectorWrapper\n self.relayFilter = settings.relayConstraints.filter.value ?? RelayFilter()\n\n // Retrieve all available relays that satisfy the `any` constraint.\n // This constraint ensures that the selected relays are associated with the current tunnel settings\n // and serve as the primary source of truth for subsequent filtering operations.\n // Further filtering will be applied based on specific criteria such as `ownership` or `provider`.\n var copy = settings\n copy.relayConstraints.filter = .any\n if let relayCandidatesForAny = try? relaySelectorWrapper.findCandidates(tunnelSettings: copy) {\n self.relayCandidatesForAny = relayCandidatesForAny\n } else {\n self.relayCandidatesForAny = RelayCandidates(entryRelays: nil, exitRelays: [])\n }\n\n // Directly setting relaysWithLocation in constructor\n if let cachedResponse = try? relaySelectorWrapper.relayCache.read().relays {\n self.relaysWithLocation = LocationRelays(\n relays: cachedResponse.wireguard.relays,\n locations: cachedResponse.locations\n )\n } else {\n self.relaysWithLocation = LocationRelays(relays: [], locations: [:])\n }\n }\n\n private var relays: [REST.ServerRelay] { relaysWithLocation.relays }\n\n var uniqueProviders: [String] {\n extractProviders(from: relays)\n }\n\n var ownedProviders: [String] {\n extractProviders(from: relays.filter { $0.owned == true })\n }\n\n var rentedProviders: [String] {\n extractProviders(from: relays.filter { $0.owned == false })\n }\n\n // MARK: - public Methods\n\n func toggleItem(_ item: RelayFilterDataSourceItem) {\n switch item.type {\n case .ownershipAny, .ownershipOwned, .ownershipRented:\n relayFilter.ownership = ownership(for: item) ?? .any\n case .allProviders:\n relayFilter.providers = relayFilter.providers == .any ? .only([]) : .any\n case .provider:\n toggleProvider(item.name)\n }\n }\n\n func availableProviders(for ownership: RelayFilter.Ownership) -> [RelayFilterDataSourceItem] {\n providers(for: ownership)\n .map {\n providerItem(for: $0)\n }.sorted()\n }\n\n func ownership(for item: RelayFilterDataSourceItem) -> RelayFilter.Ownership? {\n let ownershipMapping: [RelayFilterDataSourceItem.ItemType: RelayFilter.Ownership] = [\n .ownershipAny: .any,\n .ownershipOwned: .owned,\n .ownershipRented: .rented,\n ]\n\n return ownershipMapping[item.type]\n }\n\n func ownershipItem(for ownership: RelayFilter.Ownership) -> RelayFilterDataSourceItem? {\n let ownershipMapping: [RelayFilter.Ownership: RelayFilterDataSourceItem.ItemType] = [\n .any: .ownershipAny,\n .owned: .ownershipOwned,\n .rented: .ownershipRented,\n ]\n\n return RelayFilterDataSourceItem.ownerships\n .first { $0.type == ownershipMapping[ownership] }\n }\n\n func providerItem(for providerName: String) -> RelayFilterDataSourceItem {\n let isDaitaEnabled = settings.daita.daitaState.isEnabled\n let isProviderEnabled = isProviderEnabled(for: providerName)\n let isFilterable = getFilteredRelays(relayFilter).isEnabled\n return RelayFilterDataSourceItem(\n name: providerName,\n description: isDaitaEnabled && isProviderEnabled\n ? NSLocalizedString(\n "RELAY_FILTER_PROVIDER_DESCRIPTION_FORMAT_LABEL",\n tableName: "RelayFilter",\n value: "DAITA-enabled",\n comment: "Format for DAITA provider description"\n )\n : "",\n type: .provider,\n // If the current filter is valid, return true immediately.\n // Otherwise, check if the provider is enabled when filtering specifically by the given provider name.\n isEnabled: isFilterable || isProviderEnabled\n )\n }\n\n func getFilteredRelays(_ relayFilter: RelayFilter) -> FilterDescriptor {\n return FilterDescriptor(\n relayFilterResult: RelayCandidates(\n entryRelays: relayCandidatesForAny.entryRelays?.filter {\n RelaySelector.relayMatchesFilter($0.relay, filter: relayFilter)\n },\n exitRelays: relayCandidatesForAny.exitRelays.filter {\n RelaySelector.relayMatchesFilter($0.relay, filter: relayFilter)\n }\n ),\n settings: settings\n )\n }\n\n // MARK: - private Methods\n\n private func providers(for ownership: RelayFilter.Ownership) -> [String] {\n switch ownership {\n case .any:\n uniqueProviders\n case .owned:\n ownedProviders\n case .rented:\n rentedProviders\n }\n }\n\n private func toggleProvider(_ name: String) {\n switch relayFilter.providers {\n case .any:\n // If currently "any", switch to only the selected provider\n var providers = providers(for: relayFilter.ownership)\n providers.removeAll { $0 == name }\n relayFilter.providers = .only(providers.map { $0 })\n case var .only(selectedProviders):\n if selectedProviders.contains(name) {\n // If provider exists, remove it\n selectedProviders.removeAll { $0 == name }\n } else {\n // Otherwise, add it\n selectedProviders.append(name)\n }\n\n // If all available providers are selected, switch back to "any"\n relayFilter.providers = selectedProviders.isEmpty\n ? .only([])\n : (\n selectedProviders.count == providers(for: relayFilter.ownership).count\n ? .any\n : .only(selectedProviders)\n )\n }\n }\n\n private func extractProviders(from relays: [REST.ServerRelay]) -> [String] {\n Set(relays.map { $0.provider }).caseInsensitiveSorted()\n }\n\n private func isProviderEnabled(for providerName: String) -> Bool {\n // Check if the provider is enabled when filtering specifically by the given provider name.\n return getFilteredRelays(\n RelayFilter(ownership: relayFilter.ownership, providers: .only([providerName]))\n ).isEnabled\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\RelayFilter\RelayFilterViewModel.swift | RelayFilterViewModel.swift | Swift | 7,208 | 0.95 | 0.142105 | 0.127273 | python-kit | 407 | 2023-07-15T07:07:04.721301 | BSD-3-Clause | false | ce7b02b359e90f880e8a7c9a1b2bd89a |
//\n// RevokedDeviceInteractor.swift\n// MullvadVPN\n//\n// Created by pronebird on 26/10/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nfinal class RevokedDeviceInteractor {\n private let tunnelManager: TunnelManager\n private var tunnelObserver: TunnelObserver?\n\n var didUpdateTunnelStatus: ((TunnelStatus) -> Void)?\n\n var tunnelStatus: TunnelStatus {\n tunnelManager.tunnelStatus\n }\n\n init(tunnelManager: TunnelManager) {\n self.tunnelManager = tunnelManager\n\n let tunnelObserver =\n TunnelBlockObserver(didUpdateTunnelStatus: { [weak self] _, tunnelStatus in\n self?.didUpdateTunnelStatus?(tunnelStatus)\n })\n\n tunnelManager.addObserver(tunnelObserver)\n\n self.tunnelObserver = tunnelObserver\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\RevokedDevice\RevokedDeviceInteractor.swift | RevokedDeviceInteractor.swift | Swift | 827 | 0.95 | 0.030303 | 0.28 | node-utils | 103 | 2023-09-22T20:12:53.078848 | BSD-3-Clause | false | 9f41b71e3cf743dea6b8aa4db37e959e |
//\n// RevokedDeviceViewController.swift\n// MullvadVPN\n//\n// Created by pronebird on 07/07/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass RevokedDeviceViewController: UIViewController, RootContainment {\n private lazy var imageView: StatusImageView = {\n let statusImageView = StatusImageView(style: .failure)\n statusImageView.translatesAutoresizingMaskIntoConstraints = false\n return statusImageView\n }()\n\n private lazy var titleLabel: UILabel = {\n let titleLabel = UILabel()\n titleLabel.translatesAutoresizingMaskIntoConstraints = false\n titleLabel.font = UIFont.systemFont(ofSize: 24, weight: .bold)\n titleLabel.numberOfLines = 0\n titleLabel.textColor = .white\n titleLabel.text = NSLocalizedString(\n "TITLE_LABEL",\n tableName: "RevokedDevice",\n value: "Device is inactive",\n comment: ""\n )\n return titleLabel\n }()\n\n private lazy var bodyLabel: UILabel = {\n let bodyLabel = UILabel()\n bodyLabel.translatesAutoresizingMaskIntoConstraints = false\n bodyLabel.font = UIFont.systemFont(ofSize: 17, weight: .semibold)\n bodyLabel.numberOfLines = 0\n bodyLabel.textColor = .white\n bodyLabel.text = NSLocalizedString(\n "DESCRIPTION_LABEL",\n tableName: "RevokedDevice",\n value: "You have removed this device. To connect again, you will need to log back in.",\n comment: ""\n )\n return bodyLabel\n }()\n\n private lazy var footerLabel: UILabel = {\n let bodyLabel = UILabel()\n bodyLabel.translatesAutoresizingMaskIntoConstraints = false\n bodyLabel.font = UIFont.systemFont(ofSize: 17, weight: .semibold)\n bodyLabel.numberOfLines = 0\n bodyLabel.textColor = .white\n bodyLabel.text = NSLocalizedString(\n "UNBLOCK_INTERNET_LABEL",\n tableName: "RevokedDevice",\n value: "Going to login will unblock the Internet on this device.",\n comment: ""\n )\n return bodyLabel\n }()\n\n private lazy var logoutButton: AppButton = {\n let button = AppButton(style: .default)\n button.setAccessibilityIdentifier(.revokedDeviceLoginButton)\n button.translatesAutoresizingMaskIntoConstraints = false\n button.setTitle(\n NSLocalizedString(\n "GOTO_LOGIN_BUTTON_LABEL",\n tableName: "RevokedDevice",\n value: "Go to login",\n comment: ""\n ),\n for: .normal\n )\n return button\n }()\n\n var didFinish: (() -> Void)?\n\n override var preferredStatusBarStyle: UIStatusBarStyle {\n .lightContent\n }\n\n var preferredHeaderBarPresentation: HeaderBarPresentation {\n let tunnelState = interactor.tunnelStatus.state\n\n return HeaderBarPresentation(\n style: tunnelState.isSecured ? .secured : .unsecured,\n showsDivider: true\n )\n }\n\n var prefersHeaderBarHidden: Bool {\n false\n }\n\n private let interactor: RevokedDeviceInteractor\n\n init(interactor: RevokedDeviceInteractor) {\n self.interactor = interactor\n super.init(nibName: nil, bundle: nil)\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n override func viewDidLoad() {\n super.viewDidLoad()\n\n view.setAccessibilityIdentifier(.revokedDeviceView)\n view.backgroundColor = .secondaryColor\n view.directionalLayoutMargins = UIMetrics.contentLayoutMargins\n\n for subview in [imageView, titleLabel, bodyLabel, footerLabel, logoutButton] {\n view.addSubview(subview)\n }\n\n logoutButton.addTarget(\n self,\n action: #selector(didTapLogoutButton(_:)),\n for: .touchUpInside\n )\n\n NSLayoutConstraint.activate([\n imageView.topAnchor.constraint(\n equalTo: view.layoutMarginsGuide.topAnchor,\n constant: 30\n ),\n imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor),\n\n titleLabel.topAnchor.constraint(\n equalTo: imageView.bottomAnchor,\n constant: 30\n ),\n titleLabel.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor),\n titleLabel.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor),\n\n bodyLabel.topAnchor.constraint(\n equalTo: titleLabel.bottomAnchor,\n constant: 16\n ),\n bodyLabel.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor),\n bodyLabel.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor),\n\n footerLabel.topAnchor.constraint(\n equalTo: bodyLabel.bottomAnchor,\n constant: 16\n ),\n footerLabel.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor),\n footerLabel.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor),\n\n logoutButton.topAnchor.constraint(greaterThanOrEqualTo: footerLabel.bottomAnchor),\n logoutButton.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor),\n logoutButton.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor),\n logoutButton.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor),\n ])\n\n interactor.didUpdateTunnelStatus = { [weak self] tunnelStatus in\n self?.setNeedsHeaderBarStyleAppearanceUpdate()\n self?.updateView(tunnelState: tunnelStatus.state)\n }\n\n updateView(tunnelState: interactor.tunnelStatus.state)\n }\n\n @objc private func didTapLogoutButton(_ sender: Any?) {\n logoutButton.isEnabled = false\n\n didFinish?()\n }\n\n private func updateView(tunnelState: TunnelState) {\n logoutButton.style = tunnelState.isSecured ? .danger : .default\n footerLabel.isHidden = !tunnelState.isSecured\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\RevokedDevice\RevokedDeviceViewController.swift | RevokedDeviceViewController.swift | Swift | 6,200 | 0.95 | 0.022472 | 0.046667 | awesome-app | 156 | 2024-01-25T17:09:48.223484 | MIT | false | bc8620d7de6bea7a2239486145304c56 |
//\n// AllLocationDataSource.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-02-22.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\nimport MullvadTypes\n\nclass AllLocationDataSource: LocationDataSourceProtocol {\n private(set) var nodes = [LocationNode]()\n\n var searchableNodes: [LocationNode] {\n nodes\n }\n\n /// Constructs a collection of node trees from relays fetched from the API.\n /// ``RelayLocation.city`` is of special import since we use it to get country\n /// and city names.\n func reload(_ relays: LocationRelays) {\n let rootNode = RootLocationNode()\n let expandedRelays = nodes.flatMap { [$0] + $0.flattened }.filter { $0.showsChildren }.map { $0.code }\n\n for relay in relays.relays {\n guard\n let serverLocation = relays.locations[relay.location.rawValue]\n else { continue }\n\n let relayLocation = RelayLocation.hostname(\n String(relay.location.country),\n String(relay.location.city),\n relay.hostname\n )\n\n for ancestorOrSelf in relayLocation.ancestors + [relayLocation] {\n addLocation(\n ancestorOrSelf,\n rootNode: rootNode,\n serverLocation: serverLocation,\n relay: relay,\n showsChildren: expandedRelays.contains(ancestorOrSelf.stringRepresentation)\n )\n }\n }\n\n nodes = rootNode.children\n }\n\n func node(by location: RelayLocation) -> LocationNode? {\n let rootNode = RootLocationNode(children: nodes)\n\n return switch location {\n case let .country(countryCode):\n rootNode.descendantNodeFor(codes: [countryCode])\n case let .city(countryCode, cityCode):\n rootNode.descendantNodeFor(codes: [countryCode, cityCode])\n case let .hostname(_, _, hostCode):\n rootNode.descendantNodeFor(codes: [hostCode])\n }\n }\n\n private func addLocation(\n _ location: RelayLocation,\n rootNode: LocationNode,\n serverLocation: REST.ServerLocation,\n relay: REST.ServerRelay,\n showsChildren: Bool\n ) {\n switch location {\n case let .country(countryCode):\n let countryNode = LocationNode(\n name: serverLocation.country,\n code: LocationNode.combineNodeCodes([countryCode]),\n locations: [location],\n isActive: true, // Defaults to true, updated when children are populated.\n showsChildren: showsChildren\n )\n\n if !rootNode.children.contains(countryNode) {\n rootNode.children.append(countryNode)\n rootNode.children.sort()\n }\n\n case let .city(countryCode, cityCode):\n let cityNode = LocationNode(\n name: serverLocation.city,\n code: LocationNode.combineNodeCodes([countryCode, cityCode]),\n locations: [location],\n isActive: true, // Defaults to true, updated when children are populated.\n showsChildren: showsChildren\n )\n\n if let countryNode = rootNode.countryFor(code: countryCode),\n !countryNode.children.contains(cityNode) {\n cityNode.parent = countryNode\n countryNode.children.append(cityNode)\n countryNode.children.sort()\n }\n\n case let .hostname(countryCode, cityCode, hostCode):\n let hostNode = LocationNode(\n name: relay.hostname,\n code: LocationNode.combineNodeCodes([hostCode]),\n locations: [location],\n isActive: relay.active,\n showsChildren: showsChildren\n )\n\n if let countryNode = rootNode.countryFor(code: countryCode),\n let cityNode = countryNode.cityFor(codes: [countryCode, cityCode]),\n !cityNode.children.contains(hostNode) {\n hostNode.parent = cityNode\n cityNode.children.append(hostNode)\n cityNode.children.sort()\n\n cityNode.isActive = cityNode.children.contains(where: { hostNode in\n hostNode.isActive\n })\n\n countryNode.isActive = countryNode.children.contains(where: { cityNode in\n cityNode.isActive\n })\n }\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\SelectLocation\AllLocationDataSource.swift | AllLocationDataSource.swift | Swift | 4,562 | 0.95 | 0.062016 | 0.09009 | python-kit | 102 | 2024-12-11T18:02:18.290035 | BSD-3-Clause | false | 417c2c393127a158f91b2195fd9726c0 |
//\n// CustomListLocationNodeBuilder.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2024-03-14.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadSettings\nimport MullvadTypes\n\nstruct CustomListLocationNodeBuilder {\n let customList: CustomList\n let allLocations: [LocationNode]\n\n var customListLocationNode: CustomListLocationNode {\n let listNode = CustomListLocationNode(\n name: customList.name,\n code: customList.name,\n locations: customList.locations,\n isActive: true, // Defaults to true, updated after children have been populated.\n customList: customList\n )\n\n listNode.children = listNode.locations.compactMap { location in\n let rootNode = RootLocationNode(children: allLocations)\n\n return switch location {\n case let .country(countryCode):\n rootNode\n .countryFor(code: countryCode)?\n .copy(withParent: listNode)\n\n case let .city(countryCode, cityCode):\n rootNode\n .countryFor(code: countryCode)?\n .cityFor(codes: [countryCode, cityCode])?\n .copy(withParent: listNode)\n\n case let .hostname(countryCode, cityCode, hostCode):\n rootNode\n .countryFor(code: countryCode)?\n .cityFor(codes: [countryCode, cityCode])?\n .hostFor(code: hostCode)?\n .copy(withParent: listNode)\n }\n }\n\n listNode.isActive = !listNode.children.isEmpty\n listNode.sort()\n\n return listNode\n }\n}\n\nprivate extension CustomListLocationNode {\n func sort() {\n let sortedChildren = Dictionary(grouping: children, by: {\n return switch RelayLocation(dashSeparatedString: $0.code)! {\n case .country:\n LocationGroup.country\n case .city:\n LocationGroup.city\n case .hostname:\n LocationGroup.host\n }\n })\n .sorted(by: { $0.key < $1.key })\n .reduce([]) {\n $0 + $1.value.sorted(by: { $0.name < $1.name })\n }\n\n children = sortedChildren\n }\n}\n\nprivate enum LocationGroup: CaseIterable, Comparable {\n case country, city, host\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\SelectLocation\CustomListLocationNodeBuilder.swift | CustomListLocationNodeBuilder.swift | Swift | 2,387 | 0.95 | 0.025 | 0.102941 | awesome-app | 601 | 2025-01-28T22:14:04.517536 | MIT | false | 2317eadb7013c12760eed4a1ea5fb0bf |
//\n// CustomListsDataSource.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-02-22.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\nimport MullvadSettings\nimport MullvadTypes\n\nclass CustomListsDataSource: LocationDataSourceProtocol {\n private(set) var nodes = [LocationNode]()\n private(set) var repository: CustomListRepositoryProtocol\n\n init(repository: CustomListRepositoryProtocol) {\n self.repository = repository\n }\n\n var searchableNodes: [LocationNode] {\n nodes.flatMap { $0.children }\n }\n\n /// Constructs a collection of node trees by copying each matching counterpart\n /// from the complete list of nodes created in ``AllLocationDataSource``.\n func reload(allLocationNodes: [LocationNode]) {\n let expandedRelays = nodes.flatMap { [$0] + $0.flattened }.filter { $0.showsChildren }.map { $0.code }\n nodes = repository.fetchAll().map { list in\n let customListWrapper = CustomListLocationNodeBuilder(customList: list, allLocations: allLocationNodes)\n let listNode = customListWrapper.customListLocationNode\n listNode.showsChildren = expandedRelays.contains(listNode.code)\n\n listNode.forEachDescendant { node in\n // Each item in a section in a diffable data source needs to be unique.\n // Since LocationCellViewModel partly depends on LocationNode.code for\n // equality, each node code needs to be prefixed with the code of its\n // parent custom list to uphold this.\n node.code = LocationNode.combineNodeCodes([listNode.code, node.code])\n node.showsChildren = expandedRelays.contains(node.code)\n }\n\n return listNode\n }\n }\n\n func node(by relays: UserSelectedRelays, for customList: CustomList) -> LocationNode? {\n guard let listNode = nodes.first(where: { $0.name == customList.name }) else { return nil }\n\n if relays.customListSelection?.isList == true {\n return listNode\n } else {\n // Each search for descendant nodes needs the parent custom list node code to be\n // prefixed in order to get a match. See comment in reload() above.\n return switch relays.locations.first {\n case let .country(countryCode):\n listNode.descendantNodeFor(codes: [listNode.code, countryCode])\n case let .city(countryCode, cityCode):\n listNode.descendantNodeFor(codes: [listNode.code, countryCode, cityCode])\n case let .hostname(_, _, hostCode):\n listNode.descendantNodeFor(codes: [listNode.code, hostCode])\n case .none:\n nil\n }\n }\n }\n\n func customList(by id: UUID) -> CustomList? {\n repository.fetch(by: id)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\SelectLocation\CustomListsDataSource.swift | CustomListsDataSource.swift | Swift | 2,885 | 0.95 | 0.083333 | 0.241935 | awesome-app | 915 | 2024-04-04T00:03:17.502030 | MIT | false | c27ff55faf8038aaaa6d0c5df1a59a98 |
//\n// DAITAInfoView.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-10-10.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass DAITAInfoView: UIView {\n let infoLabel: UILabel = {\n let label = UILabel()\n label.numberOfLines = 0\n\n let infoTextParagraphStyle = NSMutableParagraphStyle()\n infoTextParagraphStyle.lineSpacing = 1.3\n infoTextParagraphStyle.alignment = .center\n\n label.attributedText = NSAttributedString(\n string: NSLocalizedString(\n "SELECT_LOCATION_DAITA_INFO",\n tableName: "SelectLocation",\n value: """\n The entry server for multihop is currently overridden by DAITA. \\n To select an entry server, please first enable “Direct only” or disable “DAITA” in the settings.\n """,\n comment: ""\n ),\n attributes: [\n .font: UIFont.systemFont(ofSize: 15),\n .foregroundColor: UIColor.white,\n .paragraphStyle: infoTextParagraphStyle,\n ]\n )\n\n return label\n }()\n\n let settingsButton: UIButton = {\n let settingsButton = AppButton(style: .default)\n settingsButton.setTitle(NSLocalizedString(\n "SELECT_LOCATION_DAITA_BUTTON",\n tableName: "SelectLocation",\n value: "Open DAITA settings",\n comment: ""\n ), for: .normal)\n\n return settingsButton\n }()\n\n var didPressDaitaSettingsButton: (() -> Void)?\n\n init() {\n super.init(frame: .zero)\n\n backgroundColor = .secondaryColor\n layoutMargins = UIMetrics.contentInsets\n\n settingsButton.addTarget(self, action: #selector(didPressButton), for: .touchUpInside)\n\n addConstrainedSubviews([infoLabel, settingsButton]) {\n infoLabel.pinEdgesToSuperviewMargins(.init([.leading(24), .trailing(24)]))\n\n settingsButton.pinEdgesToSuperviewMargins(.init([.leading(0), .trailing(0)]))\n settingsButton.topAnchor.constraint(equalTo: infoLabel.bottomAnchor, constant: 32)\n settingsButton.bottomAnchor.constraint(equalTo: centerYAnchor)\n }\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n @objc private func didPressButton() {\n didPressDaitaSettingsButton?()\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\SelectLocation\DAITAInfoView.swift | DAITAInfoView.swift | Swift | 2,436 | 0.95 | 0.051282 | 0.111111 | awesome-app | 817 | 2024-01-21T11:54:10.285885 | Apache-2.0 | false | 2d865f97e29368d9e0bd32de0da92427 |
//\n// LocationCell.swift\n// MullvadVPN\n//\n// Created by pronebird on 02/05/2019.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nprotocol LocationCellDelegate: AnyObject {\n func toggleExpanding(cell: LocationCell)\n func toggleSelecting(cell: LocationCell)\n}\n\nclass LocationCell: UITableViewCell {\n weak var delegate: LocationCellDelegate?\n\n private let locationLabel: UILabel = {\n let label = UILabel()\n label.font = UIFont.systemFont(ofSize: 16)\n label.textColor = .white\n label.lineBreakMode = .byTruncatingTail\n label.numberOfLines = 1\n return label\n }()\n\n private let statusIndicator: UIView = {\n let view = UIView()\n view.layer.cornerRadius = 8\n view.layer.cornerCurve = .circular\n return view\n }()\n\n private let tickImageView: UIImageView = {\n let imageView = UIImageView(image: UIImage.tick)\n imageView.tintColor = .white\n return imageView\n }()\n\n private let checkboxButton: UIButton = {\n let button = UIButton()\n let checkboxView = CheckboxView()\n\n checkboxView.isUserInteractionEnabled = false\n button.addConstrainedSubviews([checkboxView]) {\n checkboxView.pinEdgesToSuperviewMargins(PinnableEdges([.top(8), .bottom(8), .leading(16), .trailing(16)]))\n }\n\n return button\n }()\n\n private let collapseButton: UIButton = {\n let button = UIButton(type: .custom)\n button.isAccessibilityElement = false\n button.tintColor = .white\n return button\n }()\n\n private var locationLabelLeadingMargin: CGFloat {\n switch behavior {\n case .add:\n 0\n case .select:\n 12\n }\n }\n\n private var behavior: LocationCellBehavior = .select\n private let chevronDown = UIImage.CellDecoration.chevronDown\n private let chevronUp = UIImage.CellDecoration.chevronUp\n\n var isDisabled = false {\n didSet {\n updateDisabled(isDisabled)\n updateBackgroundColor()\n updateStatusIndicatorColor()\n }\n }\n\n var isExpanded = false {\n didSet {\n updateCollapseImage()\n updateAccessibilityCustomActions()\n }\n }\n\n var showsCollapseControl = false {\n didSet {\n collapseButton.isHidden = !showsCollapseControl\n updateAccessibilityCustomActions()\n }\n }\n\n override var indentationLevel: Int {\n didSet {\n updateBackgroundColor()\n setLayoutMargins()\n }\n }\n\n override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {\n super.init(style: style, reuseIdentifier: reuseIdentifier)\n\n setupCell()\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n private func setLayoutMargins() {\n let indentation = CGFloat(indentationLevel) * indentationWidth\n\n var contentMargins = UIMetrics.locationCellLayoutMargins\n contentMargins.leading += indentation\n\n contentView.directionalLayoutMargins = contentMargins\n }\n\n override func setHighlighted(_ highlighted: Bool, animated: Bool) {\n super.setHighlighted(highlighted, animated: animated)\n\n updateStatusIndicatorColor()\n }\n\n override func setSelected(_ selected: Bool, animated: Bool) {\n super.setSelected(selected, animated: animated)\n\n updateLeadingImage()\n updateStatusIndicatorColor()\n }\n\n private func setupCell() {\n indentationWidth = UIMetrics.TableView.cellIndentationWidth\n\n backgroundColor = .clear\n contentView.backgroundColor = .clear\n\n backgroundView = UIView()\n selectedBackgroundView = UIView()\n\n checkboxButton.addTarget(self, action: #selector(toggleCheckboxButton(_:)), for: .touchUpInside)\n collapseButton.addTarget(self, action: #selector(handleCollapseButton(_:)), for: .touchUpInside)\n\n [locationLabel, tickImageView, statusIndicator, collapseButton].forEach { subview in\n subview.translatesAutoresizingMaskIntoConstraints = false\n contentView.addSubview(subview)\n }\n\n updateCollapseImage()\n updateAccessibilityCustomActions()\n updateDisabled(isDisabled)\n updateBackgroundColor()\n setLayoutMargins()\n\n contentView.addConstrainedSubviews([\n tickImageView,\n statusIndicator,\n locationLabel,\n collapseButton,\n checkboxButton,\n ]) {\n tickImageView.pinEdgesToSuperviewMargins(PinnableEdges([.leading(0)]))\n tickImageView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor)\n\n statusIndicator.widthAnchor.constraint(equalToConstant: 16)\n statusIndicator.heightAnchor.constraint(equalTo: statusIndicator.widthAnchor)\n statusIndicator.centerXAnchor.constraint(equalTo: tickImageView.centerXAnchor)\n statusIndicator.centerYAnchor.constraint(equalTo: tickImageView.centerYAnchor)\n\n checkboxButton.pinEdgesToSuperview(PinnableEdges([.top(0), .bottom(0)]))\n checkboxButton.trailingAnchor.constraint(equalTo: locationLabel.leadingAnchor, constant: 14)\n checkboxButton.widthAnchor.constraint(\n equalToConstant: UIMetrics.contentLayoutMargins.leading + UIMetrics.contentLayoutMargins.trailing + 24\n )\n\n locationLabel.pinEdgesToSuperviewMargins(PinnableEdges([.top(0), .bottom(0)]))\n locationLabel.leadingAnchor.constraint(\n equalTo: statusIndicator.trailingAnchor,\n constant: locationLabelLeadingMargin\n )\n locationLabel.trailingAnchor.constraint(lessThanOrEqualTo: collapseButton.leadingAnchor)\n .withPriority(.defaultHigh)\n\n collapseButton.widthAnchor.constraint(\n equalToConstant: UIMetrics.contentLayoutMargins.leading + UIMetrics.contentLayoutMargins.trailing + 24\n )\n collapseButton.pinEdgesToSuperview(.all().excluding(.leading))\n }\n }\n\n private func updateLeadingImage() {\n switch behavior {\n case .add:\n checkboxButton.isHidden = false\n statusIndicator.isHidden = true\n tickImageView.isHidden = true\n case .select:\n checkboxButton.isHidden = true\n statusIndicator.isHidden = isSelected\n tickImageView.isHidden = !isSelected\n }\n }\n\n private func updateStatusIndicatorColor() {\n statusIndicator.backgroundColor = statusIndicatorColor()\n }\n\n private func updateDisabled(_ isDisabled: Bool) {\n locationLabel.alpha = isDisabled ? 0.2 : 1\n\n if isDisabled {\n accessibilityTraits.insert(.notEnabled)\n } else {\n accessibilityTraits.remove(.notEnabled)\n }\n }\n\n private func updateBackgroundColor() {\n backgroundView?.backgroundColor = backgroundColorForIdentationLevel()\n selectedBackgroundView?.backgroundColor = selectedBackgroundColorForIndentationLevel()\n }\n\n private func backgroundColorForIdentationLevel() -> UIColor {\n switch indentationLevel {\n case 1:\n return UIColor.Cell.Background.indentationLevelOne\n case 2:\n return UIColor.Cell.Background.indentationLevelTwo\n case 3:\n return UIColor.Cell.Background.indentationLevelThree\n default:\n return UIColor.Cell.Background.normal\n }\n }\n\n private func selectedBackgroundColorForIndentationLevel() -> UIColor {\n if isDisabled {\n return UIColor.Cell.Background.disabledSelected\n } else {\n return UIColor.Cell.Background.selected\n }\n }\n\n private func statusIndicatorColor() -> UIColor {\n if isDisabled {\n return UIColor.RelayStatusIndicator.inactiveColor\n } else if isHighlighted {\n return UIColor.RelayStatusIndicator.highlightColor\n } else {\n return UIColor.RelayStatusIndicator.activeColor\n }\n }\n\n @objc private func handleCollapseButton(_ sender: UIControl) {\n delegate?.toggleExpanding(cell: self)\n }\n\n @objc private func toggleCollapseAccessibilityAction() -> Bool {\n delegate?.toggleExpanding(cell: self)\n return true\n }\n\n private func updateCollapseImage() {\n let image = isExpanded ? chevronUp : chevronDown\n\n collapseButton.setAccessibilityIdentifier(isExpanded ? .collapseButton : .expandButton)\n collapseButton.setImage(image, for: .normal)\n }\n\n private func updateAccessibilityCustomActions() {\n if showsCollapseControl {\n let actionName = isExpanded\n ? NSLocalizedString(\n "SELECT_LOCATION_COLLAPSE_ACCESSIBILITY_ACTION",\n tableName: "SelectLocation",\n value: "Collapse location",\n comment: ""\n )\n : NSLocalizedString(\n "SELECT_LOCATION_EXPAND_ACCESSIBILITY_ACTION",\n tableName: "SelectLocation",\n value: "Expand location",\n comment: ""\n )\n\n accessibilityCustomActions = [\n UIAccessibilityCustomAction(\n name: actionName,\n target: self,\n selector: #selector(toggleCollapseAccessibilityAction)\n ),\n ]\n } else {\n accessibilityCustomActions = nil\n }\n }\n\n @objc private func toggleCheckboxButton(_ sender: UIControl) {\n delegate?.toggleSelecting(cell: self)\n }\n}\n\nextension LocationCell {\n enum LocationCellBehavior {\n case add\n case select\n }\n\n func configure(item: LocationCellViewModel, behavior: LocationCellBehavior) {\n isDisabled = !item.node.isActive\n locationLabel.text = item.node.name\n showsCollapseControl = !item.node.children.isEmpty\n isExpanded = item.node.showsChildren\n accessibilityValue = item.node.code\n checkboxButton.setAccessibilityIdentifier(.customListLocationCheckmarkButton)\n\n for view in checkboxButton.subviews where view is CheckboxView {\n let checkboxView = view as? CheckboxView\n checkboxView?.isChecked = item.isSelected\n }\n\n if item.node is CustomListLocationNode {\n setAccessibilityIdentifier(.customListLocationCell)\n } else {\n // Only custom list nodes have more than one location. Therefore checking first\n // location here is fine.\n if let location = item.node.locations.first {\n let accessibilityId: AccessibilityIdentifier = switch location {\n case .country: .countryLocationCell\n case .city: .cityLocationCell\n case .hostname: .relayLocationCell\n }\n setAccessibilityIdentifier(accessibilityId)\n }\n }\n\n setBehavior(behavior)\n }\n\n func setExcluded(relayTitle: String? = nil) {\n updateDisabled(true)\n\n if let relayTitle {\n locationLabel.text! += " (\(relayTitle))"\n }\n }\n\n private func setBehavior(_ newBehavior: LocationCellBehavior) {\n self.behavior = newBehavior\n updateLeadingImage()\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\SelectLocation\LocationCell.swift | LocationCell.swift | Swift | 11,490 | 0.95 | 0.048023 | 0.030612 | vue-tools | 947 | 2023-08-13T07:34:17.955775 | GPL-3.0 | false | f2b9f925315252399273e0b5f31ffab9 |
//\n// LocationCellViewModel.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2024-02-05.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadTypes\n\nstruct LocationCellViewModel: Hashable, Sendable {\n let section: LocationSection\n let node: LocationNode\n var indentationLevel = 0\n var isSelected = false\n var excludedRelayTitle: String?\n\n func hash(into hasher: inout Hasher) {\n hasher.combine(node)\n hasher.combine(node.children.count)\n hasher.combine(section)\n hasher.combine(isSelected)\n }\n\n static func == (lhs: Self, rhs: Self) -> Bool {\n lhs.node == rhs.node &&\n lhs.node.children.count == rhs.node.children.count &&\n lhs.section == rhs.section &&\n lhs.isSelected == rhs.isSelected\n }\n}\n\nextension [LocationCellViewModel] {\n mutating func addSubNodes(from item: LocationCellViewModel, at indexPath: IndexPath) {\n let section = LocationSection.allCases[indexPath.section]\n let row = indexPath.row + 1\n item.node.showsChildren = true\n\n let locations = item.node.children.map {\n LocationCellViewModel(\n section: section,\n node: $0,\n indentationLevel: item.indentationLevel + 1,\n isSelected: item.isSelected\n )\n }\n\n if row < count {\n insert(contentsOf: locations, at: row)\n } else {\n append(contentsOf: locations)\n }\n }\n\n mutating func removeSubNodes(from node: LocationNode) {\n for node in node.children {\n node.showsChildren = false\n removeAll(where: { node == $0.node })\n\n removeSubNodes(from: node)\n }\n }\n}\n\nextension LocationCellViewModel {\n /* Exclusion of other locations in the same node tree (as the currently excluded location)\n happens when there are no more hosts in that tree that can be selected.\n We check this by doing the following, in order:\n\n 1. Count hostnames in the tree. More than one means that there are other locations than\n the excluded one for the relay selector to choose from. No exlusion.\n\n 2. Count hostnames in the excluded node. More than one means that there are multiple\n locations for the relay selector to choose from. No exclusion.\n\n 3. Check existance of a location in the tree that matches the currently excluded location.\n No match means no exclusion.\n */\n func shouldExcludeLocation(_ excludedLocation: LocationCellViewModel?) -> Bool {\n guard let excludedLocation else {\n return false\n }\n\n let proxyNode = RootLocationNode(children: [node])\n let allLocations = Set(proxyNode.flattened.flatMap { $0.locations })\n let hostCount = allLocations.filter { location in\n if case .hostname = location { true } else { false }\n }.count\n\n // If the there's more than one selectable relay in the current node we don't need\n // to show this in the location tree and can return early.\n guard hostCount == 1 else { return false }\n\n let proxyExcludedNode = RootLocationNode(children: [excludedLocation.node])\n let allExcludedLocations = Set(proxyExcludedNode.flattened.flatMap { $0.locations })\n let excludedHostCount = allExcludedLocations.filter { location in\n if case .hostname = location { true } else { false }\n }.count\n\n // If the there's more than one selectable relay in the excluded node we don't need\n // to show this in the location tree and can return early.\n guard excludedHostCount == 1 else { return false }\n\n var containsExcludedLocation = false\n if allLocations.contains(where: { allExcludedLocations.contains($0) }) {\n containsExcludedLocation = true\n }\n\n // If the tree doesn't contain the excluded node we do nothing, otherwise the\n // required conditions have now all been met.\n return containsExcludedLocation\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\SelectLocation\LocationCellViewModel.swift | LocationCellViewModel.swift | Swift | 4,048 | 0.95 | 0.061947 | 0.159574 | python-kit | 896 | 2024-09-30T15:02:51.346138 | MIT | false | 393638df215e6588d6bcdab6067e16de |
//\n// LocationDataSource.swift\n// MullvadVPN\n//\n// Created by pronebird on 11/03/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport MullvadREST\nimport MullvadSettings\nimport MullvadTypes\nimport UIKit\n\nfinal class LocationDataSource:\n UITableViewDiffableDataSource<LocationSection, LocationCellViewModel>,\n LocationDiffableDataSourceProtocol {\n nonisolated(unsafe) private var currentSearchString = ""\n nonisolated(unsafe) private var dataSources: [LocationDataSourceProtocol] = []\n // The selected location.\n nonisolated(unsafe) private var selectedLocation: LocationCellViewModel?\n // When multihop is enabled, this is the "inverted" selected location, ie. entry\n // if in exit mode and exit if in entry mode.\n nonisolated(unsafe) private var excludedLocation: LocationCellViewModel?\n let tableView: UITableView\n let sections: [LocationSection]\n\n var didSelectRelayLocations: (@Sendable (UserSelectedRelays) -> Void)?\n var didTapEditCustomLists: (@Sendable () -> Void)?\n\n init(\n tableView: UITableView,\n allLocations: LocationDataSourceProtocol,\n customLists: LocationDataSourceProtocol\n ) {\n self.tableView = tableView\n\n let sections: [LocationSection] = LocationSection.allCases\n self.sections = sections\n\n self.dataSources.append(contentsOf: [customLists, allLocations])\n\n super.init(tableView: tableView) { _, indexPath, itemIdentifier in\n let cell = tableView.dequeueReusableView(\n withIdentifier: sections[indexPath.section],\n for: indexPath\n ) as! LocationCell // swiftlint:disable:this force_cast\n cell.configure(item: itemIdentifier, behavior: .select)\n return cell\n }\n\n tableView.delegate = self\n tableView.registerReusableViews(from: LocationSection.self)\n defaultRowAnimation = .fade\n }\n\n func setRelays(_ relaysWithLocation: LocationRelays, selectedRelays: RelaySelection) {\n Task { @MainActor in\n guard let allLocationsDataSource = dataSources\n .first(where: { $0 is AllLocationDataSource }) as? AllLocationDataSource,\n let customListsDataSource = dataSources\n .first(where: { $0 is CustomListsDataSource }) as? CustomListsDataSource else { return }\n allLocationsDataSource.reload(relaysWithLocation)\n customListsDataSource.reload(allLocationNodes: allLocationsDataSource.nodes)\n Task { @MainActor in\n setSelectedRelays(selectedRelays)\n filterRelays(by: currentSearchString)\n }\n }\n }\n\n func filterRelays(by searchString: String) {\n Task { @MainActor in\n currentSearchString = searchString\n\n let list = sections.enumerated().map { index, section in\n self.dataSources[index]\n .search(by: searchString)\n .flatMap { node in\n let rootNode = RootLocationNode(children: [node])\n return self.recursivelyCreateCellViewModelTree(\n for: rootNode,\n in: section,\n indentationLevel: 0\n )\n }\n }\n\n DispatchQueue.main.async {\n self.reloadDataSnapshot(with: list) {\n if searchString.isEmpty, let selectedLocation = self.selectedLocation {\n self.updateSelection(selectedLocation: selectedLocation, completion: {\n self.scrollToSelectedRelay()\n })\n } else {\n self.scrollToTop(animated: false)\n }\n }\n }\n }\n }\n\n /// Refreshes the custom list section and keeps all modifications intact (selection and expanded states).\n func refreshCustomLists() {\n Task { @MainActor in\n guard let allLocationsDataSource =\n dataSources.first(where: { $0 is AllLocationDataSource }) as? AllLocationDataSource,\n let customListsDataSource =\n dataSources.first(where: { $0 is CustomListsDataSource }) as? CustomListsDataSource\n else {\n return\n }\n\n // Reload data source with (possibly) updated custom lists.\n customListsDataSource.reload(allLocationNodes: allLocationsDataSource.nodes)\n self.filterRelays(by: currentSearchString)\n }\n }\n\n func setSelectedRelays(_ selectedRelays: RelaySelection) {\n Task { @MainActor in\n guard let _selectedLocation = mapSelection(from: selectedRelays.selected) else { return }\n selectedLocation = _selectedLocation\n excludedLocation = mapSelection(from: selectedRelays.excluded)\n excludedLocation?.excludedRelayTitle = selectedRelays.excludedTitle\n self.updateSelection(selectedLocation: _selectedLocation, completion: {\n self.scrollToSelectedRelay()\n })\n }\n }\n\n // MARK: - Private functions\n\n private func scrollToSelectedRelay() {\n indexPathForSelectedRelay()\n .flatMap {\n tableView.scrollToRow(at: $0, at: .middle, animated: false)\n }\n }\n\n private func indexPathForSelectedRelay() -> IndexPath? {\n selectedLocation.flatMap { indexPath(for: $0) }\n }\n\n private func mapSelection(from selectedRelays: UserSelectedRelays?) -> LocationCellViewModel? {\n let allLocationsDataSource =\n dataSources.first(where: { $0 is AllLocationDataSource }) as? AllLocationDataSource\n\n let customListsDataSource =\n dataSources.first(where: { $0 is CustomListsDataSource }) as? CustomListsDataSource\n\n if let selectedRelays {\n // Look for a matching custom list node.\n if let customListSelection = selectedRelays.customListSelection,\n let customList = customListsDataSource?.customList(by: customListSelection.listId),\n let selectedNode = customListsDataSource?.node(by: selectedRelays, for: customList) {\n return LocationCellViewModel(\n section: .customLists,\n node: selectedNode,\n indentationLevel: selectedNode.hierarchyLevel\n )\n // Look for a matching all locations node.\n } else if let location = selectedRelays.locations.first,\n let selectedNode = allLocationsDataSource?.node(by: location) {\n return LocationCellViewModel(\n section: .allLocations,\n node: selectedNode,\n indentationLevel: selectedNode.hierarchyLevel\n )\n }\n }\n\n return nil\n }\n\n private func updateSelection(selectedLocation: LocationCellViewModel, completion: (() -> Void)? = nil) {\n let rootNode = selectedLocation.node.root\n var snapshot = snapshot()\n\n // Exit early if no changes to the node tree should be made.\n guard selectedLocation.node != rootNode else {\n // Apply the updated snapshot\n DispatchQueue.main.async {\n self.applySnapshotUsingReloadData(snapshot, completion: completion)\n }\n return\n }\n\n // Make sure we have an index path for the selected item.\n guard let indexPath = indexPath(for: LocationCellViewModel(\n section: selectedLocation.section,\n node: rootNode\n )) else { return }\n\n // Walk tree backwards to determine which nodes should be expanded.\n selectedLocation.node.forEachAncestor { node in\n node.showsChildren = true\n }\n\n // Construct node tree.\n let nodesToAdd = recursivelyCreateCellViewModelTree(\n for: rootNode,\n in: selectedLocation.section,\n indentationLevel: 1\n )\n\n let existingItems = snapshot.itemIdentifiers(inSection: selectedLocation.section)\n snapshot.deleteItems(nodesToAdd)\n snapshot.insertItems(nodesToAdd, afterItem: existingItems[indexPath.row])\n\n // Apply the updated snapshot\n DispatchQueue.main.async {\n self.applySnapshotUsingReloadData(snapshot, completion: completion)\n }\n }\n\n override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {\n let cell = super.tableView(tableView, cellForRowAt: indexPath)\n guard let cell = cell as? LocationCell, let item = itemIdentifier(for: indexPath) else {\n return cell\n }\n\n cell.delegate = self\n\n if item.shouldExcludeLocation(excludedLocation) {\n // Only host locations should have an excluded title. Since custom list nodes contain\n // all locations of all child nodes, its first location could possibly be a host.\n // Therefore we need to check for that as well.\n if case .hostname = item.node.locations.first, !(item.node is CustomListLocationNode) {\n cell.setExcluded(relayTitle: excludedLocation?.excludedRelayTitle)\n } else {\n cell.setExcluded()\n }\n }\n\n return cell\n }\n}\n\n// MARK: - Called from LocationDiffableDataSourceProtocol\n\nextension LocationDataSource {\n func nodeShowsChildren(_ node: LocationNode) -> Bool {\n node.showsChildren\n }\n\n func nodeShouldBeSelected(_ node: LocationNode) -> Bool {\n false // N/A\n }\n}\n\nextension LocationDataSource: UITableViewDelegate {\n func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {\n switch sections[section] {\n case .allLocations:\n LocationSectionHeaderFooterView(\n configuration: LocationSectionHeaderFooterView.Configuration(\n name: LocationSection.allLocations.header,\n style: .header\n )\n )\n case .customLists:\n LocationSectionHeaderFooterView(configuration: LocationSectionHeaderFooterView.Configuration(\n name: LocationSection.customLists.header,\n style: .header,\n primaryAction: UIAction(\n handler: { [weak self] _ in\n self?.didTapEditCustomLists?()\n }\n )\n ))\n }\n }\n\n func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {\n switch sections[section] {\n case .allLocations:\n return LocationSectionHeaderFooterView(configuration: LocationSectionHeaderFooterView.Configuration(\n name: LocationSection.allLocations.footer,\n style: .footer,\n directionalEdgeInsets: NSDirectionalEdgeInsets(top: 24, leading: 16, bottom: 0, trailing: 16)\n ))\n case .customLists:\n guard dataSources[section].nodes.isEmpty else {\n return nil\n }\n\n let text = NSMutableAttributedString(string: NSLocalizedString(\n "CUSTOM_LIST_FOOTER",\n tableName: "SelectLocation",\n value: "To create a custom list, tap on ",\n comment: ""\n ))\n\n text.append(NSAttributedString(string: "\""))\n\n if let image = UIImage(systemName: "ellipsis") {\n text.append(NSAttributedString(attachment: NSTextAttachment(image: image)))\n } else {\n text.append(NSAttributedString(string: "..."))\n }\n\n text.append(NSAttributedString(string: "\""))\n\n var contentConfiguration = UIListContentConfiguration.mullvadGroupedFooter(tableStyle: tableView.style)\n contentConfiguration.attributedText = text\n\n return UIListContentView(configuration: contentConfiguration)\n }\n }\n\n func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {\n switch sections[section] {\n case .allLocations:\n dataSources[section].nodes.isEmpty ? 80 : .zero\n case .customLists:\n dataSources[section].nodes.isEmpty ? UITableView.automaticDimension : 24\n }\n }\n\n func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {\n guard let item = itemIdentifier(for: indexPath) else { return false }\n return !item.shouldExcludeLocation(excludedLocation) && item.node.isActive\n }\n\n func tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: IndexPath) -> Int {\n itemIdentifier(for: indexPath)?.indentationLevel ?? 0\n }\n\n func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {\n if let item = itemIdentifier(for: indexPath) {\n cell.setSelected(item == selectedLocation, animated: false)\n }\n }\n\n func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {\n if let indexPath = indexPathForSelectedRelay() {\n tableView.deselectRow(at: indexPath, animated: false)\n }\n return indexPath\n }\n\n func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {\n guard let item = itemIdentifier(for: indexPath) else { return }\n selectedLocation = item\n var customListSelection: UserSelectedRelays.CustomListSelection?\n if let topmostNode = item.node.root as? CustomListLocationNode {\n customListSelection = UserSelectedRelays.CustomListSelection(\n listId: topmostNode.customList.id,\n isList: topmostNode == item.node\n )\n }\n\n let relayLocations = UserSelectedRelays(\n locations: item.node.locations,\n customListSelection: customListSelection\n )\n didSelectRelayLocations?(relayLocations)\n }\n\n private func scrollToTop(animated: Bool) {\n tableView.setContentOffset(.zero, animated: animated)\n }\n}\n\nextension LocationDataSource: @preconcurrency LocationCellDelegate {\n func toggleExpanding(cell: LocationCell) {\n guard let indexPath = tableView.indexPath(for: cell),\n let item = itemIdentifier(for: indexPath) else { return }\n toggleItems(for: cell) {\n self.scroll(to: item, animated: true)\n }\n }\n\n func toggleSelecting(cell: LocationCell) {\n // No op.\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\SelectLocation\LocationDataSource.swift | LocationDataSource.swift | Swift | 14,731 | 0.95 | 0.092593 | 0.080247 | node-utils | 32 | 2025-06-15T12:14:05.372695 | GPL-3.0 | false | 0007195731815cb3c2527537b593014a |
//\n// LocationDataSourceProtocol.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2024-02-07.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\nimport MullvadTypes\n\nprotocol LocationDataSourceProtocol {\n var nodes: [LocationNode] { get }\n var searchableNodes: [LocationNode] { get }\n}\n\nextension LocationDataSourceProtocol {\n func search(by text: String) -> [LocationNode] {\n guard !text.isEmpty else {\n return nodes\n }\n\n var filteredNodes: [LocationNode] = []\n\n searchableNodes.forEach { node in\n // Use a copy of the node to preserve the expanded state,\n // allowing us to restore the previous view state after a search.\n let countryNode = node.copy()\n\n countryNode.showsChildren = false\n\n if countryNode.name.fuzzyMatch(text) {\n filteredNodes.append(countryNode)\n }\n\n countryNode.children.forEach { cityNode in\n cityNode.showsChildren = false\n cityNode.isHiddenFromSearch = true\n\n var relaysContainSearchString = false\n cityNode.children.forEach { hostNode in\n hostNode.isHiddenFromSearch = true\n\n if hostNode.name.fuzzyMatch(text) {\n relaysContainSearchString = true\n hostNode.isHiddenFromSearch = false\n }\n }\n\n if cityNode.name.fuzzyMatch(text) || relaysContainSearchString {\n if !filteredNodes.contains(countryNode) {\n filteredNodes.append(countryNode)\n }\n\n countryNode.showsChildren = true\n cityNode.isHiddenFromSearch = false\n\n if relaysContainSearchString {\n cityNode.showsChildren = true\n }\n }\n }\n }\n\n return filteredNodes\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\SelectLocation\LocationDataSourceProtocol.swift | LocationDataSourceProtocol.swift | Swift | 2,025 | 0.95 | 0.073529 | 0.166667 | python-kit | 276 | 2023-08-29T22:04:46.467741 | GPL-3.0 | false | 661bb36849c2e1b87cf4f1052b13f6ed |
//\n// LocationDiffableDataSourceProtocol.swift\n// MullvadVPNUITests\n//\n// Created by Jon Petersson on 2024-03-27.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadTypes\nimport UIKit\n\nprotocol LocationDiffableDataSourceProtocol: UITableViewDiffableDataSource<LocationSection, LocationCellViewModel> {\n var tableView: UITableView { get }\n var sections: [LocationSection] { get }\n func nodeShowsChildren(_ node: LocationNode) -> Bool\n func nodeShouldBeSelected(_ node: LocationNode) -> Bool\n}\n\nextension LocationDiffableDataSourceProtocol {\n func scroll(to item: LocationCellViewModel, animated: Bool) {\n guard\n let visibleIndexPaths = tableView.indexPathsForVisibleRows,\n let indexPath = indexPath(for: item)\n else { return }\n\n if item.node.children.count > visibleIndexPaths.count {\n tableView.scrollToRow(at: indexPath, at: .top, animated: animated)\n } else {\n if let last = item.node.children.last {\n if let lastInsertedIndexPath = self.indexPath(for: LocationCellViewModel(\n section: sections[indexPath.section],\n node: last\n )),\n let lastVisibleIndexPath = visibleIndexPaths.last,\n lastInsertedIndexPath >= lastVisibleIndexPath {\n tableView.scrollToRow(at: lastInsertedIndexPath, at: .bottom, animated: animated)\n }\n }\n }\n }\n\n func toggleItems(for cell: LocationCell, completion: (() -> Void)? = nil) {\n guard let indexPath = tableView.indexPath(for: cell),\n let item = itemIdentifier(for: indexPath) else { return }\n let snapshot = snapshot()\n let section = sections[indexPath.section]\n let isExpanded = item.node.showsChildren\n var locationList = snapshot.itemIdentifiers(inSection: section)\n\n item.node.showsChildren = !isExpanded\n\n if !isExpanded {\n locationList.addSubNodes(from: item, at: indexPath)\n addItem(locationList, toSection: section, index: indexPath.row, completion: completion)\n } else {\n locationList.removeSubNodes(from: item.node)\n updateSnapshotRetainingOnly(locationList, toSection: section, completion: completion)\n }\n }\n\n private func addItem(\n _ items: [LocationCellViewModel],\n toSection section: LocationSection,\n index: Int,\n completion: (() -> Void)? = nil\n ) {\n var snapshot = snapshot()\n let existingItems = snapshot.itemIdentifiers(inSection: section)\n\n // Filter itemsToAdd to only include items not already in the section\n let uniqueItems = items.filter { item in\n existingItems.firstIndex(where: { $0 == item }) == nil\n }\n\n // Insert unique items at the specified index\n if index < existingItems.count {\n snapshot.insertItems(uniqueItems, afterItem: existingItems[index])\n } else {\n // If the index is beyond bounds, append to the end\n snapshot.appendItems(uniqueItems, toSection: section)\n }\n applyAndReconfigureSnapshot(snapshot, in: section, completion: completion)\n }\n\n private func updateSnapshotRetainingOnly(\n _ itemsToKeep: [LocationCellViewModel],\n toSection section: LocationSection,\n completion: (() -> Void)? = nil\n ) {\n var snapshot = snapshot()\n\n // Ensure the section exists in the snapshot\n guard snapshot.sectionIdentifiers.contains(section) else { return }\n\n // Get the current items in the section\n let currentItems = snapshot.itemIdentifiers(inSection: section)\n\n // Determine the items that should be deleted\n let itemsToDelete = currentItems.filter { !itemsToKeep.contains($0) }\n snapshot.deleteItems(itemsToDelete)\n\n // Apply the updated snapshot\n applyAndReconfigureSnapshot(snapshot, in: section, completion: completion)\n }\n\n private func applyAndReconfigureSnapshot(\n _ snapshot: NSDiffableDataSourceSnapshot<LocationSection, LocationCellViewModel>,\n in section: LocationSection,\n completion: (() -> Void)? = nil\n ) {\n self.apply(snapshot, animatingDifferences: true) {\n // After adding, reconfigure specified items to update their content\n var updatedSnapshot = self.snapshot()\n\n // Ensure the items exist in the snapshot before attempting to reconfigure\n let existingItems = updatedSnapshot.itemIdentifiers(inSection: section)\n\n // Reconfigure the specified items\n updatedSnapshot.reconfigureItems(existingItems)\n\n // Apply the reconfigured snapshot without animations to avoid any flickering\n self.apply(updatedSnapshot, animatingDifferences: false)\n }\n }\n\n func reloadDataSnapshot(\n with list: [[LocationCellViewModel]],\n animated: Bool = false,\n completion: (() -> Void)? = nil\n ) {\n var snapshot = NSDiffableDataSourceSnapshot<LocationSection, LocationCellViewModel>()\n snapshot.appendSections(sections)\n for (index, section) in sections.enumerated() {\n let items = list[index]\n snapshot.appendItems(items, toSection: section)\n }\n self.apply(snapshot, animatingDifferences: animated, completion: completion)\n }\n\n func recursivelyCreateCellViewModelTree(\n for node: LocationNode,\n in section: LocationSection,\n indentationLevel: Int\n ) -> [LocationCellViewModel] {\n var viewModels = [LocationCellViewModel]()\n\n for childNode in node.children where !childNode.isHiddenFromSearch {\n viewModels.append(\n LocationCellViewModel(\n section: section,\n node: childNode,\n indentationLevel: indentationLevel,\n isSelected: nodeShouldBeSelected(childNode)\n )\n )\n\n if nodeShowsChildren(childNode) {\n viewModels.append(\n contentsOf: recursivelyCreateCellViewModelTree(\n for: childNode,\n in: section,\n indentationLevel: indentationLevel + 1\n )\n )\n }\n }\n\n return viewModels\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\SelectLocation\LocationDiffableDataSourceProtocol.swift | LocationDiffableDataSourceProtocol.swift | Swift | 6,451 | 0.95 | 0.088235 | 0.123288 | react-lib | 251 | 2024-04-27T09:30:28.261993 | GPL-3.0 | false | 313ee19065a24c27f6f0a599a529fc37 |
//\n// LocationNode.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-02-21.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\nimport MullvadTypes\n\nclass LocationNode: @unchecked Sendable {\n let name: String\n var code: String\n var locations: [RelayLocation]\n var isActive: Bool\n weak var parent: LocationNode?\n var children: [LocationNode]\n var showsChildren: Bool\n var isHiddenFromSearch: Bool\n\n init(\n name: String,\n code: String,\n locations: [RelayLocation] = [],\n isActive: Bool = true,\n parent: LocationNode? = nil,\n children: [LocationNode] = [],\n showsChildren: Bool = false,\n isHiddenFromSearch: Bool = false\n ) {\n self.name = name\n self.code = code\n self.locations = locations\n self.isActive = isActive\n self.parent = parent\n self.children = children\n self.showsChildren = showsChildren\n self.isHiddenFromSearch = isHiddenFromSearch\n }\n}\n\nextension LocationNode {\n var root: LocationNode {\n parent?.root ?? self\n }\n\n var hierarchyLevel: Int {\n var level = 0\n forEachAncestor { _ in level += 1 }\n return level\n }\n\n func countryFor(code: String) -> LocationNode? {\n self.code == code ? self : children.first(where: { $0.code == code })\n }\n\n func cityFor(codes: [String]) -> LocationNode? {\n let combinedCode = Self.combineNodeCodes(codes)\n return self.code == combinedCode ? self : children.first(where: { $0.code == combinedCode })\n }\n\n func hostFor(code: String) -> LocationNode? {\n self.code == code ? self : children.first(where: { $0.code == code })\n }\n\n func descendantNodeFor(codes: [String]) -> LocationNode? {\n let combinedCode = Self.combineNodeCodes(codes)\n return self.code == combinedCode ? self : children.compactMap { $0.descendantNodeFor(codes: codes) }.first\n }\n\n func forEachDescendant(do callback: (LocationNode) -> Void) {\n children.forEach { child in\n callback(child)\n child.forEachDescendant(do: callback)\n }\n }\n\n func forEachAncestor(do callback: (LocationNode) -> Void) {\n if let parent = parent {\n callback(parent)\n parent.forEachAncestor(do: callback)\n }\n }\n\n static func combineNodeCodes(_ codes: [String]) -> String {\n codes.joined(separator: "-")\n }\n\n var flattened: [LocationNode] {\n children + children.flatMap { $0.flattened }\n }\n}\n\nextension LocationNode {\n /// Recursively copies a node, its parent and its descendants from another\n /// node (tree), with an optional custom root parent.\n func copy(withParent parent: LocationNode? = nil) -> LocationNode {\n let node = LocationNode(\n name: name,\n code: code,\n locations: locations,\n isActive: isActive,\n parent: parent,\n children: [],\n showsChildren: showsChildren,\n isHiddenFromSearch: isHiddenFromSearch\n )\n\n node.children = recursivelyCopyChildren(withParent: node)\n\n return node\n }\n\n private func recursivelyCopyChildren(withParent parent: LocationNode) -> [LocationNode] {\n children.map { $0.copy(withParent: parent) }\n }\n}\n\nextension LocationNode: Hashable {\n func hash(into hasher: inout Hasher) {\n hasher.combine(code)\n }\n\n static func == (lhs: LocationNode, rhs: LocationNode) -> Bool {\n lhs.code == rhs.code\n }\n}\n\nextension LocationNode: Comparable {\n static func < (lhs: LocationNode, rhs: LocationNode) -> Bool {\n lhs.name.lowercased() < rhs.name.lowercased()\n }\n}\n\n/// Proxy class for building and/or searching node trees.\nclass RootLocationNode: LocationNode, @unchecked Sendable {\n init(name: String = "", code: String = "", children: [LocationNode] = []) {\n super.init(name: name, code: code, children: children)\n }\n}\n\nclass CustomListLocationNode: LocationNode, @unchecked Sendable {\n let customList: CustomList\n\n init(\n name: String,\n code: String,\n locations: [RelayLocation] = [],\n isActive: Bool = true,\n parent: LocationNode? = nil,\n children: [LocationNode] = [],\n showsChildren: Bool = false,\n isHiddenFromSearch: Bool = false,\n customList: CustomList\n ) {\n self.customList = customList\n\n super.init(\n name: name,\n code: code,\n locations: locations,\n isActive: isActive,\n parent: parent,\n children: children,\n showsChildren: showsChildren,\n isHiddenFromSearch: isHiddenFromSearch\n )\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\SelectLocation\LocationNode.swift | LocationNode.swift | Swift | 4,787 | 0.95 | 0.035294 | 0.068493 | react-lib | 91 | 2023-09-11T01:13:59.711397 | GPL-3.0 | false | fea67785e145382759b781305ab2ac89 |
//\n// LocationRelays.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-08-12.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadREST\n\nstruct LocationRelays: Sendable {\n var relays: [REST.ServerRelay]\n var locations: [String: REST.ServerLocation]\n}\n\nextension Array where Element == RelayWithLocation<REST.ServerRelay> {\n func toLocationRelays() -> LocationRelays {\n return LocationRelays(\n relays: map { $0.relay },\n locations: reduce(into: [String: REST.ServerLocation]()) { result, entry in\n result[entry.relay.location.rawValue] = REST.ServerLocation(\n country: entry.serverLocation.country,\n city: entry.serverLocation.city,\n latitude: entry.serverLocation.latitude,\n longitude: entry.serverLocation.longitude\n )\n }\n )\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\SelectLocation\LocationRelays.swift | LocationRelays.swift | Swift | 932 | 0.95 | 0 | 0.259259 | python-kit | 559 | 2024-04-05T17:58:47.594318 | GPL-3.0 | false | 83ac020b6348d0c1673b86b706949d78 |
//\n// LocationSection.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2024-02-05.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nenum LocationSection: String, Hashable, CaseIterable, CellIdentifierProtocol, Sendable {\n case customLists\n case allLocations\n\n var header: String {\n switch self {\n case .customLists:\n return NSLocalizedString(\n "HEADER_SELECT_LOCATION_ADD_CUSTOM_LISTS",\n value: "Custom lists",\n comment: ""\n )\n case .allLocations:\n return NSLocalizedString(\n "HEADER_SELECT_LOCATION_ALL_LOCATIONS",\n value: "All locations",\n comment: ""\n )\n }\n }\n\n var footer: String {\n switch self {\n case .customLists:\n return ""\n case .allLocations:\n return NSLocalizedString(\n "FOOTER_SELECT_LOCATION_ALL_LOCATIONS",\n value: "No matching relays found, check your filter settings.",\n comment: ""\n )\n }\n }\n\n var cellClass: AnyClass {\n LocationCell.self\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\SelectLocation\LocationSection.swift | LocationSection.swift | Swift | 1,192 | 0.95 | 0.042553 | 0.162791 | react-lib | 464 | 2024-03-05T01:42:42.324250 | MIT | false | 78d4f5525703bc0d8c400a4a565e7d24 |
//\n// LocationSectionHeaderView.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2024-01-25.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport UIKit\n\nclass LocationSectionHeaderFooterView: UIView, UIContentView {\n var configuration: UIContentConfiguration {\n get {\n actualConfiguration\n } set {\n guard let newConfiguration = newValue as? Configuration,\n actualConfiguration != newConfiguration else { return }\n actualConfiguration = newConfiguration\n apply(configuration: newConfiguration)\n }\n }\n\n private var actualConfiguration: Configuration\n\n private let containerView: UIStackView = {\n let containerView = UIStackView()\n containerView.axis = .horizontal\n containerView.spacing = 8\n containerView.isLayoutMarginsRelativeArrangement = true\n return containerView\n }()\n\n private let nameLabel: UILabel = {\n let label = UILabel()\n label.numberOfLines = 0\n label.lineBreakMode = .byWordWrapping\n label.textColor = .primaryTextColor\n label.font = .systemFont(ofSize: 16, weight: .semibold)\n return label\n }()\n\n private let actionButton: UIButton = {\n let button = UIButton(type: .system)\n button.setImage(UIImage(systemName: "ellipsis"), for: .normal)\n button.tintColor = UIColor(white: 1, alpha: 0.6)\n return button\n }()\n\n init(configuration: Configuration) {\n self.actualConfiguration = configuration\n super.init(frame: .zero)\n apply(configuration: configuration)\n addSubviews()\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n private func addSubviews() {\n containerView.addArrangedSubview(nameLabel)\n containerView.addArrangedSubview(actionButton)\n addConstrainedSubviews([containerView]) {\n containerView.pinEdgesToSuperviewMargins()\n actionButton.widthAnchor.constraint(equalTo: actionButton.heightAnchor)\n }\n }\n\n private func apply(configuration: Configuration) {\n let isActionHidden = configuration.primaryAction == nil\n backgroundColor = configuration.style.backgroundColor\n nameLabel.textColor = configuration.style.textColor\n nameLabel.text = configuration.name\n nameLabel.font = configuration.style.font\n nameLabel.textAlignment = configuration.style.textAlignment\n actionButton.isHidden = isActionHidden\n actionButton.accessibilityIdentifier = nil\n actualConfiguration.primaryAction.flatMap { action in\n actionButton.setAccessibilityIdentifier(.openCustomListsMenuButton)\n actionButton.addAction(action, for: .touchUpInside)\n }\n directionalLayoutMargins = actualConfiguration.directionalEdgeInsets\n }\n}\n\nextension LocationSectionHeaderFooterView {\n struct Style: Equatable {\n let font: UIFont\n let textColor: UIColor\n let textAlignment: NSTextAlignment\n let backgroundColor: UIColor\n\n static let header = Style(\n font: .preferredFont(forTextStyle: .body, weight: .semibold),\n textColor: .primaryTextColor,\n textAlignment: .natural,\n backgroundColor: .primaryColor\n )\n\n static let footer = Style(\n font: .preferredFont(forTextStyle: .body, weight: .regular),\n textColor: .secondaryTextColor,\n textAlignment: .center,\n backgroundColor: .clear\n )\n }\n\n struct Configuration: UIContentConfiguration, Equatable {\n let name: String\n let style: Style\n var directionalEdgeInsets = NSDirectionalEdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16)\n var primaryAction: UIAction?\n\n func makeContentView() -> UIView & UIContentView {\n LocationSectionHeaderFooterView(configuration: self)\n }\n\n func updated(for state: UIConfigurationState) -> Configuration {\n self\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\SelectLocation\LocationSectionHeaderFooterView.swift | LocationSectionHeaderFooterView.swift | Swift | 4,116 | 0.95 | 0.03252 | 0.065421 | vue-tools | 988 | 2023-09-15T02:10:50.651567 | BSD-3-Clause | false | e9b4e8a1590253b595e49fa9989c8bfc |
//\n// LocationViewController.swift\n// MullvadVPN\n//\n// Created by pronebird on 02/05/2019.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadREST\nimport MullvadSettings\nimport MullvadTypes\nimport UIKit\n\nprotocol LocationViewControllerDelegate: AnyObject {\n func navigateToCustomLists(nodes: [LocationNode])\n func navigateToDaitaSettings()\n func didSelectRelays(relays: UserSelectedRelays)\n func didUpdateFilter(filter: RelayFilter)\n}\n\nfinal class LocationViewController: UIViewController {\n private let searchBar = UISearchBar()\n private let tableView = UITableView(frame: .zero, style: .grouped)\n private let topContentView = UIStackView()\n private let filterView = RelayFilterView()\n private var daitaInfoView: UIView?\n private var dataSource: LocationDataSource?\n private var relaysWithLocation: LocationRelays?\n private var filter = RelayFilter()\n private var selectedRelays: RelaySelection\n private var shouldFilterDaita: Bool\n private var shouldFilterObfuscation: Bool\n weak var delegate: LocationViewControllerDelegate?\n var customListRepository: CustomListRepositoryProtocol\n\n override var preferredStatusBarStyle: UIStatusBarStyle {\n .lightContent\n }\n\n init(\n customListRepository: CustomListRepositoryProtocol,\n selectedRelays: RelaySelection,\n shouldFilterDaita: Bool,\n shouldFilterObfuscation: Bool\n ) {\n self.customListRepository = customListRepository\n self.selectedRelays = selectedRelays\n self.shouldFilterDaita = shouldFilterDaita\n self.shouldFilterObfuscation = shouldFilterObfuscation\n\n super.init(nibName: nil, bundle: nil)\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n // MARK: - View lifecycle\n\n override func viewDidLoad() {\n super.viewDidLoad()\n\n view.setAccessibilityIdentifier(.selectLocationView)\n view.backgroundColor = .secondaryColor\n\n setUpDataSource()\n setUpTableView()\n setUpTopContent()\n\n view.addConstrainedSubviews([topContentView, tableView]) {\n topContentView.pinEdgesToSuperviewMargins(.all().excluding(.bottom))\n\n tableView.pinEdgesToSuperview(.all().excluding(.top))\n tableView.topAnchor.constraint(equalTo: topContentView.bottomAnchor, constant: 8)\n }\n }\n\n override func viewDidAppear(_ animated: Bool) {\n super.viewDidAppear(animated)\n tableView.flashScrollIndicators()\n }\n\n // MARK: - Public\n\n func setRelaysWithLocation(_ relaysWithLocation: LocationRelays, filter: RelayFilter) {\n self.relaysWithLocation = relaysWithLocation\n self.filter = filter\n filterView.setFilter(filter)\n dataSource?.setRelays(relaysWithLocation, selectedRelays: selectedRelays)\n }\n\n func setDaitaChip(_ isEnabled: Bool) {\n self.shouldFilterDaita = isEnabled\n filterView.setDaita(isEnabled)\n }\n\n func setObfuscationChip(_ isEnabled: Bool) {\n self.shouldFilterObfuscation = isEnabled\n filterView.setObfuscation(isEnabled)\n }\n\n func refreshCustomLists() {\n dataSource?.refreshCustomLists()\n }\n\n func setSelectedRelays(_ selectedRelays: RelaySelection) {\n self.selectedRelays = selectedRelays\n dataSource?.setSelectedRelays(selectedRelays)\n }\n\n func toggleDaitaAutomaticRouting(isEnabled: Bool) {\n guard isEnabled else {\n daitaInfoView?.removeFromSuperview()\n daitaInfoView = nil\n\n searchBar.searchTextField.isEnabled = true\n UITextField.SearchTextFieldAppearance.inactive.apply(to: searchBar)\n return\n }\n\n guard daitaInfoView == nil else { return }\n\n let daitaInfoView = DAITAInfoView()\n self.daitaInfoView = daitaInfoView\n\n daitaInfoView.didPressDaitaSettingsButton = { [weak self] in\n self?.delegate?.navigateToDaitaSettings()\n }\n\n view.addConstrainedSubviews([daitaInfoView]) {\n daitaInfoView.pinEdgesToSuperview(.all().excluding(.top))\n daitaInfoView.topAnchor.constraint(equalTo: tableView.topAnchor)\n }\n\n searchBar.searchTextField.isEnabled = false\n }\n\n // MARK: - Private\n\n private func setUpDataSource() {\n dataSource = LocationDataSource(\n tableView: tableView,\n allLocations: AllLocationDataSource(),\n customLists: CustomListsDataSource(repository: customListRepository)\n )\n\n dataSource?.didSelectRelayLocations = { [weak self] relays in\n Task { @MainActor in\n self?.delegate?.didSelectRelays(relays: relays)\n }\n }\n\n dataSource?.didTapEditCustomLists = { [weak self] in\n guard let self else { return }\n\n Task { @MainActor in\n if let relaysWithLocation {\n let allLocationDataSource = AllLocationDataSource()\n allLocationDataSource.reload(relaysWithLocation)\n delegate?.navigateToCustomLists(nodes: allLocationDataSource.nodes)\n }\n }\n }\n\n if let relaysWithLocation {\n dataSource?.setRelays(relaysWithLocation, selectedRelays: selectedRelays)\n }\n }\n\n private func setUpTableView() {\n tableView.backgroundColor = view.backgroundColor\n tableView.separatorColor = .secondaryColor\n tableView.separatorInset = .zero\n tableView.rowHeight = 56\n tableView.sectionHeaderHeight = 56\n tableView.indicatorStyle = .white\n tableView.keyboardDismissMode = .onDrag\n tableView.setAccessibilityIdentifier(.selectLocationTableView)\n }\n\n private func setUpTopContent() {\n topContentView.axis = .vertical\n topContentView.addArrangedSubview(filterView)\n topContentView.addArrangedSubview(searchBar)\n filterView.setDaita(shouldFilterDaita)\n filterView.setObfuscation(shouldFilterObfuscation)\n\n filterView.didUpdateFilter = { [weak self] in\n self?.delegate?.didUpdateFilter(filter: $0)\n }\n\n setUpSearchBar()\n }\n\n private func setUpSearchBar() {\n searchBar.delegate = self\n searchBar.searchBarStyle = .minimal\n searchBar.layer.cornerRadius = 8\n searchBar.clipsToBounds = true\n searchBar.placeholder = NSLocalizedString(\n "SEARCHBAR_PLACEHOLDER",\n tableName: "SelectLocation",\n value: "Search for...",\n comment: ""\n )\n searchBar.searchTextField.setAccessibilityIdentifier(.selectLocationSearchTextField)\n\n UITextField.SearchTextFieldAppearance.inactive.apply(to: searchBar)\n }\n}\n\nextension LocationViewController: UISearchBarDelegate {\n func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {\n dataSource?.filterRelays(by: searchText)\n }\n\n func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {\n UITextField.SearchTextFieldAppearance.active.apply(to: searchBar)\n }\n\n func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {\n UITextField.SearchTextFieldAppearance.inactive.apply(to: searchBar)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\SelectLocation\LocationViewController.swift | LocationViewController.swift | Swift | 7,295 | 0.95 | 0.017857 | 0.054945 | python-kit | 589 | 2025-06-07T13:35:53.564415 | Apache-2.0 | false | 5fa7840b2afe460f0ad65a48bc72e688 |
//\n// LocationViewControllerWrapper.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-04-23.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadREST\nimport MullvadSettings\nimport MullvadTypes\nimport UIKit\n\nprotocol LocationViewControllerWrapperDelegate: AnyObject {\n func navigateToCustomLists(nodes: [LocationNode])\n func navigateToFilter()\n func navigateToDaitaSettings()\n func didSelectEntryRelays(_ relays: UserSelectedRelays)\n func didSelectExitRelays(_ relays: UserSelectedRelays)\n func didUpdateFilter(_ filter: RelayFilter)\n}\n\nfinal class LocationViewControllerWrapper: UIViewController {\n enum MultihopContext: Int, CaseIterable, CustomStringConvertible {\n case entry, exit\n\n var description: String {\n switch self {\n case .entry:\n NSLocalizedString(\n "MULTIHOP_ENTRY",\n tableName: "SelectLocation",\n value: "Entry",\n comment: ""\n )\n case .exit:\n NSLocalizedString(\n "MULTIHOP_EXIT",\n tableName: "SelectLocation",\n value: "Exit",\n comment: ""\n )\n }\n }\n }\n\n private var entryLocationViewController: LocationViewController?\n private let exitLocationViewController: LocationViewController\n private let segmentedControl = UISegmentedControl()\n private let locationViewContainer = UIView()\n private var settings: LatestTunnelSettings\n private var relaySelectorWrapper: RelaySelectorWrapper\n\n private var multihopContext: MultihopContext = .exit\n private var selectedEntry: UserSelectedRelays?\n private var selectedExit: UserSelectedRelays?\n\n weak var delegate: LocationViewControllerWrapperDelegate?\n\n var onNewSettings: ((LatestTunnelSettings) -> Void)?\n\n private var relayFilter: RelayFilter {\n settings.relayConstraints.filter.value ?? RelayFilter()\n }\n\n init(\n settings: LatestTunnelSettings,\n relaySelectorWrapper: RelaySelectorWrapper,\n customListRepository: CustomListRepositoryProtocol,\n startContext: MultihopContext\n ) {\n self.selectedEntry = settings.relayConstraints.entryLocations.value\n self.selectedExit = settings.relayConstraints.exitLocations.value\n self.settings = settings\n self.relaySelectorWrapper = relaySelectorWrapper\n self.multihopContext = startContext\n\n entryLocationViewController = LocationViewController(\n customListRepository: customListRepository,\n selectedRelays: RelaySelection(),\n shouldFilterDaita: false,\n shouldFilterObfuscation: false\n )\n\n exitLocationViewController = LocationViewController(\n customListRepository: customListRepository,\n selectedRelays: RelaySelection(),\n shouldFilterDaita: false,\n shouldFilterObfuscation: false\n )\n\n super.init(nibName: nil, bundle: nil)\n\n self.onNewSettings = { [weak self] newSettings in\n self?.settings = newSettings\n self?.setRelaysWithLocation()\n }\n\n setRelaysWithLocation()\n\n updateViewControllers {\n $0.delegate = self\n }\n }\n\n var didFinish: (() -> Void)?\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n override func viewDidLoad() {\n super.viewDidLoad()\n\n view.setAccessibilityIdentifier(.selectLocationViewWrapper)\n view.backgroundColor = .secondaryColor\n\n setUpNavigation()\n setUpSegmentedControl()\n addSubviews()\n add(entryLocationViewController)\n add(exitLocationViewController)\n swapViewController()\n }\n\n private func setRelaysWithLocation() {\n let emptyResult = LocationRelays(relays: [], locations: [:])\n let relaysCandidates = try? relaySelectorWrapper.findCandidates(tunnelSettings: settings)\n\n let isMultihop = settings.tunnelMultihopState.isEnabled\n let isDirectOnly = settings.daita.isDirectOnly\n let isAutomaticRouting = settings.daita.isAutomaticRouting\n let isObfuscation = settings.wireGuardObfuscation.state.affectsRelaySelection\n\n if isMultihop {\n entryLocationViewController?.setObfuscationChip(isObfuscation && !isAutomaticRouting)\n entryLocationViewController?.setDaitaChip(isDirectOnly)\n entryLocationViewController?.toggleDaitaAutomaticRouting(isEnabled: isAutomaticRouting)\n } else {\n exitLocationViewController.setObfuscationChip(isObfuscation)\n exitLocationViewController.setDaitaChip(isDirectOnly)\n }\n\n if let entryRelays = relaysCandidates?.entryRelays {\n entryLocationViewController?.setRelaysWithLocation(entryRelays.toLocationRelays(), filter: relayFilter)\n } else {\n entryLocationViewController?.setRelaysWithLocation(\n emptyResult,\n filter: relayFilter\n )\n }\n exitLocationViewController.setRelaysWithLocation(\n relaysCandidates?.exitRelays.toLocationRelays() ?? emptyResult,\n filter: relayFilter\n )\n }\n\n func refreshCustomLists() {\n updateViewControllers {\n $0.refreshCustomLists()\n }\n }\n\n private func updateViewControllers(callback: (LocationViewController) -> Void) {\n [entryLocationViewController, exitLocationViewController]\n .compactMap { $0 }\n .forEach { callback($0) }\n }\n\n private func setUpNavigation() {\n navigationItem.largeTitleDisplayMode = .never\n\n navigationItem.title = NSLocalizedString(\n "NAVIGATION_TITLE",\n tableName: "SelectLocation",\n value: "Select location",\n comment: ""\n )\n\n navigationItem.leftBarButtonItem = UIBarButtonItem(\n title: NSLocalizedString(\n "NAVIGATION_FILTER",\n tableName: "SelectLocation",\n value: "Filter",\n comment: ""\n ),\n primaryAction: UIAction(handler: { [weak self] _ in\n guard let self = self else { return }\n delegate?.navigateToFilter()\n })\n )\n navigationItem.leftBarButtonItem?.setAccessibilityIdentifier(.selectLocationFilterButton)\n\n navigationItem.rightBarButtonItem = UIBarButtonItem(\n systemItem: .done,\n primaryAction: UIAction(handler: { [weak self] _ in\n self?.didFinish?()\n })\n )\n navigationItem.rightBarButtonItem?.setAccessibilityIdentifier(.closeSelectLocationButton)\n }\n\n private func setUpSegmentedControl() {\n segmentedControl.backgroundColor = .SegmentedControl.backgroundColor\n segmentedControl.selectedSegmentTintColor = .SegmentedControl.selectedColor\n segmentedControl.setTitleTextAttributes([\n .foregroundColor: UIColor.white,\n .font: UIFont.systemFont(ofSize: 17, weight: .medium),\n ], for: .normal)\n\n segmentedControl.insertSegment(\n withTitle: MultihopContext.entry.description,\n at: MultihopContext.entry.rawValue,\n animated: false\n )\n segmentedControl.insertSegment(\n withTitle: MultihopContext.exit.description,\n at: MultihopContext.exit.rawValue,\n animated: false\n )\n\n segmentedControl.selectedSegmentIndex = multihopContext.rawValue\n segmentedControl.addTarget(self, action: #selector(segmentedControlDidChange), for: .valueChanged)\n }\n\n private func addSubviews() {\n view.addConstrainedSubviews([segmentedControl, locationViewContainer]) {\n segmentedControl.heightAnchor.constraint(equalToConstant: 44)\n segmentedControl.pinEdgesToSuperviewMargins(PinnableEdges([.top(0), .leading(8), .trailing(8)]))\n\n locationViewContainer.pinEdgesToSuperview(.all().excluding(.top))\n\n if settings.tunnelMultihopState.isEnabled {\n locationViewContainer.topAnchor.constraint(equalTo: segmentedControl.bottomAnchor, constant: 4)\n } else {\n locationViewContainer.pinEdgeToSuperviewMargin(.top(0))\n }\n }\n }\n\n private func add(_ locationViewController: LocationViewController?) {\n guard let locationViewController else { return }\n addChild(locationViewController)\n locationViewController.didMove(toParent: self)\n locationViewContainer.addConstrainedSubviews([locationViewController.view]) {\n locationViewController.view.pinEdgesToSuperview()\n }\n }\n\n @objc\n private func segmentedControlDidChange(sender: UISegmentedControl) {\n multihopContext = .allCases[segmentedControl.selectedSegmentIndex]\n swapViewController()\n }\n\n private func swapViewController() {\n var selectedRelays: RelaySelection\n var oldViewController: LocationViewController?\n var newViewController: LocationViewController?\n\n (selectedRelays, oldViewController, newViewController) = switch multihopContext {\n case .entry:\n (\n RelaySelection(\n selected: selectedEntry,\n excluded: selectedExit,\n excludedTitle: MultihopContext.exit.description\n ),\n exitLocationViewController,\n entryLocationViewController\n )\n case .exit:\n (\n RelaySelection(\n selected: selectedExit,\n excluded: settings.tunnelMultihopState.isEnabled ? selectedEntry : nil,\n excludedTitle: MultihopContext.entry.description\n ),\n entryLocationViewController,\n exitLocationViewController\n )\n }\n newViewController?.setSelectedRelays(selectedRelays)\n oldViewController?.view.isUserInteractionEnabled = false\n newViewController?.view.isUserInteractionEnabled = true\n UIView.animate(withDuration: 0.0) {\n oldViewController?.view.alpha = 0\n newViewController?.view.alpha = 1\n }\n }\n}\n\nextension LocationViewControllerWrapper: @preconcurrency LocationViewControllerDelegate {\n func navigateToCustomLists(nodes: [LocationNode]) {\n delegate?.navigateToCustomLists(nodes: nodes)\n }\n\n func navigateToDaitaSettings() {\n delegate?.navigateToDaitaSettings()\n }\n\n func didSelectRelays(relays: UserSelectedRelays) {\n switch multihopContext {\n case .entry:\n selectedEntry = relays\n delegate?.didSelectEntryRelays(relays)\n\n // Trigger change in segmented control, which in turn triggers view controller swap.\n segmentedControl.selectedSegmentIndex = MultihopContext.exit.rawValue\n segmentedControl.sendActions(for: .valueChanged)\n case .exit:\n delegate?.didSelectExitRelays(relays)\n didFinish?()\n }\n }\n\n func didUpdateFilter(filter: RelayFilter) {\n delegate?.didUpdateFilter(filter)\n }\n}\n\nprivate extension WireGuardObfuscationState {\n var affectsRelaySelection: Bool {\n switch self {\n case .shadowsocks:\n true\n case .on, .off, .automatic, .udpOverTcp:\n false\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\SelectLocation\LocationViewControllerWrapper.swift | LocationViewControllerWrapper.swift | Swift | 11,597 | 0.95 | 0.036254 | 0.028169 | react-lib | 222 | 2025-05-31T02:17:57.806317 | GPL-3.0 | false | 4338b2bae2eefebe35eeb1f6874c4aea |
//\n// RelaySelection.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-04-29.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadTypes\n\nstruct RelaySelection: Sendable {\n var selected: UserSelectedRelays?\n var excluded: UserSelectedRelays?\n var excludedTitle: String?\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\SelectLocation\RelaySelection.swift | RelaySelection.swift | Swift | 317 | 0.95 | 0 | 0.538462 | vue-tools | 598 | 2023-12-18T08:50:37.189785 | GPL-3.0 | false | bf18589e49bedabf02063950e01b266e |
//\n// CheckableSettingsCell.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-06-05.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass CheckableSettingsCell: SettingsCell {\n let checkboxView = CheckboxView()\n\n var isEnabled = true {\n didSet {\n titleLabel.isEnabled = isEnabled\n }\n }\n\n override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {\n super.init(style: style, reuseIdentifier: reuseIdentifier)\n\n setCheckboxView()\n selectedBackgroundView?.backgroundColor = .clear\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n override func prepareForReuse() {\n super.prepareForReuse()\n setCheckboxView()\n }\n\n override func setSelected(_ selected: Bool, animated: Bool) {\n super.setSelected(selected, animated: animated)\n\n checkboxView.isChecked = selected\n }\n\n override func applySubCellStyling() {\n super.applySubCellStyling()\n\n contentView.layoutMargins.left = 0\n }\n\n private func setCheckboxView() {\n setLeadingView { superview in\n superview.addConstrainedSubviews([checkboxView]) {\n checkboxView.pinEdgesToSuperview(PinnableEdges([\n .leading(0),\n .trailing(UIMetrics.SettingsCell.checkableSettingsCellLeftViewSpacing),\n .top(0),\n .bottom(0),\n ]))\n }\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Settings\CheckableSettingsCell.swift | CheckableSettingsCell.swift | Swift | 1,550 | 0.95 | 0.016667 | 0.145833 | react-lib | 373 | 2024-03-10T00:23:04.127797 | GPL-3.0 | false | c4a977bab8bbcba5979238b6f27d5904 |
//\n// SelectableSettingsCell.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-05-08.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass SelectableSettingsCell: SettingsCell {\n let tickImageView: UIImageView = {\n let imageView = UIImageView(image: UIImage.tick)\n imageView.contentMode = .center\n imageView.tintColor = .white\n imageView.alpha = 0\n return imageView\n }()\n\n override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {\n super.init(style: style, reuseIdentifier: reuseIdentifier)\n\n setTickView()\n selectedBackgroundView?.backgroundColor = UIColor.Cell.Background.selected\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n override func prepareForReuse() {\n super.prepareForReuse()\n setTickView()\n }\n\n override func setSelected(_ selected: Bool, animated: Bool) {\n super.setSelected(selected, animated: animated)\n\n tickImageView.alpha = selected ? 1 : 0\n }\n\n private func setTickView() {\n setLeadingView { superview in\n superview.addConstrainedSubviews([tickImageView]) {\n tickImageView.pinEdgesToSuperview(PinnableEdges([\n .leading(0), .top(0), .bottom(0),\n .trailing(UIMetrics.SettingsCell.selectableSettingsCellLeftViewSpacing),\n ]))\n }\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Settings\SelectableSettingsCell.swift | SelectableSettingsCell.swift | Swift | 1,495 | 0.95 | 0.019231 | 0.162791 | awesome-app | 993 | 2024-03-11T07:50:36.157783 | Apache-2.0 | false | 9847116dd959906354cc767e0e675d44 |
//\n// SelectableSettingsDetailsCell.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-10-14.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass SelectableSettingsDetailsCell: SelectableSettingsCell {\n let viewContainer = UIView()\n\n var buttonAction: (() -> Void)?\n\n override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {\n super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)\n\n let actionButton = IncreasedHitButton(type: .system)\n var actionButtonConfiguration = actionButton.configuration ?? .plain()\n actionButtonConfiguration.image = UIImage(systemName: "ellipsis")?\n .withRenderingMode(.alwaysOriginal)\n .withTintColor(.white)\n actionButton.configuration = actionButtonConfiguration\n actionButton.setAccessibilityIdentifier(.openPortSelectorMenuButton)\n\n actionButton.addTarget(\n self,\n action: #selector(didPressActionButton),\n for: .touchUpInside\n )\n\n let separatorView = UIView()\n separatorView.backgroundColor = .secondaryColor\n\n viewContainer.addConstrainedSubviews([separatorView, actionButton]) {\n separatorView.leadingAnchor.constraint(equalTo: viewContainer.leadingAnchor, constant: 16)\n separatorView.centerYAnchor.constraint(equalTo: viewContainer.centerYAnchor)\n separatorView.heightAnchor.constraint(equalToConstant: UIMetrics.SettingsCell.verticalDividerHeight)\n separatorView.widthAnchor.constraint(equalToConstant: 1)\n\n actionButton.pinEdgesToSuperview(.all().excluding(.leading))\n actionButton.leadingAnchor.constraint(equalTo: separatorView.trailingAnchor)\n actionButton.widthAnchor.constraint(equalToConstant: UIMetrics.SettingsCell.detailsButtonSize)\n }\n\n setViewContainer()\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n override func prepareForReuse() {\n super.prepareForReuse()\n setViewContainer()\n }\n\n private func setViewContainer() {\n setTrailingView { superview in\n superview.addConstrainedSubviews([viewContainer]) {\n viewContainer.pinEdgesToSuperview()\n }\n }\n }\n\n // MARK: - Actions\n\n @objc private func didPressActionButton() {\n buttonAction?()\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Settings\SelectableSettingsDetailsCell.swift | SelectableSettingsDetailsCell.swift | Swift | 2,449 | 0.95 | 0.027778 | 0.140351 | python-kit | 789 | 2024-04-14T09:42:44.080413 | MIT | false | eead9d574bfe162d53bde3f61a815835 |
//\n// SettingsAddDNSEntryCell.swift\n// MullvadVPN\n//\n// Created by pronebird on 27/10/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass SettingsAddDNSEntryCell: SettingsCell {\n var tapAction: (() -> Void)?\n\n override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {\n super.init(style: style, reuseIdentifier: reuseIdentifier)\n\n backgroundView?.backgroundColor = UIColor.Cell.Background.indentationLevelTwo\n\n let gestureRecognizer = UITapGestureRecognizer(\n target: self,\n action: #selector(handleTap(_:))\n )\n contentView.addGestureRecognizer(gestureRecognizer)\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n @objc func handleTap(_ sender: UIGestureRecognizer) {\n if case .ended = sender.state {\n tapAction?()\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Settings\SettingsAddDNSEntryCell.swift | SettingsAddDNSEntryCell.swift | Swift | 936 | 0.95 | 0.057143 | 0.25 | react-lib | 135 | 2024-07-31T23:15:47.458731 | BSD-3-Clause | false | 97f64fc56dec5b2db844e60a80dea0ff |
//\n// SettingsCell.swift\n// MullvadVPN\n//\n// Created by pronebird on 22/05/2019.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nenum SettingsDisclosureType {\n case none\n case chevron\n case externalLink\n case tick\n\n var image: UIImage? {\n switch self {\n case .none:\n nil\n case .chevron:\n UIImage.CellDecoration.chevronRight\n case .externalLink:\n UIImage.CellDecoration.externalLink\n case .tick:\n UIImage.CellDecoration.tick\n }\n }\n}\n\nclass SettingsCell: UITableViewCell, CustomCellDisclosureHandling {\n typealias InfoButtonHandler = () -> Void\n\n let disclosureImageView = UIImageView(image: nil)\n let mainContentContainer = UIView()\n let leftContentContainer = UIView()\n let rightContentContainer = UIView()\n var infoButtonHandler: InfoButtonHandler? { didSet {\n infoButton.isHidden = infoButtonHandler == nil\n }}\n\n var disclosureType: SettingsDisclosureType = .none {\n didSet {\n accessoryType = .none\n\n let image = disclosureType.image?.withTintColor(\n UIColor.Cell.disclosureIndicatorColor,\n renderingMode: .alwaysOriginal\n )\n\n if let image {\n disclosureImageView.image = image\n disclosureImageView.sizeToFit()\n accessoryView = disclosureImageView\n } else {\n accessoryView = nil\n }\n }\n }\n\n let titleLabel: UILabel = {\n let label = UILabel()\n label.font = UIFont.systemFont(ofSize: 17)\n label.textColor = UIColor.Cell.titleTextColor\n label.setContentHuggingPriority(.defaultHigh, for: .horizontal)\n label.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)\n return label\n }()\n\n let detailTitleLabel: UILabel = {\n let label = UILabel()\n label.font = UIFont.systemFont(ofSize: 13)\n label.textColor = UIColor.Cell.detailTextColor\n label.setContentHuggingPriority(.defaultLow, for: .horizontal)\n label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)\n return label\n }()\n\n private var subCellLeadingIndentation: CGFloat = 0\n private let buttonWidth: CGFloat = 24\n\n private let infoButton: UIButton = {\n let button = UIButton(type: .custom)\n button.setAccessibilityIdentifier(.infoButton)\n button.tintColor = .white\n button.setImage(UIImage.Buttons.info, for: .normal)\n button.isHidden = true\n return button\n }()\n\n override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {\n super.init(style: style, reuseIdentifier: reuseIdentifier)\n\n backgroundView = UIView()\n backgroundView?.backgroundColor = UIColor.Cell.Background.normal\n\n selectedBackgroundView = UIView()\n selectedBackgroundView?.backgroundColor = UIColor.Cell.Background.selectedAlt\n\n separatorInset = .zero\n backgroundColor = .clear\n contentView.backgroundColor = .clear\n\n infoButton.addTarget(self, action: #selector(handleInfoButton(_:)), for: .touchUpInside)\n\n subCellLeadingIndentation = contentView.layoutMargins.left + UIMetrics.TableView.cellIndentationWidth\n\n rightContentContainer.setContentHuggingPriority(.required, for: .horizontal)\n\n setLayoutMargins()\n\n let buttonAreaWidth = UIMetrics.contentLayoutMargins.leading + UIMetrics\n .contentLayoutMargins.trailing + buttonWidth\n\n let infoButtonConstraint = infoButton.trailingAnchor.constraint(\n greaterThanOrEqualTo: mainContentContainer.trailingAnchor\n )\n infoButtonConstraint.priority = .defaultLow\n\n mainContentContainer.addConstrainedSubviews([titleLabel, infoButton, detailTitleLabel]) {\n switch style {\n case .subtitle:\n titleLabel.pinEdgesToSuperview(.init([.top(0), .leading(0)]))\n detailTitleLabel.pinEdgesToSuperview(.all().excluding([.top, .trailing]))\n detailTitleLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor)\n infoButtonConstraint\n\n default:\n titleLabel.pinEdgesToSuperview(.all().excluding(.trailing))\n detailTitleLabel.pinEdgesToSuperview(.all().excluding(.leading))\n detailTitleLabel.leadingAnchor.constraint(greaterThanOrEqualTo: infoButton.trailingAnchor)\n }\n\n infoButton.leadingAnchor.constraint(\n equalTo: titleLabel.trailingAnchor,\n constant: -UIMetrics.interButtonSpacing\n )\n infoButton.centerYAnchor.constraint(equalTo: titleLabel.centerYAnchor)\n infoButton.widthAnchor.constraint(equalToConstant: buttonAreaWidth)\n }\n\n contentView.addConstrainedSubviews([leftContentContainer, mainContentContainer, rightContentContainer]) {\n mainContentContainer.pinEdgesToSuperviewMargins(.all().excluding([.leading, .trailing]))\n\n leftContentContainer.pinEdgesToSuperviewMargins(.all().excluding(.trailing))\n leftContentContainer.trailingAnchor.constraint(equalTo: mainContentContainer.leadingAnchor)\n\n rightContentContainer.pinEdgesToSuperview(.all().excluding(.leading))\n rightContentContainer.leadingAnchor.constraint(equalTo: mainContentContainer.trailingAnchor)\n rightContentContainer.widthAnchor.constraint(\n greaterThanOrEqualToConstant: UIMetrics.TableView.cellIndentationWidth\n )\n }\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n override func prepareForReuse() {\n super.prepareForReuse()\n\n infoButton.isHidden = true\n removeLeadingView()\n removeTrailingView()\n setLayoutMargins()\n }\n\n func applySubCellStyling() {\n contentView.layoutMargins.left = subCellLeadingIndentation\n backgroundView?.backgroundColor = UIColor.Cell.Background.indentationLevelOne\n }\n\n func setLeadingView(superviewProvider: (UIView) -> Void) {\n removeLeadingView()\n superviewProvider(leftContentContainer)\n }\n\n func removeLeadingView() {\n leftContentContainer.subviews.forEach { $0.removeFromSuperview() }\n }\n\n func setTrailingView(superviewProvider: (UIView) -> Void) {\n removeTrailingView()\n superviewProvider(rightContentContainer)\n }\n\n func removeTrailingView() {\n rightContentContainer.subviews.forEach { $0.removeFromSuperview() }\n }\n\n @objc private func handleInfoButton(_ sender: UIControl) {\n infoButtonHandler?()\n }\n\n private func setLayoutMargins() {\n // Set layout margins for standard acceessories added into the cell (reorder control, etc..)\n directionalLayoutMargins = UIMetrics.SettingsCell.layoutMargins\n\n // Set layout margins for cell content\n contentView.directionalLayoutMargins = UIMetrics.SettingsCell.layoutMargins\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Settings\SettingsCell.swift | SettingsCell.swift | Swift | 7,135 | 0.95 | 0.064039 | 0.054878 | react-lib | 191 | 2023-10-06T13:41:00.049444 | GPL-3.0 | false | 34fc8186f1350a4db343dc73b15d55ed |
//\n// SettingsCellFactory.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-03-09.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\nimport UIKit\n\nprotocol SettingsCellEventHandler {\n func showInfo(for button: SettingsInfoButtonItem)\n}\n\n@MainActor\nfinal class SettingsCellFactory: @preconcurrency CellFactoryProtocol, Sendable {\n let tableView: UITableView\n var delegate: SettingsCellEventHandler?\n var viewModel: SettingsViewModel\n private let interactor: SettingsInteractor\n\n init(tableView: UITableView, interactor: SettingsInteractor) {\n self.tableView = tableView\n self.interactor = interactor\n\n viewModel = SettingsViewModel(from: interactor.tunnelSettings)\n }\n\n func makeCell(for item: SettingsDataSource.Item, indexPath: IndexPath) -> UITableViewCell {\n let cell: UITableViewCell\n\n cell = tableView\n .dequeueReusableCell(\n withIdentifier: item.reuseIdentifier.rawValue\n ) ?? SettingsCell(\n style: item.reuseIdentifier.cellStyle,\n reuseIdentifier: item.reuseIdentifier.rawValue\n )\n\n // Configure the cell with the common logic\n configureCell(cell, item: item, indexPath: indexPath)\n\n return cell\n }\n\n // swiftlint:disable:next function_body_length\n func configureCell(_ cell: UITableViewCell, item: SettingsDataSource.Item, indexPath: IndexPath) {\n switch item {\n case .vpnSettings:\n guard let cell = cell as? SettingsCell else { return }\n\n cell.titleLabel.text = NSLocalizedString(\n "VPN_SETTINGS_CELL_LABEL",\n tableName: "Settings",\n value: "VPN settings",\n comment: ""\n )\n cell.detailTitleLabel.text = nil\n cell.setAccessibilityIdentifier(item.accessibilityIdentifier)\n cell.disclosureType = .chevron\n\n case .changelog:\n guard let cell = cell as? SettingsCell else { return }\n cell.titleLabel.text = NSLocalizedString(\n "APP_VERSION_CELL_LABEL",\n tableName: "Settings",\n value: "What's new",\n comment: ""\n )\n cell.detailTitleLabel.text = Bundle.main.productVersion\n cell.setAccessibilityIdentifier(item.accessibilityIdentifier)\n cell.disclosureType = .chevron\n\n case .problemReport:\n guard let cell = cell as? SettingsCell else { return }\n\n cell.titleLabel.text = NSLocalizedString(\n "REPORT_PROBLEM_CELL_LABEL",\n tableName: "Settings",\n value: "Report a problem",\n comment: ""\n )\n cell.detailTitleLabel.text = nil\n cell.setAccessibilityIdentifier(item.accessibilityIdentifier)\n cell.disclosureType = .chevron\n\n case .faq:\n guard let cell = cell as? SettingsCell else { return }\n\n cell.titleLabel.text = NSLocalizedString(\n "FAQ_AND_GUIDES_CELL_LABEL",\n tableName: "Settings",\n value: "FAQs & Guides",\n comment: ""\n )\n cell.detailTitleLabel.text = nil\n cell.setAccessibilityIdentifier(item.accessibilityIdentifier)\n cell.disclosureType = .externalLink\n\n case .apiAccess:\n guard let cell = cell as? SettingsCell else { return }\n cell.titleLabel.text = NSLocalizedString(\n "API_ACCESS_CELL_LABEL",\n tableName: "Settings",\n value: "API access",\n comment: ""\n )\n cell.detailTitleLabel.text = nil\n cell.setAccessibilityIdentifier(item.accessibilityIdentifier)\n cell.disclosureType = .chevron\n\n case .daita:\n guard let cell = cell as? SettingsCell else { return }\n\n cell.titleLabel.text = NSLocalizedString(\n "DAITA_CELL_LABEL",\n tableName: "Settings",\n value: "DAITA",\n comment: ""\n )\n\n cell.detailTitleLabel.text = NSLocalizedString(\n "DAITA_CELL_DETAIL_LABEL",\n tableName: "Settings",\n value: viewModel.daitaSettings.daitaState.isEnabled ? "On" : "Off",\n comment: ""\n )\n\n cell.setAccessibilityIdentifier(item.accessibilityIdentifier)\n cell.disclosureType = .chevron\n\n case .multihop:\n guard let cell = cell as? SettingsCell else { return }\n\n cell.titleLabel.text = NSLocalizedString(\n "MULTIHOP_CELL_LABEL",\n tableName: "Settings",\n value: "Multihop",\n comment: ""\n )\n\n cell.detailTitleLabel.text = NSLocalizedString(\n "MULTIHOP_CELL_DETAIL_LABEL",\n tableName: "Settings",\n value: viewModel.multihopState.isEnabled ? "On" : "Off",\n comment: ""\n )\n\n cell.setAccessibilityIdentifier(item.accessibilityIdentifier)\n cell.disclosureType = .chevron\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Settings\SettingsCellFactory.swift | SettingsCellFactory.swift | Swift | 5,263 | 0.95 | 0.025974 | 0.069767 | awesome-app | 931 | 2024-01-20T19:45:44.459215 | Apache-2.0 | false | 302604a53f3482f6c4fd5f297d8cb730 |
//\n// SettingsDataSource.swift\n// MullvadVPN\n//\n// Created by pronebird on 19/10/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\nimport UIKit\n\nfinal class SettingsDataSource: UITableViewDiffableDataSource<SettingsDataSource.Section, SettingsDataSource.Item>,\n UITableViewDelegate {\n enum CellReuseIdentifier: String, CaseIterable {\n case basic\n case changelog\n\n var reusableViewClass: AnyClass {\n SettingsCell.self\n }\n\n var cellStyle: UITableViewCell.CellStyle {\n switch self {\n case .basic: .default\n case .changelog: .subtitle\n }\n }\n }\n\n private enum HeaderFooterReuseIdentifier: String, CaseIterable, HeaderFooterIdentifierProtocol {\n case primary\n case spacer\n\n var headerFooterClass: AnyClass {\n switch self {\n case .primary:\n UITableViewHeaderFooterView.self\n case .spacer:\n EmptyTableViewHeaderFooterView.self\n }\n }\n }\n\n enum Section: String {\n case vpnSettings\n case apiAccess\n case version\n case problemReport\n }\n\n enum Item: String {\n case vpnSettings\n case changelog\n case problemReport\n case faq\n case apiAccess\n case daita\n case multihop\n\n var accessibilityIdentifier: AccessibilityIdentifier {\n switch self {\n case .vpnSettings:\n return .vpnSettingsCell\n case .changelog:\n return .versionCell\n case .problemReport:\n return .problemReportCell\n case .faq:\n return .faqCell\n case .apiAccess:\n return .apiAccessCell\n case .daita:\n return .daitaCell\n case .multihop:\n return .multihopCell\n }\n }\n\n var reuseIdentifier: CellReuseIdentifier {\n switch self {\n case .changelog: .changelog\n default: .basic\n }\n }\n }\n\n private let interactor: SettingsInteractor\n private var storedAccountData: StoredAccountData?\n private let settingsCellFactory: SettingsCellFactory\n private weak var tableView: UITableView?\n\n weak var delegate: SettingsDataSourceDelegate?\n\n init(tableView: UITableView, interactor: SettingsInteractor) {\n self.tableView = tableView\n self.interactor = interactor\n\n let settingsCellFactory = SettingsCellFactory(tableView: tableView, interactor: interactor)\n self.settingsCellFactory = settingsCellFactory\n\n super.init(tableView: tableView) { _, indexPath, itemIdentifier in\n settingsCellFactory.makeCell(for: itemIdentifier, indexPath: indexPath)\n }\n\n tableView.sectionFooterHeight = 0\n tableView.delegate = self\n settingsCellFactory.delegate = self\n\n registerClasses()\n updateDataSnapshot()\n\n interactor.didUpdateDeviceState = { [weak self] _ in\n self?.updateDataSnapshot()\n }\n storedAccountData = interactor.deviceState.accountData\n }\n\n func reload(from tunnelSettings: LatestTunnelSettings) {\n settingsCellFactory.viewModel = SettingsViewModel(from: tunnelSettings)\n\n var snapshot = snapshot()\n snapshot.reconfigureItems(snapshot.itemIdentifiers)\n apply(snapshot, animatingDifferences: false)\n }\n\n // MARK: - UITableViewDelegate\n\n func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {\n true\n }\n\n func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {\n guard let item = itemIdentifier(for: indexPath) else { return }\n delegate?.didSelectItem(item: item)\n }\n\n func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {\n tableView.dequeueReusableHeaderFooterView(\n withIdentifier: HeaderFooterReuseIdentifier.spacer.rawValue\n )\n }\n\n // MARK: - Private\n\n private func registerClasses() {\n HeaderFooterReuseIdentifier.allCases.forEach { reuseIdentifier in\n tableView?.register(\n reuseIdentifier.headerFooterClass,\n forHeaderFooterViewReuseIdentifier: reuseIdentifier.rawValue\n )\n }\n }\n\n private func updateDataSnapshot() {\n var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()\n\n if interactor.deviceState.isLoggedIn {\n snapshot.appendSections([.vpnSettings])\n snapshot.appendItems([\n .daita,\n .multihop,\n .vpnSettings,\n ], toSection: .vpnSettings)\n }\n\n snapshot.appendSections([.apiAccess])\n snapshot.appendItems([.apiAccess], toSection: .apiAccess)\n\n snapshot.appendSections([.version, .problemReport])\n snapshot.appendItems([.changelog], toSection: .version)\n snapshot.appendItems([.problemReport, .faq], toSection: .problemReport)\n\n apply(snapshot)\n }\n}\n\nextension SettingsDataSource: @preconcurrency SettingsCellEventHandler {\n func showInfo(for button: SettingsInfoButtonItem) {\n delegate?.showInfo(for: button)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Settings\SettingsDataSource.swift | SettingsDataSource.swift | Swift | 5,348 | 0.95 | 0.055249 | 0.060403 | node-utils | 944 | 2025-03-31T16:17:07.490001 | BSD-3-Clause | false | b17c06bbeabd3970ca870ecaae9feb0e |
//\n// SettingsDataSourceDelegate.swift\n// MullvadVPN\n//\n// Created by pronebird on 19/10/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\nimport UIKit\n\nprotocol SettingsDataSourceDelegate: AnyObject {\n func didSelectItem(item: SettingsDataSource.Item)\n func showInfo(for: SettingsInfoButtonItem)\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Settings\SettingsDataSourceDelegate.swift | SettingsDataSourceDelegate.swift | Swift | 350 | 0.95 | 0.066667 | 0.538462 | awesome-app | 64 | 2024-01-11T04:19:22.898776 | Apache-2.0 | false | 5b0ebaa46c56d92dd9b07da74dd825b8 |
//\n// SettingsDNSInfoCell.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-07-07.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass SettingsDNSInfoCell: UITableViewCell {\n let titleLabel = UILabel()\n\n override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {\n super.init(style: style, reuseIdentifier: reuseIdentifier)\n\n backgroundColor = .secondaryColor\n contentView.directionalLayoutMargins = UIMetrics.SettingsCell.layoutMargins\n\n titleLabel.translatesAutoresizingMaskIntoConstraints = false\n titleLabel.textColor = UIColor.Cell.titleTextColor\n titleLabel.numberOfLines = 0\n\n contentView.addConstrainedSubviews([titleLabel]) {\n titleLabel.pinEdgesToSuperviewMargins()\n }\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Settings\SettingsDNSInfoCell.swift | SettingsDNSInfoCell.swift | Swift | 923 | 0.95 | 0.03125 | 0.28 | node-utils | 320 | 2025-06-12T19:06:15.085289 | GPL-3.0 | false | 1a0b738b94c0fe4d75551b323f062884 |
//\n// SettingsDNSTextCell.swift\n// MullvadVPN\n//\n// Created by pronebird on 05/10/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport UIKit\n\nclass SettingsDNSTextCell: SettingsCell, UITextFieldDelegate {\n var isValidInput = true {\n didSet {\n updateCellAppearance(animated: false)\n }\n }\n\n let textField = CustomTextField()\n\n var onTextChange: ((SettingsDNSTextCell) -> Void)?\n var onReturnKey: ((SettingsDNSTextCell) -> Void)?\n\n override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {\n super.init(style: style, reuseIdentifier: reuseIdentifier)\n\n textField.font = UIFont.systemFont(ofSize: 17)\n textField.backgroundColor = .clear\n textField.textColor = UIColor.TextField.textColor\n textField.textMargins = UIMetrics.SettingsCell.textFieldContentInsets\n textField.placeholder = NSLocalizedString(\n "DNS_TEXT_CELL_PLACEHOLDER",\n tableName: "Settings",\n value: "Enter IP",\n comment: ""\n )\n textField.setAccessibilityIdentifier(.dnsSettingsEnterIPAddressTextField)\n textField.cornerRadius = 0\n textField.keyboardType = .numbersAndPunctuation\n textField.returnKeyType = .done\n textField.autocorrectionType = .no\n textField.smartInsertDeleteType = .no\n textField.smartDashesType = .no\n textField.smartQuotesType = .no\n textField.spellCheckingType = .no\n textField.autocapitalizationType = .none\n textField.delegate = self\n\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(textDidChange),\n name: UITextField.textDidChangeNotification,\n object: textField\n )\n\n backgroundView?.backgroundColor = UIColor.TextField.backgroundColor\n contentView.addSubview(textField)\n\n contentView.addConstrainedSubviews([textField]) {\n textField.pinEdgesToSuperview()\n }\n\n updateCellAppearance(animated: false)\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n override func prepareForReuse() {\n super.prepareForReuse()\n\n onTextChange = nil\n onReturnKey = nil\n\n textField.text = ""\n isValidInput = true\n }\n\n override func setEditing(_ editing: Bool, animated: Bool) {\n super.setEditing(editing, animated: animated)\n\n updateCellAppearance(animated: animated)\n }\n\n @objc func textDidChange() {\n onTextChange?(self)\n }\n\n private func updateCellAppearance(animated: Bool) {\n if animated {\n UIView.animate(withDuration: 0.25) {\n self.updateCellAppearance()\n }\n } else {\n updateCellAppearance()\n }\n }\n\n private func updateCellAppearance() {\n textField.isEnabled = isEditing\n\n if isEditing {\n textField.textMargins.left = UIMetrics.SettingsCell.textFieldContentInsets.left\n\n if isValidInput {\n textField.textColor = UIColor.TextField.textColor\n } else {\n textField.textColor = UIColor.TextField.invalidInputTextColor\n }\n\n backgroundView?.backgroundColor = UIColor.TextField.backgroundColor\n } else {\n textField.textMargins.left = UIMetrics.SettingsCell.textFieldNonEditingContentInsetLeft\n\n textField.textColor = .white\n backgroundView?.backgroundColor = UIColor.Cell.Background.indentationLevelOne\n }\n }\n\n // MARK: - UITextFieldDelegate\n\n func textFieldShouldReturn(_ textField: UITextField) -> Bool {\n onReturnKey?(self)\n return true\n }\n\n func textField(\n _ textField: UITextField,\n shouldChangeCharactersIn range: NSRange,\n replacementString string: String\n ) -> Bool {\n let ipv4AddressCharset = CharacterSet.ipv4AddressCharset\n let ipv6AddressCharset = CharacterSet.ipv6AddressCharset\n\n return [ipv4AddressCharset, ipv6AddressCharset].contains { charset in\n string.unicodeScalars.allSatisfy { scalar in\n charset.contains(scalar)\n }\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Settings\SettingsDNSTextCell.swift | SettingsDNSTextCell.swift | Swift | 4,291 | 0.95 | 0.028169 | 0.069565 | react-lib | 969 | 2023-12-14T08:33:03.208418 | MIT | false | ab0da676d6a4ec5c3df37e6265410e95 |
//\n// SettingsHeaderView.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-04-06.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass SettingsHeaderView: UITableViewHeaderFooterView {\n typealias InfoButtonHandler = () -> Void\n typealias CollapseHandler = (SettingsHeaderView) -> Void\n\n let titleLabel: UILabel = {\n let titleLabel = UILabel()\n titleLabel.translatesAutoresizingMaskIntoConstraints = false\n titleLabel.font = .systemFont(ofSize: 17)\n titleLabel.textColor = UIColor.Cell.titleTextColor\n titleLabel.numberOfLines = 0\n return titleLabel\n }()\n\n let infoButton: UIButton = {\n let button = UIButton(type: .custom)\n button.setAccessibilityIdentifier(.infoButton)\n button.tintColor = .white\n button.setImage(UIImage.Buttons.info, for: .normal)\n return button\n }()\n\n let collapseButton: UIButton = {\n let button = UIButton(type: .custom)\n button.setAccessibilityIdentifier(.expandButton)\n button.tintColor = .white\n return button\n }()\n\n var isExpanded = false {\n didSet {\n updateCollapseImage()\n updateAccessibilityCustomActions()\n }\n }\n\n var accessibilityCustomActionName = "" {\n didSet {\n updateAccessibilityCustomActions()\n }\n }\n\n var didCollapseHandler: CollapseHandler?\n var infoButtonHandler: InfoButtonHandler? { didSet {\n infoButton.isHidden = infoButtonHandler == nil\n }}\n\n private let chevronDown = UIImage(named: "IconChevronDown")\n private let chevronUp = UIImage(named: "IconChevronUp")\n private let buttonWidth: CGFloat = 24\n\n override init(reuseIdentifier: String?) {\n super.init(reuseIdentifier: reuseIdentifier)\n\n infoButton.isHidden = true\n infoButton.addTarget(\n self,\n action: #selector(handleInfoButton(_:)),\n for: .touchUpInside\n )\n\n collapseButton.addTarget(\n self,\n action: #selector(handleCollapseButton(_:)),\n for: .touchUpInside\n )\n\n contentView.directionalLayoutMargins = UIMetrics.SettingsCell.layoutMargins\n contentView.backgroundColor = UIColor.Cell.Background.normal\n\n let buttonAreaWidth = UIMetrics.contentLayoutMargins.leading + UIMetrics\n .contentLayoutMargins.trailing + buttonWidth\n\n contentView.addConstrainedSubviews([titleLabel, infoButton, collapseButton]) {\n titleLabel.pinEdgesToSuperviewMargins(.all().excluding(.trailing).excluding(.bottom))\n titleLabel.bottomAnchor.constraint(\n equalTo: contentView.bottomAnchor,\n constant: -contentView.layoutMargins.bottom\n ).withPriority(.defaultHigh)\n\n infoButton.pinEdgesToSuperview(.init([.top(0), .bottom(0)]))\n infoButton.leadingAnchor.constraint(\n equalTo: titleLabel.trailingAnchor,\n constant: -UIMetrics.interButtonSpacing\n )\n infoButton.widthAnchor.constraint(equalToConstant: buttonAreaWidth)\n\n collapseButton.pinEdgesToSuperview(.all().excluding(.leading))\n collapseButton.leadingAnchor.constraint(greaterThanOrEqualTo: infoButton.trailingAnchor)\n collapseButton.widthAnchor.constraint(equalToConstant: buttonAreaWidth)\n }\n\n updateCollapseImage()\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n @objc private func handleInfoButton(_ sender: UIControl) {\n infoButtonHandler?()\n }\n\n @objc private func handleCollapseButton(_ sender: UIControl) {\n didCollapseHandler?(self)\n }\n\n @objc private func toggleCollapseAccessibilityAction() -> Bool {\n didCollapseHandler?(self)\n return true\n }\n\n private func updateCollapseImage() {\n let image = isExpanded ? chevronUp : chevronDown\n\n collapseButton.setImage(image, for: .normal)\n collapseButton.setAccessibilityIdentifier(isExpanded ? .collapseButton : .expandButton)\n }\n\n private func updateAccessibilityCustomActions() {\n let actionName = isExpanded\n ? NSLocalizedString(\n "SETTINGS_HEADER_COLLAPSE_ACCESSIBILITY_ACTION",\n tableName: "Settings",\n value: "Collapse \(accessibilityCustomActionName)",\n comment: ""\n )\n : NSLocalizedString(\n "SETTINGS_HEADER_EXPAND_ACCESSIBILITY_ACTION",\n tableName: "Settings",\n value: "Expand \(accessibilityCustomActionName)",\n comment: ""\n )\n\n accessibilityCustomActions = [\n UIAccessibilityCustomAction(\n name: actionName,\n target: self,\n selector: #selector(toggleCollapseAccessibilityAction)\n ),\n ]\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Settings\SettingsHeaderView.swift | SettingsHeaderView.swift | Swift | 4,983 | 0.95 | 0.032895 | 0.055556 | node-utils | 863 | 2024-12-20T20:18:51.578652 | Apache-2.0 | false | a42abfbf9ebcc39580ef284a8b5533e8 |
//\n// SettingsInfoButtonItem.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-10-03.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nenum SettingsInfoButtonItem: CustomStringConvertible {\n case daita\n case daitaDirectOnly\n\n var description: String {\n switch self {\n case .daita:\n NSLocalizedString(\n "DAITA_INFORMATION_TEXT",\n tableName: "DAITA",\n value: """\n DAITA (Defence against AI-guided Traffic Analysis) hides patterns in your encrypted VPN traffic. \\n If anyone is monitoring your connection, this makes it significantly harder for them to identify \\n what websites you are visiting.\n It does this by carefully adding network noise and making all network packets the same size.\n Not all our servers are DAITA-enabled. Therefore, we use multihop automatically to enable DAITA \\n with any server.\n Attention: Be cautious if you have a limited data plan as this feature will increase your network \\n traffic.\n """,\n comment: ""\n )\n case .daitaDirectOnly:\n NSLocalizedString(\n "DIRECT_ONLY_INFORMATION_TEXT",\n tableName: "DAITA",\n value: """\n By enabling "Direct only" you will have to manually select a server that is DAITA-enabled. \\n This can cause you to end up in a blocked state until you have selected a compatible server \\n in the "Select location" view.\n """,\n comment: ""\n )\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Settings\SettingsInfoButtonItem.swift | SettingsInfoButtonItem.swift | Swift | 1,743 | 0.95 | 0.065217 | 0.162791 | awesome-app | 466 | 2023-08-08T17:37:26.194679 | GPL-3.0 | false | a14b9c1d9a8d99494a0af674e841bb31 |
//\n// SettingsInputCell.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-05-05.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass SettingsInputCell: SelectableSettingsCell {\n let textField = CustomTextField(frame: CGRect(origin: .zero, size: CGSize(width: 100, height: 30)))\n var toolbarDoneButton = UIBarButtonItem()\n\n var isValidInput: Bool {\n didSet {\n updateTextFieldInputValidity()\n }\n }\n\n var inputDidChange: ((String) -> Void)?\n var inputWasConfirmed: ((String) -> Void)?\n\n override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {\n isValidInput = true\n\n super.init(style: style, reuseIdentifier: reuseIdentifier)\n\n toolbarDoneButton = UIBarButtonItem(\n title: NSLocalizedString(\n "INPUT_CELL_TOOLBAR_BUTTON_DONE",\n tableName: "VPNSettings",\n value: "Done",\n comment: ""\n ),\n style: .done,\n target: self,\n action: #selector(confirmInput)\n )\n\n accessoryView = textField\n\n setUpTextField()\n setUpTextFieldToolbar()\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n override func prepareForReuse() {\n super.prepareForReuse()\n\n reset()\n }\n\n func reset() {\n textField.text = nil\n UITextField.SearchTextFieldAppearance.inactive.apply(to: textField)\n }\n\n func setInput(_ text: String) {\n textField.text = text\n textFieldDidChange(textField)\n }\n\n @objc func confirmInput() {\n _ = textFieldShouldReturn(textField)\n }\n\n @objc private func textFieldDidChange(_ textField: UITextField) {\n if let text = textField.text {\n inputDidChange?(text)\n toolbarDoneButton.isEnabled = isValidInput\n }\n }\n\n private func setUpTextField() {\n textField.borderStyle = .none\n textField.layer.cornerRadius = 4\n textField.font = .preferredFont(forTextStyle: .body)\n textField.textAlignment = .right\n textField.delegate = self\n textField.keyboardType = .numberPad\n textField.returnKeyType = .done\n textField.textMargins = UIMetrics.SettingsCell.inputCellTextFieldLayoutMargins\n textField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)\n\n UITextField.SearchTextFieldAppearance.inactive.apply(to: textField)\n }\n\n private func setUpTextFieldToolbar() {\n let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 44))\n toolbar.items = [\n UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil),\n toolbarDoneButton,\n ]\n\n toolbar.sizeToFit()\n\n textField.inputAccessoryView = toolbar\n }\n\n private func updateTextFieldInputValidity() {\n if isValidInput {\n textField.textColor = textField.isEditing ? .SearchTextField.textColor : .SearchTextField.inactiveTextColor\n } else {\n textField.textColor = UIColor.TextField.invalidInputTextColor\n }\n }\n}\n\nextension SettingsInputCell: UITextFieldDelegate {\n func textFieldDidBeginEditing(_ textField: UITextField) {\n inputDidChange?(textField.text ?? "")\n toolbarDoneButton.isEnabled = isValidInput\n\n UITextField.SearchTextFieldAppearance.active.apply(to: textField)\n }\n\n func textFieldShouldReturn(_ textField: UITextField) -> Bool {\n guard isValidInput else { return false }\n\n inputWasConfirmed?(textField.text ?? "")\n textField.resignFirstResponder()\n\n return true\n }\n\n func textFieldDidEndEditing(_ textField: UITextField) {\n UITextField.SearchTextFieldAppearance.inactive.apply(to: textField)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Settings\SettingsInputCell.swift | SettingsInputCell.swift | Swift | 3,911 | 0.95 | 0.030075 | 0.066667 | python-kit | 303 | 2024-03-15T01:52:23.847553 | Apache-2.0 | false | 86fef86b42b370f3537337679bce7561 |
//\n// SettingsInteractor.swift\n// MullvadVPN\n//\n// Created by pronebird on 26/10/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\nimport MullvadSettings\n\nfinal class SettingsInteractor {\n private let tunnelManager: TunnelManager\n private var tunnelObserver: TunnelObserver?\n\n var didUpdateDeviceState: ((DeviceState) -> Void)?\n var didUpdateTunnelSettings: ((LatestTunnelSettings) -> Void)?\n\n var tunnelSettings: LatestTunnelSettings {\n tunnelManager.settings\n }\n\n var deviceState: DeviceState {\n tunnelManager.deviceState\n }\n\n init(tunnelManager: TunnelManager) {\n self.tunnelManager = tunnelManager\n\n let tunnelObserver =\n TunnelBlockObserver(\n didUpdateDeviceState: { [weak self] _, deviceState, _ in\n self?.didUpdateDeviceState?(deviceState)\n },\n didUpdateTunnelSettings: { [weak self] _, settings in\n self?.didUpdateTunnelSettings?(settings)\n }\n )\n\n tunnelManager.addObserver(tunnelObserver)\n\n self.tunnelObserver = tunnelObserver\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Settings\SettingsInteractor.swift | SettingsInteractor.swift | Swift | 1,193 | 0.95 | 0.022222 | 0.194444 | node-utils | 982 | 2025-03-10T06:03:41.950764 | MIT | false | 89079afb0103a50659883488edae73c6 |
//\n// SettingsInteractorFactory.swift\n// MullvadVPN\n//\n// Created by pronebird on 26/10/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadREST\nimport MullvadSettings\n\nfinal class SettingsInteractorFactory {\n private let apiProxy: APIQuerying\n private let relayCacheTracker: RelayCacheTracker\n private let ipOverrideRepository: IPOverrideRepositoryProtocol\n\n let tunnelManager: TunnelManager\n\n init(\n tunnelManager: TunnelManager,\n apiProxy: APIQuerying,\n relayCacheTracker: RelayCacheTracker,\n ipOverrideRepository: IPOverrideRepositoryProtocol\n ) {\n self.tunnelManager = tunnelManager\n self.apiProxy = apiProxy\n self.relayCacheTracker = relayCacheTracker\n self.ipOverrideRepository = ipOverrideRepository\n }\n\n func makeVPNSettingsInteractor() -> VPNSettingsInteractor {\n VPNSettingsInteractor(tunnelManager: tunnelManager, relayCacheTracker: relayCacheTracker)\n }\n\n func makeProblemReportInteractor() -> ProblemReportInteractor {\n ProblemReportInteractor(apiProxy: apiProxy, tunnelManager: tunnelManager)\n }\n\n func makeSettingsInteractor() -> SettingsInteractor {\n SettingsInteractor(tunnelManager: tunnelManager)\n }\n\n func makeIPOverrideInteractor() -> IPOverrideInteractor {\n IPOverrideInteractor(repository: ipOverrideRepository, tunnelManager: tunnelManager)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Settings\SettingsInteractorFactory.swift | SettingsInteractorFactory.swift | Swift | 1,434 | 0.95 | 0.021739 | 0.184211 | awesome-app | 354 | 2025-05-17T05:38:09.113364 | BSD-3-Clause | false | d035db81f1bee3a70d3be8918a21c668 |
//\n// SettingsPromptAlertItem.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2024-09-16.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nenum DAITASettingsPromptItem: CustomStringConvertible {\n case daitaSettingIncompatibleWithSinglehop\n case daitaSettingIncompatibleWithMultihop\n\n var description: String {\n switch self {\n case .daitaSettingIncompatibleWithSinglehop:\n """\n DAITA isn’t available on the current server. After enabling, please go to the Switch \\n location view and select a location that supports DAITA.\n Attention: Since this increases your total network traffic, be cautious if you have a \\n limited data plan. It can also negatively impact your network speed and battery usage.\n """\n case .daitaSettingIncompatibleWithMultihop:\n """\n DAITA isn’t available on the current entry server. After enabling, please go to the Switch \\n location view and select an entry location that supports DAITA.\n Attention: Since this increases your total network traffic, be cautious if you have a \\n limited data plan. It can also negatively impact your network speed and battery usage.\n """\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Settings\SettingsPromptAlertItem.swift | SettingsPromptAlertItem.swift | Swift | 1,313 | 0.95 | 0.09375 | 0.233333 | react-lib | 490 | 2024-07-07T18:31:25.565961 | GPL-3.0 | false | 89d59a16a32e1f8e36b18182ba2cec04 |
//\n// SettingsSwitchCell.swift\n// MullvadVPN\n//\n// Created by pronebird on 19/05/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass SettingsSwitchCell: SettingsCell {\n private let switchContainer = CustomSwitchContainer()\n\n var action: ((Bool) -> Void)?\n\n override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {\n super.init(style: style, reuseIdentifier: reuseIdentifier)\n\n accessoryView = switchContainer\n\n switchContainer.control.addTarget(\n self,\n action: #selector(switchValueDidChange),\n for: .valueChanged\n )\n\n isAccessibilityElement = true\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n func setSwitchEnabled(_ isEnabled: Bool) {\n switchContainer.isEnabled = isEnabled\n }\n\n func setOn(_ isOn: Bool, animated: Bool) {\n switchContainer.control.setOn(isOn, animated: animated)\n }\n\n override func prepareForReuse() {\n super.prepareForReuse()\n\n setSwitchEnabled(true)\n }\n\n // MARK: - Actions\n\n @objc private func switchValueDidChange() {\n action?(switchContainer.control.isOn)\n }\n\n // MARK: - Accessibility\n\n override var accessibilityTraits: UIAccessibilityTraits {\n get {\n // Use UISwitch traits to make the entire cell behave as "Switch button"\n switchContainer.control.accessibilityTraits\n }\n set {\n super.accessibilityTraits = newValue\n }\n }\n\n override var accessibilityLabel: String? {\n get {\n titleLabel.text\n }\n set {\n super.accessibilityLabel = newValue\n }\n }\n\n override var accessibilityValue: String? {\n get {\n self.switchContainer.control.accessibilityValue\n }\n set {\n super.accessibilityValue = newValue\n }\n }\n\n override var accessibilityFrame: CGRect {\n get {\n UIAccessibility.convertToScreenCoordinates(self.bounds, in: self)\n }\n set {\n super.accessibilityFrame = newValue\n }\n }\n\n override var accessibilityPath: UIBezierPath? {\n get {\n UIBezierPath(roundedRect: accessibilityFrame, cornerRadius: 4)\n }\n set {\n super.accessibilityPath = newValue\n }\n }\n\n override func accessibilityActivate() -> Bool {\n guard switchContainer.isEnabled else { return false }\n\n let newValue = !switchContainer.control.isOn\n\n setOn(newValue, animated: true)\n action?(newValue)\n\n return true\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Settings\SettingsSwitchCell.swift | SettingsSwitchCell.swift | Swift | 2,693 | 0.95 | 0.017857 | 0.113636 | node-utils | 904 | 2024-12-23T10:51:56.328477 | MIT | false | 246fcd025b5b2c1484467c39c3461851 |
//\n// SettingsViewController.swift\n// MullvadVPN\n//\n// Created by pronebird on 20/03/2019.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadSettings\nimport Routing\nimport UIKit\n\nprotocol SettingsViewControllerDelegate: AnyObject, Sendable {\n func settingsViewControllerDidFinish(_ controller: SettingsViewController)\n func settingsViewController(\n _ controller: SettingsViewController,\n didRequestRoutePresentation route: SettingsNavigationRoute\n )\n}\n\nclass SettingsViewController: UITableViewController {\n weak var delegate: SettingsViewControllerDelegate?\n private var dataSource: SettingsDataSource?\n private let interactor: SettingsInteractor\n private let alertPresenter: AlertPresenter\n\n override var preferredStatusBarStyle: UIStatusBarStyle {\n .lightContent\n }\n\n init(interactor: SettingsInteractor, alertPresenter: AlertPresenter) {\n self.interactor = interactor\n self.alertPresenter = alertPresenter\n\n super.init(style: .grouped)\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n override func viewDidLoad() {\n super.viewDidLoad()\n\n navigationItem.title = NSLocalizedString(\n "NAVIGATION_TITLE",\n tableName: "Settings",\n value: "Settings",\n comment: ""\n )\n\n let doneButton = UIBarButtonItem(\n systemItem: .done,\n primaryAction: UIAction(handler: { [weak self] _ in\n guard let self else { return }\n\n delegate?.settingsViewControllerDidFinish(self)\n })\n )\n doneButton.setAccessibilityIdentifier(.settingsDoneButton)\n navigationItem.rightBarButtonItem = doneButton\n\n tableView.setAccessibilityIdentifier(.settingsTableView)\n tableView.backgroundColor = .secondaryColor\n tableView.separatorColor = .secondaryColor\n tableView.rowHeight = UITableView.automaticDimension\n tableView.estimatedRowHeight = 60\n\n dataSource = SettingsDataSource(tableView: tableView, interactor: interactor)\n dataSource?.delegate = self\n\n interactor.didUpdateTunnelSettings = { [weak self] newSettings in\n self?.dataSource?.reload(from: newSettings)\n }\n }\n}\n\nextension SettingsViewController: @preconcurrency SettingsDataSourceDelegate {\n func didSelectItem(item: SettingsDataSource.Item) {\n guard let route = item.navigationRoute else { return }\n delegate?.settingsViewController(self, didRequestRoutePresentation: route)\n }\n\n func showInfo(for item: SettingsInfoButtonItem) {\n let presentation = AlertPresentation(\n id: "settings-info-alert",\n icon: .info,\n message: item.description,\n buttons: [\n AlertAction(\n title: NSLocalizedString(\n "SETTINGS_INFO_ALERT_OK_ACTION",\n tableName: "Settings",\n value: "Got it!",\n comment: ""\n ),\n style: .default\n ),\n ]\n )\n\n alertPresenter.showAlert(presentation: presentation, animated: true)\n }\n}\n\nextension SettingsDataSource.Item {\n var navigationRoute: SettingsNavigationRoute? {\n switch self {\n case .vpnSettings:\n return .vpnSettings\n case .changelog:\n return .changelog\n case .problemReport:\n return .problemReport\n case .faq:\n return .faq\n case .apiAccess:\n return .apiAccess\n case .daita:\n return .daita\n case .multihop:\n return .multihop\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Settings\SettingsViewController.swift | SettingsViewController.swift | Swift | 3,821 | 0.95 | 0.02381 | 0.064815 | python-kit | 316 | 2024-03-21T12:40:31.641501 | Apache-2.0 | false | 9675ae7b24601ff0b3059df7c6748cbe |
//\n// SettingsViewModel.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-10-03.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\n\nstruct SettingsViewModel {\n private(set) var daitaSettings: DAITASettings\n private(set) var multihopState: MultihopState\n\n init(from tunnelSettings: LatestTunnelSettings = LatestTunnelSettings()) {\n daitaSettings = tunnelSettings.daita\n multihopState = tunnelSettings.tunnelMultihopState\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Settings\SettingsViewModel.swift | SettingsViewModel.swift | Swift | 499 | 0.95 | 0 | 0.4375 | vue-tools | 18 | 2024-08-28T23:36:29.358836 | GPL-3.0 | false | 6f28babb4ac4b1fb770d2505428011a6 |
//\n// ShadowsocksObfuscationSettingsView.swift\n// MullvadVPN\n//\n// Created by Andrew Bulhak on 2024-11-07.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\nimport SwiftUI\n\nstruct ShadowsocksObfuscationSettingsView<VM>: View where VM: ShadowsocksObfuscationSettingsViewModel {\n @StateObject var viewModel: VM\n\n var body: some View {\n let portString = NSLocalizedString(\n "SHADOWSOCKS_PORT_LABEL",\n tableName: "Shadowsocks",\n value: "Port",\n comment: ""\n )\n\n SingleChoiceList(\n title: portString,\n options: [WireGuardObfuscationShadowsocksPort.automatic],\n value: $viewModel.value,\n tableAccessibilityIdentifier: AccessibilityIdentifier.wireGuardObfuscationShadowsocksTable.asString,\n itemDescription: { item in NSLocalizedString(\n "SHADOWSOCKS_PORT_VALUE_\(item)",\n tableName: "Shadowsocks",\n value: "\(item)",\n comment: ""\n ) },\n parseCustomValue: { UInt16($0).flatMap { $0 > 0 ? WireGuardObfuscationShadowsocksPort.custom($0) : nil }\n },\n formatCustomValue: {\n if case let .custom(port) = $0 {\n "\(port)"\n } else {\n nil\n }\n },\n customLabel: NSLocalizedString(\n "SHADOWSOCKS_PORT_VALUE_CUSTOM",\n tableName: "Shadowsocks",\n value: "Custom",\n comment: ""\n ),\n customPrompt: NSLocalizedString(\n "SHADOWSOCKS_PORT_VALUE_PORT_PROMPT",\n tableName: "Shadowsocks",\n value: "Port",\n comment: ""\n ),\n customLegend: NSLocalizedString(\n "SHADOWSOCKS_PORT_VALUE_PORT_LEGEND",\n tableName: "Shadowsocks",\n value: "Valid range: 1 - 65535",\n comment: ""\n ),\n customInputMinWidth: 100,\n customInputMaxLength: 5,\n customFieldMode: .numericText\n ).onDisappear {\n viewModel.commit()\n }\n }\n}\n\n#Preview {\n let model = MockShadowsocksObfuscationSettingsViewModel(shadowsocksPort: .automatic)\n return ShadowsocksObfuscationSettingsView(viewModel: model)\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Settings\Obfuscation\ShadowsocksObfuscationSettingsView.swift | ShadowsocksObfuscationSettingsView.swift | Swift | 2,408 | 0.95 | 0.013699 | 0.117647 | vue-tools | 948 | 2023-10-17T17:39:14.054663 | BSD-3-Clause | false | 7cb136e9e7664c14b8206aa383dd02d4 |
//\n// ShadowsocksObfuscationSettingsViewModel.swift\n// MullvadVPN\n//\n// Created by Andrew Bulhak on 2024-11-07.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadSettings\n\nprotocol ShadowsocksObfuscationSettingsViewModel: ObservableObject {\n var value: WireGuardObfuscationShadowsocksPort { get set }\n\n func commit()\n}\n\n/** A simple mock view model for use in Previews and similar */\nclass MockShadowsocksObfuscationSettingsViewModel: ShadowsocksObfuscationSettingsViewModel {\n @Published var value: WireGuardObfuscationShadowsocksPort\n\n init(shadowsocksPort: WireGuardObfuscationShadowsocksPort = .automatic) {\n self.value = shadowsocksPort\n }\n\n func commit() {}\n}\n\n/// ** The live view model which interfaces with the TunnelManager */\nclass TunnelShadowsocksObfuscationSettingsViewModel: TunnelObfuscationSettingsWatchingObservableObject<\n WireGuardObfuscationShadowsocksPort\n>,\n ShadowsocksObfuscationSettingsViewModel {\n init(tunnelManager: TunnelManager) {\n super.init(\n tunnelManager: tunnelManager,\n keyPath: \.shadowsocksPort\n )\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Settings\Obfuscation\ShadowsocksObfuscationSettingsViewModel.swift | ShadowsocksObfuscationSettingsViewModel.swift | Swift | 1,164 | 0.95 | 0.075 | 0.272727 | awesome-app | 866 | 2025-03-22T13:49:43.810741 | Apache-2.0 | false | d89d8d26977ac6cb5b18109b65deb794 |
//\n// TunnelObfuscationSettingsWatchingObservableObject.swift\n// MullvadVPN\n//\n// Created by Andrew Bulhak on 2024-11-07.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadSettings\n\n/// a generic ObservableObject that binds to obfuscation settings in TunnelManager.\n/// Used as the basis for ViewModels for SwiftUI interfaces for these settings.\n\nclass TunnelObfuscationSettingsWatchingObservableObject<T: Equatable>: ObservableObject {\n let tunnelManager: TunnelManager\n let keyPath: WritableKeyPath<WireGuardObfuscationSettings, T>\n private var tunnelObserver: TunnelObserver?\n\n @Published var value: T\n\n init(tunnelManager: TunnelManager, keyPath: WritableKeyPath<WireGuardObfuscationSettings, T>) {\n self.tunnelManager = tunnelManager\n self.keyPath = keyPath\n self.value = tunnelManager.settings.wireGuardObfuscation[keyPath: keyPath]\n tunnelObserver =\n TunnelBlockObserver(didUpdateTunnelSettings: { [weak self] _, newSettings in\n guard let self else { return }\n updateValueFromSettings(newSettings.wireGuardObfuscation)\n })\n }\n\n private func updateValueFromSettings(_ settings: WireGuardObfuscationSettings) {\n let newValue = settings[keyPath: keyPath]\n if value != newValue {\n value = newValue\n }\n }\n\n // Commit the temporarily stored value upstream\n func commit() {\n var obfuscationSettings = tunnelManager.settings.wireGuardObfuscation\n obfuscationSettings[keyPath: keyPath] = value\n tunnelManager.updateSettings([.obfuscation(obfuscationSettings)])\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Settings\Obfuscation\TunnelObfuscationSettingsWatchingObservableObject.swift | TunnelObfuscationSettingsWatchingObservableObject.swift | Swift | 1,678 | 0.95 | 0.108696 | 0.25641 | node-utils | 265 | 2025-03-01T20:52:44.295178 | GPL-3.0 | false | e6726dc7893a0c00094d245419fe1185 |
//\n// UDPOverTCPObfuscationSettingsView.swift\n// MullvadVPN\n//\n// Created by Andrew Bulhak on 2024-10-28.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\nimport SwiftUI\n\nstruct UDPOverTCPObfuscationSettingsView<VM>: View where VM: UDPOverTCPObfuscationSettingsViewModel {\n @StateObject var viewModel: VM\n\n var body: some View {\n let portString = NSLocalizedString(\n "UDP_TCP_PORT_LABEL",\n tableName: "UdpToTcp",\n value: "Port",\n comment: ""\n )\n SingleChoiceList(\n title: portString,\n options: [WireGuardObfuscationUdpOverTcpPort.automatic, .port80, .port5001],\n value: $viewModel.value,\n tableAccessibilityIdentifier: AccessibilityIdentifier.wireGuardObfuscationUdpOverTcpTable.asString,\n itemDescription: { item in NSLocalizedString(\n "UDP_TCP_PORT_VALUE_\(item)",\n tableName: "UdpToTcp",\n value: "\(item)",\n comment: ""\n ) }\n ).onDisappear {\n viewModel.commit()\n }\n }\n}\n\n#Preview {\n let model = MockUDPOverTCPObfuscationSettingsViewModel(udpTcpPort: .port5001)\n return UDPOverTCPObfuscationSettingsView(viewModel: model)\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Settings\Obfuscation\UDPOverTCPObfuscationSettingsView.swift | UDPOverTCPObfuscationSettingsView.swift | Swift | 1,297 | 0.95 | 0 | 0.210526 | awesome-app | 721 | 2023-10-31T06:19:32.129319 | GPL-3.0 | false | da6eaea0a6c62da19970befd72bc85c4 |
//\n// UDPOverTCPObfuscationSettingsViewModel.swift\n// MullvadVPN\n//\n// Created by Andrew Bulhak on 2024-11-05.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadSettings\n\nprotocol UDPOverTCPObfuscationSettingsViewModel: ObservableObject {\n var value: WireGuardObfuscationUdpOverTcpPort { get set }\n\n func commit()\n}\n\n/** A simple mock view model for use in Previews and similar */\nclass MockUDPOverTCPObfuscationSettingsViewModel: UDPOverTCPObfuscationSettingsViewModel {\n @Published var value: WireGuardObfuscationUdpOverTcpPort\n\n init(udpTcpPort: WireGuardObfuscationUdpOverTcpPort = .automatic) {\n self.value = udpTcpPort\n }\n\n func commit() {}\n}\n\n/** The live view model which interfaces with the TunnelManager */\nclass TunnelUDPOverTCPObfuscationSettingsViewModel: TunnelObfuscationSettingsWatchingObservableObject<\n WireGuardObfuscationUdpOverTcpPort\n>,\n UDPOverTCPObfuscationSettingsViewModel {\n init(tunnelManager: TunnelManager) {\n super.init(\n tunnelManager: tunnelManager,\n keyPath: \.udpOverTcpPort\n )\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Settings\Obfuscation\UDPOverTCPObfuscationSettingsViewModel.swift | UDPOverTCPObfuscationSettingsViewModel.swift | Swift | 1,140 | 0.95 | 0.075 | 0.272727 | vue-tools | 644 | 2024-08-20T08:54:33.152014 | GPL-3.0 | false | d45ae521260c832fc54e7feb57c0c6bc |
//\n// SingleChoiceList.swift\n// MullvadVPN\n//\n// Created by Andrew Bulhak on 2024-11-06.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport SwiftUI\n\n/**\n A component presenting a vertical list in the Mullvad style for selecting a single item from a list.\n This is parametrised over a value type known as `Value`, which can be any Equatable type. One would typically use an `enum` for this. As the name suggests, this allows one value to be chosen, which it sets a provided binding to.\n\n The simplest use case for `SingleChoiceList` is to present a list of options, each of which being a simple value without additional data; i.e.,\n\n ```swift\n SingleChoiceList(\n title: "Colour",\n options: [.red, .green, .blue],\n value: $colour,\n itemDescription: { NSLocalizedString("colour_\($0)") }\n )\n ```\n\n `SingleChoiceList` also provides support for having a value that takes a user-defined value, and presents a UI for filling this. In this case, the caller needs to provide not only the UI elements but functions for parsing the entered text to a value and unparsing the value to the text field, like so:\n\n ```swift\n enum TipAmount {\n case none\n case fivePercent\n case tenPercent\n case custom(Int)\n }\n\n SingleChoiceList(\n title: "Tip",\n options: [.none, .fivePercent, .tenPercent],\n value: $tipAmount,\n parseCustomValue: { Int($0).map { TipAmount.custom($0) },\n formatCustomValue: {\n if case let .custom(t) = $0 { "\(t)" } else { nil }\n },\n customLabel: "Custom",\n customPrompt: "% ",\n customFieldMode: .numericText\n )\n\n ```\n */\n\n// swiftlint:disable function_parameter_count\n\nstruct SingleChoiceList<Value>: View where Value: Equatable {\n let title: String\n private let options: [OptionSpec]\n var value: Binding<Value>\n @State var initialValue: Value?\n let tableAccessibilityIdentifier: String\n let itemDescription: (Value) -> String\n let customFieldMode: CustomFieldMode\n // a latch to keep the custom field selected through changes of focus until the user taps elsewhere\n @State var customFieldSelected = false\n\n /// The configuration for the field for a custom value row\n enum CustomFieldMode {\n /// The field is a text field into which any text may be typed\n case freeText\n /// The field is a text field configured for numeric input; i.e., the user will see a numeric keyboard\n case numericText\n }\n\n // Assumption: there will be only one custom value input per list.\n // This makes sense if it's something like a port; if we ever need to\n // use this with a type with more than one form of custom value, we will\n // need to add some mitigations\n @State var customValueInput = ""\n @FocusState var customValueIsFocused: Bool\n @State var customValueInputIsInvalid = false\n\n // an individual option being presented in a row\n fileprivate struct OptionSpec: Identifiable {\n enum OptValue {\n // this row consists of a constant item with a fixed Value. It may only be selected as is\n case literal(Value)\n // this row consists of a text field into which the user can enter a custom value, which may yield a valid Value. This has accompanying text, and functions to translate between text field contents and the Value. (The fromValue method only needs to give a non-nil value if its input is a custom value that could have come from this row.)\n case custom(\n label: String,\n prompt: String,\n legend: String?,\n minInputWidth: CGFloat?,\n maxInputLength: Int?,\n toValue: (String) -> Value?,\n fromValue: (Value) -> String?\n )\n }\n\n let id: Int\n let value: OptValue\n }\n\n // an internal constructor, building the element from basics\n fileprivate init(\n title: String,\n optionSpecs: [OptionSpec.OptValue],\n value: Binding<Value>,\n tableAccessibilityIdentifier: String?,\n itemDescription: ((Value) -> String)? = nil,\n customFieldMode: CustomFieldMode = .freeText\n ) {\n self.title = title\n self.options = optionSpecs.enumerated().map { OptionSpec(id: $0.offset, value: $0.element) }\n self.value = value\n self.itemDescription = itemDescription ?? { "\($0)" }\n self.tableAccessibilityIdentifier = tableAccessibilityIdentifier ?? "SingleChoiceList"\n self.customFieldMode = customFieldMode\n self.initialValue = value.wrappedValue\n }\n\n /// Create a `SingleChoiceList` presenting a choice of several fixed values.\n ///\n /// - Parameters:\n /// - title: The title of the list, which is typically the name of the item being chosen.\n /// - options: A list of `Value`s to be presented.\n /// - itemDescription: An optional function that, when given a `Value`, returns the string representation to present in the list. If not provided, this will be generated naïvely using string interpolation.\n init(\n title: String,\n options: [Value],\n value: Binding<Value>,\n tableAccessibilityIdentifier: String? = nil,\n itemDescription: ((Value) -> String)? = nil,\n itemAccessibilityIdentifier: ((Value) -> String)? = nil\n ) {\n self.init(\n title: title,\n optionSpecs: options.map { .literal($0) },\n value: value,\n tableAccessibilityIdentifier: tableAccessibilityIdentifier,\n itemDescription: itemDescription\n )\n }\n\n /// Create a `SingleChoiceList` presenting a choice of several fixed values, plus a row where the user may enter an argument for a custom value.\n ///\n /// - Parameters:\n /// - title: The title of the list, which is typically the name of the item being chosen.\n /// - options: A list of fixed `Value`s to be presented.\n /// - tableAccessibilityIdentifier: an optional string value for the accessibility identifier of the table element enclosing the list. If not present, it will be "SingleChoiceList"\n /// - itemDescription: An optional function that, when given a `Value`, returns the string representation to present in the list. If not provided, this will be generated naïvely using string interpolation. This is only used for the non-custom values.\n /// - parseCustomValue: A function that attempts to parse the text entered into the text field and produce a `Value` (typically the tagged custom value with an argument applied to it). If the text is not valid for a value, it should return `nil`\n /// - formatCustomValue: A function that, when passed a `Value` containing user-entered custom data, formats that data into a string, which should match what the user would have entered. This function can expect to only be called for the custom value, and should return `nil` in the event of its argument not being a valid custom value.\n /// - customLabel: The caption to display in the custom row, next to the text field.\n /// - customPrompt: The text to display, greyed, in the text field when it is empty. This also serves to set the width of the field, and should be right-padded with spaces as appropriate.\n /// - customLegend: Optional text to display below the custom field, i.e., to explain sensible values\n /// - customInputWidth: An optional minimum width (in pseudo-pixels) for the custom input field\n /// - customInputMaxLength: An optional maximum length to which input is truncated\n /// - customFieldMode: An enumeration that sets the mode of the custom value entry text field. If this is `.numericText`, the data is expected to be a decimal number, and the device will present a numeric keyboard when the field is focussed. If it is `.freeText`, a standard alphanumeric keyboard will be presented. If not specified, this defaults to `.freeText`.\n init(\n title: String,\n options: [Value],\n value: Binding<Value>,\n tableAccessibilityIdentifier: String? = nil,\n itemDescription: ((Value) -> String)? = nil,\n parseCustomValue: @escaping ((String) -> Value?),\n formatCustomValue: @escaping ((Value) -> String?),\n customLabel: String,\n customPrompt: String,\n customLegend: String? = nil,\n customInputMinWidth: CGFloat? = nil,\n customInputMaxLength: Int? = nil,\n customFieldMode: CustomFieldMode = .freeText\n ) {\n self.init(\n title: title,\n optionSpecs: options.map { .literal($0) } + [.custom(\n label: customLabel,\n prompt: customPrompt,\n legend: customLegend,\n minInputWidth: customInputMinWidth,\n maxInputLength: customInputMaxLength,\n toValue: parseCustomValue,\n fromValue: formatCustomValue\n )],\n value: value,\n tableAccessibilityIdentifier: tableAccessibilityIdentifier,\n itemDescription: itemDescription,\n customFieldMode: customFieldMode\n )\n }\n\n // Construct a row with arbitrary content and the correct style\n private func row<V: View>(isSelected: Bool, @ViewBuilder items: () -> V) -> some View {\n HStack {\n Image(uiImage: UIImage.tick).opacity(isSelected ? 1.0 : 0.0)\n Spacer().frame(width: UIMetrics.SettingsCell.selectableSettingsCellLeftViewSpacing)\n\n items()\n }\n .padding(EdgeInsets(UIMetrics.SettingsCell.layoutMargins))\n .background(\n isSelected\n ? Color(UIColor.Cell.Background.selected)\n : Color(UIColor.Cell.Background.indentationLevelOne)\n )\n .foregroundColor(Color(UIColor.Cell.titleTextColor))\n }\n\n // Construct a literal row for a specific literal value\n private func literalRow(_ item: Value) -> some View {\n row(\n isSelected: value.wrappedValue == item && !customFieldSelected\n ) {\n Text(verbatim: itemDescription(item))\n Spacer()\n }\n .onTapGesture {\n value.wrappedValue = item\n customValueIsFocused = false\n customValueInput = ""\n customFieldSelected = false\n }\n }\n\n // Construct the one row with a custom input field for a custom value\n // swiftlint:disable function_body_length\n private func customRow(\n label: String,\n prompt: String,\n inputWidth: CGFloat?,\n maxInputLength: Int?,\n toValue: @escaping (String) -> Value?,\n fromValue: @escaping (Value) -> String?\n ) -> some View {\n row(\n isSelected: value.wrappedValue == toValue(customValueInput) || customFieldSelected\n ) {\n Text(label)\n Spacer()\n TextField(\n "value",\n text: $customValueInput,\n prompt: Text(prompt).foregroundColor(\n customValueIsFocused\n ? Color(UIColor.TextField.placeholderTextColor)\n : Color(UIColor.TextField.inactivePlaceholderTextColor)\n )\n )\n .keyboardType(customFieldMode == .numericText ? .numberPad : .default)\n .multilineTextAlignment(\n customFieldMode == .numericText\n ? .trailing\n : .leading\n )\n .frame(minWidth: inputWidth, maxWidth: .infinity)\n .fixedSize()\n .padding(4)\n .foregroundColor(\n customValueIsFocused\n ? customValueInputIsInvalid\n ? Color(UIColor.TextField.invalidInputTextColor)\n : Color(UIColor.TextField.textColor)\n : Color(UIColor.TextField.inactiveTextColor)\n )\n .background(\n customValueIsFocused\n ? Color(UIColor.TextField.backgroundColor)\n : Color(UIColor.TextField.inactiveBackgroundColor)\n )\n .cornerRadius(4.0)\n // .border doesn't honour .cornerRadius, so overlaying a RoundedRectangle is necessary\n .overlay(\n RoundedRectangle(cornerRadius: 4.0)\n .stroke(\n customValueInputIsInvalid ? Color(UIColor.TextField.invalidInputTextColor) : .clear,\n lineWidth: 1\n )\n )\n .focused($customValueIsFocused)\n .onChange(of: customValueInput) { _ in\n if let maxInputLength {\n if customValueInput.count > maxInputLength {\n customValueInput = String(customValueInput.prefix(maxInputLength))\n }\n }\n if let parsedValue = toValue(customValueInput) {\n value.wrappedValue = parsedValue\n customValueInputIsInvalid = false\n } else {\n // this is not a valid value, so we fall back to the\n // initial value, showing the invalid-value state if\n // the field is not empty\n // As `customValueIsFocused` takes a while to propagate, we\n // only reset the field to the initial value if it was previously\n // a custom value. Otherwise, blanking this field when the user\n // has selected another field will cause the user's choice to be\n // overridden.\n if let initialValue, fromValue(value.wrappedValue) != nil {\n value.wrappedValue = initialValue\n }\n customValueInputIsInvalid = !customValueInput.isEmpty\n }\n }\n .onAppear {\n if let valueText = fromValue(value.wrappedValue) {\n customValueInput = valueText\n }\n }\n }\n .onTapGesture {\n customFieldSelected = true\n if let v = toValue(customValueInput) {\n value.wrappedValue = v\n } else {\n customValueIsFocused = true\n }\n }\n }\n\n // swiftlint:enable function_body_length\n\n private func subtitleRow(_ text: String) -> some View {\n HStack {\n Text(text)\n .font(.callout)\n .opacity(0.6)\n Spacer()\n }\n .padding(.horizontal, UIMetrics.SettingsCell.layoutMargins.leading)\n .padding(.vertical, 4)\n .background(\n Color(.secondaryColor)\n )\n .foregroundColor(Color(UIColor.Cell.titleTextColor))\n }\n\n var body: some View {\n VStack(spacing: UIMetrics.TableView.separatorHeight) {\n HStack {\n Text(title).fontWeight(.semibold)\n Spacer()\n }\n .padding(EdgeInsets(UIMetrics.SettingsCell.layoutMargins))\n .background(Color(UIColor.Cell.Background.normal))\n List {\n Section {\n ForEach(options) { opt in\n switch opt.value {\n case let .literal(v):\n literalRow(v)\n .listRowSeparator(.hidden)\n case let .custom(\n label,\n prompt,\n legend,\n inputWidth,\n maxInputLength,\n toValue,\n fromValue\n ):\n customRow(\n label: label,\n prompt: prompt,\n inputWidth: inputWidth,\n maxInputLength: maxInputLength,\n toValue: toValue,\n fromValue: fromValue\n )\n .listRowSeparator(.hidden)\n if let legend {\n subtitleRow(legend)\n .listRowSeparator(.hidden)\n }\n }\n }\n }\n .listRowInsets(.init()) // remove insets\n }\n .accessibilityIdentifier(tableAccessibilityIdentifier)\n .listStyle(.plain)\n .listRowSpacing(UIMetrics.TableView.separatorHeight)\n .environment(\.defaultMinListRowHeight, 0)\n Spacer()\n }\n .padding(EdgeInsets(top: 24, leading: 0, bottom: 0, trailing: 0))\n .background(Color(.secondaryColor))\n .foregroundColor(Color(.primaryTextColor))\n .onAppear {\n initialValue = value.wrappedValue\n }\n }\n}\n\n// swiftlint:enable function_parameter_count\n\n#Preview("Static values") {\n StatefulPreviewWrapper(1) { SingleChoiceList(title: "Test", options: [1, 2, 3], value: $0) }\n}\n\n#Preview("Optional value") {\n enum ExampleValue: Equatable {\n case two\n case three\n case someNumber(Int)\n }\n return StatefulPreviewWrapper(ExampleValue.two) { value in\n VStack {\n let vs = "Value = \(value.wrappedValue)"\n Text(vs)\n SingleChoiceList(\n title: "Test",\n options: [.two, .three],\n value: value,\n parseCustomValue: { Int($0).flatMap { $0 > 3 ? ExampleValue.someNumber($0) : nil } },\n formatCustomValue: { if case let .someNumber(n) = $0 { "\(n)" } else { nil } },\n customLabel: "Custom",\n customPrompt: "Number",\n customLegend: "The legend goes here",\n customInputMinWidth: 120,\n customInputMaxLength: 6,\n customFieldMode: .numericText\n )\n }\n }\n} // swiftlint:disable:this file_length\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Settings\SwiftUI components\SingleChoiceList.swift | SingleChoiceList.swift | Swift | 18,152 | 0.95 | 0.089623 | 0.151134 | vue-tools | 700 | 2025-03-25T16:31:46.344691 | MIT | false | fc4f397e723a8f84617518b4cbb08703 |
//\n// StatefulPreviewWrapper.swift\n// MullvadVPN\n//\n// Created by Andrew Bulhak on 2024-11-06.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\n// This should probably live somewhere more central than `View controllers/Settings/SwiftUI components`. Where exactly is to be determined.\n\nimport SwiftUI\n\n/** A wrapper for providing a state binding for SwiftUI Views in #Preview. This takes as arguments an initial value for the binding and a block which accepts the binding and returns a View to be previewed\n The usage looks like:\n\n ```\n #Preview {\n StatefulPreviewWrapper(initvalue) { ComponentToBePreviewed(binding: $0) }\n }\n ```\n */\n\nstruct StatefulPreviewWrapper<Value, Content: View>: View {\n @State var value: Value\n var content: (Binding<Value>) -> Content\n\n var body: some View {\n content($value)\n }\n\n init(_ value: Value, content: @escaping (Binding<Value>) -> Content) {\n self._value = State(wrappedValue: value)\n self.content = content\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Settings\SwiftUI components\StatefulPreviewWrapper.swift | StatefulPreviewWrapper.swift | Swift | 1,012 | 0.95 | 0.085714 | 0.392857 | vue-tools | 920 | 2025-05-06T03:50:23.117626 | MIT | false | a4d75a86dd7c323d7b962d58d0aa65bb |
//\n// TermsOfServiceContentView.swift\n// MullvadVPN\n//\n// Created by pronebird on 28/04/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass TermsOfServiceContentView: UIView {\n let titleLabel: UILabel = {\n let titleLabel = UILabel()\n titleLabel.translatesAutoresizingMaskIntoConstraints = false\n titleLabel.font = UIFont.systemFont(ofSize: 24, weight: .bold)\n titleLabel.numberOfLines = 0\n titleLabel.textColor = .white\n titleLabel.allowsDefaultTighteningForTruncation = true\n titleLabel.text = NSLocalizedString(\n "PRIVACY_NOTICE_HEADING",\n tableName: "TermsOfService",\n value: "Do you agree to remaining anonymous?",\n comment: ""\n )\n titleLabel.lineBreakMode = .byWordWrapping\n titleLabel.lineBreakStrategy = []\n return titleLabel\n }()\n\n let bodyLabel: UILabel = {\n let bodyLabel = UILabel()\n\n let message = NSMutableAttributedString(string: NSLocalizedString(\n "PRIVACY_NOTICE_BODY",\n tableName: "TermsOfService",\n value: """\n You have a right to privacy. That’s why we never store activity logs, don’t ask for personal \\n information, and encourage anonymous payments.\n In some situations, as outlined in our privacy policy, we might process personal data that you \\n choose to send, for example if you email us.\n We strongly believe in retaining as little data as possible because we want you to remain anonymous.\n """,\n comment: ""\n ))\n message.apply(paragraphStyle: .alert)\n\n bodyLabel.attributedText = message\n bodyLabel.translatesAutoresizingMaskIntoConstraints = false\n bodyLabel.font = UIFont.systemFont(ofSize: 18)\n bodyLabel.textColor = .white\n bodyLabel.numberOfLines = 0\n\n return bodyLabel\n }()\n\n let privacyPolicyLink: LinkButton = {\n let button = LinkButton()\n button.translatesAutoresizingMaskIntoConstraints = false\n button.titleString = NSLocalizedString(\n "PRIVACY_POLICY_LINK_TITLE",\n tableName: "TermsOfService",\n value: "Privacy policy",\n comment: ""\n )\n button.setImage(UIImage(named: "IconExtlink"), for: .normal)\n return button\n }()\n\n let agreeButton: AppButton = {\n let button = AppButton(style: .default)\n button.translatesAutoresizingMaskIntoConstraints = false\n button.setAccessibilityIdentifier(.agreeButton)\n button.setTitle(NSLocalizedString(\n "CONTINUE_BUTTON_TITLE",\n tableName: "TermsOfService",\n value: "Agree and continue",\n comment: ""\n ), for: .normal)\n return button\n }()\n\n let scrollView: UIScrollView = {\n let scrollView = UIScrollView()\n scrollView.translatesAutoresizingMaskIntoConstraints = false\n return scrollView\n }()\n\n let scrollContentContainer: UIView = {\n let contentView = UIView()\n contentView.translatesAutoresizingMaskIntoConstraints = false\n contentView.directionalLayoutMargins = UIMetrics.contentLayoutMargins\n return contentView\n }()\n\n let footerContainer: UIView = {\n let container = UIView()\n container.translatesAutoresizingMaskIntoConstraints = false\n container.directionalLayoutMargins = UIMetrics.contentLayoutMargins\n container.backgroundColor = .secondaryColor\n return container\n }()\n\n override init(frame: CGRect) {\n super.init(frame: frame)\n\n self.setAccessibilityIdentifier(.termsOfServiceView)\n\n addSubviews()\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n // MARK: - Private\n\n private func addSubviews() {\n addSubview(scrollView)\n addSubview(footerContainer)\n\n scrollView.addSubview(scrollContentContainer)\n [titleLabel, bodyLabel, privacyPolicyLink].forEach { scrollContentContainer.addSubview($0) }\n footerContainer.addSubview(agreeButton)\n\n scrollView.setContentCompressionResistancePriority(.defaultLow, for: .vertical)\n footerContainer.setContentCompressionResistancePriority(.defaultHigh, for: .vertical)\n\n NSLayoutConstraint.activate([\n scrollView.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor),\n scrollView.leadingAnchor.constraint(equalTo: leadingAnchor),\n scrollView.trailingAnchor.constraint(equalTo: trailingAnchor),\n\n scrollContentContainer.widthAnchor.constraint(equalTo: scrollView.widthAnchor),\n scrollContentContainer.topAnchor.constraint(equalTo: scrollView.topAnchor),\n scrollContentContainer.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),\n scrollContentContainer.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),\n scrollContentContainer.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),\n\n footerContainer.topAnchor.constraint(equalTo: scrollView.bottomAnchor),\n footerContainer.leadingAnchor.constraint(equalTo: leadingAnchor),\n footerContainer.trailingAnchor.constraint(equalTo: trailingAnchor),\n footerContainer.bottomAnchor.constraint(equalTo: bottomAnchor),\n\n agreeButton.topAnchor.constraint(equalTo: footerContainer.layoutMarginsGuide.topAnchor),\n agreeButton.leadingAnchor\n .constraint(equalTo: footerContainer.layoutMarginsGuide.leadingAnchor),\n agreeButton.trailingAnchor\n .constraint(equalTo: footerContainer.layoutMarginsGuide.trailingAnchor),\n agreeButton.bottomAnchor\n .constraint(equalTo: footerContainer.layoutMarginsGuide.bottomAnchor),\n\n titleLabel.topAnchor\n .constraint(equalTo: scrollContentContainer.layoutMarginsGuide.topAnchor),\n titleLabel.leadingAnchor\n .constraint(equalTo: scrollContentContainer.layoutMarginsGuide.leadingAnchor),\n titleLabel.trailingAnchor\n .constraint(equalTo: scrollContentContainer.layoutMarginsGuide.trailingAnchor),\n\n bodyLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 24),\n bodyLabel.leadingAnchor\n .constraint(equalTo: scrollContentContainer.layoutMarginsGuide.leadingAnchor),\n bodyLabel.trailingAnchor\n .constraint(equalTo: scrollContentContainer.layoutMarginsGuide.trailingAnchor),\n\n privacyPolicyLink.topAnchor.constraint(equalTo: bodyLabel.bottomAnchor, constant: 24),\n privacyPolicyLink.leadingAnchor\n .constraint(equalTo: scrollContentContainer.layoutMarginsGuide.leadingAnchor),\n privacyPolicyLink.trailingAnchor\n .constraint(\n lessThanOrEqualTo: scrollContentContainer.layoutMarginsGuide\n .trailingAnchor\n ),\n privacyPolicyLink.bottomAnchor\n .constraint(equalTo: scrollContentContainer.layoutMarginsGuide.bottomAnchor),\n\n ])\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\TermsOfService\TermsOfServiceContentView.swift | TermsOfServiceContentView.swift | Swift | 7,271 | 0.95 | 0.044944 | 0.05298 | python-kit | 422 | 2025-05-22T07:21:55.791295 | BSD-3-Clause | false | 7f55653eaa1e85e4c381fc74c59ae7da |
//\n// TermsOfServiceViewController.swift\n// MullvadVPN\n//\n// Created by pronebird on 21/02/2020.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass TermsOfServiceViewController: UIViewController, RootContainment {\n var showPrivacyPolicy: (() -> Void)?\n var completionHandler: (() -> Void)?\n\n override var preferredStatusBarStyle: UIStatusBarStyle {\n .lightContent\n }\n\n var preferredHeaderBarPresentation: HeaderBarPresentation {\n HeaderBarPresentation(style: .default, showsDivider: false)\n }\n\n var prefersHeaderBarHidden: Bool {\n false\n }\n\n // MARK: - View lifecycle\n\n override func viewDidLoad() {\n super.viewDidLoad()\n\n let contentView = TermsOfServiceContentView()\n contentView.translatesAutoresizingMaskIntoConstraints = false\n contentView.agreeButton.addTarget(\n self,\n action: #selector(handleAgreeButton(_:)),\n for: .touchUpInside\n )\n contentView.privacyPolicyLink.addTarget(\n self,\n action: #selector(handlePrivacyPolicyButton(_:)),\n for: .touchUpInside\n )\n\n view.backgroundColor = .primaryColor\n view.addSubview(contentView)\n\n NSLayoutConstraint.activate([\n contentView.topAnchor.constraint(equalTo: view.topAnchor),\n contentView.leadingAnchor.constraint(equalTo: view.leadingAnchor),\n contentView.trailingAnchor.constraint(equalTo: view.trailingAnchor),\n contentView.bottomAnchor.constraint(equalTo: view.bottomAnchor),\n ])\n }\n\n // MARK: - Actions\n\n @objc private func handlePrivacyPolicyButton(_ sender: Any) {\n showPrivacyPolicy?()\n }\n\n @objc private func handleAgreeButton(_ sender: Any) {\n completionHandler?()\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\TermsOfService\TermsOfServiceViewController.swift | TermsOfServiceViewController.swift | Swift | 1,836 | 0.95 | 0.046154 | 0.173077 | react-lib | 868 | 2025-01-29T15:56:40.828772 | MIT | false | 9af8fc6ddadb0e036b49140cde76efc9 |
//\n// CustomOverlayRenderer.swift\n// MullvadVPN\n//\n// Created by pronebird on 26/10/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MapKit\n\nclass CustomOverlayRenderer: MKOverlayRenderer {\n override func draw(_ mapRect: MKMapRect, zoomScale: MKZoomScale, in context: CGContext) {\n let drawRect = rect(for: mapRect)\n context.setFillColor(UIColor.secondaryColor.cgColor)\n context.fill(drawRect)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Tunnel\CustomOverlayRenderer.swift | CustomOverlayRenderer.swift | Swift | 456 | 0.95 | 0.117647 | 0.466667 | vue-tools | 451 | 2024-02-22T11:38:28.213100 | MIT | false | 25e019901c89eebfb6ef185ca0619a9c |
//\n// MapViewController.swift\n// MullvadVPN\n//\n// Created by pronebird on 03/01/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MapKit\nimport MullvadLogging\nimport Operations\n\nprivate let locationMarkerReuseIdentifier = "location"\nprivate let geoJSONSourceFileName = "countries.geo.json"\n\nfinal class MapViewController: UIViewController, MKMapViewDelegate {\n private let logger = Logger(label: "MapViewController")\n private let animationQueue = AsyncOperationQueue.makeSerial()\n\n private let locationMarker = MKPointAnnotation()\n private var willChangeRegion = false\n private var regionDidChangeCompletion: (() -> Void)?\n private let mapView = MKMapView()\n private var isFirstLayoutPass = true\n private var center: CLLocationCoordinate2D?\n var alignmentView: UIView?\n\n // MARK: - View lifecycle\n\n override func viewDidLoad() {\n super.viewDidLoad()\n\n mapView.delegate = self\n mapView.register(\n MKAnnotationView.self,\n forAnnotationViewWithReuseIdentifier: locationMarkerReuseIdentifier\n )\n\n mapView.showsUserLocation = false\n mapView.isZoomEnabled = false\n mapView.isScrollEnabled = false\n mapView.isUserInteractionEnabled = false\n mapView.accessibilityElementsHidden = true\n\n // Use dark style for the map to dim the map grid\n mapView.overrideUserInterfaceStyle = .dark\n\n addTileOverlay()\n loadGeoJSONData()\n addMapView()\n }\n\n override func viewWillTransition(\n to size: CGSize,\n with coordinator: UIViewControllerTransitionCoordinator\n ) {\n super.viewWillTransition(to: size, with: coordinator)\n\n coordinator.animate(alongsideTransition: nil, completion: { context in\n self.recomputeVisibleRegion(animated: context.isAnimated)\n })\n }\n\n override func viewDidLayoutSubviews() {\n super.viewDidLayoutSubviews()\n\n if isFirstLayoutPass {\n isFirstLayoutPass = false\n recomputeVisibleRegion(animated: false)\n }\n }\n\n // MARK: - Public\n\n func addLocationMarker(coordinate: CLLocationCoordinate2D) {\n locationMarker.coordinate = coordinate\n mapView.addAnnotation(locationMarker)\n }\n\n func removeLocationMarker() {\n mapView.removeAnnotation(locationMarker)\n }\n\n func setCenter(\n _ center: CLLocationCoordinate2D?,\n animated: Bool,\n completion: (() -> Void)? = nil\n ) {\n enqueueAnimation(cancelOtherAnimations: true) { finish in\n self.setCenterInternal(center, animated: animated) {\n finish()\n completion?()\n }\n }\n }\n\n // MARK: - MKMapViewDelegate\n\n func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {\n if let polygon = overlay as? MKPolygon {\n let renderer = MKPolygonRenderer(polygon: polygon)\n renderer.fillColor = .primaryColor\n renderer.strokeColor = .secondaryColor\n renderer.lineWidth = 1\n renderer.lineCap = .round\n renderer.lineJoin = .round\n return renderer\n }\n\n if let tileOverlay = overlay as? MKTileOverlay {\n return CustomOverlayRenderer(overlay: tileOverlay)\n }\n\n return MKOverlayRenderer()\n }\n\n func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {\n guard annotation === locationMarker else { return nil }\n\n let view = mapView.dequeueReusableAnnotationView(\n withIdentifier: locationMarkerReuseIdentifier,\n for: annotation\n )\n view.isDraggable = false\n view.canShowCallout = false\n view.image = UIImage(named: "LocationMarkerSecure")\n\n return view\n }\n\n func mapView(_ mapView: MKMapView, regionWillChangeAnimated animated: Bool) {\n willChangeRegion = true\n }\n\n func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {\n willChangeRegion = false\n\n let handler = regionDidChangeCompletion\n regionDidChangeCompletion = nil\n handler?()\n }\n\n // MARK: - Private\n\n private func addMapView() {\n mapView.translatesAutoresizingMaskIntoConstraints = false\n view.addSubview(mapView)\n\n NSLayoutConstraint.activate([\n mapView.topAnchor.constraint(equalTo: view.topAnchor),\n mapView.leadingAnchor.constraint(equalTo: view.leadingAnchor),\n mapView.trailingAnchor.constraint(equalTo: view.trailingAnchor),\n mapView.bottomAnchor.constraint(equalTo: view.bottomAnchor),\n ])\n }\n\n private func addTileOverlay() {\n let tileOverlay = MKTileOverlay(urlTemplate: nil)\n tileOverlay.canReplaceMapContent = true\n\n mapView.addOverlay(tileOverlay, level: .aboveLabels)\n }\n\n private func loadGeoJSONData() {\n guard let fileURL = Bundle.main.url(forResource: geoJSONSourceFileName, withExtension: nil)\n else {\n logger.debug("Failed to locate \(geoJSONSourceFileName) in main bundle.")\n return\n }\n\n do {\n let data = try Data(contentsOf: fileURL)\n guard let features = try MKGeoJSONDecoder().decode(data) as? [MKGeoJSONFeature]\n else { return }\n\n var overlays = [MKOverlay]()\n\n for feature in features {\n for geometry in feature.geometry {\n if let polygon = geometry as? MKPolygon {\n if let interiorPolygons = polygon.interiorPolygons,\n !interiorPolygons.isEmpty {\n overlays\n .append(MKPolygon(\n points: polygon.points(),\n count: polygon.pointCount\n ))\n overlays.append(contentsOf: interiorPolygons)\n } else {\n overlays.append(polygon)\n }\n }\n\n if let multiPolygon = geometry as? MKMultiPolygon {\n overlays.append(contentsOf: multiPolygon.polygons)\n }\n }\n }\n\n mapView.addOverlays(overlays, level: .aboveLabels)\n } catch {\n logger.error(error: error, message: "Failed to load geojson.")\n }\n }\n\n private func setCenterInternal(\n _ center: CLLocationCoordinate2D?,\n animated: Bool,\n completion: (() -> Void)?\n ) {\n let region = makeRegion(center: center)\n\n self.center = center\n\n // Map view does not call delegate methods when attempting to set the same region.\n mapView.setRegion(region, animated: animated)\n\n if willChangeRegion {\n regionDidChangeCompletion = completion\n } else {\n completion?()\n }\n }\n\n private func recomputeVisibleRegion(animated: Bool) {\n enqueueAnimation(cancelOtherAnimations: false) { finish in\n self.setCenterInternal(self.center, animated: animated, completion: finish)\n }\n }\n\n private func enqueueAnimation(\n cancelOtherAnimations: Bool,\n block: @escaping (_ finish: @escaping () -> Void) -> Void\n ) {\n nonisolated(unsafe) let nonisolatedBlock = block\n let operation = AsyncBlockOperation(dispatchQueue: .main) { finish in\n nonisolatedBlock {\n finish(nil)\n }\n }\n\n if cancelOtherAnimations {\n animationQueue.cancelAllOperations()\n }\n\n animationQueue.addOperation(operation)\n }\n\n private func makeRegion(center: CLLocationCoordinate2D?) -> MKCoordinateRegion {\n guard let center else {\n return makeZoomedOutRegion()\n }\n\n let sourceRegion = makeZoomedInRegion(center: center)\n\n guard let alignmentView else {\n return sourceRegion\n }\n\n return makeRegion(from: sourceRegion, withCenterMatching: alignmentView)\n }\n\n private func makeZoomedInRegion(center: CLLocationCoordinate2D) -> MKCoordinateRegion {\n let span = MKCoordinateSpan(latitudeDelta: 30, longitudeDelta: 30)\n let region = MKCoordinateRegion(center: center, span: span)\n\n return mapView.regionThatFits(region)\n }\n\n private func makeZoomedOutRegion() -> MKCoordinateRegion {\n let coordinate = CLLocationCoordinate2D(latitude: 0, longitude: 0)\n let span = MKCoordinateSpan(latitudeDelta: 90, longitudeDelta: 90)\n let region = MKCoordinateRegion(center: coordinate, span: span)\n\n return mapView.regionThatFits(region)\n }\n\n private func makeRegion(\n from region: MKCoordinateRegion,\n withCenterMatching alignmentView: UIView\n ) -> MKCoordinateRegion {\n // Map view center lies within layout margins frame.\n let mapViewLayoutFrame = mapView.layoutMarginsGuide.layoutFrame\n\n guard mapViewLayoutFrame.width > 0, mapView.frame.width > 0,\n region.span.longitudeDelta > 0,\n mapView.region.span.longitudeDelta > 0 else { return region }\n\n // MKMapView.convert(_:toRectTo:) returns CGRect scaled to the zoom level derived from\n // currently set region.\n // Calculate the ratio that we can use to translate the rect within its own coordinate\n // system before converting it into MKCoordinateRegion.\n let newZoomLevel = mapViewLayoutFrame.width / region.span.longitudeDelta\n let currentZoomLevel = mapViewLayoutFrame.width / mapView.region.span.longitudeDelta\n let zoomDelta = currentZoomLevel / newZoomLevel\n\n let alignmentViewRect = alignmentView.convert(alignmentView.bounds, to: mapView)\n let horizontalOffset = (mapViewLayoutFrame.midX - alignmentViewRect.midX) * zoomDelta\n let verticalOffset = (mapViewLayoutFrame.midY - alignmentViewRect.midY) * zoomDelta\n\n let regionRect = mapView.convert(region, toRectTo: mapView)\n let offsetRegionRect = regionRect.offsetBy(dx: horizontalOffset, dy: verticalOffset)\n let offsetRegion = mapView.convert(offsetRegionRect, toRegionFrom: mapView)\n\n if CLLocationCoordinate2DIsValid(offsetRegion.center) {\n return offsetRegion\n } else {\n return region\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Tunnel\MapViewController.swift | MapViewController.swift | Swift | 10,515 | 0.95 | 0.054487 | 0.071713 | awesome-app | 967 | 2023-11-09T14:55:55.980382 | BSD-3-Clause | false | 8c9704e136af896aaad861ffcbc12e01 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.