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// ListCustomListCoordinator.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-03-06.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\nimport MullvadTypes\nimport Routing\nimport UIKit\n\nclass ListCustomListCoordinator: Coordinator, Presentable, Presenting {\n let navigationController: UINavigationController\n let interactor: CustomListInteractorProtocol\n let tunnelManager: TunnelManager\n let listViewController: ListCustomListViewController\n let nodes: [LocationNode]\n\n var presentedViewController: UIViewController {\n navigationController\n }\n\n var didFinish: ((ListCustomListCoordinator) -> Void)?\n\n init(\n navigationController: UINavigationController,\n interactor: CustomListInteractorProtocol,\n tunnelManager: TunnelManager,\n nodes: [LocationNode]\n ) {\n self.navigationController = navigationController\n self.interactor = interactor\n self.tunnelManager = tunnelManager\n self.nodes = nodes\n\n listViewController = ListCustomListViewController(interactor: interactor)\n }\n\n func start() {\n listViewController.didFinish = { [weak self] in\n guard let self else { return }\n didFinish?(self)\n }\n listViewController.didSelectItem = { [weak self] in\n self?.edit(list: $0)\n }\n\n navigationController.pushViewController(listViewController, animated: false)\n }\n\n private func edit(list: CustomList) {\n let coordinator = EditCustomListCoordinator(\n navigationController: navigationController,\n customListInteractor: interactor,\n customList: list,\n nodes: nodes\n )\n\n coordinator.didFinish = { [weak self] editCustomListCoordinator, action, list in\n guard let self else { return }\n\n popToList()\n editCustomListCoordinator.removeFromParent()\n\n var relayConstraints = tunnelManager.settings.relayConstraints\n relayConstraints.entryLocations = self.updateRelayConstraint(\n relayConstraints.entryLocations,\n for: action,\n in: list\n )\n relayConstraints.exitLocations = self.updateRelayConstraint(\n relayConstraints.exitLocations,\n for: action,\n in: list\n )\n\n tunnelManager.updateSettings([.relayConstraints(relayConstraints)]) { [weak self] in\n self?.tunnelManager.reconnectTunnel(selectNewRelay: true)\n }\n }\n\n coordinator.didCancel = { [weak self] editCustomListCoordinator in\n guard let self else { return }\n popToList()\n editCustomListCoordinator.removeFromParent()\n }\n\n coordinator.start()\n addChild(coordinator)\n }\n\n private func updateRelayConstraint(\n _ relayConstraint: RelayConstraint<UserSelectedRelays>,\n for action: EditCustomListCoordinator.FinishAction,\n in list: CustomList\n ) -> RelayConstraint<UserSelectedRelays> {\n var relayConstraint = relayConstraint\n\n guard let customListSelection = relayConstraint.value?.customListSelection,\n customListSelection.listId == list.id\n else { return relayConstraint }\n\n switch action {\n case .save:\n if customListSelection.isList {\n let selectedRelays = UserSelectedRelays(\n locations: list.locations,\n customListSelection: UserSelectedRelays.CustomListSelection(listId: list.id, isList: true)\n )\n relayConstraint = .only(selectedRelays)\n } else {\n let selectedConstraintIsRemovedFromList = list.locations.filter {\n relayConstraint.value?.locations.contains($0) ?? false\n }.isEmpty\n\n if selectedConstraintIsRemovedFromList {\n relayConstraint = .only(UserSelectedRelays(locations: []))\n }\n }\n case .delete:\n relayConstraint = .only(UserSelectedRelays(locations: []))\n }\n\n return relayConstraint\n }\n\n private func popToList() {\n if interactor.fetchAll().isEmpty {\n navigationController.dismiss(animated: true)\n didFinish?(self)\n } else if let listController = navigationController.viewControllers\n .first(where: { $0 is ListCustomListViewController }) {\n navigationController.popToViewController(listController, animated: true)\n listViewController.updateDataSource(reloadExisting: true, animated: false)\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\CustomLists\ListCustomListCoordinator.swift
ListCustomListCoordinator.swift
Swift
4,733
0.95
0.064748
0.059322
node-utils
360
2024-09-03T11:26:37.924858
Apache-2.0
false
1ce8c23f83bb3365b7fba0dc40f39528
//\n// ListCustomListViewController.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-03-06.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\nimport UIKit\n\nprivate enum SectionIdentifier: Hashable {\n case `default`\n}\n\nprivate struct ItemIdentifier: Hashable {\n var id: UUID\n}\n\nprivate enum CellReuseIdentifier: String, CaseIterable, CellIdentifierProtocol {\n case `default`\n\n var cellClass: AnyClass {\n switch self {\n default: BasicCell.self\n }\n }\n}\n\nclass ListCustomListViewController: UIViewController {\n private typealias DataSource = UITableViewDiffableDataSource<SectionIdentifier, ItemIdentifier>\n\n private let interactor: CustomListInteractorProtocol\n private var dataSource: DataSource?\n private var fetchedItems: [CustomList] = []\n private var tableView = UITableView(frame: .zero, style: .plain)\n var didSelectItem: ((CustomList) -> Void)?\n var didFinish: (() -> Void)?\n\n init(interactor: CustomListInteractorProtocol) {\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.backgroundColor = .secondaryColor\n view.setAccessibilityIdentifier(.listCustomListsView)\n\n addSubviews()\n configureNavigationItem()\n configureDataSource()\n configureTableView()\n }\n\n func updateDataSource(reloadExisting: Bool, animated: Bool = true) {\n fetchedItems = interactor.fetchAll()\n var snapshot = NSDiffableDataSourceSnapshot<SectionIdentifier, ItemIdentifier>()\n snapshot.appendSections([.default])\n\n let itemIdentifiers = fetchedItems.map { ItemIdentifier(id: $0.id) }\n snapshot.appendItems(itemIdentifiers, toSection: .default)\n\n if reloadExisting {\n for item in fetchedItems {\n snapshot.reconfigureItems([ItemIdentifier(id: item.id)])\n }\n }\n\n dataSource?.apply(snapshot, animatingDifferences: animated)\n }\n\n private func addSubviews() {\n view.addConstrainedSubviews([tableView]) {\n tableView.pinEdgesToSuperview()\n }\n }\n\n private func configureTableView() {\n tableView.delegate = self\n tableView.backgroundColor = .secondaryColor\n tableView.separatorColor = .secondaryColor\n tableView.separatorInset = .zero\n tableView.separatorStyle = .singleLine\n tableView.rowHeight = UIMetrics.SettingsCell.customListsCellHeight\n tableView.registerReusableViews(from: CellReuseIdentifier.self)\n tableView.setAccessibilityIdentifier(.listCustomListsTableView)\n }\n\n private func configureNavigationItem() {\n navigationItem.title = NSLocalizedString(\n "LIST_CUSTOM_LIST_NAVIGATION_TITLE",\n tableName: "CustomList",\n value: "Edit custom list",\n comment: ""\n )\n\n navigationItem.rightBarButtonItem = UIBarButtonItem(\n systemItem: .done,\n primaryAction: UIAction(handler: { [weak self] _ in\n self?.didFinish?()\n })\n )\n\n navigationItem.rightBarButtonItem?.setAccessibilityIdentifier(.listCustomListDoneButton)\n }\n\n private func configureDataSource() {\n dataSource = DataSource(\n tableView: tableView,\n cellProvider: { [weak self] _, indexPath, itemIdentifier in\n self?.dequeueCell(at: indexPath, itemIdentifier: itemIdentifier)\n }\n )\n\n updateDataSource(reloadExisting: false, animated: false)\n }\n\n private func dequeueCell(\n at indexPath: IndexPath,\n itemIdentifier: ItemIdentifier\n ) -> UITableViewCell {\n let cell = tableView.dequeueReusableView(withIdentifier: CellReuseIdentifier.default, for: indexPath)\n let item = fetchedItems[indexPath.row]\n var contentConfiguration = ListCellContentConfiguration()\n contentConfiguration.text = item.name\n cell.contentConfiguration = contentConfiguration\n\n if let cell = cell as? DynamicBackgroundConfiguration {\n cell.setAutoAdaptingBackgroundConfiguration(.mullvadListPlainCell(), selectionType: .dimmed)\n }\n\n if let cell = cell as? CustomCellDisclosureHandling {\n cell.disclosureType = .chevron\n }\n return cell\n }\n}\n\nextension ListCustomListViewController: UITableViewDelegate {\n func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {\n tableView.deselectRow(at: indexPath, animated: false)\n\n let item = fetchedItems[indexPath.row]\n didSelectItem?(item)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\CustomLists\ListCustomListViewController.swift
ListCustomListViewController.swift
Swift
4,808
0.95
0.046053
0.056452
node-utils
96
2024-02-07T19:34:16.088016
BSD-3-Clause
false
7592c8f955fec2f7f6ddf46a02a97f8e
//\n// SettingsChildCoordinator.swift\n// MullvadVPN\n//\n// Created by pronebird on 08/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Routing\n\n/// Types that are child coordinators of ``SettingsCoordinator``.\nprotocol SettingsChildCoordinator: Coordinator {\n func start(animated: Bool)\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\SettingsChildCoordinator.swift
SettingsChildCoordinator.swift
Swift
323
0.95
0
0.666667
node-utils
706
2025-02-22T16:01:09.196298
GPL-3.0
false
7c0ceae5116089b6b3bc27647188595f
//\n// SettingsCoordinator.swift\n// MullvadVPN\n//\n// Created by pronebird on 09/01/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadLogging\nimport MullvadSettings\nimport Operations\nimport Routing\nimport SwiftUI\nimport UIKit\n\n/// Settings navigation route.\nenum SettingsNavigationRoute: Equatable {\n /// The route that's always displayed first upon entering settings.\n case root\n\n /// VPN settings.\n case vpnSettings\n\n /// Problem report.\n case problemReport\n\n /// FAQ section displayed as a modal safari browser.\n case faq\n\n /// API access route.\n case apiAccess\n\n /// changelog route.\n case changelog\n\n /// Multihop route.\n case multihop\n\n /// DAITA route.\n case daita\n}\n\n/// Top-level settings coordinator.\n@MainActor\nfinal class SettingsCoordinator: Coordinator, Presentable, Presenting, SettingsViewControllerDelegate,\n UINavigationControllerDelegate, Sendable {\n private let logger = Logger(label: "SettingsNavigationCoordinator")\n\n private var currentRoute: SettingsNavigationRoute?\n nonisolated(unsafe) private var modalRoute: SettingsNavigationRoute?\n private let interactorFactory: SettingsInteractorFactory\n private var viewControllerFactory: SettingsViewControllerFactory?\n\n let navigationController: UINavigationController\n\n var presentedViewController: UIViewController {\n navigationController\n }\n\n /// Event handler invoked when navigating bebtween child routes within the horizontal stack.\n var willNavigate: ((\n _ coordinator: SettingsCoordinator,\n _ from: SettingsNavigationRoute?,\n _ to: SettingsNavigationRoute\n ) -> Void)?\n\n /// Event handler invoked when coordinator and its view hierarchy should be dismissed.\n nonisolated(unsafe) var didFinish: (@Sendable (SettingsCoordinator) -> Void)?\n\n /// Designated initializer.\n /// - Parameters:\n /// - navigationController: a navigation controller that the coordinator will be managing.\n /// - interactorFactory: an instance of a factory that produces interactors for the child routes.\n init(\n navigationController: UINavigationController,\n interactorFactory: SettingsInteractorFactory,\n accessMethodRepository: AccessMethodRepositoryProtocol,\n proxyConfigurationTester: ProxyConfigurationTesterProtocol,\n ipOverrideRepository: IPOverrideRepository\n ) {\n self.navigationController = navigationController\n self.interactorFactory = interactorFactory\n\n super.init()\n\n viewControllerFactory = SettingsViewControllerFactory(\n interactorFactory: interactorFactory,\n accessMethodRepository: accessMethodRepository,\n proxyConfigurationTester: proxyConfigurationTester,\n ipOverrideRepository: ipOverrideRepository,\n navigationController: navigationController,\n alertPresenter: AlertPresenter(context: self)\n )\n }\n\n /// Start the coordinator fllow.\n /// - Parameter initialRoute: the initial route to display.\n func start(initialRoute: SettingsNavigationRoute? = nil) {\n navigationController.navigationBar.prefersLargeTitles = true\n navigationController.delegate = self\n\n push(from: makeChild(for: .root), animated: false)\n if let initialRoute, initialRoute != .root {\n push(from: makeChild(for: initialRoute), animated: false)\n }\n }\n\n // MARK: - Navigation\n\n /// Request navigation to the speciifc route.\n ///\n /// - Parameters:\n /// - route: the route to present.\n /// - animated: whether transition should be animated.\n /// - completion: a completion handler, typically called immediately for horizontal navigation and\n func navigate(\n to route: SettingsNavigationRoute,\n animated: Bool,\n completion: (@Sendable @MainActor () -> Void)? = nil\n ) {\n switch route {\n case .root:\n popToRoot(animated: animated)\n completion?()\n\n case .faq:\n guard modalRoute == nil else {\n completion?()\n return\n }\n\n modalRoute = route\n\n logger.debug("Show modal \(route)")\n\n let safariCoordinator = SafariCoordinator(url: ApplicationConfiguration.faqAndGuidesURL)\n\n safariCoordinator.didFinish = { [weak self] in\n self?.modalRoute = nil\n }\n\n presentChild(safariCoordinator, animated: animated, completion: completion)\n\n default:\n // Ignore navigation if the route is already presented.\n guard currentRoute != route else {\n completion?()\n return\n }\n\n let child = makeChild(for: route)\n\n // Pop to root first, then push the child.\n if navigationController.viewControllers.count > 1 {\n popToRoot(animated: animated)\n }\n push(from: child, animated: animated)\n\n completion?()\n }\n }\n\n // MARK: - UINavigationControllerDelegate\n\n func navigationController(\n _ navigationController: UINavigationController,\n willShow viewController: UIViewController,\n animated: Bool\n ) {\n /*\n Navigation controller calls this delegate method on `viewWillAppear`, for instance during cancellation\n of interactive dismissal of a modally presented settings navigation controller, so it's important that we\n ignore repeating routes.\n */\n guard let route = route(for: viewController), currentRoute != route else { return }\n\n logger.debug(\n "Navigate from \(currentRoute.map { "\($0)" } ?? "none") -> \(route)"\n )\n\n willNavigate?(self, currentRoute, route)\n\n currentRoute = route\n\n // Release child coordinators when moving to root.\n if case .root = route {\n releaseChildren()\n }\n }\n\n // MARK: - SettingsViewControllerDelegate\n\n nonisolated func settingsViewControllerDidFinish(_ controller: SettingsViewController) {\n didFinish?(self)\n }\n\n nonisolated func settingsViewController(\n _ controller: SettingsViewController,\n didRequestRoutePresentation route: SettingsNavigationRoute\n ) {\n Task {\n await navigate(to: route, animated: true)\n }\n }\n\n // MARK: - Route handling\n\n /// Pop to root route.\n /// - Parameter animated: whether to animate the transition.\n private func popToRoot(animated: Bool) {\n navigationController.popToRootViewController(animated: animated)\n releaseChildren()\n }\n\n /// Push the child into navigation stack.\n /// - Parameters:\n /// - result: the result of creating a child representing a route.\n /// - animated: whether to animate the transition.\n private func push(from result: SettingsViewControllerFactory.MakeChildResult, animated: Bool) {\n switch result {\n case let .viewController(vc):\n navigationController.pushViewController(vc, animated: animated)\n\n case let .childCoordinator(child):\n addChild(child)\n child.start(animated: animated)\n\n case .failed:\n break\n }\n }\n\n /// Release all child coordinators conforming to ``SettingsChildCoordinator`` protocol.\n private func releaseChildren() {\n childCoordinators.forEach { coordinator in\n if coordinator is SettingsChildCoordinator {\n coordinator.removeFromParent()\n }\n }\n }\n\n // MARK: - Route mapping\n\n /// Produce a view controller or a child coordinator representing the route.\n /// - Parameter route: the route for which to request the new view controller or child coordinator.\n /// - Returns: a result of creating a child for the route.\n private func makeChild(for route: SettingsNavigationRoute) -> SettingsViewControllerFactory.MakeChildResult {\n if route == .root {\n let controller = SettingsViewController(\n interactor: interactorFactory.makeSettingsInteractor(),\n alertPresenter: AlertPresenter(context: self)\n )\n controller.delegate = self\n return .viewController(controller)\n } else {\n return viewControllerFactory?.makeRoute(for: route) ?? .failed\n }\n }\n\n /// Map the view controller to the individual route.\n /// - Parameter viewController: an instance of a view controller within the navigation stack.\n /// - Returns: a route upon success, otherwise `nil`.\n private func route(for viewController: UIViewController) -> SettingsNavigationRoute? {\n switch viewController {\n case is SettingsViewController:\n return .root\n case is VPNSettingsViewController:\n return .vpnSettings\n case is ProblemReportViewController:\n return .problemReport\n case is ListAccessMethodViewController:\n return .apiAccess\n default:\n return nil\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\SettingsCoordinator.swift
SettingsCoordinator.swift
Swift
9,135
0.95
0.079422
0.237885
vue-tools
600
2025-03-11T22:38:02.183671
MIT
false
40b66ef3bdee6d8d193f49254c908f67
//\n// SettingsFieldValidationErrorConfiguration.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-02-16.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nstruct SettingsFieldValidationError: LocalizedError, Equatable {\n var errorDescription: String?\n}\n\nstruct SettingsFieldValidationErrorConfiguration: UIContentConfiguration, Equatable {\n var errors: [SettingsFieldValidationError] = []\n var directionalLayoutMargins: NSDirectionalEdgeInsets = UIMetrics.SettingsCell.settingsValidationErrorLayoutMargins\n\n func makeContentView() -> UIView & UIContentView {\n return SettingsFieldValidationErrorContentView(configuration: self)\n }\n\n func updated(for state: UIConfigurationState) -> Self {\n return self\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\SettingsFieldValidationErrorConfiguration.swift
SettingsFieldValidationErrorConfiguration.swift
Swift
781
0.95
0.038462
0.333333
awesome-app
682
2024-09-15T23:47:28.017302
BSD-3-Clause
false
37c49b56a66d50ef9e18cf2c3b9c5e42
//\n// SettingsFieldValidationErrorContentView.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-02-16.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass SettingsFieldValidationErrorContentView: UIView, UIContentView {\n let contentView = UIStackView()\n\n var icon: UIImageView {\n let view = UIImageView(image: UIImage.Buttons.alert.withTintColor(.dangerColor))\n view.heightAnchor.constraint(equalToConstant: 14).isActive = true\n view.widthAnchor.constraint(equalTo: view.heightAnchor, multiplier: 1).isActive = true\n return view\n }\n\n var configuration: UIContentConfiguration {\n get {\n actualConfiguration\n }\n set {\n guard let newConfiguration = newValue as? SettingsFieldValidationErrorConfiguration else { return }\n\n let previousConfiguration = actualConfiguration\n actualConfiguration = newConfiguration\n\n configureSubviews(previousConfiguration: previousConfiguration)\n }\n }\n\n private var actualConfiguration: SettingsFieldValidationErrorConfiguration\n\n func supports(_ configuration: UIContentConfiguration) -> Bool {\n configuration is SettingsFieldValidationErrorConfiguration\n }\n\n init(configuration: SettingsFieldValidationErrorConfiguration) {\n actualConfiguration = configuration\n\n super.init(frame: CGRect(x: 0, y: 0, width: 100, height: 44))\n\n addSubviews()\n configureSubviews()\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n private func addSubviews() {\n contentView.axis = .vertical\n contentView.spacing = 6\n\n addConstrainedSubviews([contentView]) {\n contentView.pinEdgesToSuperviewMargins()\n }\n }\n\n private func configureSubviews(previousConfiguration: SettingsFieldValidationErrorConfiguration? = nil) {\n guard actualConfiguration != previousConfiguration else { return }\n\n configureLayoutMargins()\n\n contentView.arrangedSubviews.forEach { view in\n view.removeFromSuperview()\n }\n\n actualConfiguration.errors.forEach { error in\n let label = UILabel()\n label.text = error.errorDescription\n label.numberOfLines = 0\n label.font = .systemFont(ofSize: 13)\n label.textColor = .white.withAlphaComponent(0.6)\n\n let stackView = UIStackView(arrangedSubviews: [icon, label])\n stackView.alignment = .top\n stackView.spacing = 6\n\n contentView.addArrangedSubview(stackView)\n }\n }\n\n private func configureLayoutMargins() {\n directionalLayoutMargins = actualConfiguration.directionalLayoutMargins\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\SettingsFieldValidationErrorContentView.swift
SettingsFieldValidationErrorContentView.swift
Swift
2,797
0.95
0.011111
0.101449
vue-tools
970
2024-03-03T20:11:20.143433
GPL-3.0
false
24da30202414693df17781eb77f2ce0a
//\n// SettingsValidationErrorConfiguration.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-02-16.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nstruct SettingsValidationErrorConfiguration: UIContentConfiguration, Equatable {\n var errors: [CustomListFieldValidationError] = []\n var directionalLayoutMargins: NSDirectionalEdgeInsets = UIMetrics.SettingsCell.settingsValidationErrorLayoutMargins\n\n func makeContentView() -> UIView & UIContentView {\n return SettingsValidationErrorContentView(configuration: self)\n }\n\n func updated(for state: UIConfigurationState) -> Self {\n return self\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\SettingsValidationErrorConfiguration.swift
SettingsValidationErrorConfiguration.swift
Swift
666
0.95
0.045455
0.388889
node-utils
241
2023-11-08T18:30:23.985943
BSD-3-Clause
false
435ee83f28bfbe408d2ae97122a01436
//\n// SettingsValidationErrorContentView.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-02-16.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass SettingsValidationErrorContentView: UIView, UIContentView {\n let contentView = UIStackView()\n\n var icon: UIImageView {\n let view = UIImageView(image: UIImage(resource: .iconAlert).withTintColor(.dangerColor))\n view.heightAnchor.constraint(equalToConstant: 14).isActive = true\n view.widthAnchor.constraint(equalTo: view.heightAnchor, multiplier: 1).isActive = true\n return view\n }\n\n var configuration: UIContentConfiguration {\n get {\n actualConfiguration\n }\n set {\n guard let newConfiguration = newValue as? SettingsValidationErrorConfiguration else { return }\n\n let previousConfiguration = actualConfiguration\n actualConfiguration = newConfiguration\n\n configureSubviews(previousConfiguration: previousConfiguration)\n }\n }\n\n private var actualConfiguration: SettingsValidationErrorConfiguration\n\n func supports(_ configuration: UIContentConfiguration) -> Bool {\n configuration is SettingsValidationErrorConfiguration\n }\n\n init(configuration: SettingsValidationErrorConfiguration) {\n actualConfiguration = configuration\n\n super.init(frame: CGRect(x: 0, y: 0, width: 100, height: 44))\n\n addSubviews()\n configureSubviews()\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n private func addSubviews() {\n contentView.axis = .vertical\n contentView.spacing = 6\n\n addConstrainedSubviews([contentView]) {\n contentView.pinEdgesToSuperviewMargins()\n }\n }\n\n private func configureSubviews(previousConfiguration: SettingsValidationErrorConfiguration? = nil) {\n guard actualConfiguration != previousConfiguration else { return }\n\n configureLayoutMargins()\n\n contentView.arrangedSubviews.forEach { view in\n view.removeFromSuperview()\n }\n\n actualConfiguration.errors.forEach { error in\n let label = UILabel()\n label.text = error.errorDescription\n label.numberOfLines = 0\n label.font = .systemFont(ofSize: 13)\n label.textColor = .white.withAlphaComponent(0.6)\n\n let stackView = UIStackView(arrangedSubviews: [icon, label])\n stackView.alignment = .top\n stackView.spacing = 6\n\n contentView.addArrangedSubview(stackView)\n }\n }\n\n private func configureLayoutMargins() {\n directionalLayoutMargins = actualConfiguration.directionalLayoutMargins\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\SettingsValidationErrorContentView.swift
SettingsValidationErrorContentView.swift
Swift
2,770
0.95
0.011111
0.101449
react-lib
74
2025-02-17T08:37:59.160946
GPL-3.0
false
e7a4cbcb7c9d52a64cee46c7a1ff2571
//\n// SettingsViewControllerFactory.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-11-26.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\nimport Routing\nimport SwiftUI\nimport UIKit\n\n@MainActor\nstruct SettingsViewControllerFactory {\n /// The result of creating a child representing a route.\n enum MakeChildResult {\n /// View controller that should be pushed into navigation stack.\n case viewController(UIViewController)\n\n /// Child coordinator that should be added to the children hierarchy.\n /// The child is responsile for presenting itself.\n case childCoordinator(SettingsChildCoordinator)\n\n /// Failure to produce a child.\n case failed\n }\n\n private let interactorFactory: SettingsInteractorFactory\n private let accessMethodRepository: AccessMethodRepositoryProtocol\n private let proxyConfigurationTester: ProxyConfigurationTesterProtocol\n private let ipOverrideRepository: IPOverrideRepository\n private let navigationController: UINavigationController\n private let alertPresenter: AlertPresenter\n\n init(\n interactorFactory: SettingsInteractorFactory,\n accessMethodRepository: AccessMethodRepositoryProtocol,\n proxyConfigurationTester: ProxyConfigurationTesterProtocol,\n ipOverrideRepository: IPOverrideRepository,\n navigationController: UINavigationController,\n alertPresenter: AlertPresenter\n ) {\n self.interactorFactory = interactorFactory\n self.accessMethodRepository = accessMethodRepository\n self.proxyConfigurationTester = proxyConfigurationTester\n self.ipOverrideRepository = ipOverrideRepository\n self.navigationController = navigationController\n self.alertPresenter = alertPresenter\n }\n\n func makeRoute(for route: SettingsNavigationRoute) -> MakeChildResult {\n switch route {\n case .root:\n // Handled in SettingsCoordinator.\n .failed\n case .faq:\n // Handled separately and presented as a modal.\n .failed\n case .vpnSettings:\n makeVPNSettingsViewCoordinator()\n case .problemReport:\n makeProblemReportViewController()\n case .apiAccess:\n makeAPIAccessCoordinator()\n case .changelog:\n makeChangelogCoordinator()\n case .multihop:\n makeMultihopViewController()\n case .daita:\n makeDAITASettingsCoordinator()\n }\n }\n\n private func makeVPNSettingsViewCoordinator() -> MakeChildResult {\n return .childCoordinator(VPNSettingsCoordinator(\n navigationController: navigationController,\n interactorFactory: interactorFactory,\n ipOverrideRepository: ipOverrideRepository\n ))\n }\n\n private func makeProblemReportViewController() -> MakeChildResult {\n return .viewController(ProblemReportViewController(\n interactor: interactorFactory.makeProblemReportInteractor(),\n alertPresenter: alertPresenter\n ))\n }\n\n private func makeAPIAccessCoordinator() -> MakeChildResult {\n return .childCoordinator(ListAccessMethodCoordinator(\n navigationController: navigationController,\n accessMethodRepository: accessMethodRepository,\n proxyConfigurationTester: proxyConfigurationTester\n ))\n }\n\n private func makeChangelogCoordinator() -> MakeChildResult {\n return .childCoordinator(\n ChangeLogCoordinator(\n route: .settings(.changelog),\n navigationController: navigationController,\n viewModel: ChangeLogViewModel(changeLogReader: ChangeLogReader())\n )\n )\n }\n\n private func makeMultihopViewController() -> MakeChildResult {\n let viewModel = MultihopTunnelSettingsViewModel(tunnelManager: interactorFactory.tunnelManager)\n let view = SettingsMultihopView(tunnelViewModel: viewModel)\n\n let host = UIHostingController(rootView: view)\n host.title = NSLocalizedString(\n "NAVIGATION_TITLE_MULTIHOP",\n tableName: "Settings",\n value: "Multihop",\n comment: ""\n )\n host.view.setAccessibilityIdentifier(.multihopView)\n\n return .viewController(host)\n }\n\n private func makeDAITASettingsCoordinator() -> MakeChildResult {\n let viewModel = DAITATunnelSettingsViewModel(tunnelManager: interactorFactory.tunnelManager)\n let coordinator = DAITASettingsCoordinator(\n navigationController: navigationController,\n route: .settings(.daita),\n viewModel: viewModel\n )\n\n return .childCoordinator(coordinator)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\SettingsViewControllerFactory.swift
SettingsViewControllerFactory.swift
Swift
4,771
0.95
0.022388
0.118644
react-lib
295
2023-08-27T14:43:24.677504
GPL-3.0
false
8a6f0d1bcd1a0e8a9b154f8afb2e803a
//\n// TunnelSettingsObservable.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-11-21.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\n\nprotocol TunnelSettingsObservable<TunnelSetting>: ObservableObject {\n associatedtype TunnelSetting\n\n var value: TunnelSetting { get set }\n func evaluate(setting: TunnelSetting)\n}\n\nclass MockTunnelSettingsViewModel<TunnelSetting>: TunnelSettingsObservable {\n @Published var value: TunnelSetting\n\n init(setting: TunnelSetting) {\n value = setting\n }\n\n func evaluate(setting: TunnelSetting) {}\n}\n\nprotocol TunnelSettingsObserver<TunnelSetting>: TunnelSettingsObservable {\n associatedtype TunnelSetting\n\n var tunnelManager: TunnelManager { get }\n var tunnelObserver: TunnelObserver? { get set }\n\n init(tunnelManager: TunnelManager)\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\TunnelSettingsObservable.swift
TunnelSettingsObservable.swift
Swift
856
0.95
0.028571
0.269231
python-kit
767
2025-04-20T06:44:21.356921
MIT
false
de8258c3ed67dd7b189e4a4d2991d893
//\n// AboutViewController.swift\n// MullvadVPN\n//\n// Created by pronebird on 08/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\n/// View controller used for presenting a detailed information on some topic using a scrollable stack view.\nclass AboutViewController: UIViewController {\n private let scrollView = UIScrollView()\n private let contentView = UIStackView()\n private let header: String?\n private let preamble: String?\n private let body: [String]\n\n init(header: String?, preamble: String?, body: [String]) {\n self.header = header\n self.preamble = preamble\n self.body = body\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 navigationController?.navigationBar.configureCustomAppeareance()\n\n setUpContentView()\n\n scrollView.addConstrainedSubviews([contentView]) {\n contentView.pinEdgesToSuperview()\n contentView.widthAnchor.constraint(equalTo: scrollView.widthAnchor)\n }\n\n view.addConstrainedSubviews([scrollView]) {\n scrollView.pinEdgesToSuperview()\n }\n }\n\n private func setUpContentView() {\n contentView.axis = .vertical\n contentView.spacing = 15\n contentView.layoutMargins = UIMetrics.contentInsets\n contentView.isLayoutMarginsRelativeArrangement = true\n\n if let header {\n let label = UILabel()\n\n label.text = header\n label.font = .systemFont(ofSize: 28, weight: .bold)\n label.textColor = .primaryTextColor\n label.numberOfLines = 0\n label.textAlignment = .center\n\n contentView.addArrangedSubview(label)\n contentView.setCustomSpacing(32, after: label)\n }\n\n if let preamble {\n let label = UILabel()\n\n label.text = preamble\n label.font = .systemFont(ofSize: 18)\n label.textColor = .primaryTextColor\n label.numberOfLines = 0\n label.textAlignment = .center\n\n contentView.addArrangedSubview(label)\n contentView.setCustomSpacing(24, after: label)\n }\n\n for text in body {\n let label = UILabel()\n\n label.text = text\n label.font = .systemFont(ofSize: 15)\n label.textColor = .secondaryTextColor\n label.numberOfLines = 0\n\n contentView.addArrangedSubview(label)\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\AboutViewController.swift
AboutViewController.swift
Swift
2,658
0.95
0.054348
0.111111
react-lib
399
2024-07-27T21:49:27.479435
GPL-3.0
false
ae6eb448d53c3fd0110b1784f80be206
//\n// Binding.swift\n// MullvadVPN\n//\n// Created by pronebird on 14/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport UIKit\n\nextension CurrentValueSubject {\n /// Creates `UIAction` that automatically updates the value from text field.\n ///\n /// - Parameter keyPath: the key path to the field that should be updated.\n /// - Returns: an instance of `UIAction`.\n @MainActor func bindTextAction(to keyPath: WritableKeyPath<Output, String>) -> UIAction {\n UIAction { action in\n guard let textField = action.sender as? UITextField else { return }\n\n self.value[keyPath: keyPath] = textField.text ?? ""\n }\n }\n\n /// Creates `UIAction` that automatically updates the value from input from a switch control.\n ///\n /// - Parameter keyPath: the key path to the field that should be updated.\n /// - Returns: an instance of `UIAction`.\n @MainActor func bindSwitchAction(to keyPath: WritableKeyPath<Output, Bool>) -> UIAction {\n UIAction { action in\n guard let toggle = action.sender as? UISwitch else { return }\n\n self.value[keyPath: keyPath] = toggle.isOn\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\CurrentValueSubject+UIActionBindings.swift
CurrentValueSubject+UIActionBindings.swift
Swift
1,204
0.95
0.027778
0.483871
node-utils
866
2025-04-18T12:22:27.777166
MIT
false
0b3abaa1607ed2cff10aca3a2f1430bb
//\n// Publisher+PreviousValue.swift\n// MullvadVPN\n//\n// Created by pronebird on 27/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport Foundation\n\nextension Publisher {\n /// A publisher producing a pair that contains the previous and new value.\n ///\n /// - Returns: A publisher emitting a tuple containing the previous and new value.\n func withPreviousValue() -> some Publisher<(Output?, Output), Failure> {\n return scan(nil) { ($0?.1, $1) }.compactMap { $0 }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Publisher+PreviousValue.swift
Publisher+PreviousValue.swift
Swift
532
0.95
0
0.588235
awesome-app
246
2024-11-27T03:31:46.575913
MIT
false
f096b83a40013a1679c1a36040eafbaa
//\n// AddAccessMethodCoordinator.swift\n// MullvadVPN\n//\n// Created by pronebird on 08/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport MullvadSettings\nimport Routing\nimport UIKit\n\nclass AddAccessMethodCoordinator: Coordinator, Presentable, Presenting {\n private let subject: CurrentValueSubject<AccessMethodViewModel, Never> = .init(AccessMethodViewModel())\n\n let navigationController: UINavigationController\n let accessMethodRepository: AccessMethodRepositoryProtocol\n let proxyConfigurationTester: ProxyConfigurationTesterProtocol\n\n var presentedViewController: UIViewController {\n navigationController\n }\n\n init(\n navigationController: UINavigationController,\n accessMethodRepo: AccessMethodRepositoryProtocol,\n proxyConfigurationTester: ProxyConfigurationTesterProtocol\n ) {\n self.navigationController = navigationController\n self.accessMethodRepository = accessMethodRepo\n self.proxyConfigurationTester = proxyConfigurationTester\n }\n\n func start() {\n let controller = MethodSettingsViewController(\n subject: subject,\n interactor: EditAccessMethodInteractor(\n subject: subject,\n repository: accessMethodRepository,\n proxyConfigurationTester: proxyConfigurationTester\n ),\n alertPresenter: AlertPresenter(context: self)\n )\n\n setUpControllerNavigationItem(controller)\n controller.delegate = self\n\n LocalNetworkProbe().triggerLocalNetworkPrivacyAlert()\n navigationController.pushViewController(controller, animated: false)\n }\n\n private func setUpControllerNavigationItem(_ controller: MethodSettingsViewController) {\n controller.navigationItem.prompt = NSLocalizedString(\n "METHOD_SETTINGS_NAVIGATION_ADD_PROMPT",\n tableName: "APIAccess",\n value: "The app will test the method before saving.",\n comment: ""\n )\n\n controller.navigationItem.title = NSLocalizedString(\n "METHOD_SETTINGS_NAVIGATION_ADD_TITLE",\n tableName: "APIAccess",\n value: "Add access method",\n comment: ""\n )\n\n controller.saveBarButton.title = NSLocalizedString(\n "METHOD_SETTINGS_NAVIGATION_ADD_BUTTON",\n tableName: "APIAccess",\n value: "Add",\n comment: ""\n )\n\n controller.navigationItem.leftBarButtonItem = UIBarButtonItem(\n systemItem: .cancel,\n primaryAction: UIAction(handler: { [weak self] _ in\n self?.dismiss(animated: true)\n })\n )\n }\n}\n\nextension AddAccessMethodCoordinator: @preconcurrency MethodSettingsViewControllerDelegate {\n func accessMethodDidSave(_ accessMethod: PersistentAccessMethod) {\n dismiss(animated: true)\n }\n\n func controllerShouldShowProtocolPicker(_ controller: MethodSettingsViewController) {\n let picker = AccessMethodProtocolPicker(navigationController: navigationController)\n\n picker.present(currentValue: subject.value.method) { [weak self] newMethod in\n self?.subject.value.method = newMethod\n }\n }\n\n func controllerShouldShowShadowsocksCipherPicker(_ controller: MethodSettingsViewController) {\n let picker = ShadowsocksCipherPicker(navigationController: navigationController)\n\n picker.present(currentValue: subject.value.shadowsocks.cipher) { [weak self] selectedCipher in\n self?.subject.value.shadowsocks.cipher = selectedCipher\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Add\AddAccessMethodCoordinator.swift
AddAccessMethodCoordinator.swift
Swift
3,633
0.95
0.009615
0.08046
python-kit
251
2023-12-16T15:15:29.121752
BSD-3-Clause
false
9b642f8045121df854a0457819d91365
//\n// BasicCell.swift\n// MullvadVPN\n//\n// Created by pronebird on 09/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\n/// Basic cell that supports dynamic background configuration and custom cell disclosure.\nclass BasicCell: UITableViewCell, DynamicBackgroundConfiguration, CustomCellDisclosureHandling {\n private lazy var disclosureImageView = UIImageView(image: nil)\n\n var backgroundConfigurationResolver: BackgroundConfigurationResolver? {\n didSet {\n backgroundConfiguration = backgroundConfigurationResolver?(configurationState)\n }\n }\n\n override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {\n super.init(style: style, reuseIdentifier: reuseIdentifier)\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n override func updateConfiguration(using state: UICellConfigurationState) {\n if let backgroundConfiguration = backgroundConfigurationResolver?(state) {\n self.backgroundConfiguration = backgroundConfiguration\n } else {\n super.updateConfiguration(using: state)\n }\n }\n\n var disclosureType: SettingsDisclosureType = .none {\n didSet {\n accessoryType = .none\n\n guard let image = disclosureType.image?.withTintColor(\n UIColor.Cell.disclosureIndicatorColor,\n renderingMode: .alwaysOriginal\n ) else {\n accessoryView = nil\n return\n }\n\n disclosureImageView.image = image\n disclosureImageView.sizeToFit()\n accessoryView = disclosureImageView\n }\n }\n\n override func prepareForReuse() {\n super.prepareForReuse()\n\n disclosureType = .none\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Cells\BasicCell.swift
BasicCell.swift
Swift
1,825
0.95
0.033333
0.163265
vue-tools
137
2025-05-01T07:35:46.204603
GPL-3.0
false
ef96a7620bad73f14a36005858713458
//\n// ButtonCellConfiguration.swift\n// MullvadVPN\n//\n// Created by pronebird on 17/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\n/// The content configuration for cells that contain the full-width button.\nstruct ButtonCellContentConfiguration: UIContentConfiguration, Equatable {\n /// Button label.\n var text: String?\n\n /// Button style.\n var style: AppButton.Style = .default\n\n /// Indicates whether button is enabled.\n var isEnabled = true\n\n /// Primary action for button.\n var primaryAction: UIAction?\n\n /// The button content edge insets.\n var directionalContentEdgeInsets: NSDirectionalEdgeInsets = UIMetrics.SettingsCell.insetLayoutMargins\n\n // Accessibility identifier.\n var accessibilityIdentifier: AccessibilityIdentifier?\n\n func makeContentView() -> UIView & UIContentView {\n return ButtonCellContentView(configuration: self)\n }\n\n func updated(for state: UIConfigurationState) -> Self {\n return self\n }\n}\n\nextension ButtonCellContentConfiguration {\n struct TextProperties: Equatable {\n var font = UIFont.systemFont(ofSize: 17)\n var color = UIColor.Cell.titleTextColor\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Cells\ButtonCellContentConfiguration.swift
ButtonCellContentConfiguration.swift
Swift
1,208
0.95
0.066667
0.4
node-utils
142
2023-11-25T05:32:18.906280
GPL-3.0
false
abd79164e5a733eaa848d07bd474868d
//\n// ButtonCellContentView.swift\n// MullvadVPN\n//\n// Created by pronebird on 17/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\n/// Content view presenting a full-width button.\nclass ButtonCellContentView: UIView, UIContentView {\n private let button = AppButton()\n\n /// Default cell corner radius in inset grouped table view\n private let tableViewCellCornerRadius: CGFloat = 10\n\n var configuration: UIContentConfiguration {\n get {\n actualConfiguration\n }\n set {\n guard let newConfiguration = newValue as? ButtonCellContentConfiguration,\n actualConfiguration != newConfiguration else { return }\n\n let previousConfiguration = actualConfiguration\n actualConfiguration = newConfiguration\n\n configureSubviews(previousConfiguration: previousConfiguration)\n }\n }\n\n private var actualConfiguration: ButtonCellContentConfiguration\n\n func supports(_ configuration: UIContentConfiguration) -> Bool {\n configuration is ButtonCellContentConfiguration\n }\n\n init(configuration: ButtonCellContentConfiguration) {\n actualConfiguration = configuration\n\n super.init(frame: CGRect(x: 0, y: 0, width: 100, height: 44))\n\n configureSubviews()\n addSubviews()\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n func configureSubviews(previousConfiguration: ButtonCellContentConfiguration? = nil) {\n guard actualConfiguration != previousConfiguration else { return }\n\n configureButton()\n configureActions(previousConfiguration: previousConfiguration)\n }\n\n private func configureActions(previousConfiguration: ButtonCellContentConfiguration? = nil) {\n previousConfiguration?.primaryAction.map { button.removeAction($0, for: .touchUpInside) }\n actualConfiguration.primaryAction.map { button.addAction($0, for: .touchUpInside) }\n }\n\n private func configureButton() {\n button.setTitle(actualConfiguration.text, for: .normal)\n button.titleLabel?.font = .systemFont(ofSize: 17)\n button.isEnabled = actualConfiguration.isEnabled\n button.style = actualConfiguration.style\n button.configuration?.contentInsets = actualConfiguration.directionalContentEdgeInsets\n button.setAccessibilityIdentifier(actualConfiguration.accessibilityIdentifier)\n }\n\n private func addSubviews() {\n addConstrainedSubviews([button]) {\n button.pinEdgesToSuperview()\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Cells\ButtonCellContentView.swift
ButtonCellContentView.swift
Swift
2,605
0.95
0.051282
0.147541
vue-tools
184
2024-10-06T09:48:35.393778
GPL-3.0
false
95688af2d62d6aacefc05c36b6d9a066
//\n// CustomCellDisclosureHandling.swift\n// MullvadVPN\n//\n// Created by pronebird on 09/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\n/// Types handling custom disclosure accessory in table view cells.\nprotocol CustomCellDisclosureHandling: UITableViewCell {\n /// Custom disclosure type.\n ///\n /// Cannot be used together with `accessoryType` property. Automatically resets `accessoryType` upon assignment.\n var disclosureType: SettingsDisclosureType { get set }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Cells\CustomCellDisclosureHandling.swift
CustomCellDisclosureHandling.swift
Swift
520
0.95
0
0.733333
react-lib
608
2024-05-10T19:24:02.649146
BSD-3-Clause
false
c580989f5b0fe91d3b26b50fc831c400
//\n// DynamicBackgroundConfiguration.swift\n// MullvadVPN\n//\n// Created by pronebird on 09/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\n/// Types providing dynamic background configuration based on cell configuration state.\nprotocol DynamicBackgroundConfiguration: UITableViewCell {\n typealias BackgroundConfigurationResolver = (UICellConfigurationState) -> UIBackgroundConfiguration\n\n /// Background configuration resolver closure.\n /// The closure is called immediately upon assignment, the returned configuration is assigned to `backgroundConfiguration`.\n /// All subsequent calls happen on `updateConfiguration(using:)`.\n var backgroundConfigurationResolver: BackgroundConfigurationResolver? { get set }\n}\n\nextension DynamicBackgroundConfiguration {\n /// Automatically maintains transparent background configuration in any cell state.\n func setAutoAdaptingClearBackgroundConfiguration() {\n backgroundConfigurationResolver = { _ in .clear() }\n }\n\n /// Automatically adjust background configuration for the cell state based on provided template and type of visual cell selection preference.\n ///\n /// - Parameters:\n /// - backgroundConfiguration: a background configuration template.\n /// - selectionType: a cell selection to apply.\n func setAutoAdaptingBackgroundConfiguration(\n _ backgroundConfiguration: UIBackgroundConfiguration,\n selectionType: UIBackgroundConfiguration.CellSelectionType\n ) {\n backgroundConfigurationResolver = { state in\n backgroundConfiguration.adapted(for: state, selectionType: selectionType)\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Cells\DynamicBackgroundConfiguration.swift
DynamicBackgroundConfiguration.swift
Swift
1,671
0.95
0.05
0.485714
python-kit
757
2025-01-25T01:03:06.205946
GPL-3.0
false
81bb3377ee1d926d9aa55d5d3b7faa30
//\n// ListCellContentConfiguration.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-01-25.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\n/// Content configuration presenting a label and switch control.\nstruct ListCellContentConfiguration: UIContentConfiguration, Equatable {\n struct TextProperties: Equatable {\n var font = UIFont.systemFont(ofSize: 17)\n var color = UIColor.Cell.titleTextColor\n }\n\n struct SecondaryTextProperties: Equatable {\n var font = UIFont.systemFont(ofSize: 17)\n var color = UIColor.Cell.detailTextColor.withAlphaComponent(0.8)\n }\n\n struct TertiaryTextProperties: Equatable {\n var font = UIFont.systemFont(ofSize: 15)\n var color = UIColor.Cell.titleTextColor.withAlphaComponent(0.6)\n }\n\n /// Primary text label.\n var text: String?\n let textProperties = TextProperties()\n\n /// Secondary (trailing) text label.\n var secondaryText: String?\n let secondaryTextProperties = SecondaryTextProperties()\n\n /// Tertiary (below primary) text label.\n var tertiaryText: String?\n let tertiaryTextProperties = TertiaryTextProperties()\n\n /// Content view layout margins.\n var directionalLayoutMargins = NSDirectionalEdgeInsets(\n top: 8,\n leading: 24,\n bottom: 8,\n trailing: 24\n )\n\n func makeContentView() -> UIView & UIContentView {\n return ListCellContentView(configuration: self)\n }\n\n func updated(for state: UIConfigurationState) -> Self {\n return self\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Cells\ListCellContentConfiguration.swift
ListCellContentConfiguration.swift
Swift
1,561
0.95
0.036364
0.266667
awesome-app
896
2023-11-17T09:30:20.352477
MIT
false
8c2cf79bf8ad4701ee05a9ff43fce9ad
//\n// ListCellContentView.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-01-25.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\n/// Content view presenting a primary, secondary (trailing) and tertiary (below primary) label.\nclass ListCellContentView: UIView, UIContentView, UITextFieldDelegate {\n private var textLabel = UILabel()\n private var secondaryTextLabel = UILabel()\n private var tertiaryTextLabel = UILabel()\n\n var configuration: UIContentConfiguration {\n get {\n actualConfiguration\n }\n set {\n guard let newConfiguration = newValue as? ListCellContentConfiguration,\n actualConfiguration != newConfiguration else { return }\n\n let previousConfiguration = actualConfiguration\n actualConfiguration = newConfiguration\n\n configureSubviews(previousConfiguration: previousConfiguration)\n }\n }\n\n private var actualConfiguration: ListCellContentConfiguration\n\n func supports(_ configuration: UIContentConfiguration) -> Bool {\n configuration is ListCellContentConfiguration\n }\n\n init(configuration: ListCellContentConfiguration) {\n actualConfiguration = configuration\n\n super.init(frame: CGRect(x: 0, y: 0, width: 100, height: 0))\n\n configureSubviews()\n addSubviews()\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n func configureSubviews(previousConfiguration: ListCellContentConfiguration? = nil) {\n configureTextLabel()\n configureSecondaryTextLabel()\n configureTertiaryTextLabel()\n configureLayoutMargins()\n }\n\n private func configureTextLabel() {\n let textProperties = actualConfiguration.textProperties\n\n textLabel.font = textProperties.font\n textLabel.textColor = textProperties.color\n\n textLabel.text = actualConfiguration.text\n }\n\n private func configureSecondaryTextLabel() {\n let textProperties = actualConfiguration.secondaryTextProperties\n\n secondaryTextLabel.font = textProperties.font\n secondaryTextLabel.textColor = textProperties.color\n\n secondaryTextLabel.text = actualConfiguration.secondaryText\n }\n\n private func configureTertiaryTextLabel() {\n let textProperties = actualConfiguration.tertiaryTextProperties\n\n tertiaryTextLabel.font = textProperties.font\n tertiaryTextLabel.textColor = textProperties.color\n\n tertiaryTextLabel.text = actualConfiguration.tertiaryText\n }\n\n private func configureLayoutMargins() {\n directionalLayoutMargins = actualConfiguration.directionalLayoutMargins\n }\n\n private func addSubviews() {\n let leadingTextContainer = UIStackView(arrangedSubviews: [textLabel, tertiaryTextLabel])\n leadingTextContainer.axis = .vertical\n\n addConstrainedSubviews([leadingTextContainer, secondaryTextLabel]) {\n leadingTextContainer.pinEdgesToSuperviewMargins(.all().excluding(.trailing))\n leadingTextContainer.centerYAnchor.constraint(equalTo: centerYAnchor)\n secondaryTextLabel.pinEdgesToSuperviewMargins(.all().excluding(.leading))\n secondaryTextLabel.leadingAnchor.constraint(\n greaterThanOrEqualToSystemSpacingAfter: leadingTextContainer.trailingAnchor,\n multiplier: 1\n )\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Cells\ListCellContentView.swift
ListCellContentView.swift
Swift
3,449
0.95
0.009709
0.101266
awesome-app
690
2024-08-30T00:45:59.945229
Apache-2.0
false
5c6909cebcc6fc06e428d1e77039a6fa
//\n// SwitchCellContentConfiguration.swift\n// MullvadVPN\n//\n// Created by pronebird on 09/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\n/// Content configuration presenting a label and switch control.\nstruct SwitchCellContentConfiguration: UIContentConfiguration, Equatable {\n struct TextProperties: Equatable {\n var font = UIFont.systemFont(ofSize: 17)\n var color = UIColor.Cell.titleTextColor\n }\n\n var accessibilityIdentifier: AccessibilityIdentifier?\n\n /// Text label.\n var text: String?\n\n /// Whether the toggle is on or off.\n var isOn = false\n\n /// The action dispacthed on toggle change.\n var onChange: UIAction?\n\n /// Text label properties.\n var textProperties = TextProperties()\n\n /// Content view layout margins.\n var directionalLayoutMargins: NSDirectionalEdgeInsets = UIMetrics.SettingsCell.apiAccessInsetLayoutMargins\n\n func makeContentView() -> UIView & UIContentView {\n return SwitchCellContentView(configuration: self)\n }\n\n func updated(for state: UIConfigurationState) -> Self {\n return self\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Cells\SwitchCellContentConfiguration.swift
SwitchCellContentConfiguration.swift
Swift
1,135
0.95
0.047619
0.40625
awesome-app
42
2024-06-10T12:55:32.563918
Apache-2.0
false
de6437211d21784e2e7428798bd081bf
//\n// SwitchCellContentView.swift\n// MullvadVPN\n//\n// Created by pronebird on 09/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\n/// Content view presenting a label and switch control.\nclass SwitchCellContentView: UIView, UIContentView, UITextFieldDelegate {\n private var textLabel = UILabel()\n private let switchContainer = CustomSwitchContainer()\n\n var configuration: UIContentConfiguration {\n get {\n actualConfiguration\n }\n set {\n guard let newConfiguration = newValue as? SwitchCellContentConfiguration,\n actualConfiguration != newConfiguration else { return }\n\n let previousConfiguration = actualConfiguration\n actualConfiguration = newConfiguration\n\n configureSubviews(previousConfiguration: previousConfiguration)\n }\n }\n\n private var actualConfiguration: SwitchCellContentConfiguration\n\n func supports(_ configuration: UIContentConfiguration) -> Bool {\n configuration is SwitchCellContentConfiguration\n }\n\n init(configuration: SwitchCellContentConfiguration) {\n actualConfiguration = configuration\n\n super.init(frame: CGRect(x: 0, y: 0, width: 100, height: 0))\n\n configureSubviews()\n addSubviews()\n configureAccessibility()\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n func configureSubviews(previousConfiguration: SwitchCellContentConfiguration? = nil) {\n configureTextLabel()\n configureSwitch()\n configureLayoutMargins()\n configureActions(previousConfiguration: previousConfiguration)\n }\n\n private func configureActions(previousConfiguration: SwitchCellContentConfiguration? = nil) {\n previousConfiguration?.onChange.map { switchContainer.control.removeAction($0, for: .valueChanged) }\n actualConfiguration.onChange.map { switchContainer.control.addAction($0, for: .valueChanged) }\n }\n\n private func configureLayoutMargins() {\n directionalLayoutMargins = actualConfiguration.directionalLayoutMargins\n }\n\n private func configureTextLabel() {\n let textProperties = actualConfiguration.textProperties\n\n textLabel.font = textProperties.font\n textLabel.textColor = textProperties.color\n\n textLabel.text = actualConfiguration.text\n }\n\n private func configureSwitch() {\n switchContainer.control.isOn = actualConfiguration.isOn\n switchContainer.transform = CGAffineTransform(scaleX: 0.85, y: 0.85)\n switchContainer.setAccessibilityIdentifier(actualConfiguration.accessibilityIdentifier)\n }\n\n private func addSubviews() {\n addConstrainedSubviews([textLabel, switchContainer]) {\n textLabel.pinEdgesToSuperviewMargins(.all().excluding(.trailing))\n switchContainer.centerYAnchor.constraint(equalTo: centerYAnchor)\n switchContainer.pinEdgeToSuperview(.trailing(UIMetrics.SettingsCell.apiAccessSwitchCellTrailingMargin))\n switchContainer.leadingAnchor.constraint(\n greaterThanOrEqualToSystemSpacingAfter: textLabel.trailingAnchor,\n multiplier: 1\n )\n }\n }\n\n private func configureAccessibility() {\n isAccessibilityElement = true\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 actualConfiguration.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 switchContainer.control.setOn(newValue, animated: true)\n switchContainer.control.sendActions(for: .valueChanged)\n\n return true\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Cells\SwitchCellContentView.swift
SwitchCellContentView.swift
Swift
4,863
0.95
0.032051
0.079365
vue-tools
10
2024-01-24T14:35:20.883653
Apache-2.0
false
567d1b44134f4de90fcb76b897babfce
//\n// TextCellContentConfiguration+Extensions.swift\n// MullvadVPN\n//\n// Created by pronebird on 14/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nextension TextCellContentConfiguration.TextFieldProperties {\n /// Returns text field properties configured with automatic resign on return key and "done" return key.\n static func withAutoResignAndDoneReturnKey() -> Self {\n .init(resignOnReturn: true, returnKey: .done)\n }\n\n /// Returns text field properties configured with automatic resign on return key and "done" return key and all auto-correction and smart features disabled.\n static func withSmartFeaturesDisabled() -> Self {\n withAutoResignAndDoneReturnKey().disabling(features: .all)\n }\n}\n\nextension TextCellContentConfiguration {\n /// Type of placeholder to set on the text field.\n enum PlaceholderType {\n case required, optional\n\n var localizedDescription: String {\n switch self {\n case .required:\n NSLocalizedString(\n "REQUIRED_PLACEHOLDER",\n tableName: "APIAccess",\n value: "Required",\n comment: ""\n )\n case .optional:\n NSLocalizedString(\n "OPTIONAL_PLACEHOLDER",\n tableName: "APIAccess",\n value: "Optional",\n comment: ""\n )\n }\n }\n }\n\n /// Set localized text placeholder using on the given placeholder type.\n /// - Parameter type: a placeholder type.\n mutating func setPlaceholder(type: PlaceholderType) {\n placeholder = type.localizedDescription\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Cells\TextCellContentConfiguration+Extensions.swift
TextCellContentConfiguration+Extensions.swift
Swift
1,743
0.95
0.018868
0.255319
react-lib
664
2024-08-02T09:26:47.058778
Apache-2.0
false
5f08a721f929b03818927ae85171700e
//\n// TextCellContentConfiguration.swift\n// MullvadVPN\n//\n// Created by pronebird on 09/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\n/// Content configuration presenting a label and text field.\nstruct TextCellContentConfiguration: UIContentConfiguration, Equatable {\n /// The text label.\n var text: String?\n\n /// The input field text.\n var inputText: String?\n\n /// The text input filter that can be used to prevent user from entering illegal characters.\n var inputFilter: TextInputFilter = .allowAll\n\n /// The maximum input length.\n var maxLength: Int?\n\n /// The text field placeholder.\n var placeholder: String?\n\n /// The editing events configuration.\n var editingEvents = EditingEvents()\n\n /// The text properties configuration.\n var textProperties = TextProperties()\n\n /// The text field properties configuration.\n var textFieldProperties = TextFieldProperties()\n\n /// The content view layout margins.\n var directionalLayoutMargins: NSDirectionalEdgeInsets = UIMetrics.SettingsCell.apiAccessInsetLayoutMargins\n\n func makeContentView() -> UIView & UIContentView {\n return TextCellContentView(configuration: self)\n }\n\n func updated(for state: UIConfigurationState) -> Self {\n return self\n }\n}\n\nextension TextCellContentConfiguration {\n /// The text label properties.\n struct TextProperties: Equatable {\n var font = UIFont.systemFont(ofSize: 17)\n var color = UIColor.Cell.titleTextColor\n }\n\n /// The text input filter.\n enum TextInputFilter: Equatable {\n /// Allow all input.\n case allowAll\n\n /// Allow digits only.\n case digitsOnly\n }\n\n /// Editing events configuration assigned on the text field.\n struct EditingEvents: Equatable {\n /// The action invoked on text field input change.\n var onChange: UIAction?\n /// The action invoked when text field begins editing.\n var onBegin: UIAction?\n /// The action invoked when text field ends editing.\n var onEnd: UIAction?\n /// The action invoked on the touch ending the editing session. (i.e. the return key)\n var onEndOnExit: UIAction?\n }\n\n /// Text field configuration.\n struct TextFieldProperties: Equatable {\n /// Text font.\n var font = UIFont.systemFont(ofSize: 17)\n /// Text color.\n var textColor = UIColor.Cell.textFieldTextColor\n\n /// Placeholder color.\n var placeholderColor = UIColor.Cell.textFieldPlaceholderColor\n\n /// Automatically resign keyboard on return key.\n var resignOnReturn = false\n\n /// Text content type.\n var textContentType: UITextContentType?\n\n /// Keyboard type.\n var keyboardType: UIKeyboardType = .default\n\n /// Return key type.\n var returnKey: UIReturnKeyType = .default\n\n /// Indicates whether the text input should be obscured.\n /// Set to `true` for password entry.\n var isSecureTextEntry = false\n\n /// Autocorrection type.\n var autocorrectionType: UITextAutocorrectionType = .default\n\n /// Autocapitalization type.\n var autocapitalizationType: UITextAutocapitalizationType = .sentences\n\n /// Spellchecking type.\n var spellCheckingType: UITextSpellCheckingType = .default\n\n var smartInsertDeleteType: UITextSmartInsertDeleteType = .default\n var smartDashesType: UITextSmartDashesType = .default\n var smartQuotesType: UITextSmartQuotesType = .default\n\n /// An option set describing a set of text field features to enable or disable in bulk.\n struct Features: OptionSet {\n /// Autocorrection.\n static let autoCorrect = Features(rawValue: 1 << 1)\n /// Spellcheck.\n static let spellCheck = Features(rawValue: 1 << 2)\n /// Autocapitalization.\n static let autoCapitalization = Features(rawValue: 1 << 3)\n /// Smart features such as automatic hyphenation or insertion of a space at the end of word etc.\n static let smart = Features(rawValue: 1 << 4)\n /// All of the above.\n static let all = Features([.autoCorrect, .spellCheck, .autoCapitalization, .smart])\n\n let rawValue: Int\n }\n\n /// Produce text field configuration with the given text field features disabled.\n /// - Parameter features: the text field features to disable.\n /// - Returns: new text field configuration.\n func disabling(features: Features) -> TextFieldProperties {\n var mutableProperties = self\n mutableProperties.disable(features: features)\n return mutableProperties\n }\n\n /// Disable a set of text field features mutating the current configuration in-place.\n /// - Parameter features: the text field features to disable.\n mutating func disable(features: Features) {\n if features.contains(.autoCorrect) {\n autocorrectionType = .no\n }\n if features.contains(.spellCheck) {\n spellCheckingType = .no\n }\n if features.contains(.autoCapitalization) {\n autocapitalizationType = .none\n }\n if features.contains(.smart) {\n smartInsertDeleteType = .no\n smartDashesType = .no\n smartQuotesType = .no\n }\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Cells\TextCellContentConfiguration.swift
TextCellContentConfiguration.swift
Swift
5,495
0.95
0.0375
0.387597
react-lib
782
2023-08-10T15:19:09.490617
GPL-3.0
false
e6888965105a57714a1e2b2f2d8aa00e
//\n// TextCellContentView.swift\n// MullvadVPN\n//\n// Created by pronebird on 09/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\n/// Content view presenting a label and text field.\nclass TextCellContentView: UIView, UIContentView, UIGestureRecognizerDelegate, Sendable {\n private var textLabel = UILabel()\n private var textField = CustomTextField()\n\n var configuration: UIContentConfiguration {\n get {\n actualConfiguration\n }\n set {\n guard let newConfiguration = newValue as? TextCellContentConfiguration,\n actualConfiguration != newConfiguration else { return }\n\n let previousConfiguration = actualConfiguration\n actualConfiguration = newConfiguration\n\n configureSubviews(previousConfiguration: previousConfiguration)\n }\n }\n\n private var actualConfiguration: TextCellContentConfiguration\n\n func supports(_ configuration: UIContentConfiguration) -> Bool {\n configuration is TextCellContentConfiguration\n }\n\n init(configuration: TextCellContentConfiguration) {\n actualConfiguration = configuration\n\n super.init(frame: CGRect(x: 0, y: 0, width: 100, height: 44))\n\n configureSubviews()\n addSubviews()\n addTapGestureRecognizer()\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n private func configureSubviews(previousConfiguration: TextCellContentConfiguration? = nil) {\n guard actualConfiguration != previousConfiguration else { return }\n\n configureTextLabel()\n configureTextField()\n configureLayoutMargins()\n configureActions(previousConfiguration: previousConfiguration)\n }\n\n private func configureActions(previousConfiguration: TextCellContentConfiguration? = nil) {\n previousConfiguration?.editingEvents.unregister(from: textField)\n actualConfiguration.editingEvents.register(in: textField)\n }\n\n private func configureLayoutMargins() {\n directionalLayoutMargins = actualConfiguration.directionalLayoutMargins\n }\n\n private func configureTextLabel() {\n let textProperties = actualConfiguration.textProperties\n\n textLabel.font = textProperties.font\n textLabel.textColor = textProperties.color\n\n textLabel.text = actualConfiguration.text\n }\n\n private func configureTextField() {\n textField.text = actualConfiguration.inputText\n textField.placeholder = actualConfiguration.placeholder\n textField.delegate = self\n\n actualConfiguration.textFieldProperties.apply(to: textField)\n }\n\n private func addSubviews() {\n textField.setContentHuggingPriority(.defaultLow, for: .horizontal)\n textField.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)\n\n textLabel.setContentHuggingPriority(.defaultHigh, for: .horizontal)\n textLabel.setContentCompressionResistancePriority(.defaultHigh + 1, for: .horizontal)\n\n addConstrainedSubviews([textLabel, textField]) {\n textField.pinEdgesToSuperviewMargins(.all().excluding(.leading))\n textLabel.pinEdgesToSuperviewMargins(.all().excluding(.trailing))\n textField.leadingAnchor.constraint(equalToSystemSpacingAfter: textLabel.trailingAnchor, multiplier: 1)\n }\n }\n\n // MARK: - Gesture recognition\n\n /// Add tap recognizer that activates the text field on tap anywhere within the content view.\n private func addTapGestureRecognizer() {\n let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))\n tapGestureRecognizer.delegate = self\n addGestureRecognizer(tapGestureRecognizer)\n }\n\n @objc private func handleTap(_ gestureRecognizer: UIGestureRecognizer) {\n if gestureRecognizer.state == .ended {\n textField.selectedTextRange = textField.textRange(\n from: textField.endOfDocument,\n to: textField.endOfDocument\n )\n textField.becomeFirstResponder()\n }\n }\n\n override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {\n // Allow our tap recognizer to evaluate only when the text field is not the first responder yet.\n super.gestureRecognizerShouldBegin(gestureRecognizer) && !textField.isFirstResponder\n }\n\n func gestureRecognizer(\n _ gestureRecognizer: UIGestureRecognizer,\n shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer\n ) -> Bool {\n // Since the text field is right-aligned, a tap in the middle of it puts the caret at the front rather than at\n // the end.\n // In order to circumvent that, the tap recognizer used by the text field should be forced to fail once\n // before the text field becomes the first responder.\n // However long tap and other recognizers are unaffected, which makes it possible to tap and hold to grab\n // the cursor.\n otherGestureRecognizer.view == textField && otherGestureRecognizer.isKind(of: UITapGestureRecognizer.self)\n }\n\n func gestureRecognizer(\n _ gestureRecognizer: UIGestureRecognizer,\n shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer\n ) -> Bool {\n // Simultaneous recogition is a prerequisite for enabling failure requirements.\n true\n }\n}\n\nextension TextCellContentView: UITextFieldDelegate {\n func textFieldShouldReturn(_ textField: UITextField) -> Bool {\n if actualConfiguration.textFieldProperties.resignOnReturn {\n textField.resignFirstResponder()\n }\n return true\n }\n\n func textField(\n _ textField: UITextField,\n shouldChangeCharactersIn range: NSRange,\n replacementString string: String\n ) -> Bool {\n guard\n let currentString = textField.text,\n let stringRange = Range(range, in: currentString) else { return false }\n let updatedText = currentString.replacingCharacters(in: stringRange, with: string)\n\n if let maxLength = actualConfiguration.maxLength, maxLength < updatedText.count {\n return false\n }\n\n switch actualConfiguration.inputFilter {\n case .allowAll:\n return true\n case .digitsOnly:\n return string.allSatisfy { $0.isASCII && $0.isNumber }\n }\n }\n}\n\nextension TextCellContentConfiguration.TextFieldProperties {\n @MainActor\n func apply(to textField: CustomTextField) {\n textField.font = font\n textField.backgroundColor = .clear\n textField.textColor = textColor\n textField.placeholderTextColor = placeholderColor\n textField.textAlignment = .right\n textField.textMargins = .zero\n textField.cornerRadius = 0\n textField.textContentType = textContentType\n textField.keyboardType = keyboardType\n textField.returnKeyType = returnKey\n textField.isSecureTextEntry = isSecureTextEntry\n textField.autocorrectionType = autocorrectionType\n textField.smartInsertDeleteType = smartInsertDeleteType\n textField.smartDashesType = smartDashesType\n textField.smartQuotesType = smartQuotesType\n textField.spellCheckingType = spellCheckingType\n textField.autocapitalizationType = autocapitalizationType\n }\n}\n\nextension TextCellContentConfiguration.EditingEvents {\n @MainActor\n func register(in textField: UITextField) {\n onChange.map { textField.addAction($0, for: .editingChanged) }\n onBegin.map { textField.addAction($0, for: .editingDidBegin) }\n onEnd.map { textField.addAction($0, for: .editingDidEnd) }\n onEndOnExit.map { textField.addAction($0, for: .editingDidEndOnExit) }\n }\n\n @MainActor\n func unregister(from textField: UITextField) {\n onChange.map { textField.removeAction($0, for: .editingChanged) }\n onBegin.map { textField.removeAction($0, for: .editingDidBegin) }\n onEnd.map { textField.removeAction($0, for: .editingDidEnd) }\n onEndOnExit.map { textField.removeAction($0, for: .editingDidEndOnExit) }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Cells\TextCellContentView.swift
TextCellContentView.swift
Swift
8,229
0.95
0.083333
0.1
awesome-app
680
2024-05-29T08:52:24.111711
MIT
false
250d1185720b3b0a2ea13eb82939088b
//\n// AccessMethodCellReuseIdentifier.swift\n// MullvadVPN\n//\n// Created by pronebird on 14/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\n/// Cell reuse identifier used by table view controllers implementing various parts of API access management.\nenum AccessMethodCellReuseIdentifier: String, CaseIterable, CellIdentifierProtocol {\n /// Cells with static text and disclosure view.\n case textWithDisclosure\n\n /// Cells with a label and text field.\n case textInput\n\n /// Cells with a label and switch control.\n case toggle\n\n /// Cells that contain a button.\n case button\n\n /// Cells that contain a number of validation errors.\n case validationError\n\n /// Cells that contain the status of API method testing.\n case testingStatus\n\n var cellClass: AnyClass {\n BasicCell.self\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Common\AccessMethodCellReuseIdentifier.swift
AccessMethodCellReuseIdentifier.swift
Swift
872
0.95
0.029412
0.538462
node-utils
7
2024-10-27T19:30:03.596656
GPL-3.0
false
33441afbe78ee14ad00e9656f6882a06
//\n// AccessMethodHeaderFooterReuseIdentifier.swift\n// MullvadVPN\n//\n// Created by pronebird on 14/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\n/// Header footer view reuse identifier used in view controllers implementing access method management.\nenum AccessMethodHeaderFooterReuseIdentifier: String, CaseIterable, HeaderFooterIdentifierProtocol {\n case primary\n\n var headerFooterClass: AnyClass {\n switch self {\n case .primary: UITableViewHeaderFooterView.self\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Common\AccessMethodHeaderFooterReuseIdentifier.swift
AccessMethodHeaderFooterReuseIdentifier.swift
Swift
545
0.95
0.05
0.470588
react-lib
841
2024-08-13T08:08:55.447205
BSD-3-Clause
false
38fe04c7befdf3186501591af10fb43d
//\n// AccessMethodViewModelEditing.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-01-23.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\n\nprotocol AccessMethodEditing: AnyObject {\n func accessMethodDidSave(_ accessMethod: PersistentAccessMethod)\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Common\AccessMethodViewModelEditing.swift
AccessMethodViewModelEditing.swift
Swift
304
0.95
0
0.636364
awesome-app
320
2024-05-29T11:16:42.417149
BSD-3-Clause
false
6de04fdd70106d0d951b1cb4a1be269f
//\n// ProxyProtocolConfigurationItemIdentifier.swift\n// MullvadVPN\n//\n// Created by pronebird on 14/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\n/// Item identifier used by diffable data sources implementing proxy configuration.\nenum ProxyProtocolConfigurationItemIdentifier: Hashable {\n case socks(SocksItemIdentifier)\n case shadowsocks(ShadowsocksItemIdentifier)\n\n /// Cell identifier for the item identifier.\n var cellIdentifier: AccessMethodCellReuseIdentifier {\n switch self {\n case let .shadowsocks(itemIdentifier):\n itemIdentifier.cellIdentifier\n case let .socks(itemIdentifier):\n itemIdentifier.cellIdentifier\n }\n }\n\n /// Indicates whether cell representing the item should be selectable.\n var isSelectable: Bool {\n switch self {\n case let .shadowsocks(itemIdentifier):\n itemIdentifier.isSelectable\n case let .socks(itemIdentifier):\n itemIdentifier.isSelectable\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Common\ProxyProtocolConfigurationItemIdentifier.swift
ProxyProtocolConfigurationItemIdentifier.swift
Swift
1,051
0.95
0.085714
0.322581
node-utils
935
2025-05-17T10:55:24.403064
GPL-3.0
false
88766e0463cef6b1a503695426c99374
//\n// ShadowsocksItemIdentifier.swift\n// MullvadVPN\n//\n// Created by pronebird on 14/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\n/// Item identifier used by diffable data sources implementing shadowsocks configuration.\nenum ShadowsocksItemIdentifier: Hashable, CaseIterable {\n case server\n case port\n case password\n case cipher\n\n /// Cell identifier for the item identifier.\n var cellIdentifier: AccessMethodCellReuseIdentifier {\n switch self {\n case .server, .port, .password:\n .textInput\n case .cipher:\n .textWithDisclosure\n }\n }\n\n /// Indicates whether cell representing the item should be selectable.\n var isSelectable: Bool {\n self == .cipher\n }\n\n /// The text describing the item identifier and suitable to be used as a field label.\n var text: String {\n switch self {\n case .server:\n NSLocalizedString("SHADOWSOCKS_SERVER", tableName: "APIAccess", value: "Server", comment: "")\n case .port:\n NSLocalizedString("SHADOWSOCKS_PORT", tableName: "APIAccess", value: "Port", comment: "")\n case .password:\n NSLocalizedString("SHADOWSOCKS_PASSWORD", tableName: "APIAccess", value: "Password", comment: "")\n case .cipher:\n NSLocalizedString("SHADOWSOCKS_CIPHER", tableName: "APIAccess", value: "Cipher", comment: "")\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Common\ShadowsocksItemIdentifier.swift
ShadowsocksItemIdentifier.swift
Swift
1,454
0.95
0.065217
0.268293
react-lib
149
2025-03-02T10:49:32.805886
MIT
false
886453240faf3464cb5911f1d3c7229c
//\n// ShadowsocksSectionHandler.swift\n// MullvadVPN\n//\n// Created by pronebird on 14/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport UIKit\n\n/// Type responsible for handling cells in shadowsocks table view section.\n@MainActor\nstruct ShadowsocksSectionHandler {\n private let authenticationInputMaxLength = 2048\n\n let tableStyle: UITableView.Style\n let subject: CurrentValueSubject<AccessMethodViewModel, Never>\n\n func configure(_ cell: UITableViewCell, itemIdentifier: ShadowsocksItemIdentifier) {\n switch itemIdentifier {\n case .server:\n configureServer(cell, itemIdentifier: itemIdentifier)\n case .port:\n configurePort(cell, itemIdentifier: itemIdentifier)\n case .password:\n configurePassword(cell, itemIdentifier: itemIdentifier)\n case .cipher:\n configureCipher(cell, itemIdentifier: itemIdentifier)\n }\n }\n\n func configureServer(_ cell: UITableViewCell, itemIdentifier: ShadowsocksItemIdentifier) {\n var contentConfiguration = TextCellContentConfiguration()\n contentConfiguration.text = itemIdentifier.text\n contentConfiguration.setPlaceholder(type: .required)\n contentConfiguration.inputText = subject.value.shadowsocks.server\n contentConfiguration.editingEvents.onChange = subject.bindTextAction(to: \.shadowsocks.server)\n contentConfiguration.textFieldProperties = .withSmartFeaturesDisabled()\n cell.contentConfiguration = contentConfiguration\n }\n\n func configurePort(_ cell: UITableViewCell, itemIdentifier: ShadowsocksItemIdentifier) {\n var contentConfiguration = TextCellContentConfiguration()\n contentConfiguration.text = itemIdentifier.text\n contentConfiguration.setPlaceholder(type: .required)\n contentConfiguration.inputText = subject.value.shadowsocks.port\n contentConfiguration.inputFilter = .digitsOnly\n contentConfiguration.editingEvents.onChange = subject.bindTextAction(to: \.shadowsocks.port)\n contentConfiguration.textFieldProperties = .withSmartFeaturesDisabled()\n contentConfiguration.textFieldProperties.keyboardType = .numberPad\n cell.contentConfiguration = contentConfiguration\n }\n\n func configurePassword(_ cell: UITableViewCell, itemIdentifier: ShadowsocksItemIdentifier) {\n var contentConfiguration = TextCellContentConfiguration()\n contentConfiguration.text = itemIdentifier.text\n contentConfiguration.maxLength = authenticationInputMaxLength\n contentConfiguration.setPlaceholder(type: .optional)\n contentConfiguration.inputText = subject.value.shadowsocks.password\n contentConfiguration.editingEvents.onChange = subject.bindTextAction(to: \.shadowsocks.password)\n contentConfiguration.textFieldProperties = .withSmartFeaturesDisabled()\n contentConfiguration.textFieldProperties.isSecureTextEntry = true\n contentConfiguration.textFieldProperties.textContentType = .password\n cell.contentConfiguration = contentConfiguration\n }\n\n func configureCipher(_ cell: UITableViewCell, itemIdentifier: ShadowsocksItemIdentifier) {\n var contentConfiguration = UIListContentConfiguration.mullvadValueCell(tableStyle: tableStyle)\n contentConfiguration.text = itemIdentifier.text\n contentConfiguration.secondaryText = subject.value.shadowsocks.cipher.rawValue.description\n cell.contentConfiguration = contentConfiguration\n\n if let cell = cell as? CustomCellDisclosureHandling {\n cell.disclosureType = .chevron\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Common\ShadowsocksSectionHandler.swift
ShadowsocksSectionHandler.swift
Swift
3,641
0.95
0.038462
0.115942
awesome-app
614
2024-11-18T20:04:39.575201
MIT
false
e47c1cd22757853f23dadb5315898196
//\n// SocksItemIdentifier.swift\n// MullvadVPN\n//\n// Created by pronebird on 14/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\n/// Item identifier used by diffable data sources implementing socks configuration.\nenum SocksItemIdentifier: Hashable, CaseIterable {\n case server\n case port\n case authentication\n case username\n case password\n\n /// Compute item identifiers that should be present in the diffable data source.\n ///\n /// - Parameter authenticate: whether user opt-in for socks proxy authentication.\n /// - Returns: item identifiers to display in the diffable data source.\n static func allCases(authenticate: Bool) -> [Self] {\n allCases.filter { itemIdentifier in\n if authenticate {\n return true\n } else {\n return itemIdentifier != .username && itemIdentifier != .password\n }\n }\n }\n\n /// Returns cell identifier for the item identiifer.\n var cellIdentifier: AccessMethodCellReuseIdentifier {\n switch self {\n case .server, .username, .password, .port:\n .textInput\n case .authentication:\n .toggle\n }\n }\n\n /// Indicates whether cell representing the item should be selectable.\n var isSelectable: Bool {\n false\n }\n\n /// The text describing the item identifier and suitable to be used as a field label.\n var text: String {\n switch self {\n case .server:\n NSLocalizedString("SOCKS_SERVER", tableName: "APIAccess", value: "Server", comment: "")\n case .port:\n NSLocalizedString("SOCKS_PORT", tableName: "APIAccess", value: "Port", comment: "")\n case .authentication:\n NSLocalizedString("SOCKS_AUTHENTICATION", tableName: "APIAccess", value: "Authentication", comment: "")\n case .username:\n NSLocalizedString("SOCKS_USERNAME", tableName: "APIAccess", value: "Username", comment: "")\n case .password:\n NSLocalizedString("SOCKS_PASSWORD", tableName: "APIAccess", value: "Password", comment: "")\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Common\SocksItemIdentifier.swift
SocksItemIdentifier.swift
Swift
2,143
0.95
0.079365
0.263158
vue-tools
511
2024-05-14T19:45:53.750523
BSD-3-Clause
false
973b89aae1d362fe2fa61a67c9102b21
//\n// SocksSectionHandler.swift\n// MullvadVPN\n//\n// Created by pronebird on 14/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport UIKit\n\n/// Type responsible for handling cells in socks table view section.\n@MainActor\nstruct SocksSectionHandler {\n private let authenticationInputMaxLength = 255\n\n let tableStyle: UITableView.Style\n let subject: CurrentValueSubject<AccessMethodViewModel, Never>\n\n func configure(_ cell: UITableViewCell, itemIdentifier: SocksItemIdentifier) {\n switch itemIdentifier {\n case .server:\n configureServer(cell, itemIdentifier: itemIdentifier)\n case .port:\n configurePort(cell, itemIdentifier: itemIdentifier)\n case .username:\n configureUsername(cell, itemIdentifier: itemIdentifier)\n case .password:\n configurePassword(cell, itemIdentifier: itemIdentifier)\n case .authentication:\n configureAuthentication(cell, itemIdentifier: itemIdentifier)\n }\n }\n\n private func configureServer(_ cell: UITableViewCell, itemIdentifier: SocksItemIdentifier) {\n var contentConfiguration = TextCellContentConfiguration()\n contentConfiguration.text = itemIdentifier.text\n contentConfiguration.setPlaceholder(type: .required)\n contentConfiguration.inputText = subject.value.socks.server\n contentConfiguration.textFieldProperties = .withSmartFeaturesDisabled()\n contentConfiguration.editingEvents.onChange = subject.bindTextAction(to: \.socks.server)\n cell.setAccessibilityIdentifier(.socks5ServerCell)\n cell.contentConfiguration = contentConfiguration\n }\n\n private func configurePort(_ cell: UITableViewCell, itemIdentifier: SocksItemIdentifier) {\n var contentConfiguration = TextCellContentConfiguration()\n contentConfiguration.text = itemIdentifier.text\n contentConfiguration.setPlaceholder(type: .required)\n contentConfiguration.inputText = subject.value.socks.port\n contentConfiguration.inputFilter = .digitsOnly\n contentConfiguration.editingEvents.onChange = subject.bindTextAction(to: \.socks.port)\n contentConfiguration.textFieldProperties = .withSmartFeaturesDisabled()\n contentConfiguration.textFieldProperties.keyboardType = .numberPad\n cell.setAccessibilityIdentifier(.socks5PortCell)\n cell.contentConfiguration = contentConfiguration\n }\n\n private func configureAuthentication(_ cell: UITableViewCell, itemIdentifier: SocksItemIdentifier) {\n var contentConfiguration = SwitchCellContentConfiguration()\n contentConfiguration.text = itemIdentifier.text\n contentConfiguration.isOn = subject.value.socks.authenticate\n contentConfiguration.onChange = subject.bindSwitchAction(to: \.socks.authenticate)\n contentConfiguration.accessibilityIdentifier = .socks5AuthenticationSwitch\n cell.contentConfiguration = contentConfiguration\n }\n\n private func configureUsername(_ cell: UITableViewCell, itemIdentifier: SocksItemIdentifier) {\n var contentConfiguration = TextCellContentConfiguration()\n contentConfiguration.text = itemIdentifier.text\n contentConfiguration.maxLength = authenticationInputMaxLength\n contentConfiguration.setPlaceholder(type: .required)\n contentConfiguration.inputText = subject.value.socks.username\n contentConfiguration.textFieldProperties = .withSmartFeaturesDisabled()\n contentConfiguration.textFieldProperties.textContentType = .username\n contentConfiguration.editingEvents.onChange = subject.bindTextAction(to: \.socks.username)\n cell.contentConfiguration = contentConfiguration\n }\n\n private func configurePassword(_ cell: UITableViewCell, itemIdentifier: SocksItemIdentifier) {\n var contentConfiguration = TextCellContentConfiguration()\n contentConfiguration.text = itemIdentifier.text\n contentConfiguration.maxLength = authenticationInputMaxLength\n contentConfiguration.setPlaceholder(type: .required)\n contentConfiguration.inputText = subject.value.socks.password\n contentConfiguration.editingEvents.onChange = subject.bindTextAction(to: \.socks.password)\n contentConfiguration.textFieldProperties = .withSmartFeaturesDisabled()\n contentConfiguration.textFieldProperties.isSecureTextEntry = true\n contentConfiguration.textFieldProperties.textContentType = .password\n cell.contentConfiguration = contentConfiguration\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Common\SocksSectionHandler.swift
SocksSectionHandler.swift
Swift
4,555
0.95
0.021739
0.096386
node-utils
974
2024-09-18T14:18:47.917167
MIT
false
493cdd667cc8a986cd35e3cb3166f001
//\n// EditAccessMethodCoordinator.swift\n// MullvadVPN\n//\n// Created by pronebird on 21/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport MullvadSettings\nimport Routing\nimport UIKit\n\nclass EditAccessMethodCoordinator: Coordinator, Presenting {\n let navigationController: UINavigationController\n let proxyConfigurationTester: ProxyConfigurationTesterProtocol\n let accessMethodRepository: AccessMethodRepositoryProtocol\n let methodIdentifier: UUID\n var methodSettingsSubject: CurrentValueSubject<AccessMethodViewModel, Never> = .init(AccessMethodViewModel())\n var editAccessMethodSubject: CurrentValueSubject<AccessMethodViewModel, Never> = .init(AccessMethodViewModel())\n\n var onFinish: ((EditAccessMethodCoordinator) -> Void)?\n\n var presentationContext: UIViewController {\n navigationController\n }\n\n init(\n navigationController: UINavigationController,\n accessMethodRepo: AccessMethodRepositoryProtocol,\n proxyConfigurationTester: ProxyConfigurationTesterProtocol,\n methodIdentifier: UUID\n ) {\n self.navigationController = navigationController\n self.accessMethodRepository = accessMethodRepo\n self.proxyConfigurationTester = proxyConfigurationTester\n self.methodIdentifier = methodIdentifier\n }\n\n func start() {\n editAccessMethodSubject = getViewModelSubjectFromStore()\n\n let interactor = EditAccessMethodInteractor(\n subject: editAccessMethodSubject,\n repository: accessMethodRepository,\n proxyConfigurationTester: proxyConfigurationTester\n )\n\n let controller = EditAccessMethodViewController(\n subject: editAccessMethodSubject,\n interactor: interactor,\n alertPresenter: AlertPresenter(context: self)\n )\n controller.delegate = self\n\n navigationController.pushViewController(controller, animated: true)\n }\n}\n\nextension EditAccessMethodCoordinator: @preconcurrency EditAccessMethodViewControllerDelegate {\n func controllerShouldShowMethodSettings(_ controller: EditAccessMethodViewController) {\n methodSettingsSubject = getViewModelSubjectFromStore()\n\n let interactor = EditAccessMethodInteractor(\n subject: methodSettingsSubject,\n repository: accessMethodRepository,\n proxyConfigurationTester: proxyConfigurationTester\n )\n\n let controller = MethodSettingsViewController(\n subject: methodSettingsSubject,\n interactor: interactor,\n alertPresenter: AlertPresenter(context: self)\n )\n\n controller.navigationItem.prompt = NSLocalizedString(\n "METHOD_SETTINGS_NAVIGATION_ADD_PROMPT",\n tableName: "APIAccess",\n value: "The app will test the method before saving.",\n comment: ""\n )\n\n controller.navigationItem.title = NSLocalizedString(\n "METHOD_SETTINGS_NAVIGATION_ADD_TITLE",\n tableName: "APIAccess",\n value: "Method settings",\n comment: ""\n )\n\n controller.saveBarButton.title = NSLocalizedString(\n "METHOD_SETTINGS_NAVIGATION_ADD_BUTTON",\n tableName: "APIAccess",\n value: "Save",\n comment: ""\n )\n\n controller.delegate = self\n\n navigationController.pushViewController(controller, animated: true)\n }\n\n func controllerDidDeleteAccessMethod(_ controller: EditAccessMethodViewController) {\n onFinish?(self)\n }\n\n func controllerShouldShowMethodInfo(_ controller: EditAccessMethodViewController, config: InfoModalConfig) {\n let aboutController = AboutViewController(\n header: config.header,\n preamble: config.preamble,\n body: config.body\n )\n let aboutNavController = UINavigationController(rootViewController: aboutController)\n\n aboutController.navigationItem.rightBarButtonItem = UIBarButtonItem(\n systemItem: .done,\n primaryAction: UIAction { [weak aboutNavController] _ in\n aboutNavController?.dismiss(animated: true)\n }\n )\n\n navigationController.present(aboutNavController, animated: true)\n }\n\n private func getViewModelSubjectFromStore() -> CurrentValueSubject<AccessMethodViewModel, Never> {\n let persistentMethod = accessMethodRepository.fetch(by: methodIdentifier)\n return CurrentValueSubject<AccessMethodViewModel, Never>(persistentMethod?.toViewModel() ?? .init())\n }\n}\n\nextension EditAccessMethodCoordinator: @preconcurrency MethodSettingsViewControllerDelegate {\n func accessMethodDidSave(_ accessMethod: PersistentAccessMethod) {\n editAccessMethodSubject.value = accessMethod.toViewModel()\n navigationController.popViewController(animated: true)\n }\n\n func controllerShouldShowProtocolPicker(_ controller: MethodSettingsViewController) {\n let picker = AccessMethodProtocolPicker(navigationController: navigationController)\n\n picker.present(currentValue: methodSettingsSubject.value.method) { [weak self] newMethod in\n self?.methodSettingsSubject.value.method = newMethod\n }\n }\n\n func controllerShouldShowShadowsocksCipherPicker(_ controller: MethodSettingsViewController) {\n let picker = ShadowsocksCipherPicker(navigationController: navigationController)\n\n picker.present(currentValue: methodSettingsSubject.value.shadowsocks.cipher) { [weak self] selectedCipher in\n self?.methodSettingsSubject.value.shadowsocks.cipher = selectedCipher\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Edit\EditAccessMethodCoordinator.swift
EditAccessMethodCoordinator.swift
Swift
5,664
0.95
0.006623
0.056452
awesome-app
155
2024-04-04T11:13:28.618900
GPL-3.0
false
3b910291c0ddb783b2991137ca228e81
//\n// EditAccessMethodInteractor.swift\n// MullvadVPN\n//\n// Created by pronebird on 23/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\n@preconcurrency import Combine\nimport Foundation\nimport MullvadSettings\n\nstruct EditAccessMethodInteractor: EditAccessMethodInteractorProtocol {\n let subject: CurrentValueSubject<AccessMethodViewModel, Never>\n let repository: AccessMethodRepositoryProtocol\n let proxyConfigurationTester: ProxyConfigurationTesterProtocol\n\n func saveAccessMethod() {\n guard let persistentMethod = try? subject.value.intoPersistentAccessMethod() else { return }\n\n repository.save(persistentMethod)\n }\n\n func deleteAccessMethod() {\n repository.delete(id: subject.value.id)\n }\n\n func startProxyConfigurationTest(_ completion: (@Sendable (Bool) -> Void)?) {\n guard let config = try? subject.value.intoPersistentProxyConfiguration() else { return }\n\n let subject = subject\n subject.value.testingStatus = .inProgress\n\n proxyConfigurationTester.start(configuration: config) { error in\n let succeeded = error == nil\n\n subject.value.testingStatus = succeeded ? .succeeded : .failed\n\n completion?(succeeded)\n }\n }\n\n func cancelProxyConfigurationTest() {\n subject.value.testingStatus = .initial\n\n proxyConfigurationTester.cancel()\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Edit\EditAccessMethodInteractor.swift
EditAccessMethodInteractor.swift
Swift
1,404
0.95
0.041667
0.194444
awesome-app
747
2024-08-16T04:42:01.408484
Apache-2.0
false
39140a9ffaa76a3c61bf2ff202ced9a8
//\n// EditAccessMethodInteractorProtocol.swift\n// MullvadVPN\n//\n// Created by pronebird on 23/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\n\n/// The type implementing the interface for persisting changes to the underlying access method view model in the editing context.\nprotocol EditAccessMethodInteractorProtocol: ProxyConfigurationInteractorProtocol {\n /// Save changes to persistent store.\n ///\n /// - Calling this method when the underlying view model fails validation does nothing.\n /// - View controllers are responsible to validate the view model before calling this method.\n func saveAccessMethod()\n\n /// Delete the access method from persistent store.\n ///\n /// - Calling this method multiple times does nothing.\n /// - View model does not have to pass validation for this method to work as the identifier field is the only requirement.\n /// - View controller presenting the UI for editing the access method must be dismissed after calling this method.\n func deleteAccessMethod()\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Edit\EditAccessMethodInteractorProtocol.swift
EditAccessMethodInteractorProtocol.swift
Swift
1,077
0.95
0.12
0.772727
node-utils
372
2024-03-01T08:17:16.128706
BSD-3-Clause
false
aa60fefe3955849547f4b9a3eee48914
//\n// EditAccessMethodItemIdentifier.swift\n// MullvadVPN\n//\n// Created by pronebird on 17/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nenum EditAccessMethodItemIdentifier: Hashable {\n case enableMethod\n case methodSettings\n case testMethod\n case testingStatus\n case cancelTest\n case deleteMethod\n\n /// Cell identifier for the item identifier.\n var cellIdentifier: AccessMethodCellReuseIdentifier {\n switch self {\n case .enableMethod:\n .toggle\n case .methodSettings:\n .textWithDisclosure\n case .testMethod, .cancelTest, .deleteMethod:\n .button\n case .testingStatus:\n .testingStatus\n }\n }\n\n /// Returns `true` if the cell background should be made transparent.\n var isClearBackground: Bool {\n switch self {\n case .testMethod, .cancelTest, .testingStatus, .deleteMethod:\n return true\n case .enableMethod, .methodSettings:\n return false\n }\n }\n\n /// Whether cell representing the item should be selectable.\n var isSelectable: Bool {\n switch self {\n case .enableMethod, .testMethod, .cancelTest, .testingStatus, .deleteMethod:\n false\n case .methodSettings:\n true\n }\n }\n\n /// The text label for the corresponding cell.\n var text: String? {\n switch self {\n case .enableMethod:\n NSLocalizedString("ENABLE_METHOD", tableName: "APIAccess", value: "Enable method", comment: "")\n case .methodSettings:\n NSLocalizedString("METHOD_SETTINGS", tableName: "APIAccess", value: "Method settings", comment: "")\n case .testMethod:\n NSLocalizedString("TEST_METHOD", tableName: "APIAccess", value: "Test method", comment: "")\n case .cancelTest:\n NSLocalizedString("CANCEL_TEST", tableName: "APIAccess", value: "Cancel", comment: "")\n case .testingStatus:\n nil\n case .deleteMethod:\n NSLocalizedString("DELETE_METHOD", tableName: "APIAccess", value: "Delete method", comment: "")\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Edit\EditAccessMethodItemIdentifier.swift
EditAccessMethodItemIdentifier.swift
Swift
2,173
0.95
0.1
0.171875
vue-tools
216
2025-01-09T17:43:36.570423
GPL-3.0
false
d7355178c48d1a98135e6f86d26c414c
//\n// EditAccessMethodSectionIdentifier.swift\n// MullvadVPN\n//\n// Created by pronebird on 17/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nenum EditAccessMethodSectionIdentifier: Hashable {\n case enableMethod\n case methodSettings\n case testMethod\n case cancelTest\n case testingStatus\n case deleteMethod\n\n /// The section footer text.\n var sectionFooter: String? {\n switch self {\n case .testMethod:\n NSLocalizedString(\n "TEST_METHOD_FOOTER",\n tableName: "APIAccess",\n value: "Performs a connection test to a Mullvad API server via this access method.",\n comment: ""\n )\n\n case .enableMethod, .methodSettings, .cancelTest, .testingStatus, .deleteMethod:\n nil\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Edit\EditAccessMethodSectionIdentifier.swift
EditAccessMethodSectionIdentifier.swift
Swift
860
0.95
0.029412
0.266667
react-lib
2
2025-01-11T01:46:44.789732
BSD-3-Clause
false
66966309ac245d181cabec37f42affbe
//\n// EditAccessMethodViewController.swift\n// MullvadVPN\n//\n// Created by pronebird on 17/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport MullvadSettings\nimport UIKit\n\n/// The view controller providing the interface for editing the existing access method.\nclass EditAccessMethodViewController: UIViewController {\n typealias EditAccessMethodDataSource = UITableViewDiffableDataSource<\n EditAccessMethodSectionIdentifier,\n EditAccessMethodItemIdentifier\n >\n\n private let tableView = UITableView(frame: .zero, style: .insetGrouped)\n private let subject: CurrentValueSubject<AccessMethodViewModel, Never>\n private let interactor: EditAccessMethodInteractorProtocol\n private var alertPresenter: AlertPresenter\n private var cancellables = Set<AnyCancellable>()\n private var dataSource: EditAccessMethodDataSource?\n\n weak var delegate: EditAccessMethodViewControllerDelegate?\n\n init(\n subject: CurrentValueSubject<AccessMethodViewModel, Never>,\n interactor: EditAccessMethodInteractorProtocol,\n alertPresenter: AlertPresenter\n ) {\n self.subject = subject\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 tableView.setAccessibilityIdentifier(.editAccessMethodView)\n tableView.backgroundColor = .secondaryColor\n tableView.delegate = self\n\n isModalInPresentation = true\n\n let headerView = createHeaderView()\n view.addConstrainedSubviews([headerView, tableView]) {\n headerView.pinEdgesToSuperviewMargins(PinnableEdges([.leading(8), .trailing(8), .top(0)]))\n tableView.pinEdgesToSuperview(.all().excluding(.top))\n tableView.topAnchor.constraint(equalTo: headerView.bottomAnchor, constant: 20)\n }\n\n configureDataSource()\n configureNavigationItem()\n }\n\n override func viewWillDisappear(_ animated: Bool) {\n super.viewWillDisappear(animated)\n interactor.cancelProxyConfigurationTest()\n }\n\n private func createHeaderView() -> UIView {\n var headerView: InfoHeaderView?\n\n if let headerConfig = subject.value.infoHeaderConfig {\n headerView = InfoHeaderView(config: headerConfig)\n\n headerView?.onAbout = { [weak self] in\n guard let self, let infoModalConfig = subject.value.infoModalConfig else { return }\n delegate?.controllerShouldShowMethodInfo(self, config: infoModalConfig)\n }\n }\n\n return headerView ?? UIView()\n }\n}\n\n// MARK: - UITableViewDelegate\n\nextension EditAccessMethodViewController: UITableViewDelegate {\n func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {\n guard let itemIdentifier = dataSource?.itemIdentifier(for: indexPath) else { return false }\n\n return itemIdentifier.isSelectable\n }\n\n func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {\n guard let itemIdentifier = dataSource?.itemIdentifier(for: indexPath) else { return }\n\n if case .methodSettings = itemIdentifier {\n delegate?.controllerShouldShowMethodSettings(self)\n }\n }\n\n func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {\n return UIMetrics.SettingsCell.apiAccessCellHeight\n }\n\n func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {\n return nil\n }\n\n // Header height shenanigans to avoid extra spacing in testing sections when testing is NOT ongoing.\n func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {\n guard let sectionIdentifier = dataSource?.snapshot().sectionIdentifiers[section] else { return 0 }\n\n switch sectionIdentifier {\n case .methodSettings, .deleteMethod, .testMethod:\n return UITableView.automaticDimension\n case .testingStatus:\n return subject.value.testingStatus == .initial ? 0 : UITableView.automaticDimension\n case .enableMethod, .cancelTest:\n return 0\n }\n }\n\n func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {\n guard let sectionIdentifier = dataSource?.snapshot().sectionIdentifiers[section] else { return nil }\n guard let sectionFooterText = sectionIdentifier.sectionFooter else { return nil }\n\n guard let headerView = tableView\n .dequeueReusableView(withIdentifier: AccessMethodHeaderFooterReuseIdentifier.primary)\n else { return nil }\n\n var contentConfiguration = UIListContentConfiguration.mullvadGroupedFooter(tableStyle: tableView.style)\n contentConfiguration.text = sectionFooterText\n\n headerView.contentConfiguration = contentConfiguration\n\n return headerView\n }\n\n // Footer height shenanigans to avoid extra spacing in testing sections when testing is NOT ongoing.\n func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {\n guard let sectionIdentifier = dataSource?.snapshot().sectionIdentifiers[section] else { return 0 }\n let marginToDeleteMethodItem: CGFloat = 24\n\n switch sectionIdentifier {\n case .enableMethod, .methodSettings, .deleteMethod, .testMethod:\n return UITableView.automaticDimension\n case .testingStatus:\n switch subject.value.testingStatus {\n case .initial, .inProgress:\n return 0\n case .succeeded, .failed:\n return marginToDeleteMethodItem\n }\n case .cancelTest:\n return subject.value.testingStatus == .inProgress ? marginToDeleteMethodItem : 0\n }\n }\n\n // MARK: - Cell configuration\n\n private func dequeueCell(at indexPath: IndexPath, for itemIdentifier: EditAccessMethodItemIdentifier)\n -> UITableViewCell {\n let cell = tableView.dequeueReusableView(withIdentifier: itemIdentifier.cellIdentifier, for: indexPath)\n\n configureBackground(cell: cell, itemIdentifier: itemIdentifier)\n\n switch itemIdentifier {\n case .testMethod:\n configureTestMethod(cell, itemIdentifier: itemIdentifier)\n case .cancelTest:\n configureCancelTest(cell, itemIdentifier: itemIdentifier)\n case .testingStatus:\n configureTestingStatus(cell, itemIdentifier: itemIdentifier)\n case .deleteMethod:\n configureDeleteMethod(cell, itemIdentifier: itemIdentifier)\n case .enableMethod:\n configureEnableMethod(cell, itemIdentifier: itemIdentifier)\n case .methodSettings:\n configureMethodSettings(cell, itemIdentifier: itemIdentifier)\n }\n\n return cell\n }\n\n private func configureBackground(cell: UITableViewCell, itemIdentifier: EditAccessMethodItemIdentifier) {\n guard let cell = cell as? DynamicBackgroundConfiguration else { return }\n\n guard !itemIdentifier.isClearBackground else {\n cell.setAutoAdaptingClearBackgroundConfiguration()\n return\n }\n\n cell.setAutoAdaptingBackgroundConfiguration(.mullvadListGroupedCell(), selectionType: .dimmed)\n }\n\n private func configureTestMethod(_ cell: UITableViewCell, itemIdentifier: EditAccessMethodItemIdentifier) {\n var contentConfiguration = ButtonCellContentConfiguration()\n contentConfiguration.accessibilityIdentifier = .accessMethodTestButton\n contentConfiguration.text = itemIdentifier.text\n contentConfiguration.isEnabled = subject.value.testingStatus != .inProgress\n contentConfiguration.primaryAction = UIAction { [weak self] _ in\n self?.onTest()\n }\n cell.contentConfiguration = contentConfiguration\n }\n\n private func configureCancelTest(_ cell: UITableViewCell, itemIdentifier: EditAccessMethodItemIdentifier) {\n var contentConfiguration = ButtonCellContentConfiguration()\n contentConfiguration.accessibilityIdentifier = .accessMethodTestButton\n contentConfiguration.text = itemIdentifier.text\n contentConfiguration.isEnabled = subject.value.testingStatus == .inProgress\n contentConfiguration.primaryAction = UIAction { [weak self] _ in\n self?.onCancelTest()\n }\n cell.contentConfiguration = contentConfiguration\n }\n\n private func configureTestingStatus(_ cell: UITableViewCell, itemIdentifier: EditAccessMethodItemIdentifier) {\n var contentConfiguration = MethodTestingStatusCellContentConfiguration()\n contentConfiguration.status = subject.value.testingStatus.viewStatus\n cell.contentConfiguration = contentConfiguration\n }\n\n private func configureEnableMethod(_ cell: UITableViewCell, itemIdentifier: EditAccessMethodItemIdentifier) {\n var contentConfiguration = SwitchCellContentConfiguration()\n contentConfiguration.accessibilityIdentifier = .accessMethodEnableSwitch\n contentConfiguration.text = itemIdentifier.text\n contentConfiguration.isOn = subject.value.isEnabled\n contentConfiguration.onChange = UIAction { [weak self] action in\n if let customSwitch = action.sender as? UISwitch {\n self?.subject.value.isEnabled = customSwitch.isOn\n self?.onSave()\n }\n }\n cell.contentConfiguration = contentConfiguration\n }\n\n private func configureMethodSettings(_ cell: UITableViewCell, itemIdentifier: EditAccessMethodItemIdentifier) {\n var contentConfiguration = UIListContentConfiguration.mullvadCell(tableStyle: tableView.style)\n contentConfiguration.text = itemIdentifier.text\n cell.contentConfiguration = contentConfiguration\n\n if let cell = cell as? CustomCellDisclosureHandling {\n cell.disclosureType = .chevron\n }\n }\n\n private func configureDeleteMethod(_ cell: UITableViewCell, itemIdentifier: EditAccessMethodItemIdentifier) {\n var contentConfiguration = ButtonCellContentConfiguration()\n contentConfiguration.style = .tableInsetGroupedDanger\n contentConfiguration.text = itemIdentifier.text\n contentConfiguration.primaryAction = UIAction { [weak self] _ in\n self?.onDelete()\n }\n cell.contentConfiguration = contentConfiguration\n }\n\n // MARK: - Data source handling\n\n private func configureDataSource() {\n tableView.registerReusableViews(from: AccessMethodCellReuseIdentifier.self)\n tableView.registerReusableViews(from: AccessMethodHeaderFooterReuseIdentifier.self)\n\n dataSource = UITableViewDiffableDataSource(\n tableView: tableView,\n cellProvider: { [weak self] _, indexPath, itemIdentifier in\n self?.dequeueCell(at: indexPath, for: itemIdentifier)\n }\n )\n\n subject.withPreviousValue()\n .sink { [weak self] previousValue, newValue in\n self?.viewModelDidChange(previousValue: previousValue, newValue: newValue)\n }\n .store(in: &cancellables)\n }\n\n private func viewModelDidChange(previousValue: AccessMethodViewModel?, newValue: AccessMethodViewModel) {\n let animated = view.window != nil\n\n configureNavigationItem()\n updateDataSource(\n previousValue: previousValue,\n newValue: newValue,\n animated: animated\n )\n }\n\n private func updateDataSource(\n previousValue: AccessMethodViewModel?,\n newValue: AccessMethodViewModel,\n animated: Bool\n ) {\n var snapshot = NSDiffableDataSourceSnapshot<EditAccessMethodSectionIdentifier, EditAccessMethodItemIdentifier>()\n\n snapshot.appendSections([.enableMethod])\n snapshot.appendItems([.enableMethod], toSection: .enableMethod)\n\n // Add method settings if the access method is configurable.\n if newValue.method.hasProxyConfiguration {\n snapshot.appendSections([.methodSettings])\n snapshot.appendItems([.methodSettings], toSection: .methodSettings)\n }\n\n snapshot.appendSections([.testMethod])\n snapshot.appendItems([.testMethod], toSection: .testMethod)\n\n // Reconfigure the test button on status changes.\n if let previousValue, previousValue.testingStatus != newValue.testingStatus {\n snapshot.reconfigureItems([.testMethod])\n }\n\n snapshot.appendSections([.testingStatus])\n snapshot.appendSections([.cancelTest])\n\n // Add test status below the test button.\n if newValue.testingStatus != .initial {\n snapshot.appendItems([.testingStatus], toSection: .testingStatus)\n\n if let previousValue, previousValue.testingStatus != newValue.testingStatus {\n snapshot.reconfigureItems([.testingStatus])\n }\n\n // Show cancel test button below test status.\n if newValue.testingStatus == .inProgress {\n snapshot.appendItems([.cancelTest], toSection: .cancelTest)\n }\n }\n\n // Add delete button for user-defined access methods.\n if !newValue.method.isPermanent {\n snapshot.appendSections([.deleteMethod])\n snapshot.appendItems([.deleteMethod], toSection: .deleteMethod)\n }\n\n dataSource?.apply(snapshot, animatingDifferences: animated)\n }\n\n // MARK: - Misc\n\n private func configureNavigationItem() {\n navigationItem.title = subject.value.navigationItemTitle\n }\n\n private func onSave() {\n interactor.saveAccessMethod()\n }\n\n private func onDelete() {\n let methodName = subject.value.name.isEmpty\n ? NSLocalizedString(\n "METHOD_SETTINGS_SAVE_PROMPT",\n tableName: "APIAccess",\n value: "method?",\n comment: ""\n )\n : subject.value.name\n\n let presentation = AlertPresentation(\n id: "api-access-methods-delete-method-alert",\n icon: .alert,\n message: NSLocalizedString(\n "METHOD_SETTINGS_DELETE_PROMPT",\n tableName: "APIAccess",\n value: "Delete \(methodName)?",\n comment: ""\n ),\n buttons: [\n AlertAction(\n title: NSLocalizedString(\n "METHOD_SETTINGS_DELETE_BUTTON",\n tableName: "APIAccess",\n value: "Delete",\n comment: ""\n ),\n style: .destructive,\n handler: { [weak self] in\n guard let self else { return }\n interactor.deleteAccessMethod()\n delegate?.controllerDidDeleteAccessMethod(self)\n }\n ),\n AlertAction(\n title: NSLocalizedString(\n "METHOD_SETTINGS_CANCEL_BUTTON",\n tableName: "APIAccess",\n value: "Cancel",\n comment: ""\n ),\n style: .default\n ),\n ]\n )\n\n alertPresenter.showAlert(presentation: presentation, animated: true)\n }\n\n private func onTest() {\n interactor.startProxyConfigurationTest()\n }\n\n private func onCancelTest() {\n interactor.cancelProxyConfigurationTest()\n }\n} // swiftlint:disable:this file_length\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Edit\EditAccessMethodViewController.swift
EditAccessMethodViewController.swift
Swift
15,852
0.95
0.056235
0.056716
react-lib
547
2023-11-11T23:19:40.860451
GPL-3.0
false
d363e85fd85b1fd8b7d2a5f2ebbc7138
//\n// EditAccessMethodViewControllerDelegate.swift\n// MullvadVPN\n//\n// Created by pronebird on 23/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadSettings\n\nprotocol EditAccessMethodViewControllerDelegate: AnyObject, AccessMethodEditing {\n /// The view controller requests the delegate to present the proxy configuration view controller.\n /// - Parameter controller: the calling controller.\n func controllerShouldShowMethodSettings(_ controller: EditAccessMethodViewController)\n\n /// The view controller deleted the access method.\n ///\n /// The delegate should consider dismissing the view controller.\n ///\n /// - Parameter controller: the calling controller.\n func controllerDidDeleteAccessMethod(_ controller: EditAccessMethodViewController)\n\n /// The view controller requests the delegate to present information about the access method.\n /// - Parameter controller: the calling controller.\n func controllerShouldShowMethodInfo(_ controller: EditAccessMethodViewController, config: InfoModalConfig)\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Edit\EditAccessMethodViewControllerDelegate.swift
EditAccessMethodViewControllerDelegate.swift
Swift
1,097
0.95
0
0.695652
react-lib
763
2024-07-05T02:27:48.046804
MIT
false
9c9a8424a7c4f5dc1b3967395d5026a7
//\n// ProxyConfigurationInteractorProtocol.swift\n// MullvadVPN\n//\n// Created by pronebird on 23/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\n\n/// The type implementing the facilities for testing proxy configuration.\nprotocol ProxyConfigurationInteractorProtocol {\n /// Start testing proxy configuration with data from view model.\n ///\n /// - It's expected that the completion handler is not called if testing is cancelled.\n /// - The interactor should update the underlying view model to indicate the progress of testing. The view controller is expected to keep track of that and update\n /// the UI accordingly.\n ///\n /// - Parameter completion: completion handler receiving `true` if the test succeeded, otherwise `false`.\n func startProxyConfigurationTest(_ completion: (@Sendable (Bool) -> Void)?)\n\n /// Cancel currently running configuration test.\n /// The interactor is expected to reset the testing status to the initial.\n func cancelProxyConfigurationTest()\n}\n\nextension ProxyConfigurationInteractorProtocol {\n /// Start testing proxy configuration with data from view model.\n func startProxyConfigurationTest() {\n startProxyConfigurationTest(nil)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Edit\ProxyConfigurationInteractorProtocol.swift
ProxyConfigurationInteractorProtocol.swift
Swift
1,279
0.95
0.090909
0.62069
awesome-app
140
2024-11-25T14:21:27.008749
GPL-3.0
false
7a8f4814363085d2477b52f4fb3c458b
//\n// MethodSettingsCellConfiguration.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-01-19.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport MullvadTypes\nimport UIKit\n\n@MainActor\nclass MethodSettingsCellConfiguration {\n private let subject: CurrentValueSubject<AccessMethodViewModel, Never>\n private let tableView: UITableView\n\n var onCancelTest: (() -> Void)?\n\n private var isTesting: Bool {\n subject.value.testingStatus == .inProgress\n }\n\n init(tableView: UITableView, subject: CurrentValueSubject<AccessMethodViewModel, Never>) {\n self.tableView = tableView\n self.subject = subject\n }\n\n func dequeueCell(\n at indexPath: IndexPath,\n for itemIdentifier: MethodSettingsItemIdentifier,\n contentValidationErrors: [AccessMethodFieldValidationError]\n ) -> UITableViewCell {\n let cell = tableView.dequeueReusableView(withIdentifier: itemIdentifier.cellIdentifier, for: indexPath)\n\n configureBackground(\n cell: cell,\n itemIdentifier: itemIdentifier,\n contentValidationErrors: contentValidationErrors\n )\n\n switch itemIdentifier {\n case .name:\n configureName(cell, itemIdentifier: itemIdentifier)\n case .protocol:\n configureProtocol(cell, itemIdentifier: itemIdentifier)\n case let .proxyConfiguration(proxyItemIdentifier):\n configureProxy(cell, itemIdentifier: proxyItemIdentifier)\n case .validationError:\n configureValidationError(\n cell,\n itemIdentifier: itemIdentifier,\n contentValidationErrors: contentValidationErrors\n )\n case .testingStatus:\n configureTestingStatus(cell, itemIdentifier: itemIdentifier)\n case .cancelTest:\n configureCancelTest(cell, itemIdentifier: itemIdentifier)\n }\n\n return cell\n }\n\n private func configureBackground(\n cell: UITableViewCell,\n itemIdentifier: MethodSettingsItemIdentifier,\n contentValidationErrors: [AccessMethodFieldValidationError]\n ) {\n configureErrorState(\n cell: cell,\n itemIdentifier: itemIdentifier,\n contentValidationErrors: contentValidationErrors\n )\n\n guard let cell = cell as? DynamicBackgroundConfiguration else { return }\n\n guard !itemIdentifier.isClearBackground else {\n cell.setAutoAdaptingClearBackgroundConfiguration()\n return\n }\n\n cell.setAutoAdaptingBackgroundConfiguration(.mullvadListGroupedCell(), selectionType: .dimmed)\n }\n\n private func configureErrorState(\n cell: UITableViewCell,\n itemIdentifier: MethodSettingsItemIdentifier,\n contentValidationErrors: [AccessMethodFieldValidationError]\n ) {\n guard case .proxyConfiguration = itemIdentifier else {\n return\n }\n\n let itemsWithErrors = MethodSettingsItemIdentifier.fromFieldValidationErrors(\n contentValidationErrors,\n selectedMethod: subject.value.method\n )\n\n if itemsWithErrors.contains(itemIdentifier) {\n cell.layer.cornerRadius = 10\n cell.layer.borderWidth = 1\n cell.layer.borderColor = UIColor.Cell.validationErrorBorderColor.cgColor\n } else {\n cell.layer.borderWidth = 0\n }\n }\n\n private func configureName(_ cell: UITableViewCell, itemIdentifier: MethodSettingsItemIdentifier) {\n var contentConfiguration = TextCellContentConfiguration()\n contentConfiguration.text = itemIdentifier.text\n contentConfiguration.setPlaceholder(type: .required)\n contentConfiguration.textFieldProperties = .withSmartFeaturesDisabled()\n contentConfiguration.inputText = subject.value.name\n contentConfiguration.maxLength = NameInputFormatter.maxLength\n contentConfiguration.editingEvents.onChange = subject.bindTextAction(to: \.name)\n\n cell.setAccessibilityIdentifier(.accessMethodNameTextField)\n cell.setDisabled(isTesting)\n cell.contentConfiguration = contentConfiguration\n }\n\n private func configureProxy(_ cell: UITableViewCell, itemIdentifier: ProxyProtocolConfigurationItemIdentifier) {\n switch itemIdentifier {\n case let .socks(socksItemIdentifier):\n let section = SocksSectionHandler(tableStyle: tableView.style, subject: subject)\n section.configure(cell, itemIdentifier: socksItemIdentifier)\n\n case let .shadowsocks(shadowsocksItemIdentifier):\n let section = ShadowsocksSectionHandler(tableStyle: tableView.style, subject: subject)\n section.configure(cell, itemIdentifier: shadowsocksItemIdentifier)\n }\n\n cell.setDisabled(isTesting)\n }\n\n private func configureValidationError(\n _ cell: UITableViewCell,\n itemIdentifier: MethodSettingsItemIdentifier,\n contentValidationErrors: [AccessMethodFieldValidationError]\n ) {\n var contentConfiguration = SettingsFieldValidationErrorConfiguration()\n contentConfiguration.errors = contentValidationErrors.settingsFieldValidationErrors\n\n cell.contentConfiguration = contentConfiguration\n }\n\n private func configureProtocol(_ cell: UITableViewCell, itemIdentifier: MethodSettingsItemIdentifier) {\n var contentConfiguration = UIListContentConfiguration.mullvadValueCell(\n tableStyle: tableView.style,\n isEnabled: !isTesting\n )\n contentConfiguration.text = itemIdentifier.text\n contentConfiguration.secondaryText = subject.value.method.localizedDescription\n cell.contentConfiguration = contentConfiguration\n\n if let cell = cell as? CustomCellDisclosureHandling {\n cell.disclosureType = .chevron\n }\n\n cell.setAccessibilityIdentifier(.accessMethodProtocolSelectionCell)\n cell.setDisabled(isTesting)\n }\n\n private func configureCancelTest(_ cell: UITableViewCell, itemIdentifier: MethodSettingsItemIdentifier) {\n var contentConfiguration = ButtonCellContentConfiguration()\n contentConfiguration.text = itemIdentifier.text\n contentConfiguration.isEnabled = isTesting\n contentConfiguration.primaryAction = UIAction { [weak self] _ in\n self?.onCancelTest?()\n }\n\n cell.contentConfiguration = contentConfiguration\n }\n\n private func configureTestingStatus(_ cell: UITableViewCell, itemIdentifier: MethodSettingsItemIdentifier) {\n let viewStatus = subject.value.testingStatus.viewStatus\n\n var contentConfiguration = MethodTestingStatusCellContentConfiguration()\n contentConfiguration.status = viewStatus\n contentConfiguration.detailText = viewStatus == .reachable\n ? NSLocalizedString(\n "METHOD_SETTINGS_SAVING_CHANGES",\n tableName: "APIAccess",\n value: "Saving changes...",\n comment: ""\n )\n : nil\n\n cell.contentConfiguration = contentConfiguration\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Edit\MethodSettings\MethodSettingsCellConfiguration.swift
MethodSettingsCellConfiguration.swift
Swift
7,131
0.95
0.036649
0.04375
python-kit
265
2024-03-05T06:53:21.681931
GPL-3.0
false
2bdb9e5351032f9528cd2b25bb582949
//\n// MethodSettingsDataSourceConfiguration.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-01-19.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\n@MainActor\nclass MethodSettingsDataSourceConfiguration {\n private let dataSource: UITableViewDiffableDataSource<\n MethodSettingsSectionIdentifier,\n MethodSettingsItemIdentifier\n >?\n\n init(\n dataSource: UITableViewDiffableDataSource<MethodSettingsSectionIdentifier, MethodSettingsItemIdentifier>\n ) {\n self.dataSource = dataSource\n }\n\n func updateDataSource(\n previousValue: AccessMethodViewModel?,\n newValue: AccessMethodViewModel,\n previousValidationError: [AccessMethodFieldValidationError],\n newValidationError: [AccessMethodFieldValidationError],\n animated: Bool,\n completion: (() -> Void)? = nil\n ) {\n var snapshot = NSDiffableDataSourceSnapshot<MethodSettingsSectionIdentifier, MethodSettingsItemIdentifier>()\n\n // Add name field for user-defined access methods.\n if !newValue.method.isPermanent {\n snapshot.appendSections([.name])\n snapshot.appendItems([.name], toSection: .name)\n }\n\n snapshot.appendSections([.protocol])\n snapshot.appendItems([.protocol], toSection: .protocol)\n // Reconfigure protocol cell on change.\n if let previousValue, previousValue.method != newValue.method {\n snapshot.reconfigureItems([.protocol])\n }\n\n // Add proxy configuration section if the access method is configurable.\n if newValue.method.hasProxyConfiguration {\n snapshot.appendSections([.proxyConfiguration])\n }\n\n switch newValue.method {\n case .direct, .bridges, .encryptedDNS:\n break\n\n case .shadowsocks:\n snapshot.appendItems(MethodSettingsItemIdentifier.allShadowsocksItems, toSection: .proxyConfiguration)\n // Reconfigure cipher cell on change.\n if let previousValue, previousValue.shadowsocks.cipher != newValue.shadowsocks.cipher {\n snapshot.reconfigureItems([.proxyConfiguration(.shadowsocks(.cipher))])\n }\n\n // Reconfigure the proxy configuration cell if validation error changed.\n if previousValidationError != newValidationError {\n snapshot.reconfigureItems(MethodSettingsItemIdentifier.allShadowsocksItems)\n }\n case .socks5:\n snapshot.appendItems(\n MethodSettingsItemIdentifier.allSocksItems(authenticate: newValue.socks.authenticate),\n toSection: .proxyConfiguration\n )\n\n // Reconfigure the proxy configuration cell if validation error changed.\n if previousValidationError != newValidationError {\n snapshot.reconfigureItems(\n MethodSettingsItemIdentifier.allSocksItems(authenticate: newValue.socks.authenticate)\n )\n }\n }\n\n snapshot.appendSections([.validationError])\n snapshot.appendItems([.validationError], toSection: .validationError)\n\n snapshot.appendSections([.testingStatus])\n snapshot.appendSections([.cancelTest])\n\n // Add test status below the test button.\n if newValue.testingStatus != .initial {\n snapshot.appendItems([.testingStatus], toSection: .testingStatus)\n\n // Show cancel test button below test status.\n if newValue.testingStatus == .inProgress {\n snapshot.appendItems([.cancelTest], toSection: .cancelTest)\n }\n }\n\n if let previousValue, previousValue.testingStatus != newValue.testingStatus {\n snapshot.reconfigureItems(snapshot.itemIdentifiers)\n }\n\n dataSource?.apply(snapshot, animatingDifferences: animated, completion: completion)\n }\n\n func updateDataSourceWithContentValidationErrors(viewModel: AccessMethodViewModel) {\n guard var snapshot = dataSource?.snapshot() else {\n return\n }\n\n let itemsToReload: [MethodSettingsItemIdentifier] = switch viewModel.method {\n case .direct, .bridges, .encryptedDNS:\n []\n case .shadowsocks:\n MethodSettingsItemIdentifier.allShadowsocksItems\n case .socks5:\n MethodSettingsItemIdentifier.allSocksItems(authenticate: viewModel.socks.authenticate)\n }\n\n snapshot.reconfigureItems(itemsToReload + [.validationError])\n dataSource?.apply(snapshot, animatingDifferences: false)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Edit\MethodSettings\MethodSettingsDataSourceConfiguration.swift
MethodSettingsDataSourceConfiguration.swift
Swift
4,593
0.95
0.132231
0.148515
vue-tools
104
2024-10-31T09:04:47.977879
Apache-2.0
false
3a119635c8883ef34cb109173d706ae8
//\n// MethodSettingsItemIdentifier.swift\n// MullvadVPN\n//\n// Created by pronebird on 22/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nenum MethodSettingsItemIdentifier: Hashable {\n case name\n case `protocol`\n case proxyConfiguration(ProxyProtocolConfigurationItemIdentifier)\n case validationError\n case testingStatus\n case cancelTest\n\n /// Returns all shadowsocks items wrapped into `ProxyConfigurationItemIdentifier.proxyConfiguration`.\n static var allShadowsocksItems: [MethodSettingsItemIdentifier] {\n ShadowsocksItemIdentifier.allCases.map { .proxyConfiguration(.shadowsocks($0)) }\n }\n\n /// Returns all socks items wrapped into `ProxyConfigurationItemIdentifier.proxyConfiguration`.\n static func allSocksItems(authenticate: Bool) -> [MethodSettingsItemIdentifier] {\n SocksItemIdentifier.allCases(authenticate: authenticate).map { .proxyConfiguration(.socks($0)) }\n }\n\n /// Cell identifiers for the item identifier.\n var cellIdentifier: AccessMethodCellReuseIdentifier {\n switch self {\n case .name:\n .textInput\n case .protocol:\n .textWithDisclosure\n case let .proxyConfiguration(itemIdentifier):\n itemIdentifier.cellIdentifier\n case .validationError:\n .validationError\n case .testingStatus:\n .testingStatus\n case .cancelTest:\n .button\n }\n }\n\n /// Returns `true` if the cell background should be made transparent.\n var isClearBackground: Bool {\n switch self {\n case .validationError, .cancelTest, .testingStatus:\n return true\n case .name, .protocol, .proxyConfiguration:\n return false\n }\n }\n\n /// Indicates whether cell representing the item should be selectable.\n var isSelectable: Bool {\n switch self {\n case .name, .validationError, .testingStatus, .cancelTest:\n false\n case .protocol:\n true\n case let .proxyConfiguration(itemIdentifier):\n itemIdentifier.isSelectable\n }\n }\n\n /// The text label for the corresponding cell.\n var text: String? {\n switch self {\n case .name:\n NSLocalizedString("NAME", tableName: "APIAccess", value: "Name", comment: "")\n case .protocol:\n NSLocalizedString("TYPE", tableName: "APIAccess", value: "Type", comment: "")\n case .proxyConfiguration, .validationError:\n nil\n case .cancelTest:\n NSLocalizedString("CANCEL_TEST", tableName: "APIAccess", value: "Cancel", comment: "")\n case .testingStatus:\n nil\n }\n }\n\n static func fromFieldValidationErrors(\n _ errors: [AccessMethodFieldValidationError],\n selectedMethod: AccessMethodKind\n ) -> [MethodSettingsItemIdentifier] {\n switch selectedMethod {\n case .direct, .bridges, .encryptedDNS:\n []\n case .shadowsocks:\n errors.compactMap { error in\n switch error.field {\n case .name: .name\n case .server: .proxyConfiguration(.shadowsocks(.server))\n case .port: .proxyConfiguration(.shadowsocks(.port))\n case .username: nil\n case .password: .proxyConfiguration(.shadowsocks(.password))\n }\n }\n case .socks5:\n errors.map { error in\n switch error.field {\n case .name: .name\n case .server: .proxyConfiguration(.socks(.server))\n case .port: .proxyConfiguration(.socks(.port))\n case .username: .proxyConfiguration(.socks(.username))\n case .password: .proxyConfiguration(.socks(.password))\n }\n }\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Edit\MethodSettings\MethodSettingsItemIdentifier.swift
MethodSettingsItemIdentifier.swift
Swift
3,870
0.95
0.087719
0.12381
python-kit
646
2025-06-07T19:07:36.994598
MIT
false
f6a42c2255f821480825dae1af3a2f92
//\n// MethodSettingsSectionIdentifier.swift\n// MullvadVPN\n//\n// Created by pronebird on 21/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nenum MethodSettingsSectionIdentifier: Hashable {\n case name\n case `protocol`\n case proxyConfiguration\n case validationError\n case testingStatus\n case cancelTest\n\n var sectionName: String? {\n switch self {\n case .name, .protocol, .validationError, .testingStatus, .cancelTest:\n nil\n case .proxyConfiguration:\n NSLocalizedString(\n "HOST_CONFIG_SECTION_TITLE",\n tableName: "APIAccess",\n value: "Server details",\n comment: ""\n )\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Edit\MethodSettings\MethodSettingsSectionIdentifier.swift
MethodSettingsSectionIdentifier.swift
Swift
763
0.95
0.03125
0.241379
react-lib
431
2025-01-18T13:56:18.434780
GPL-3.0
false
636e355f4eaa7ac08de5e45c99c88ca0
//\n// MethodSettingsViewController.swift\n// MullvadVPN\n//\n// Created by pronebird on 21/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport struct MullvadTypes.Duration\nimport UIKit\n\n/// The view controller providing the interface for editing method settings\n/// and testing the proxy configuration.\nclass MethodSettingsViewController: UITableViewController {\n typealias MethodSettingsDataSource = UITableViewDiffableDataSource<\n MethodSettingsSectionIdentifier,\n MethodSettingsItemIdentifier\n >\n\n private let subject: CurrentValueSubject<AccessMethodViewModel, Never>\n private let interactor: EditAccessMethodInteractorProtocol\n private var cancellables = Set<AnyCancellable>()\n private var alertPresenter: AlertPresenter\n private var inputValidationErrors: [AccessMethodFieldValidationError] = []\n private var contentValidationErrors: [AccessMethodFieldValidationError] = []\n private var dataSource: MethodSettingsDataSource?\n\n private lazy var cellConfiguration: MethodSettingsCellConfiguration = {\n var configuration = MethodSettingsCellConfiguration(tableView: tableView, subject: subject)\n configuration.onCancelTest = { [weak self] in\n self?.onCancelTest()\n }\n return configuration\n }()\n\n private lazy var dataSourceConfiguration: MethodSettingsDataSourceConfiguration? = {\n return dataSource.flatMap { dataSource in\n MethodSettingsDataSourceConfiguration(dataSource: dataSource)\n }\n }()\n\n private var isTesting: Bool {\n subject.value.testingStatus == .inProgress\n }\n\n lazy var saveBarButton: UIBarButtonItem = {\n let barButtonItem = UIBarButtonItem(\n title: NSLocalizedString("SAVE_NAVIGATION_BUTTON", tableName: "APIAccess", value: "Save", comment: ""),\n primaryAction: UIAction { [weak self] _ in\n self?.onTest()\n }\n )\n barButtonItem.style = .done\n return barButtonItem\n }()\n\n weak var delegate: MethodSettingsViewControllerDelegate?\n\n init(\n subject: CurrentValueSubject<AccessMethodViewModel, Never>,\n interactor: EditAccessMethodInteractorProtocol,\n alertPresenter: AlertPresenter\n ) {\n self.subject = subject\n self.interactor = interactor\n self.alertPresenter = alertPresenter\n\n super.init(style: .insetGrouped)\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(.addAccessMethodTableView)\n view.directionalLayoutMargins = UIMetrics.contentLayoutMargins\n view.backgroundColor = .secondaryColor\n\n navigationItem.rightBarButtonItem = saveBarButton\n navigationItem.rightBarButtonItem?.setAccessibilityIdentifier(.accessMethodAddButton)\n navigationItem.rightBarButtonItem?.isAccessibilityElement = true\n isModalInPresentation = true\n\n configureTableView()\n configureDataSource()\n }\n\n override func viewWillAppear(_ animated: Bool) {\n super.viewWillAppear(animated)\n\n inputValidationErrors.removeAll()\n contentValidationErrors.removeAll()\n }\n\n override func viewWillDisappear(_ animated: Bool) {\n super.viewWillDisappear(animated)\n interactor.cancelProxyConfigurationTest()\n }\n\n // MARK: - UITableViewDelegate\n\n override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {\n guard let itemIdentifier = dataSource?.itemIdentifier(for: indexPath) else { return 0 }\n\n switch itemIdentifier {\n case .name, .protocol, .proxyConfiguration, .cancelTest:\n return UIMetrics.SettingsCell.apiAccessCellHeight\n case .validationError:\n return contentValidationErrors.isEmpty\n ? UIMetrics.SettingsCell.apiAccessCellHeight\n : UITableView.automaticDimension\n case .testingStatus:\n return UITableView.automaticDimension\n }\n }\n\n override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {\n guard let sectionIdentifier = dataSource?.snapshot().sectionIdentifiers[section] else { return nil }\n\n guard let headerView = tableView\n .dequeueReusableView(withIdentifier: AccessMethodHeaderFooterReuseIdentifier.primary)\n else { return nil }\n\n var contentConfiguration = UIListContentConfiguration.mullvadGroupedHeader(tableStyle: tableView.style)\n contentConfiguration.text = sectionIdentifier.sectionName\n\n headerView.contentConfiguration = contentConfiguration\n\n return headerView\n }\n\n override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {\n guard let sectionIdentifier = dataSource?.snapshot().sectionIdentifiers[section] else { return 0 }\n\n switch sectionIdentifier {\n case .name, .protocol, .proxyConfiguration, .testingStatus:\n return UITableView.automaticDimension\n case .validationError, .cancelTest:\n return 0\n }\n }\n\n override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {\n return nil\n }\n\n override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {\n guard let sectionIdentifier = dataSource?.snapshot().sectionIdentifiers[section] else { return 0 }\n\n switch sectionIdentifier {\n case .name, .protocol, .cancelTest:\n return UITableView.automaticDimension\n case .proxyConfiguration, .validationError, .testingStatus:\n return 0\n }\n }\n\n override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {\n guard !isTesting, let itemIdentifier = dataSource?.itemIdentifier(for: indexPath),\n itemIdentifier.isSelectable else { return nil }\n\n return indexPath\n }\n\n override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {\n guard let itemIdentifier = dataSource?.itemIdentifier(for: indexPath) else { return false }\n\n return itemIdentifier.isSelectable\n }\n\n override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {\n let itemIdentifier = dataSource?.itemIdentifier(for: indexPath)\n\n switch itemIdentifier {\n case .protocol:\n showProtocolSelector()\n case .proxyConfiguration(.shadowsocks(.cipher)):\n showShadowsocksCipher()\n default:\n break\n }\n }\n\n // MARK: - Pickers handling\n\n private func showProtocolSelector() {\n view.endEditing(false)\n delegate?.controllerShouldShowProtocolPicker(self)\n }\n\n private func showShadowsocksCipher() {\n view.endEditing(false)\n delegate?.controllerShouldShowShadowsocksCipherPicker(self)\n }\n\n // MARK: - Data source handling\n\n private func configureDataSource() {\n tableView.registerReusableViews(from: AccessMethodCellReuseIdentifier.self)\n tableView.registerReusableViews(from: AccessMethodHeaderFooterReuseIdentifier.self)\n\n dataSource = UITableViewDiffableDataSource(\n tableView: tableView,\n cellProvider: { [weak self] _, indexPath, itemIdentifier in\n guard let self else { return nil }\n\n return cellConfiguration.dequeueCell(\n at: indexPath,\n for: itemIdentifier,\n contentValidationErrors: contentValidationErrors\n )\n }\n )\n\n subject.withPreviousValue()\n .sink { [weak self] previousValue, newValue in\n self?.viewModelDidChange(previousValue: previousValue, newValue: newValue)\n }\n .store(in: &cancellables)\n }\n\n private func viewModelDidChange(previousValue: AccessMethodViewModel?, newValue: AccessMethodViewModel) {\n let animated = view.window != nil\n let previousValidationError = inputValidationErrors\n\n validateInput()\n\n dataSourceConfiguration?.updateDataSource(\n previousValue: previousValue,\n newValue: newValue,\n previousValidationError: previousValidationError,\n newValidationError: inputValidationErrors,\n animated: animated\n ) { [weak self] in\n if let indexPathToScrollTo = self?.dataSource?.indexPath(for: .testingStatus) {\n self?.tableView.scrollToRow(at: indexPathToScrollTo, at: .top, animated: true)\n }\n }\n }\n\n private func configureTableView() {\n tableView.delegate = self\n tableView.backgroundColor = .secondaryColor\n tableView.separatorColor = .secondaryColor\n tableView.separatorInset.left = UIMetrics.SettingsCell.apiAccessInsetLayoutMargins.leading\n }\n\n // MARK: - Misc\n\n private func validateInput() {\n let validationResult = Result { try subject.value.validate() }\n let validationError = validationResult.error as? AccessMethodValidationError\n\n // Only look for empty values for input validation.\n inputValidationErrors = validationError?.fieldErrors.filter { error in\n error.kind == .emptyValue\n } ?? []\n\n saveBarButton.isEnabled = !isTesting && inputValidationErrors.isEmpty\n }\n\n private func validateContent() {\n let validationResult = Result { try subject.value.validate() }\n let validationError = validationResult.error as? AccessMethodValidationError\n\n // Only look for format errors for test(save validation.\n contentValidationErrors = validationError?.fieldErrors.filter { error in\n error.kind != .emptyValue\n } ?? []\n }\n\n private func onSave(transitionDelay: Duration = .zero) {\n interactor.saveAccessMethod()\n\n DispatchQueue.main.asyncAfter(deadline: .now() + transitionDelay.timeInterval) { [weak self] in\n guard\n let self,\n let accessMethod = try? subject.value.intoPersistentAccessMethod()\n else { return }\n\n delegate?.accessMethodDidSave(accessMethod)\n }\n }\n\n private func onTest() {\n validateContent()\n\n guard contentValidationErrors.isEmpty else {\n dataSourceConfiguration?.updateDataSourceWithContentValidationErrors(viewModel: subject.value)\n return\n }\n\n view.endEditing(true)\n saveBarButton.isEnabled = false\n\n interactor.startProxyConfigurationTest { [weak self] _ in\n Task { @MainActor in\n self?.onTestCompleted()\n }\n }\n }\n\n private func onTestCompleted() {\n switch subject.value.testingStatus {\n case .initial, .inProgress:\n break\n\n case .failed:\n let presentation = AlertPresentation(\n id: "api-access-methods-testing-status-failed-alert",\n accessibilityIdentifier: .accessMethodUnreachableAlert,\n icon: .warning,\n message: NSLocalizedString(\n "METHOD_SETTINGS_SAVE_PROMPT",\n tableName: "APIAccess",\n value: "API could not be reached, save anyway?",\n comment: ""\n ),\n buttons: [\n AlertAction(\n title: NSLocalizedString(\n "METHOD_SETTINGS_SAVE_BUTTON",\n tableName: "APIAccess",\n value: "Save anyway",\n comment: ""\n ),\n style: .default,\n accessibilityId: .accessMethodUnreachableSaveButton,\n handler: { [weak self] in\n self?.onSave()\n }\n ),\n AlertAction(\n title: NSLocalizedString(\n "METHOD_SETTINGS_BACK_BUTTON",\n tableName: "APIAccess",\n value: "Back to editing",\n comment: ""\n ),\n style: .default,\n accessibilityId: .accessMethodUnreachableBackButton\n ),\n ]\n )\n\n alertPresenter.showAlert(presentation: presentation, animated: true)\n case .succeeded:\n onSave(transitionDelay: .seconds(1))\n }\n }\n\n private func onCancelTest() {\n interactor.cancelProxyConfigurationTest()\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Edit\MethodSettings\MethodSettingsViewController.swift
MethodSettingsViewController.swift
Swift
12,911
0.95
0.058496
0.051195
vue-tools
666
2024-07-08T19:21:40.358129
MIT
false
567f12f5b5b9f34012f4d89cec3b4c8d
//\n// MethodSettingsViewControllerDelegate.swift\n// MullvadVPN\n//\n// Created by pronebird on 23/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nprotocol MethodSettingsViewControllerDelegate: AnyObject, AccessMethodEditing {\n func controllerShouldShowProtocolPicker(_ controller: MethodSettingsViewController)\n func controllerShouldShowShadowsocksCipherPicker(_ controller: MethodSettingsViewController)\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Edit\MethodSettings\MethodSettingsViewControllerDelegate.swift
MethodSettingsViewControllerDelegate.swift
Swift
457
0.95
0
0.583333
python-kit
199
2025-06-23T08:40:08.133875
Apache-2.0
false
d394fd7f315d708d8566ac4f9878f8bd
//\n// ListAccessMethodCoordinator.swift\n// MullvadVPN\n//\n// Created by pronebird on 08/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\nimport Routing\nimport UIKit\n\nclass ListAccessMethodCoordinator: Coordinator, Presenting, SettingsChildCoordinator {\n let navigationController: UINavigationController\n let accessMethodRepository: AccessMethodRepositoryProtocol\n let proxyConfigurationTester: ProxyConfigurationTesterProtocol\n\n var presentationContext: UIViewController {\n navigationController\n }\n\n init(\n navigationController: UINavigationController,\n accessMethodRepository: AccessMethodRepositoryProtocol,\n proxyConfigurationTester: ProxyConfigurationTesterProtocol\n ) {\n self.navigationController = navigationController\n self.accessMethodRepository = accessMethodRepository\n self.proxyConfigurationTester = proxyConfigurationTester\n }\n\n func start(animated: Bool) {\n let listController = ListAccessMethodViewController(\n interactor: ListAccessMethodInteractor(repository: accessMethodRepository)\n )\n listController.delegate = self\n navigationController.pushViewController(listController, animated: animated)\n }\n\n private func addNew() {\n let coordinator = AddAccessMethodCoordinator(\n navigationController: CustomNavigationController(),\n accessMethodRepo: accessMethodRepository,\n proxyConfigurationTester: proxyConfigurationTester\n )\n\n coordinator.start()\n presentChild(coordinator, animated: true)\n }\n\n private func edit(item: ListAccessMethodItem) {\n // Remove previous edit coordinator to prevent accumulation.\n childCoordinators.filter { $0 is EditAccessMethodCoordinator }.forEach { $0.removeFromParent() }\n\n let editCoordinator = EditAccessMethodCoordinator(\n navigationController: navigationController,\n accessMethodRepo: accessMethodRepository,\n proxyConfigurationTester: proxyConfigurationTester,\n methodIdentifier: item.id\n )\n editCoordinator.onFinish = { [weak self] coordinator in\n self?.popToList()\n coordinator.removeFromParent()\n }\n editCoordinator.start()\n addChild(editCoordinator)\n }\n\n private func popToList() {\n guard let listController = navigationController.viewControllers\n .first(where: { $0 is ListAccessMethodViewController }) else { return }\n\n navigationController.popToViewController(listController, animated: true)\n }\n\n private func about() {\n let header = NSLocalizedString(\n "ABOUT_API_ACCESS_HEADER",\n tableName: "APIAccess",\n value: "API access",\n comment: ""\n )\n let preamble = NSLocalizedString(\n "ABOUT_API_ACCESS_PREAMBLE",\n tableName: "APIAccess",\n value: "Manage default and setup custom methods to access the Mullvad API.",\n comment: ""\n )\n let body = [\n NSLocalizedString(\n "ABOUT_API_ACCESS_BODY_1",\n tableName: "APIAccess",\n value: """\n The app needs to communicate with a Mullvad API server to log you in, fetch server lists, \\n and other critical operations.\n """,\n comment: ""\n ),\n NSLocalizedString(\n "ABOUT_API_ACCESS_BODY_2",\n tableName: "APIAccess",\n value: """\n On some networks, where various types of censorship are being used, the API servers might \\n not be directly reachable.\n """,\n comment: ""\n ),\n NSLocalizedString(\n "ABOUT_API_ACCESS_BODY_3",\n tableName: "APIAccess",\n value: """\n This feature allows you to circumvent that censorship by adding custom ways to access the \\n API via proxies and similar methods.\n """,\n comment: ""\n ),\n ]\n\n let aboutController = AboutViewController(header: header, preamble: preamble, body: body)\n let aboutNavController = UINavigationController(rootViewController: aboutController)\n\n aboutController.navigationItem.rightBarButtonItem = UIBarButtonItem(\n systemItem: .done,\n primaryAction: UIAction { [weak aboutNavController] _ in\n aboutNavController?.dismiss(animated: true)\n }\n )\n\n navigationController.present(aboutNavController, animated: true)\n }\n}\n\nextension ListAccessMethodCoordinator: @preconcurrency ListAccessMethodViewControllerDelegate {\n func controllerShouldShowAbout(_ controller: ListAccessMethodViewController) {\n about()\n }\n\n func controllerShouldAddNew(_ controller: ListAccessMethodViewController) {\n addNew()\n }\n\n func controller(_ controller: ListAccessMethodViewController, shouldEditItem item: ListAccessMethodItem) {\n edit(item: item)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\List\ListAccessMethodCoordinator.swift
ListAccessMethodCoordinator.swift
Swift
5,197
0.95
0.006897
0.062992
python-kit
198
2025-04-14T03:55:34.603512
GPL-3.0
false
d3b6a5a2c6a9597794fceafea555c4de
//\n// ListAccessMethodInteractor.swift\n// MullvadVPN\n//\n// Created by pronebird on 02/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport MullvadSettings\n\n/// A concrete implementation of an API access list interactor.\nstruct ListAccessMethodInteractor: ListAccessMethodInteractorProtocol {\n let repository: AccessMethodRepositoryProtocol\n\n init(repository: AccessMethodRepositoryProtocol) {\n self.repository = repository\n }\n\n var itemsPublisher: AnyPublisher<[ListAccessMethodItem], Never> {\n repository.accessMethodsPublisher\n .receive(on: RunLoop.main)\n .map { methods in\n methods.map { $0.toListItem() }\n }\n .eraseToAnyPublisher()\n }\n\n var itemInUsePublisher: AnyPublisher<ListAccessMethodItem?, Never> {\n repository.lastReachableAccessMethodPublisher\n .receive(on: RunLoop.main)\n .map { $0.toListItem() }\n .eraseToAnyPublisher()\n }\n\n func item(by id: UUID) -> ListAccessMethodItem? {\n repository.fetch(by: id)?.toListItem()\n }\n\n func fetch() -> [ListAccessMethodItem] {\n repository.fetchAll().map { $0.toListItem() }\n }\n}\n\nextension PersistentAccessMethod {\n func toListItem() -> ListAccessMethodItem {\n let sanitizedName = name.trimmingCharacters(in: .whitespaces)\n let itemName = sanitizedName.isEmpty ? kind.localizedDescription : sanitizedName\n\n return ListAccessMethodItem(\n id: id,\n name: itemName,\n detail: isEnabled\n ? kind.localizedDescription\n : NSLocalizedString(\n "LIST_ACCESS_METHODS_DISABLED",\n tableName: "APIAccess",\n value: "Disabled",\n comment: ""\n ),\n isEnabled: isEnabled\n )\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\List\ListAccessMethodInteractor.swift
ListAccessMethodInteractor.swift
Swift
1,909
0.95
0
0.145455
awesome-app
738
2024-02-05T20:01:35.235166
Apache-2.0
false
1ac2b992f6531cbf2936c1647d871cc5
//\n// ListAccessMethodInteractorProtocol.swift\n// MullvadVPN\n//\n// Created by pronebird on 02/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport MullvadSettings\n\n/// Types describing API access list interactor.\nprotocol ListAccessMethodInteractorProtocol {\n /// Publisher that produces a list of method items upon persistent store modifications.\n var itemsPublisher: AnyPublisher<[ListAccessMethodItem], Never> { get }\n\n /// Publisher that produces the last reachable method item upon persistent store modifications.\n var itemInUsePublisher: AnyPublisher<ListAccessMethodItem?, Never> { get }\n\n /// Returns an item by id.\n func item(by id: UUID) -> ListAccessMethodItem?\n\n /// Fetch all items.\n func fetch() -> [ListAccessMethodItem]\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\List\ListAccessMethodInteractorProtocol.swift
ListAccessMethodInteractorProtocol.swift
Swift
806
0.95
0
0.6
node-utils
318
2023-12-23T17:29:16.560964
BSD-3-Clause
false
da87e88532ce6a9d0c6c0cd3138b9c41
//\n// ListAccessMethodItem.swift\n// MullvadVPN\n//\n// Created by pronebird on 02/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\n/// A concrete implementation of an API access list item.\nstruct ListAccessMethodItem: Hashable, Identifiable, Equatable {\n /// The unique ID.\n let id: UUID\n\n /// The localized name.\n let name: String\n\n /// The detailed information displayed alongside.\n let detail: String?\n\n /// Whether method is enabled or not.\n let isEnabled: Bool\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\List\ListAccessMethodItem.swift
ListAccessMethodItem.swift
Swift
535
0.95
0
0.631579
awesome-app
406
2023-08-25T01:11:06.160661
Apache-2.0
false
0703d1f2daeecfd2a303dc9802856d4b
//\n// ListAccessMethodViewController.swift\n// MullvadVPN\n//\n// Created by pronebird on 02/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport MullvadREST\nimport MullvadSettings\nimport UIKit\n\nenum ListAccessMethodSectionIdentifier: Hashable {\n case primary\n}\n\nstruct ListAccessMethodItemIdentifier: Hashable {\n let id: UUID\n}\n\n/// View controller presenting a list of API access methods.\nclass ListAccessMethodViewController: UIViewController, UITableViewDelegate {\n typealias ListAccessMethodDataSource = UITableViewDiffableDataSource<\n ListAccessMethodSectionIdentifier,\n ListAccessMethodItemIdentifier\n >\n\n private let interactor: ListAccessMethodInteractorProtocol\n private var lastReachableMethodItem: ListAccessMethodItem?\n private var cancellables = Set<AnyCancellable>()\n\n private var dataSource: ListAccessMethodDataSource?\n private var fetchedItems: [ListAccessMethodItem] = []\n private let contentController = UITableViewController(style: .plain)\n private var tableView: UITableView {\n contentController.tableView\n }\n\n weak var delegate: ListAccessMethodViewControllerDelegate?\n\n /// Designated initializer.\n /// - Parameter interactor: the object implementing access and manipulation of the API access list.\n init(interactor: ListAccessMethodInteractorProtocol) {\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.backgroundColor = .secondaryColor\n\n tableView.delegate = self\n tableView.backgroundColor = .secondaryColor\n tableView.separatorColor = .secondaryColor\n tableView.separatorInset = .zero\n\n tableView.registerReusableViews(from: CellReuseIdentifier.self)\n\n view.setAccessibilityIdentifier(.apiAccessView)\n\n let headerView = createHeaderView()\n view.addConstrainedSubviews([headerView, tableView]) {\n headerView.pinEdgesToSuperviewMargins(PinnableEdges([.leading(8), .trailing(8), .top(0)]))\n tableView.pinEdgesToSuperview(.all().excluding(.top))\n tableView.topAnchor.constraint(equalTo: headerView.bottomAnchor, constant: 20)\n }\n\n addChild(contentController)\n contentController.didMove(toParent: self)\n\n interactor.itemsPublisher.sink { [weak self] _ in\n self?.updateDataSource(animated: true)\n }\n .store(in: &cancellables)\n\n interactor.itemInUsePublisher.sink { [weak self] item in\n self?.lastReachableMethodItem = item\n self?.updateDataSource(animated: true)\n }\n .store(in: &cancellables)\n\n configureNavigationItem()\n configureDataSource()\n }\n\n func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {\n guard let itemIdentifier = dataSource?.itemIdentifier(for: indexPath) else { return 0 }\n\n if itemIdentifier.id == lastReachableMethodItem?.id {\n return UITableView.automaticDimension\n } else {\n return UIMetrics.SettingsCell.apiAccessCellHeight\n }\n }\n\n func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {\n let container = UIView()\n\n let button = AppButton(style: .tableInsetGroupedDefault)\n button.setTitle(\n NSLocalizedString(\n "LIST_ACCESS_METHODS_ADD_BUTTON",\n tableName: "APIAccess",\n value: "Add",\n comment: ""\n ),\n for: .normal\n )\n button.addAction(UIAction { [weak self] _ in\n self?.sendAddNew()\n }, for: .touchUpInside)\n button.setAccessibilityIdentifier(.addAccessMethodButton)\n\n let fontSize = button.titleLabel?.font.pointSize ?? 0\n button.titleLabel?.font = UIFont.systemFont(ofSize: fontSize, weight: .regular)\n\n container.addConstrainedSubviews([button]) {\n button.pinEdgesToSuperview(.init([.top(40), .trailing(16), .bottom(0), .leading(16)]))\n }\n\n container.directionalLayoutMargins = UIMetrics.SettingsCell.apiAccessInsetLayoutMargins\n\n return container\n }\n\n func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {\n let item = fetchedItems[indexPath.row]\n sendEdit(item: item)\n }\n\n private func configureNavigationItem() {\n navigationItem.title = NSLocalizedString(\n "NAVIGATION_TITLE",\n tableName: "Settings",\n value: "API access",\n comment: ""\n )\n }\n\n private func createHeaderView() -> InfoHeaderView {\n let body = NSLocalizedString(\n "ACCESS_METHOD_HEADER_BODY",\n tableName: "APIAccess",\n value: "Manage default and setup custom methods to access the Mullvad API.",\n comment: ""\n )\n let link = NSLocalizedString(\n "ACCESS_METHOD_HEADER_LINK",\n tableName: "APIAccess",\n value: "About API access...",\n comment: ""\n )\n\n let headerView = InfoHeaderView(config: InfoHeaderConfig(body: body, link: link))\n\n headerView.onAbout = { [weak self] in\n self?.sendAbout()\n }\n\n return headerView\n }\n\n private func configureDataSource() {\n dataSource = ListAccessMethodDataSource(\n tableView: tableView,\n cellProvider: { [weak self] _, indexPath, itemIdentifier in\n self?.dequeueCell(at: indexPath, itemIdentifier: itemIdentifier)\n }\n )\n updateDataSource(animated: false)\n }\n\n private func updateDataSource(animated: Bool = true) {\n guard let dataSource else { return }\n fetchedItems = interactor.fetch()\n\n var snapshot = NSDiffableDataSourceSnapshot<ListAccessMethodSectionIdentifier, ListAccessMethodItemIdentifier>()\n snapshot.appendSections([.primary])\n\n let itemIdentifiers = fetchedItems.map { item in\n ListAccessMethodItemIdentifier(id: item.id)\n }\n snapshot.appendItems(itemIdentifiers, toSection: .primary)\n\n if dataSource.snapshot().numberOfItems == fetchedItems.count {\n for item in fetchedItems {\n snapshot.reloadItems([ListAccessMethodItemIdentifier(id: item.id)])\n }\n }\n\n dataSource.apply(snapshot, animatingDifferences: animated)\n }\n\n private func dequeueCell(\n at indexPath: IndexPath,\n itemIdentifier: ListAccessMethodItemIdentifier\n ) -> UITableViewCell {\n let cell = tableView.dequeueReusableView(withIdentifier: CellReuseIdentifier.default, for: indexPath)\n let item = fetchedItems[indexPath.row]\n\n var contentConfiguration = ListCellContentConfiguration()\n contentConfiguration.text = item.name\n contentConfiguration.secondaryText = item.detail\n contentConfiguration.tertiaryText = lastReachableMethodItem?.id == item.id\n ? NSLocalizedString("LIST_ACCESS_METHODS_IN_USE_ITEM", tableName: "APIAccess", value: "In use", comment: "")\n : ""\n cell.contentConfiguration = contentConfiguration\n\n if let cell = cell as? DynamicBackgroundConfiguration {\n cell.setAutoAdaptingBackgroundConfiguration(.mullvadListPlainCell(), selectionType: .dimmed)\n }\n\n if let cell = cell as? CustomCellDisclosureHandling {\n cell.disclosureType = .chevron\n }\n\n let accessibilityId: AccessibilityIdentifier? = switch item.id.uuidString {\n case AccessMethodRepository.directId.uuidString:\n AccessibilityIdentifier.accessMethodDirectCell\n case AccessMethodRepository.bridgeId.uuidString:\n AccessibilityIdentifier.accessMethodBridgesCell\n case AccessMethodRepository.encryptedDNSId.uuidString:\n AccessibilityIdentifier.accessMethodEncryptedDNSCell\n default:\n nil\n }\n cell.setAccessibilityIdentifier(accessibilityId)\n\n return cell\n }\n\n private func sendAddNew() {\n delegate?.controllerShouldAddNew(self)\n }\n\n private func sendAbout() {\n delegate?.controllerShouldShowAbout(self)\n }\n\n private func sendEdit(item: ListAccessMethodItem) {\n delegate?.controller(self, shouldEditItem: item)\n }\n}\n\nprivate enum CellReuseIdentifier: String, CaseIterable, CellIdentifierProtocol {\n case `default`\n\n var cellClass: AnyClass {\n switch self {\n case .default: BasicCell.self\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\List\ListAccessMethodViewController.swift
ListAccessMethodViewController.swift
Swift
8,749
0.95
0.046332
0.047847
awesome-app
51
2024-03-22T12:34:19.412109
GPL-3.0
false
dfaea476fdcb4656bd3250adc53a0b08
//\n// ListAccessMethodViewControllerDelegate.swift\n// MullvadVPN\n//\n// Created by pronebird on 23/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nprotocol ListAccessMethodViewControllerDelegate: AnyObject {\n /// The view controller requests the delegate to present the about view.\n ///\n /// - Parameter controller: the calling view controller.\n func controllerShouldShowAbout(_ controller: ListAccessMethodViewController)\n\n /// The view controller requests the delegate to present the add new method controller.\n ///\n /// - Parameter controller: the calling view controller.\n func controllerShouldAddNew(_ controller: ListAccessMethodViewController)\n\n /// The view controller requests the delegate to present the view controller for editing the existing access method.\n ///\n /// - Parameters:\n /// - controller: the calling view controller\n /// - item: the selected item.\n func controller(_ controller: ListAccessMethodViewController, shouldEditItem item: ListAccessMethodItem)\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\List\ListAccessMethodViewControllerDelegate.swift
ListAccessMethodViewControllerDelegate.swift
Swift
1,072
0.95
0.035714
0.75
python-kit
890
2024-02-21T16:10:41.544453
BSD-3-Clause
false
227798b78108ea10f3995b4f38c0195f
//\n// AccessMethodKind.swift\n// MullvadVPN\n//\n// Created by pronebird on 02/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadSettings\n\n/// A kind of API access method.\nenum AccessMethodKind: Equatable, Hashable, CaseIterable {\n /// Direct communication.\n case direct\n\n /// Communication over bridges.\n case bridges\n\n /// Communication over shadowsocks.\n case shadowsocks\n\n /// Communication over proxy address from a DNS.\n case encryptedDNS\n\n /// Communication over socks v5 proxy.\n case socks5\n\n /// Returns `true` if the method is permanent and cannot be deleted.\n var isPermanent: Bool {\n switch self {\n case .direct, .bridges, .encryptedDNS:\n true\n case .shadowsocks, .socks5:\n false\n }\n }\n\n /// Returns all access method kinds that can be added by user.\n static var allUserDefinedKinds: [AccessMethodKind] {\n allCases.filter { !$0.isPermanent }\n }\n\n /// Returns localized description describing the access method.\n var localizedDescription: String {\n switch self {\n case .direct, .bridges, .encryptedDNS:\n ""\n case .shadowsocks:\n NSLocalizedString("SHADOWSOCKS", tableName: "APIAccess", value: "Shadowsocks", comment: "")\n case .socks5:\n NSLocalizedString("SOCKS_V5", tableName: "APIAccess", value: "Socks5", comment: "").uppercased()\n }\n }\n\n /// Returns `true` if access method is configurable.\n /// Methods that aren't configurable do not offer any additional configuration.\n var hasProxyConfiguration: Bool {\n switch self {\n case .direct, .bridges, .encryptedDNS:\n false\n case .shadowsocks, .socks5:\n true\n }\n }\n}\n\nextension PersistentAccessMethod {\n /// A kind of access method.\n var kind: AccessMethodKind {\n switch proxyConfiguration {\n case .direct:\n .direct\n case .encryptedDNS:\n .encryptedDNS\n case .bridges:\n .bridges\n case .shadowsocks:\n .shadowsocks\n case .socks5:\n .socks5\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Models\AccessMethodKind.swift
AccessMethodKind.swift
Swift
2,214
0.95
0.071429
0.260274
react-lib
529
2025-01-15T19:55:06.753153
Apache-2.0
false
576e804298ba0c2eda2c8b9b5c5c7455
//\n// AccessMethodValidationError.swift\n// MullvadVPN\n//\n// Created by pronebird on 17/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\n\n/// Access method validation error that holds an array of individual per-field validation errors.\nstruct AccessMethodValidationError: LocalizedError, Equatable {\n /// The list of per-field errors.\n let fieldErrors: [AccessMethodFieldValidationError]\n\n var errorDescription: String? {\n if fieldErrors.count > 1 {\n NSLocalizedString(\n "VALIDATION_ERRORS_MULTIPLE",\n tableName: "APIAccess",\n value: "Multiple validation errors occurred.",\n comment: ""\n )\n } else {\n fieldErrors.first?.localizedDescription\n }\n }\n}\n\n/// Access method field validation error.\nstruct AccessMethodFieldValidationError: LocalizedError, Equatable {\n /// Validated field.\n enum Field: String, CustomStringConvertible, Equatable {\n case name, server, port, username, password\n\n var description: String {\n rawValue\n }\n }\n\n /// Validated field context.\n enum Context: String, CustomStringConvertible, Equatable {\n case socks, shadowsocks\n\n var description: String {\n rawValue\n }\n }\n\n /// Validation error kind.\n enum Kind: Equatable {\n /// The evaluated field is empty.\n case emptyValue\n\n /// Failure to parse IP address.\n case invalidIPAddress\n\n /// Invalid port number, i.e zero.\n case invalidPort\n\n /// The name input is too long.\n case nameTooLong\n }\n\n /// Kind of validation error.\n let kind: Kind\n\n /// Error field.\n let field: Field\n\n /// Validation field context.\n let context: Context\n\n var errorDescription: String? {\n switch kind {\n case .emptyValue:\n NSLocalizedString(\n "VALIDATION_ERRORS_EMPTY_FIELD",\n tableName: "APIAccess",\n value: "\(field) cannot be empty.",\n comment: ""\n )\n case .invalidIPAddress:\n NSLocalizedString(\n "VALIDATION_ERRORS_INVALD ADDRESS",\n tableName: "APIAccess",\n value: "Please enter a valid IPv4 or IPv6 address.",\n comment: ""\n )\n case .invalidPort:\n NSLocalizedString(\n "VALIDATION_ERRORS_INVALID_PORT",\n tableName: "APIAccess",\n value: "Please enter a valid port.",\n comment: ""\n )\n case .nameTooLong:\n String(\n format: NSLocalizedString(\n "VALIDATION_ERRORS_NAME_TOO_LONG",\n tableName: "APIAccess",\n value: "Name should be no longer than %i characters.",\n comment: ""\n ),\n NameInputFormatter.maxLength\n )\n }\n }\n}\n\nextension Collection<AccessMethodFieldValidationError> {\n var settingsFieldValidationErrors: [SettingsFieldValidationError] {\n map { SettingsFieldValidationError(errorDescription: $0.errorDescription) }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Models\AccessMethodValidationError.swift
AccessMethodValidationError.swift
Swift
3,278
0.95
0.017241
0.2
react-lib
419
2024-04-13T18:46:31.482464
BSD-3-Clause
false
e4420bd484cdfb3a1e73bde88e2baa03
//\n// AccessMethodViewModel+NavigationItem.swift\n// MullvadVPN\n//\n// Created by pronebird on 29/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nextension AccessMethodViewModel {\n /// Title suitable for navigation item.\n /// User-defined name is preferred unless it's blank, in which case the name of access method is used instead.\n var navigationItemTitle: String {\n if name.trimmingCharacters(in: .whitespaces).isEmpty {\n method.localizedDescription\n } else {\n name\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Models\AccessMethodViewModel+NavigationItem.swift
AccessMethodViewModel+NavigationItem.swift
Swift
576
0.95
0.095238
0.473684
python-kit
55
2024-06-16T09:22:12.306445
MIT
false
2a93bef177749a3df47b1d8959b6ed11
//\n// AccessMethodViewModel+Persistent.swift\n// MullvadVPN\n//\n// Created by pronebird on 15/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadSettings\nimport MullvadTypes\nimport Network\n\nextension AccessMethodViewModel {\n /// Validate view model. Throws on failure.\n ///\n /// - Throws: an instance of ``AccessMethodValidationError``.\n func validate() throws {\n _ = try intoPersistentAccessMethod()\n }\n\n /// Transform view model into persistent model that can be used with ``AccessMethodRepository``.\n ///\n /// - Throws: an instance of ``AccessMethodValidationError``.\n /// - Returns: an instance of ``PersistentAccessMethod``.\n func intoPersistentAccessMethod() throws -> PersistentAccessMethod {\n let configuration: PersistentProxyConfiguration\n\n do {\n configuration = try intoPersistentProxyConfiguration()\n } catch let error as AccessMethodValidationError {\n var fieldErrors = error.fieldErrors\n\n do {\n _ = try validateName()\n } catch let error as AccessMethodValidationError {\n fieldErrors.append(contentsOf: error.fieldErrors)\n }\n\n throw AccessMethodValidationError(fieldErrors: fieldErrors)\n }\n\n return PersistentAccessMethod(\n id: id,\n name: try validateName(),\n isEnabled: isEnabled,\n proxyConfiguration: configuration\n )\n }\n\n /// Transform view model's proxy configuration into persistent configuration that can be used with ``AccessMethodRepository``.\n ///\n /// - Throws: an instance of ``AccessMethodValidationError``.\n /// - Returns: an instance of ``PersistentProxyConfiguration``.\n func intoPersistentProxyConfiguration() throws -> PersistentProxyConfiguration {\n switch method {\n case .direct:\n .direct\n case .bridges:\n .bridges\n case .encryptedDNS:\n .encryptedDNS\n case .socks5:\n try socks.intoPersistentProxyConfiguration()\n case .shadowsocks:\n try shadowsocks.intoPersistentProxyConfiguration()\n }\n }\n\n private func validateName() throws -> String {\n // Context doesn't matter for name field errors.\n if name.isEmpty {\n let fieldError = AccessMethodFieldValidationError(kind: .emptyValue, field: .name, context: .shadowsocks)\n throw AccessMethodValidationError(fieldErrors: [fieldError])\n } else if name.count > NameInputFormatter.maxLength {\n let fieldError = AccessMethodFieldValidationError(kind: .nameTooLong, field: .name, context: .shadowsocks)\n throw AccessMethodValidationError(fieldErrors: [fieldError])\n }\n\n return name\n }\n}\n\nextension AccessMethodViewModel.Socks {\n /// Transform socks view model into persistent proxy configuration that can be used with ``AccessMethodRepository``.\n ///\n /// - Throws: an instance of ``AccessMethodValidationError``.\n /// - Returns: an instance of ``PersistentProxyConfiguration``.\n func intoPersistentProxyConfiguration() throws -> PersistentProxyConfiguration {\n var draftConfiguration = PersistentProxyConfiguration.SocksConfiguration(\n server: .ipv4(.loopback),\n port: 0,\n authentication: .noAuthentication\n )\n\n let context: AccessMethodFieldValidationError.Context = .socks\n var fieldErrors: [AccessMethodFieldValidationError] = []\n\n if server.isEmpty {\n fieldErrors.append(AccessMethodFieldValidationError(kind: .emptyValue, field: .server, context: context))\n } else {\n switch CommonValidators.parseIPAddress(from: server, context: context) {\n case let .success(serverAddress):\n draftConfiguration.server = serverAddress\n case let .failure(error):\n fieldErrors.append(error)\n }\n }\n\n if port.isEmpty {\n fieldErrors.append(AccessMethodFieldValidationError(kind: .emptyValue, field: .port, context: context))\n } else {\n switch CommonValidators.parsePort(from: port, context: context) {\n case let .success(port):\n draftConfiguration.port = port\n case let .failure(error):\n fieldErrors.append(error)\n }\n }\n\n if authenticate {\n if username.isEmpty {\n fieldErrors.append(\n AccessMethodFieldValidationError(kind: .emptyValue, field: .username, context: context)\n )\n }\n\n if password.isEmpty {\n fieldErrors.append(\n AccessMethodFieldValidationError(kind: .emptyValue, field: .password, context: context)\n )\n }\n\n if !(username.isEmpty && password.isEmpty) {\n draftConfiguration.authentication = .authentication(PersistentProxyConfiguration.UserCredential(\n username: username,\n password: password\n ))\n }\n }\n\n if fieldErrors.isEmpty {\n return .socks5(draftConfiguration)\n } else {\n throw AccessMethodValidationError(fieldErrors: fieldErrors)\n }\n }\n}\n\nextension AccessMethodViewModel.Shadowsocks {\n /// Transform shadowsocks view model into persistent proxy configuration that can be used with ``AccessMethodRepository``.\n ///\n /// - Throws: an instance of ``AccessMethodValidationError``.\n /// - Returns: an instance of ``PersistentProxyConfiguration``.\n func intoPersistentProxyConfiguration() throws -> PersistentProxyConfiguration {\n var draftConfiguration = PersistentProxyConfiguration.ShadowsocksConfiguration(\n server: .ipv4(.loopback),\n port: 0,\n password: "",\n cipher: .default\n )\n\n let context: AccessMethodFieldValidationError.Context = .shadowsocks\n var fieldErrors: [AccessMethodFieldValidationError] = []\n\n if server.isEmpty {\n fieldErrors.append(AccessMethodFieldValidationError(kind: .emptyValue, field: .server, context: context))\n } else {\n switch CommonValidators.parseIPAddress(from: server, context: context) {\n case let .success(serverAddress):\n draftConfiguration.server = serverAddress\n case let .failure(error):\n fieldErrors.append(error)\n }\n }\n\n if port.isEmpty {\n fieldErrors.append(AccessMethodFieldValidationError(kind: .emptyValue, field: .port, context: context))\n } else {\n switch CommonValidators.parsePort(from: port, context: context) {\n case let .success(port):\n draftConfiguration.port = port\n case let .failure(error):\n fieldErrors.append(error)\n }\n }\n\n draftConfiguration.password = password\n draftConfiguration.cipher = cipher\n\n if fieldErrors.isEmpty {\n return .shadowsocks(draftConfiguration)\n } else {\n throw AccessMethodValidationError(fieldErrors: fieldErrors)\n }\n }\n}\n\nprivate enum CommonValidators {\n /// Parse port from string.\n ///\n /// - Parameters:\n /// - value: a string input.\n /// - context: an input context.\n /// - Returns: a result containing a parsed port number on success, otherwise an instance of ``AccessMethodFieldValidationError``.\n static func parsePort(from value: String, context: AccessMethodFieldValidationError.Context)\n -> Result<UInt16, AccessMethodFieldValidationError> {\n guard let portNumber = UInt16(value) else {\n return .failure(AccessMethodFieldValidationError(kind: .invalidPort, field: .port, context: context))\n }\n\n guard portNumber > 0 else {\n return .failure(AccessMethodFieldValidationError(kind: .invalidPort, field: .port, context: context))\n }\n\n return .success(portNumber)\n }\n\n /// Parse IP address from string by using Apple's facilities.\n ///\n /// - Parameters:\n /// - value: a string input.\n /// - context: an input context\n /// - Returns: a result containing an IP address on success, otherwise an instance of ``AccessMethodFieldValidationError``.\n static func parseIPAddress(\n from value: String,\n context: AccessMethodFieldValidationError.Context\n ) -> Result<AnyIPAddress, AccessMethodFieldValidationError> {\n if let address = AnyIPAddress(value) {\n return .success(address)\n } else {\n return .failure(AccessMethodFieldValidationError(kind: .invalidIPAddress, field: .server, context: context))\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Models\AccessMethodViewModel+Persistent.swift
AccessMethodViewModel+Persistent.swift
Swift
8,862
0.95
0.114894
0.188406
awesome-app
166
2024-10-19T04:08:21.459795
MIT
false
350f0942bc28d95c566d1fa6926d4a64
//\n// AccessMethodViewModel.swift\n// MullvadVPN\n//\n// Created by pronebird on 14/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadSettings\nimport MullvadTypes\n\n/// The view model used by view controllers editing access method data.\nstruct AccessMethodViewModel: Identifiable {\n /// Socks configuration view model.\n struct Socks {\n /// Server IP address input.\n var server = ""\n /// Server port input.\n var port = ""\n /// Authentication username.\n var username = ""\n /// Authentication password.\n var password = ""\n /// Indicates whether authentication is enabled.\n var authenticate = false\n }\n\n /// Shadowsocks configuration view model.\n struct Shadowsocks {\n /// Server IP address input.\n var server = ""\n /// Server port input.\n var port = ""\n /// Server password.\n var password = ""\n /// Shadowsocks cipher.\n var cipher = ShadowsocksCipherOptions.default\n }\n\n /// Access method testing status view model.\n enum TestingStatus {\n /// The default state before the testing began.\n case initial\n /// Testing is in progress.\n case inProgress\n /// Testing failed.\n case failed\n /// Testing succeeded.\n case succeeded\n }\n\n /// The unique identifier used for referencing the access method entry in a persistent store.\n var id = UUID()\n\n /// The user-defined name for access method.\n var name = ""\n\n /// The selected access method kind.\n /// Determines which subview model is used when presenting proxy configuration in UI.\n var method: AccessMethodKind = .shadowsocks\n\n /// The flag indicating whether configuration is enabled.\n var isEnabled = true\n\n /// The status of testing the entered proxy configuration.\n var testingStatus: TestingStatus = .initial\n\n /// Socks configuration view model.\n var socks = Socks()\n\n /// Shadowsocks configuration view model.\n var shadowsocks = Shadowsocks()\n}\n\nextension AccessMethodViewModel {\n var infoHeaderConfig: InfoHeaderConfig? {\n switch id {\n case AccessMethodRepository.directId:\n InfoHeaderConfig(\n body: NSLocalizedString(\n "DIRECT_ACCESS_METHOD_HEADER_BODY",\n tableName: "APIAccess",\n value: "The app communicates with a Mullvad API server directly.",\n comment: ""\n ),\n link: NSLocalizedString(\n "DIRECT_ACCESS_METHOD_HEADER_LINK",\n tableName: "APIAccess",\n value: "About Direct method...",\n comment: ""\n )\n )\n case AccessMethodRepository.bridgeId:\n InfoHeaderConfig(\n body: NSLocalizedString(\n "BRIDGES_ACCESS_METHOD_HEADER_BODY",\n tableName: "APIAccess",\n value: "The app communicates with a Mullvad API server via a Mullvad bridge server.",\n comment: ""\n ),\n link: NSLocalizedString(\n "BRIDGES_ACCESS_METHOD_HEADER_LINK",\n tableName: "APIAccess",\n value: "About Mullvad bridges method...",\n comment: ""\n )\n )\n case AccessMethodRepository.encryptedDNSId:\n InfoHeaderConfig(\n body: NSLocalizedString(\n "ENCRYPTED_DNS_ACCESS_METHOD_HEADER_BODY",\n tableName: "APIAccess",\n value: "The app communicates with a Mullvad API server via a proxy address.",\n comment: ""\n ),\n link: NSLocalizedString(\n "ENCRYPTED_DNS_ACCESS_METHOD_HEADER_LINK",\n tableName: "APIAccess",\n value: "About Encrypted DNS proxy method...",\n comment: ""\n )\n )\n default:\n nil\n }\n }\n\n var infoModalConfig: InfoModalConfig? {\n switch id {\n case AccessMethodRepository.directId:\n InfoModalConfig(\n header: NSLocalizedString(\n "DIRECT_ACCESS_METHOD_MODAL_HEADER",\n tableName: "APIAccess",\n value: "Direct",\n comment: ""\n ),\n preamble: NSLocalizedString(\n "DIRECT_ACCESS_METHOD_MODAL_PREAMBLE",\n tableName: "APIAccess",\n value: "The app communicates with a Mullvad API server directly.",\n comment: ""\n ),\n body: [\n NSLocalizedString(\n "DIRECT_ACCESS_METHOD_MODAL_BODY_PART_1",\n tableName: "APIAccess",\n value: """\n With the "Direct" method, the app communicates with a Mullvad API server \\n directly without any intermediate proxies.\n """,\n comment: ""\n ),\n NSLocalizedString(\n "DIRECT_ACCESS_METHOD_MODAL_BODY_PART_2",\n tableName: "APIAccess",\n value: "This can be useful when you are not affected by censorship.",\n comment: ""\n ),\n ]\n )\n case AccessMethodRepository.bridgeId:\n InfoModalConfig(\n header: NSLocalizedString(\n "BRIDGES_ACCESS_METHOD_MODAL_HEADER",\n tableName: "APIAccess",\n value: "Mullvad bridges",\n comment: ""\n ),\n preamble: NSLocalizedString(\n "BRIDGES_ACCESS_METHOD_MODAL_PREAMBLE",\n tableName: "APIAccess",\n value: "The app communicates with a Mullvad API server via a Mullvad bridge server.",\n comment: ""\n ),\n body: [\n NSLocalizedString(\n "BRIDGES_ACCESS_METHOD_MODAL_BODY_PART_1",\n tableName: "APIAccess",\n value: """\n With the "Mullvad bridges" method, the app communicates with a Mullvad API server via a \\n Mullvad bridge server. It does this by sending the traffic obfuscated by Shadowsocks.\n """,\n comment: ""\n ),\n NSLocalizedString(\n "BRIDGES_ACCESS_METHOD_MODAL_BODY_PART_2",\n tableName: "APIAccess",\n value: "This can be useful if the API is censored but Mullvad’s bridge servers are not.",\n comment: ""\n ),\n ]\n )\n case AccessMethodRepository.encryptedDNSId:\n InfoModalConfig(\n header: NSLocalizedString(\n "ENCRYPTED_DNS_ACCESS_METHOD_MODAL_HEADER",\n tableName: "APIAccess",\n value: "Encrypted DNS proxy",\n comment: ""\n ),\n preamble: NSLocalizedString(\n "ENCRYPTED_DNS_ACCESS_METHOD_MODAL_PREAMBLE",\n tableName: "APIAccess",\n value: "The app communicates with a Mullvad API server via a proxy address.",\n comment: ""\n ),\n body: [\n NSLocalizedString(\n "ENCRYPTED_DNS_ACCESS_METHOD_MODAL_BODY_PART_1",\n tableName: "APIAccess",\n value: """\n With the "Encrypted DNS proxy" method, the app will communicate with our \\n Mullvad API through a proxy address.\n It does this by retrieving an address from a DNS over HTTPS (DoH) server and \\n then using that to reach our API servers.\n """,\n comment: ""\n ),\n NSLocalizedString(\n "ENCRYPTED_DNS_ACCESS_METHOD_MODAL_BODY_PART_2",\n tableName: "APIAccess",\n value: """\n If you are not connected to our VPN, then the Encrypted DNS proxy will use your own non-VPN IP \\n when connecting.\n The DoH servers are hosted by one of the following providers: Quad9 or Cloudflare.\n """,\n comment: ""\n ),\n ]\n )\n default:\n nil\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Models\AccessMethodViewModel.swift
AccessMethodViewModel.swift
Swift
9,042
0.95
0.021097
0.142857
python-kit
901
2025-01-16T03:50:08.241382
BSD-3-Clause
false
fc5e3559a4a496fb35dacc15f9d613d2
//\n// PersistentAccessMethod+ViewModel.swift\n// MullvadVPN\n//\n// Created by pronebird on 17/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadSettings\n\nextension PersistentAccessMethod {\n /// Convert persistent model into view model.\n /// - Returns: an instance of ``AccessMethodViewModel``.\n func toViewModel() -> AccessMethodViewModel {\n AccessMethodViewModel(\n id: id,\n name: name,\n method: kind,\n isEnabled: isEnabled,\n socks: proxyConfiguration.socksViewModel,\n shadowsocks: proxyConfiguration.shadowsocksViewModel\n )\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Models\PersistentAccessMethod+ViewModel.swift
PersistentAccessMethod+ViewModel.swift
Swift
677
0.95
0
0.391304
awesome-app
776
2023-07-30T17:29:15.736641
GPL-3.0
false
e8d56ffc744b5df281e1dda66bdc9937
//\n// PersistentProxyConfiguration+ViewModel.swift\n// MullvadVPN\n//\n// Created by pronebird on 29/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadSettings\n\nextension PersistentProxyConfiguration {\n /// View model for socks configuration.\n var socksViewModel: AccessMethodViewModel.Socks {\n guard case let .socks5(config) = self else {\n return AccessMethodViewModel.Socks()\n }\n\n var socks = AccessMethodViewModel.Socks(\n server: "\(config.server)",\n port: "\(config.port)"\n )\n\n switch config.authentication {\n case let .authentication(userCredential):\n socks.username = userCredential.username\n socks.password = userCredential.password\n socks.authenticate = true\n\n case .noAuthentication:\n socks.authenticate = false\n }\n\n return socks\n }\n\n /// View model for shadowsocks configuration.\n var shadowsocksViewModel: AccessMethodViewModel.Shadowsocks {\n guard case let .shadowsocks(config) = self else {\n return AccessMethodViewModel.Shadowsocks()\n }\n return AccessMethodViewModel.Shadowsocks(\n server: "\(config.server)",\n port: "\(config.port)",\n password: config.password,\n cipher: config.cipher\n )\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Models\PersistentProxyConfiguration+ViewModel.swift
PersistentProxyConfiguration+ViewModel.swift
Swift
1,402
0.95
0.061224
0.214286
awesome-app
344
2025-06-27T23:44:37.512271
BSD-3-Clause
false
098d56788f6e52f4dbe374774c5161ef
//\n// AccessMethodProtocolPicker.swift\n// MullvadVPN\n//\n// Created by pronebird on 14/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\nimport UIKit\n\n/// Type implementing the access method protocol picker.\n@MainActor\nstruct AccessMethodProtocolPicker {\n /// The navigation controller used for presenting the picker.\n let navigationController: UINavigationController\n\n /// Push access method protocol picker onto the navigation stack.\n /// - Parameters:\n /// - currentValue: current selection.\n /// - completion: a completion handler.\n func present(currentValue: AccessMethodKind, completion: @escaping (AccessMethodKind) -> Void) {\n let navigationController = navigationController\n\n let dataSource = AccessMethodProtocolPickerDataSource()\n let controller = ListItemPickerViewController(dataSource: dataSource, selectedItemID: currentValue)\n controller.view.setAccessibilityIdentifier(.accessMethodProtocolPickerView)\n\n controller.navigationItem.title = NSLocalizedString(\n "SELECT_PROTOCOL_NAV_TITLE",\n tableName: "APIAccess",\n value: "Type",\n comment: ""\n )\n\n controller.onSelect = { selectedItem in\n navigationController.popViewController(animated: true)\n completion(selectedItem.method)\n }\n\n navigationController.pushViewController(controller, animated: true)\n }\n}\n\n/// Type implementing the data source for the access method protocol picker.\nstruct AccessMethodProtocolPickerDataSource: ListItemDataSourceProtocol {\n struct Item: ListItemDataSourceItem {\n let method: AccessMethodKind\n\n var id: AccessMethodKind { method }\n var text: String { method.localizedDescription }\n }\n\n let items: [Item] = AccessMethodKind.allUserDefinedKinds.map { Item(method: $0) }\n\n var itemCount: Int {\n items.count\n }\n\n func item(at indexPath: IndexPath) -> Item {\n items[indexPath.row]\n }\n\n func indexPath(for itemID: AccessMethodKind) -> IndexPath? {\n guard let index = items.firstIndex(where: { $0.id == itemID }) else { return nil }\n\n return IndexPath(row: index, section: 0)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Pickers\AccessMethodProtocolPicker.swift
AccessMethodProtocolPicker.swift
Swift
2,252
0.95
0.043478
0.254545
awesome-app
163
2025-01-17T00:33:35.655707
BSD-3-Clause
false
de6d9118788957ccd4c80744f3263936
//\n// ShadowsocksCipherPicker.swift\n// MullvadVPN\n//\n// Created by pronebird on 14/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\nimport UIKit\n\n/// Type implementing the shadowsocks cipher picker.\n@MainActor\nstruct ShadowsocksCipherPicker {\n /// The navigation controller used for presenting the picker.\n let navigationController: UINavigationController\n\n /// Push shadowsocks cipher picker onto the navigation stack.\n /// - Parameters:\n /// - currentValue: current selection.\n /// - completion: a completion handler.\n func present(currentValue: ShadowsocksCipherOptions, completion: @escaping (ShadowsocksCipherOptions) -> Void) {\n let navigationController = navigationController\n\n let dataSource = ShadowsocksCipherPickerDataSource()\n let controller = ListItemPickerViewController(dataSource: dataSource, selectedItemID: currentValue)\n\n controller.navigationItem.title = NSLocalizedString(\n "SELECT_SHADOWSOCKS_CIPHER_NAV_TITLE",\n tableName: "APIAccess",\n value: "Cipher",\n comment: ""\n )\n\n controller.onSelect = { selectedItem in\n navigationController.popViewController(animated: true)\n completion(selectedItem.cipher)\n }\n\n navigationController.pushViewController(controller, animated: true)\n }\n}\n\n/// Type implementing the data source for the shadowsocks cipher picker.\nstruct ShadowsocksCipherPickerDataSource: ListItemDataSourceProtocol {\n struct Item: ListItemDataSourceItem {\n let cipher: ShadowsocksCipherOptions\n\n var id: ShadowsocksCipherOptions { cipher }\n var text: String { "\(cipher.rawValue.description)" }\n }\n\n let items = ShadowsocksCipherOptions.all.map { Item(cipher: $0) }\n\n var itemCount: Int {\n items.count\n }\n\n func item(at indexPath: IndexPath) -> Item {\n items[indexPath.row]\n }\n\n func indexPath(for itemID: ShadowsocksCipherOptions) -> IndexPath? {\n guard let index = items.firstIndex(where: { $0.id == itemID }) else { return nil }\n\n return IndexPath(row: index, section: 0)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\APIAccess\Pickers\ShadowsocksCipherPicker.swift
ShadowsocksCipherPicker.swift
Swift
2,185
0.95
0.044118
0.259259
react-lib
83
2025-04-17T14:02:54.380713
Apache-2.0
false
c22f77314692b09b52ecdbd6525ef93a
//\n// DAITASettingsCoordinator.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2025-01-20.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Routing\nimport SwiftUI\n\nclass DAITASettingsCoordinator: Coordinator, SettingsChildCoordinator, Presentable, Presenting {\n private let navigationController: UINavigationController\n private let viewModel: DAITATunnelSettingsViewModel\n private var alertPresenter: AlertPresenter?\n private let route: AppRoute\n\n var presentedViewController: UIViewController {\n navigationController\n }\n\n var didFinish: ((DAITASettingsCoordinator) -> Void)?\n\n init(\n navigationController: UINavigationController,\n route: AppRoute,\n viewModel: DAITATunnelSettingsViewModel\n ) {\n self.navigationController = navigationController\n self.route = route\n self.viewModel = viewModel\n\n super.init()\n\n alertPresenter = AlertPresenter(context: self)\n }\n\n func start(animated: Bool) {\n let view = SettingsDAITAView(tunnelViewModel: self.viewModel)\n\n viewModel.didFailDAITAValidation = { [weak self] result in\n guard let self else { return }\n\n showPrompt(\n for: result.item,\n onSave: {\n self.viewModel.value = result.setting\n },\n onDiscard: {}\n )\n }\n\n let host = UIHostingController(rootView: view)\n host.title = NSLocalizedString(\n "NAVIGATION_TITLE_DAITA",\n tableName: "Settings",\n value: "DAITA",\n comment: ""\n )\n host.view.setAccessibilityIdentifier(.daitaView)\n customiseNavigation(on: host)\n\n navigationController.pushViewController(host, animated: animated)\n }\n\n private func customiseNavigation(on viewController: UIViewController) {\n if route == .daita {\n navigationController.navigationItem.largeTitleDisplayMode = .always\n navigationController.navigationBar.prefersLargeTitles = true\n\n let doneButton = UIBarButtonItem(\n systemItem: .done,\n primaryAction: UIAction(handler: { [weak self] _ in\n guard let self else { return }\n didFinish?(self)\n })\n )\n viewController.navigationItem.rightBarButtonItem = doneButton\n }\n }\n\n private func showPrompt(\n for item: DAITASettingsPromptItem,\n onSave: @escaping () -> Void,\n onDiscard: @escaping () -> Void\n ) {\n let presentation = AlertPresentation(\n id: "settings-daita-prompt",\n accessibilityIdentifier: .daitaPromptAlert,\n icon: .warning,\n message: NSLocalizedString(\n "SETTINGS_DAITA_ENABLE_TEXT",\n tableName: "DAITA",\n value: item.description,\n comment: ""\n ),\n buttons: [\n AlertAction(\n title: String(format: NSLocalizedString(\n "SETTINGS_DAITA_ENABLE_OK_ACTION",\n tableName: "DAITA",\n value: "Enable \"%@\"",\n comment: ""\n ), item.title),\n style: .default,\n accessibilityId: .daitaConfirmAlertEnableButton,\n handler: { onSave() }\n ),\n AlertAction(\n title: NSLocalizedString(\n "SETTINGS_DAITA_ENABLE_CANCEL_ACTION",\n tableName: "DAITA",\n value: "Cancel",\n comment: ""\n ),\n style: .default,\n handler: { onDiscard() }\n ),\n ]\n )\n\n alertPresenter?.showAlert(presentation: presentation, animated: true)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\DAITA\DAITASettingsCoordinator.swift
DAITASettingsCoordinator.swift
Swift
3,974
0.95
0.032258
0.064815
node-utils
267
2024-02-03T19:19:19.532192
Apache-2.0
false
c696b99964c19043f156f91630bc2413
//\n// DAITASettingsPromptItem.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(Setting)\n case daitaSettingIncompatibleWithMultihop(Setting)\n\n enum Setting {\n case daita\n case directOnly\n }\n\n var title: String {\n switch self {\n case let .daitaSettingIncompatibleWithSinglehop(setting), let .daitaSettingIncompatibleWithMultihop(setting):\n switch setting {\n case .daita:\n "DAITA"\n case .directOnly:\n "Direct only"\n }\n }\n }\n\n var description: String {\n switch self {\n case .daitaSettingIncompatibleWithSinglehop:\n """\n DAITA isn't available at the currently selected location. After enabling, please go to \\n the "Select location" view and select a location that supports DAITA.\n """\n case .daitaSettingIncompatibleWithMultihop:\n """\n DAITA isn't available on the current entry server. After enabling, please go to the \\n "Select location" view and select an entry location that supports DAITA.\n """\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\DAITA\DAITASettingsPromptItem.swift
DAITASettingsPromptItem.swift
Swift
1,348
0.95
0.066667
0.170732
react-lib
913
2024-01-09T20:28:44.265822
MIT
false
9f31a4191a9f4be08905393c54c32b37
//\n// DAITATunnelSettingsViewModel.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-11-21.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadREST\nimport MullvadSettings\n\nclass DAITATunnelSettingsViewModel: TunnelSettingsObserver, ObservableObject {\n typealias TunnelSetting = DAITASettings\n\n let tunnelManager: TunnelManager\n var tunnelObserver: TunnelObserver?\n\n var didFailDAITAValidation: (((item: DAITASettingsPromptItem, setting: DAITASettings)) -> Void)?\n\n var value: DAITASettings {\n willSet {\n guard newValue != value else { return }\n\n objectWillChange.send()\n tunnelManager.updateSettings([.daita(newValue)])\n }\n }\n\n required init(tunnelManager: TunnelManager) {\n self.tunnelManager = tunnelManager\n value = tunnelManager.settings.daita\n\n tunnelObserver = TunnelBlockObserver(didUpdateTunnelSettings: { [weak self] _, newSettings in\n self?.value = newSettings.daita\n })\n }\n\n func evaluate(setting: DAITASettings) {\n if let error = evaluateDaitaSettingsCompatibility(setting) {\n let promptItem = promptItem(from: error, setting: setting)\n\n didFailDAITAValidation?((item: promptItem, setting: setting))\n return\n }\n\n value = setting\n }\n}\n\nextension DAITATunnelSettingsViewModel {\n private func promptItem(\n from error: DAITASettingsCompatibilityError,\n setting: DAITASettings\n ) -> DAITASettingsPromptItem {\n let promptItemSetting: DAITASettingsPromptItem.Setting = if setting.daitaState != value.daitaState {\n .daita\n } else {\n .directOnly\n }\n\n var promptItem: DAITASettingsPromptItem\n\n switch error {\n case .singlehop:\n promptItem = .daitaSettingIncompatibleWithSinglehop(promptItemSetting)\n case .multihop:\n promptItem = .daitaSettingIncompatibleWithMultihop(promptItemSetting)\n }\n\n return promptItem\n }\n\n private func evaluateDaitaSettingsCompatibility(_ settings: DAITASettings) -> DAITASettingsCompatibilityError? {\n guard settings.daitaState.isEnabled else { return nil }\n\n var tunnelSettings = tunnelManager.settings\n tunnelSettings.daita = settings\n\n var compatibilityError: DAITASettingsCompatibilityError?\n\n do {\n _ = try tunnelManager.selectRelays(tunnelSettings: tunnelSettings)\n } catch let error as NoRelaysSatisfyingConstraintsError where error.reason == .noDaitaRelaysFound {\n // Return error if no relays could be selected due to DAITA constraints.\n compatibilityError = tunnelSettings.tunnelMultihopState.isEnabled ? .multihop : .singlehop\n } catch _ as NoRelaysSatisfyingConstraintsError {\n // Even if the constraints error is not DAITA specific, if both DAITA and Direct only are enabled,\n // we should return a DAITA related error since the current settings would have resulted in the\n // relay selector not being able to select a DAITA relay anyway.\n if settings.isDirectOnly {\n compatibilityError = tunnelSettings.tunnelMultihopState.isEnabled ? .multihop : .singlehop\n }\n } catch {}\n\n return compatibilityError\n }\n}\n\nclass MockDAITATunnelSettingsViewModel: TunnelSettingsObservable {\n @Published var value: DAITASettings\n\n init(daitaSettings: DAITASettings = DAITASettings()) {\n value = daitaSettings\n }\n\n func evaluate(setting: MullvadSettings.DAITASettings) {}\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\DAITA\DAITATunnelSettingsViewModel.swift
DAITATunnelSettingsViewModel.swift
Swift
3,627
0.95
0.121495
0.130952
react-lib
261
2025-05-26T07:03:26.215805
BSD-3-Clause
false
391baa68d19e396f79f13da082845397
//\n// SettingsDAITAView.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-11-14.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\nimport SwiftUI\n\nstruct SettingsDAITAView<ViewModel>: View where ViewModel: TunnelSettingsObservable<DAITASettings> {\n @StateObject var tunnelViewModel: ViewModel\n\n var body: some View {\n SettingsInfoContainerView {\n VStack(alignment: .leading, spacing: 8) {\n SettingsInfoView(viewModel: dataViewModel)\n\n VStack {\n GroupedRowView {\n SwitchRowView(\n isOn: daitaIsEnabled,\n text: NSLocalizedString(\n "SETTINGS_SWITCH_DAITA_ENABLE",\n tableName: "Settings",\n value: "Enable",\n comment: ""\n ),\n accessibilityId: .daitaSwitch\n )\n RowSeparator()\n SwitchRowView(\n isOn: directOnlyIsEnabled,\n disabled: !daitaIsEnabled.wrappedValue,\n text: NSLocalizedString(\n "SETTINGS_SWITCH_DAITA_DIRECT_ONLY",\n tableName: "Settings",\n value: "Direct only",\n comment: ""\n ),\n accessibilityId: .daitaDirectOnlySwitch\n )\n }\n\n SettingsRowViewFooter(\n text: NSLocalizedString(\n "SETTINGS_SWITCH_DAITA_ENABLE",\n tableName: "Settings",\n value: """\n By enabling "Direct only" you will have to manually select a server that \\n is DAITA-enabled. Multihop won't automatically be used to enable DAITA with \\n any server.\n """,\n comment: ""\n )\n )\n }\n .padding(.leading, UIMetrics.contentInsets.left)\n .padding(.trailing, UIMetrics.contentInsets.right)\n }\n }\n }\n}\n\n#Preview {\n SettingsDAITAView(tunnelViewModel: MockDAITATunnelSettingsViewModel())\n}\n\nextension SettingsDAITAView {\n var daitaIsEnabled: Binding<Bool> {\n Binding<Bool>(\n get: {\n tunnelViewModel.value.daitaState.isEnabled\n }, set: { enabled in\n var settings = tunnelViewModel.value\n settings.daitaState.isEnabled = enabled\n\n tunnelViewModel.evaluate(setting: settings)\n }\n )\n }\n\n var directOnlyIsEnabled: Binding<Bool> {\n Binding<Bool>(\n get: {\n tunnelViewModel.value.directOnlyState.isEnabled\n }, set: { enabled in\n var settings = tunnelViewModel.value\n settings.directOnlyState.isEnabled = enabled\n\n tunnelViewModel.evaluate(setting: settings)\n }\n )\n }\n}\n\nextension SettingsDAITAView {\n private var dataViewModel: SettingsInfoViewModel {\n SettingsInfoViewModel(\n pages: [\n SettingsInfoViewModelPage(\n body: NSLocalizedString(\n "SETTINGS_INFO_DAITA_PAGE_1",\n tableName: "Settings",\n value: """\n **Attention: This increases network traffic and will also negatively affect speed, latency, \\n and battery usage. Use with caution on limited plans.**\n\n DAITA (Defense against AI-guided Traffic Analysis) hides patterns in \\n your encrypted VPN traffic.\n\n By using sophisticated AI it’s possible to analyze the traffic of data \\n packets going in and out of your device (even if the traffic is encrypted).\n """,\n comment: ""\n ),\n image: .daitaOffIllustration\n ),\n SettingsInfoViewModelPage(\n body: NSLocalizedString(\n "SETTINGS_INFO_DAITA_PAGE_2",\n tableName: "Settings",\n value: """\n If an observer monitors these data packets, DAITA makes it significantly \\n harder for them to identify which websites you are visiting or with whom \\n you are communicating.\n\n DAITA does this by carefully adding network noise and making all network \\n packets the same size.\n\n Not all our servers are DAITA-enabled. Therefore, we use multihop \\n automatically to enable DAITA with any server.\n\n """,\n comment: ""\n ),\n image: .daitaOnIllustration\n ),\n ]\n )\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\DAITA\SettingsDAITAView.swift
SettingsDAITAView.swift
Swift
5,388
0.95
0.013986
0.070866
python-kit
829
2025-07-06T13:16:47.136386
Apache-2.0
false
991b6f3869a6e84690b27497257bd4cc
//\n// IPOverrideCoordinator.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-01-15.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\nimport MullvadTypes\nimport Routing\nimport UIKit\n\nclass IPOverrideCoordinator: Coordinator, Presenting, SettingsChildCoordinator {\n private let navigationController: UINavigationController\n private let interactor: IPOverrideInteractor\n\n var presentationContext: UIViewController {\n navigationController\n }\n\n init(\n navigationController: UINavigationController,\n repository: IPOverrideRepositoryProtocol,\n tunnelManager: TunnelManager\n ) {\n self.navigationController = navigationController\n interactor = IPOverrideInteractor(repository: repository, tunnelManager: tunnelManager)\n }\n\n func start(animated: Bool) {\n let controller = IPOverrideViewController(\n interactor: interactor,\n alertPresenter: AlertPresenter(context: self)\n )\n\n controller.delegate = self\n\n navigationController.pushViewController(controller, animated: animated)\n }\n}\n\nextension IPOverrideCoordinator: @preconcurrency IPOverrideViewControllerDelegate {\n func presentImportTextController() {\n let viewController = IPOverrideTextViewController(interactor: interactor)\n let customNavigationController = CustomNavigationController(rootViewController: viewController)\n\n presentationContext.present(customNavigationController, animated: true)\n }\n\n func presentAbout() {\n let header = NSLocalizedString(\n "IP_OVERRIDE_HEADER",\n tableName: "IPOverride",\n value: "Server IP override",\n comment: ""\n )\n let body = [\n NSLocalizedString(\n "IP_OVERRIDE_BODY_1",\n tableName: "IPOverride",\n value: """\n On some networks, where various types of censorship are being used, our server IP addresses are \\n sometimes blocked.\n """,\n comment: ""\n ),\n NSLocalizedString(\n "IP_OVERRIDE_BODY_2",\n tableName: "IPOverride",\n value: """\n To circumvent this you can import a file or a text, provided by our support team, \\n with new IP addresses that override the default addresses of the servers in the Select location view.\n """,\n comment: ""\n ),\n NSLocalizedString(\n "IP_OVERRIDE_BODY_3",\n tableName: "IPOverride",\n value: """\n If you are having issues connecting to VPN servers, please contact support.\n """,\n comment: ""\n ),\n ]\n\n let aboutController = AboutViewController(header: header, preamble: nil, body: body)\n let aboutNavController = UINavigationController(rootViewController: aboutController)\n\n aboutController.navigationItem.rightBarButtonItem = UIBarButtonItem(\n systemItem: .done,\n primaryAction: UIAction { [weak aboutNavController] _ in\n aboutNavController?.dismiss(animated: true)\n }\n )\n\n navigationController.present(aboutNavController, animated: true)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\IPOverride\IPOverrideCoordinator.swift
IPOverrideCoordinator.swift
Swift
3,376
0.95
0.010101
0.081395
python-kit
199
2025-05-07T08:30:07.991236
BSD-3-Clause
false
99c6d79a3fa769b9c159ec8d94ebe2e8
//\n// IPOverrideInteractor.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-01-30.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport MullvadLogging\nimport MullvadSettings\nimport MullvadTypes\n\nfinal class IPOverrideInteractor {\n private let logger = Logger(label: "IPOverrideInteractor")\n private let repository: IPOverrideRepositoryProtocol\n private let tunnelManager: TunnelManager\n private var statusWorkItem: DispatchWorkItem?\n\n private let statusSubject = CurrentValueSubject<IPOverrideStatus, Never>(.noImports)\n var statusPublisher: AnyPublisher<IPOverrideStatus, Never> {\n statusSubject.eraseToAnyPublisher()\n }\n\n var defaultStatus: IPOverrideStatus {\n if repository.fetchAll().isEmpty {\n return .noImports\n } else {\n return .active\n }\n }\n\n init(repository: IPOverrideRepositoryProtocol, tunnelManager: TunnelManager) {\n self.repository = repository\n self.tunnelManager = tunnelManager\n\n resetToDefaultStatus()\n }\n\n func `import`(url: URL) {\n let data = (try? Data(contentsOf: url)) ?? Data()\n handleImport(of: data, context: .file)\n }\n\n func `import`(text: String) {\n let data = text.data(using: .utf8) ?? Data()\n handleImport(of: data, context: .text)\n }\n\n func deleteAllOverrides() {\n repository.deleteAll()\n\n updateTunnel()\n resetToDefaultStatus()\n }\n\n private func handleImport(of data: Data, context: IPOverrideStatus.Context) {\n do {\n let overrides = try repository.parse(data: data)\n\n repository.add(overrides)\n statusSubject.send(.importSuccessful(context))\n } catch {\n statusSubject.send(.importFailed(context))\n logger.error("Error importing ip overrides: \(error)")\n }\n\n updateTunnel()\n\n // After an import - successful or not - the UI should be reset back to default\n // state after a certain amount of time.\n resetToDefaultStatus(delay: .seconds(10))\n }\n\n private func updateTunnel() {\n do {\n try tunnelManager.refreshRelayCacheTracker()\n } catch {\n logger.error(error: error, message: "Could not refresh relay cache tracker.")\n }\n\n switch tunnelManager.tunnelStatus.observedState {\n case .connecting, .connected, .reconnecting:\n tunnelManager.reconnectTunnel(selectNewRelay: true)\n default:\n break\n }\n }\n\n private func resetToDefaultStatus(delay: Duration = .zero) {\n statusWorkItem?.cancel()\n\n let statusWorkItem = DispatchWorkItem { [weak self] in\n guard let self, self.statusWorkItem?.isCancelled == false else { return }\n self.statusSubject.send(self.defaultStatus)\n }\n self.statusWorkItem = statusWorkItem\n\n DispatchQueue.main.asyncAfter(deadline: .now() + delay.timeInterval, execute: statusWorkItem)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\IPOverride\IPOverrideInteractor.swift
IPOverrideInteractor.swift
Swift
3,025
0.95
0.079208
0.109756
react-lib
161
2024-06-11T12:28:32.212473
BSD-3-Clause
false
c5ad6a6b57dce9a5dcc1caaa31fcd03c
//\n// IPOverrideStatus.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-01-17.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nenum IPOverrideStatus: Equatable, CustomStringConvertible {\n case active, noImports, importSuccessful(Context), importFailed(Context)\n\n enum Context {\n case file, text\n\n // Used in "statusDescription" below to form a complete sentence and therefore not localized here.\n var description: String {\n switch self {\n case .file: "of file"\n case .text: "via text"\n }\n }\n }\n\n var title: String {\n switch self {\n case .active:\n NSLocalizedString(\n "IP_OVERRIDE_STATUS_TITLE_ACTIVE",\n tableName: "IPOverride",\n value: "Overrides active",\n comment: ""\n )\n case .noImports, .importFailed:\n NSLocalizedString(\n "IP_OVERRIDE_STATUS_TITLE_NO_IMPORTS",\n tableName: "IPOverride",\n value: "No overrides imported",\n comment: ""\n )\n case .importSuccessful:\n NSLocalizedString(\n "IP_OVERRIDE_STATUS_TITLE_IMPORT_SUCCESSFUL",\n tableName: "IPOverride",\n value: "Import successful",\n comment: ""\n )\n }\n }\n\n var icon: UIImage? {\n let titleConfiguration = UIImage.SymbolConfiguration(textStyle: .body)\n let weightConfiguration = UIImage.SymbolConfiguration(weight: .bold)\n let combinedConfiguration = titleConfiguration.applying(weightConfiguration)\n\n switch self {\n case .active, .noImports:\n return nil\n case .importFailed:\n return UIImage(systemName: "xmark", withConfiguration: combinedConfiguration)?\n .withRenderingMode(.alwaysOriginal)\n .withTintColor(.dangerColor)\n case .importSuccessful:\n return UIImage(systemName: "checkmark", withConfiguration: combinedConfiguration)?\n .withRenderingMode(.alwaysOriginal)\n .withTintColor(.successColor)\n }\n }\n\n var description: String {\n switch self {\n case .active, .noImports:\n ""\n case let .importFailed(context):\n String(format: NSLocalizedString(\n "IP_OVERRIDE_STATUS_DESCRIPTION_INACTIVE",\n tableName: "IPOverride",\n value: "Import %@ was unsuccessful, please try again.",\n comment: ""\n ), context.description)\n case let .importSuccessful(context):\n String(format: NSLocalizedString(\n "IP_OVERRIDE_STATUS_DESCRIPTION_INACTIVE",\n tableName: "IPOverride",\n value: "Import %@ was successful, overrides are now active.",\n comment: ""\n ), context.description)\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\IPOverride\IPOverrideStatus.swift
IPOverrideStatus.swift
Swift
2,999
0.95
0.054945
0.096386
awesome-app
530
2024-07-21T03:14:04.671946
MIT
false
dde45b87d3ad50fc3fb9da45ae2172d7
//\n// IPOverrideStatusView.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-01-17.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass IPOverrideStatusView: UIView {\n private lazy var titleLabel: UILabel = {\n let label = UILabel()\n label.font = .systemFont(ofSize: 15, weight: .bold)\n label.textColor = .white\n return label\n }()\n\n private lazy var statusIcon: UIImageView = {\n return UIImageView()\n }()\n\n private lazy var descriptionLabel: UILabel = {\n let label = UILabel()\n label.font = .systemFont(ofSize: 12, weight: .semibold)\n label.textColor = .white.withAlphaComponent(0.6)\n label.numberOfLines = 0\n return label\n }()\n\n init() {\n super.init(frame: .zero)\n\n let titleContainerView = UIStackView(arrangedSubviews: [titleLabel, statusIcon, UIView()])\n titleContainerView.spacing = 6\n\n let contentContainterView = UIStackView(arrangedSubviews: [\n titleContainerView,\n descriptionLabel,\n ])\n contentContainterView.axis = .vertical\n contentContainterView.spacing = 4\n\n addConstrainedSubviews([contentContainterView]) {\n contentContainterView.pinEdgesToSuperview()\n }\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n func setStatus(_ status: IPOverrideStatus) {\n titleLabel.text = status.title.uppercased()\n statusIcon.image = status.icon\n descriptionLabel.text = status.description\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\IPOverride\IPOverrideStatusView.swift
IPOverrideStatusView.swift
Swift
1,610
0.95
0.017241
0.145833
awesome-app
988
2025-06-19T03:44:07.480035
BSD-3-Clause
false
a27fa492fcdc8e74f1a5664446c7d185
//\n// IPOverrideTextViewController.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-01-16.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass IPOverrideTextViewController: UIViewController {\n private let interactor: IPOverrideInteractor\n private var textView = CustomTextView()\n\n private lazy var importButton: UIBarButtonItem = {\n return UIBarButtonItem(\n title: NSLocalizedString(\n "IMPORT_TEXT_IMPORT_BUTTON",\n tableName: "IPOverride",\n value: "Import",\n comment: ""\n ),\n primaryAction: UIAction(handler: { [weak self] _ in\n self?.interactor.import(text: self?.textView.text ?? "")\n self?.dismiss(animated: true)\n })\n )\n }()\n\n init(interactor: IPOverrideInteractor) {\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.backgroundColor = .secondaryColor\n\n navigationItem.title = NSLocalizedString(\n "IMPORT_TEXT_NAVIGATION_TITLE",\n tableName: "IPOverride",\n value: "Import via text",\n comment: ""\n )\n\n navigationItem.leftBarButtonItem = UIBarButtonItem(\n systemItem: .cancel,\n primaryAction: UIAction(handler: { [weak self] _ in\n self?.dismiss(animated: true)\n })\n )\n\n importButton.isEnabled = !textView.text.isEmpty\n navigationItem.rightBarButtonItem = importButton\n\n textView.becomeFirstResponder()\n textView.delegate = self\n textView.spellCheckingType = .no\n textView.autocorrectionType = .no\n textView.textColor = UIColor.label\n textView.font = UIFont.monospacedSystemFont(\n ofSize: UIFont.systemFont(ofSize: 14).pointSize,\n weight: .regular\n )\n\n view.addConstrainedSubviews([textView]) {\n textView.pinEdgesToSuperview(.all().excluding(.top))\n textView.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor, constant: 0)\n }\n }\n}\n\nextension IPOverrideTextViewController: UITextViewDelegate {\n func textViewDidChange(_ textView: UITextView) {\n importButton.isEnabled = !textView.text.isEmpty\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\IPOverride\IPOverrideTextViewController.swift
IPOverrideTextViewController.swift
Swift
2,496
0.95
0.012048
0.101449
vue-tools
47
2025-01-16T23:13:03.810756
Apache-2.0
false
84bfcf1bbdb24bd95f0b5d2d7c29f66d
//\n// IPOverrideViewController.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-01-15.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport MullvadSettings\nimport UIKit\n\nclass IPOverrideViewController: UIViewController {\n private let interactor: IPOverrideInteractor\n private var cancellables = Set<AnyCancellable>()\n private let alertPresenter: AlertPresenter\n\n weak var delegate: IPOverrideViewControllerDelegate?\n\n private lazy var containerView: UIStackView = {\n let view = UIStackView()\n view.axis = .vertical\n view.spacing = 20\n return view\n }()\n\n private lazy var clearButton: AppButton = {\n let button = AppButton(style: .danger)\n button.addTarget(self, action: #selector(didTapClearButton), for: .touchUpInside)\n button.setTitle(NSLocalizedString(\n "IP_OVERRIDE_CLEAR_BUTTON",\n tableName: "IPOverride",\n value: "Clear all overrides",\n comment: ""\n ), for: .normal)\n return button\n }()\n\n private let statusView = IPOverrideStatusView()\n\n init(interactor: IPOverrideInteractor, 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 view.directionalLayoutMargins = UIMetrics.contentHeadingLayoutMargins\n\n configureNavigation()\n addHeaderView()\n addImportButtons()\n addStatusLabel()\n\n view.addConstrainedSubviews([containerView, clearButton]) {\n containerView.pinEdgesToSuperviewMargins(.all().excluding(.bottom))\n clearButton.pinEdgesToSuperviewMargins(PinnableEdges([.leading(0), .trailing(0), .bottom(16)]))\n }\n\n interactor.statusPublisher.sink { [weak self] status in\n self?.statusView.setStatus(status)\n self?.clearButton.isEnabled = self?.interactor.defaultStatus == .active\n }.store(in: &cancellables)\n }\n\n private func configureNavigation() {\n title = NSLocalizedString(\n "IP_OVERRIDE_HEADER",\n tableName: "IPOverride",\n value: "Server IP override",\n comment: ""\n )\n }\n\n private func addHeaderView() {\n let body = NSLocalizedString(\n "IP_OVERRIDE_HEADER_BODY",\n tableName: "IPOverride",\n value: "Import files or text with the new IP addresses for the servers in the Select location view.",\n comment: ""\n )\n let link = NSLocalizedString(\n "IP_OVERRIDE_HEADER_LINK",\n tableName: "IPOverride",\n value: "About Server IP override...",\n comment: ""\n )\n\n let headerView = InfoHeaderView(config: InfoHeaderConfig(body: body, link: link))\n\n headerView.onAbout = { [weak self] in\n self?.delegate?.presentAbout()\n }\n\n containerView.addArrangedSubview(headerView)\n }\n\n private func addImportButtons() {\n let importTextButton = AppButton(style: .default)\n importTextButton.addTarget(self, action: #selector(didTapImportTextButton), for: .touchUpInside)\n importTextButton.setTitle(NSLocalizedString(\n "IP_OVERRIDE_IMPORT_TEXT_BUTTON",\n tableName: "IPOverride",\n value: "Import via text",\n comment: ""\n ), for: .normal)\n\n let importFileButton = AppButton(style: .default)\n importFileButton.addTarget(self, action: #selector(didTapImportFileButton), for: .touchUpInside)\n importFileButton.setTitle(NSLocalizedString(\n "IP_OVERRIDE_IMPORT_FILE_BUTTON",\n tableName: "IPOverride",\n value: "Import file",\n comment: ""\n ), for: .normal)\n\n let stackView = UIStackView(arrangedSubviews: [importTextButton, importFileButton])\n stackView.distribution = .fillEqually\n stackView.spacing = 12\n\n containerView.addArrangedSubview(stackView)\n }\n\n private func addStatusLabel() {\n containerView.addArrangedSubview(statusView)\n }\n\n @objc private func didTapClearButton() {\n let presentation = AlertPresentation(\n id: "ip-override-clear-alert",\n icon: .alert,\n title: NSLocalizedString(\n "IP_OVERRIDE_CLEAR_DIALOG_TITLE",\n tableName: "IPOverride",\n value: "Clear all overrides?",\n comment: ""\n ),\n message: NSLocalizedString(\n "IP_OVERRIDE_CLEAR_DIALOG_MESSAGE",\n tableName: "IPOverride",\n value: """\n Clearing the imported overrides changes the server IPs, in the Select location view, \\n back to default.\n """,\n comment: ""\n ),\n buttons: [\n AlertAction(\n title: NSLocalizedString(\n "IP_OVERRIDE_CLEAR_DIALOG_CLEAR_BUTTON",\n tableName: "IPOverride",\n value: "Clear",\n comment: ""\n ),\n style: .destructive,\n handler: { [weak self] in\n self?.interactor.deleteAllOverrides()\n }\n ),\n AlertAction(\n title: NSLocalizedString(\n "IP_OVERRIDE_CLEAR_DIALOG_CANCEL_BUTTON",\n tableName: "IPOverride",\n value: "Cancel",\n comment: ""\n ),\n style: .default\n ),\n ]\n )\n\n alertPresenter.showAlert(presentation: presentation, animated: true)\n }\n\n @objc private func didTapImportTextButton() {\n delegate?.presentImportTextController()\n }\n\n @objc private func didTapImportFileButton() {\n let documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: [.json, .text])\n documentPicker.delegate = self\n\n present(documentPicker, animated: true)\n }\n}\n\nextension IPOverrideViewController: UIDocumentPickerDelegate {\n func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {\n if let url = urls.first {\n url.securelyScoped { [weak self] scopedUrl in\n scopedUrl.flatMap { self?.interactor.import(url: $0) }\n }\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\IPOverride\IPOverrideViewController.swift
IPOverrideViewController.swift
Swift
6,758
0.95
0.044335
0.040462
react-lib
218
2024-09-01T00:37:37.079468
GPL-3.0
false
41bcddf0b67bd784e8508e5a222a63d9
//\n// IPOverrideViewControllerDelegate.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-01-16.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nprotocol IPOverrideViewControllerDelegate: AnyObject {\n func presentImportTextController()\n func presentAbout()\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\IPOverride\IPOverrideViewControllerDelegate.swift
IPOverrideViewControllerDelegate.swift
Swift
310
0.95
0
0.583333
python-kit
940
2024-09-14T02:08:26.050825
Apache-2.0
false
a2a18db53e9765dfec95795d374fa3fb
//\n// MultihopTunnelSettingsViewModel.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-11-21.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\n\nclass MultihopTunnelSettingsViewModel: TunnelSettingsObserver, ObservableObject {\n typealias TunnelSetting = MultihopState\n\n let tunnelManager: TunnelManager\n var tunnelObserver: TunnelObserver?\n\n var value: MultihopState {\n willSet(newValue) {\n guard newValue != value else { return }\n\n objectWillChange.send()\n tunnelManager.updateSettings([.multihop(newValue)])\n }\n }\n\n required init(tunnelManager: TunnelManager) {\n self.tunnelManager = tunnelManager\n value = tunnelManager.settings.tunnelMultihopState\n\n tunnelObserver = TunnelBlockObserver(didUpdateTunnelSettings: { [weak self] _, newSettings in\n self?.value = newSettings.tunnelMultihopState\n })\n }\n\n func evaluate(setting: MultihopState) {\n // No op.\n }\n}\n\nclass MockMultihopTunnelSettingsViewModel: TunnelSettingsObservable {\n @Published var value: MultihopState\n\n init(multihopState: MultihopState = .off) {\n value = multihopState\n }\n\n func evaluate(setting: MullvadSettings.MultihopState) {}\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\Multihop\MultihopTunnelSettingsViewModel.swift
MultihopTunnelSettingsViewModel.swift
Swift
1,289
0.95
0.041667
0.216216
awesome-app
24
2025-06-11T03:03:53.414759
Apache-2.0
false
798a4259a2ec1696558cfb46989ce3db
//\n// SettingsMultihopView.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-11-14.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\nimport SwiftUI\n\nstruct SettingsMultihopView<ViewModel>: View where ViewModel: TunnelSettingsObservable<MultihopState> {\n @StateObject var tunnelViewModel: ViewModel\n\n var body: some View {\n SettingsInfoContainerView {\n VStack(alignment: .leading, spacing: 8) {\n SettingsInfoView(viewModel: dataViewModel)\n\n SwitchRowView(\n isOn: $tunnelViewModel.value.isEnabled,\n text: NSLocalizedString(\n "SETTINGS_SWITCH_MULTIHOP",\n tableName: "Settings",\n value: "Enable",\n comment: ""\n ),\n accessibilityId: .multihopSwitch\n )\n .padding(.leading, UIMetrics.contentInsets.left)\n .padding(.trailing, UIMetrics.contentInsets.right)\n }\n }\n }\n}\n\n#Preview {\n SettingsMultihopView(tunnelViewModel: MockMultihopTunnelSettingsViewModel())\n}\n\nextension SettingsMultihopView {\n private var dataViewModel: SettingsInfoViewModel {\n SettingsInfoViewModel(\n pages: [\n SettingsInfoViewModelPage(\n body: NSLocalizedString(\n "SETTINGS_INFO_MULTIHOP",\n tableName: "Settings",\n value: """\n Multihop routes your traffic into one WireGuard server and out another, making it \\n harder to trace. This results in increased latency but increases anonymity online.\n """,\n comment: ""\n ),\n image: .multihopIllustration\n ),\n ]\n )\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\Multihop\SettingsMultihopView.swift
SettingsMultihopView.swift
Swift
1,956
0.95
0
0.148148
python-kit
186
2024-12-17T05:04:20.709883
MIT
false
664fb90594aee0a66b1395d423c5acb2
//\n// GroupedRowView.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-11-21.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport SwiftUI\n\nstruct GroupedRowView<Content: View>: View {\n let content: Content\n\n init(@ViewBuilder _ content: () -> Content) {\n self.content = content()\n }\n\n var body: some View {\n VStack(spacing: 0) {\n content\n }\n .background(Color(UIColor.primaryColor))\n .cornerRadius(UIMetrics.SettingsRowView.cornerRadius)\n }\n}\n\n#Preview("GroupedRowView") {\n StatefulPreviewWrapper((enabled: true, directOnly: false)) { values in\n GroupedRowView {\n SwitchRowView(isOn: values.enabled, text: "Enable")\n SwitchRowView(isOn: values.directOnly, text: "Direct only")\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\Views\GroupedRowView.swift
GroupedRowView.swift
Swift
818
0.95
0
0.275862
react-lib
887
2025-03-14T12:45:23.700516
GPL-3.0
false
69e014a61b3dc7d90bea0de4f95ab1c0
//\n// SettingsInfoContainerView.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-11-21.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport SwiftUI\n\nstruct SettingsInfoContainerView<Content: View>: View {\n let content: Content\n\n init(@ViewBuilder _ content: () -> Content) {\n self.content = content()\n }\n\n var body: some View {\n ScrollView {\n VStack {\n content\n .padding(.top, UIMetrics.contentInsets.top)\n .padding(.bottom, UIMetrics.contentInsets.bottom)\n }\n }\n .background(Color(.secondaryColor))\n }\n}\n\n#Preview {\n SettingsInfoContainerView {\n SettingsMultihopView(tunnelViewModel: MockMultihopTunnelSettingsViewModel())\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\Views\SettingsInfoContainerView.swift
SettingsInfoContainerView.swift
Swift
791
0.95
0
0.275862
python-kit
773
2023-09-09T13:38:09.875950
MIT
false
4179c67a6d50da70e942784637f72d5d
//\n// SettingsInfoView.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-11-13.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport SwiftUI\n\nstruct SettingsInfoViewModel {\n let pages: [SettingsInfoViewModelPage]\n}\n\nstruct SettingsInfoViewModelPage: Hashable {\n let body: String\n let image: ImageResource\n}\n\nstruct SettingsInfoView: View {\n let viewModel: SettingsInfoViewModel\n\n // Extra spacing to allow for some room around the page indicators.\n var pageIndicatorSpacing: CGFloat {\n viewModel.pages.count > 1 ? 72 : 24\n }\n\n var body: some View {\n ZStack {\n TabView {\n contentView()\n }\n .padding(UIMetrics.SettingsInfoView.layoutMargins)\n .tabViewStyle(.page)\n .foregroundColor(Color(.primaryTextColor))\n .background {\n Color(.secondaryColor)\n }\n hiddenViewToStretchHeightInsideScrollView()\n }\n }\n\n// A TabView inside a Scrollview has no height. This hidden view stretches the TabView to have the size of the heighest page.\n private func hiddenViewToStretchHeightInsideScrollView() -> some View {\n return ZStack {\n contentView()\n }\n .padding(UIMetrics.SettingsInfoView.layoutMargins)\n .padding(.bottom, 1)\n .hidden()\n }\n\n private func bodyText(_ page: SettingsInfoViewModelPage) -> some View {\n (try? AttributedString(\n markdown: page.body,\n options: AttributedString.MarkdownParsingOptions(interpretedSyntax: .inlineOnlyPreservingWhitespace)\n )).map(Text.init) ?? Text(page.body)\n }\n\n private func contentView() -> some View {\n ForEach(viewModel.pages, id: \.self) { page in\n VStack {\n VStack(alignment: .leading, spacing: 16) {\n Image(page.image)\n .resizable()\n .aspectRatio(contentMode: .fit)\n bodyText(page)\n .font(.subheadline)\n .opacity(0.6)\n }\n Spacer()\n }\n .padding(.bottom, pageIndicatorSpacing)\n }\n }\n}\n\n#Preview("Single page") {\n SettingsInfoView(viewModel: SettingsInfoViewModel(\n pages: [\n SettingsInfoViewModelPage(\n body: """\n Multihop routes your traffic into one WireGuard server and out another, making it \\n harder to trace. This results in increased latency but increases anonymity online.\n """,\n image: .multihopIllustration\n ),\n ]\n ))\n}\n\n#Preview("Multiple pages") {\n SettingsInfoView(viewModel: SettingsInfoViewModel(\n pages: [\n SettingsInfoViewModelPage(\n body: """\n Multihop routes your traffic into one WireGuard server and out another, making it \\n harder to trace. This results in increased latency but increases anonymity online.\n """,\n image: .multihopIllustration\n ),\n SettingsInfoViewModelPage(\n body: """\n Multihop routes your traffic into one WireGuard server and out another, making it \\n harder to trace. This results in increased latency but increases anonymity online.\n Multihop routes your traffic into one WireGuard server and out another, making it \\n harder to trace. This results in increased latency but increases anonymity online.\n """,\n image: .multihopIllustration\n ),\n ]\n ))\n}\n\n#Preview("Single inside Scrollview") {\n ScrollView {\n SettingsInfoView(viewModel: SettingsInfoViewModel(\n pages: [\n SettingsInfoViewModelPage(\n body: """\n Multihop routes your traffic into one WireGuard server and out another, making it \\n harder to trace. This results in increased latency but increases anonymity online.\n """,\n image: .multihopIllustration\n ),\n ]\n ))\n }\n}\n\n#Preview("Multiple inside Scrollview") {\n ScrollView {\n SettingsInfoView(viewModel: SettingsInfoViewModel(\n pages: [\n SettingsInfoViewModelPage(\n body: NSLocalizedString(\n "SETTINGS_INFO_DAITA_PAGE_1",\n tableName: "Settings",\n value: """\n **Attention: This increases network traffic and will also negatively affect speed, latency, \\n and battery usage. Use with caution on limited plans.**\n\n DAITA (Defense against AI-guided Traffic Analysis) hides patterns in \\n your encrypted VPN traffic.\n\n By using sophisticated AI it’s possible to analyze the traffic of data \\n packets going in and out of your device (even if the traffic is encrypted).\n """,\n comment: ""\n ),\n image: .daitaOffIllustration\n ),\n SettingsInfoViewModelPage(\n body: NSLocalizedString(\n "SETTINGS_INFO_DAITA_PAGE_2",\n tableName: "Settings",\n value: """\n If an observer monitors these data packets, DAITA makes it significantly \\n harder for them to identify which websites you are visiting or with whom \\n you are communicating.\n\n DAITA does this by carefully adding network noise and making all network \\n packets the same size.\n\n Not all our servers are DAITA-enabled. Therefore, we use multihop \\n automatically to enable DAITA with any server.\n """,\n comment: ""\n ),\n image: .daitaOnIllustration\n ),\n ]\n ))\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\Views\SettingsInfoView.swift
SettingsInfoView.swift
Swift
6,285
0.95
0.022857
0.088608
awesome-app
725
2023-12-24T07:54:15.010947
GPL-3.0
false
b66cf2786b6f003f968df8de37f25da1
//\n// SettingsRowViewFooter.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-11-18.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport SwiftUI\n\nstruct SettingsRowViewFooter: View {\n let text: String\n\n var body: some View {\n Text(verbatim: text)\n .font(.footnote)\n .opacity(0.6)\n .foregroundStyle(Color(.primaryTextColor))\n .padding(UIMetrics.SettingsRowView.footerLayoutMargins)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\Views\SettingsRowViewFooter.swift
SettingsRowViewFooter.swift
Swift
476
0.95
0
0.388889
python-kit
667
2023-07-31T13:48:04.614216
MIT
false
41d32e08b70204f9c7f07e2aca6fd8ec
//\n// SwitchRowView.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-11-13.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport SwiftUI\n\nstruct SwitchRowView: View {\n @Binding var isOn: Bool\n\n var disabled = false\n let text: String\n var accessibilityId: AccessibilityIdentifier?\n\n var didTapInfoButton: (() -> Void)?\n\n var body: some View {\n Toggle(isOn: $isOn, label: {\n Text(text)\n })\n .toggleStyle(CustomToggleStyle(\n disabled: disabled,\n accessibilityId: accessibilityId,\n infoButtonAction: didTapInfoButton\n ))\n .disabled(disabled)\n .font(.headline)\n .frame(height: UIMetrics.SettingsRowView.height)\n .padding(UIMetrics.SettingsRowView.layoutMargins)\n .background(Color(.primaryColor))\n .foregroundColor(Color(.primaryTextColor))\n .cornerRadius(UIMetrics.SettingsRowView.cornerRadius)\n }\n}\n\n#Preview("SwitchRowView") {\n StatefulPreviewWrapper(true) {\n SwitchRowView(\n isOn: $0,\n text: "Enable",\n didTapInfoButton: {\n print("Tapped")\n }\n )\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\Settings\Views\SwitchRowView.swift
SwitchRowView.swift
Swift
1,201
0.95
0
0.186047
awesome-app
469
2024-05-22T08:32:20.362178
MIT
false
ea317a88de413893859e9191ca917918
//\n// Bundle+ProductVersion.swift\n// MullvadVPN\n//\n// Created by pronebird on 22/02/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nextension Bundle {\n /// Returns the product version string based on the following rules:\n ///\n /// 1. Dev builds (debug): XXXX.YY-devZ\n /// 2. TestFlight builds: XXXX.YY-betaZ\n /// 3. AppStore builds: XXXX.YY\n ///\n /// Note: XXXX.YY is an app version (i.e 2020.5) and Z is a build number (i.e 1)\n var productVersion: String {\n let version = object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "???"\n let buildNumber = object(forInfoDictionaryKey: kCFBundleVersionKey as String) as? String ??\n "???"\n\n #if DEBUG\n return "\(version)-dev\(buildNumber)"\n #else\n if appStoreReceiptURL?.lastPathComponent == "sandboxReceipt" {\n return "\(version)-beta\(buildNumber)"\n } else {\n return version\n }\n #endif\n }\n\n /// Returns short version XXXX.YY (i.e 2020.5).\n var shortVersion: String {\n object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "???"\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\Bundle+ProductVersion.swift
Bundle+ProductVersion.swift
Swift
1,199
0.95
0.051282
0.514286
python-kit
62
2024-06-06T09:16:06.002023
Apache-2.0
false
908e761024f74c563a2cb2896284e87b
//\n// CGSize+Helpers.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2024-10-10.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nextension CGSize {\n // Function to deduct insets from CGSize\n func deducting(insets: NSDirectionalEdgeInsets) -> CGSize {\n let newWidth = width - (insets.leading + insets.trailing)\n let newHeight = height - (insets.top + insets.bottom)\n return CGSize(width: newWidth, height: newHeight)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\CGSize+Helpers.swift
CGSize+Helpers.swift
Swift
482
0.95
0
0.5
react-lib
804
2024-06-15T23:09:36.255988
GPL-3.0
false
7d7c4e289ef557d64a4f57cfa523285c
//\n// CharacterSet+IPAddress.swift\n// MullvadVPN\n//\n// Created by pronebird on 07/10/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nextension CharacterSet {\n static var ipv4AddressCharset: CharacterSet {\n CharacterSet(charactersIn: "0123456789.")\n }\n\n static var ipv6AddressCharset: CharacterSet {\n CharacterSet(charactersIn: "0123456789abcdef:.")\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\CharacterSet+IPAddress.swift
CharacterSet+IPAddress.swift
Swift
423
0.95
0
0.4375
awesome-app
392
2024-03-04T00:26:39.207905
BSD-3-Clause
false
9431d7bad42bcbf30ee8c1961ec1c06a
//\n// CodingErrors+CustomErrorDescription.swift\n// MullvadVPN\n//\n// Created by pronebird on 17/02/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\n\nextension DecodingError: MullvadTypes.CustomErrorDescriptionProtocol {\n public var customErrorDescription: String? {\n switch self {\n case let .typeMismatch(type, context):\n return "Type mismatch, expected \(type) for key at \"\(context.codingPath.codingPathString)\"."\n\n case let .valueNotFound(_, context):\n return "Value not found at \"\(context.codingPath.codingPathString)\"."\n\n case let .keyNotFound(codingKey, context):\n return "Key \"\(codingKey.stringValue)\" not found at \"\(context.codingPath.codingPathString)\"."\n\n case .dataCorrupted:\n return "Data corrupted."\n\n @unknown default:\n return nil\n }\n }\n}\n\nextension EncodingError: MullvadTypes.CustomErrorDescriptionProtocol {\n public var customErrorDescription: String? {\n switch self {\n case let .invalidValue(_, context):\n return "Invalid value at \"\(context.codingPath.codingPathString)\""\n\n @unknown default:\n return nil\n }\n }\n}\n\nprivate extension [CodingKey] {\n var codingPathString: String {\n if isEmpty {\n return "<root>"\n } else {\n return map { $0.stringValue }\n .joined(separator: ".")\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\CodingErrors+CustomErrorDescription.swift
CodingErrors+CustomErrorDescription.swift
Swift
1,504
0.95
0.074074
0.155556
awesome-app
344
2024-10-12T17:34:50.200126
Apache-2.0
false
857e59774200bad24b3fed69824a65ea
//\n// Collection+Sorting.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-06-14.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nextension Collection where Element: StringProtocol {\n public func caseInsensitiveSorted() -> [Element] {\n sorted { $0.caseInsensitiveCompare($1) == .orderedAscending }\n }\n}\n\nextension MutableCollection where Element: StringProtocol, Self: RandomAccessCollection {\n public mutating func caseInsensitiveSort() {\n sort { $0.caseInsensitiveCompare($1) == .orderedAscending }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\Collection+Sorting.swift
Collection+Sorting.swift
Swift
578
0.95
0
0.388889
python-kit
355
2025-03-11T23:59:18.471633
BSD-3-Clause
false
b2be05106bec172a85c3c48c0e51adfc
//\n// Color.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-12-06.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport SwiftUI\n\nextension Color {\n /// Returns the color darker by the given percent (in range from 0..1)\n func darkened(by percent: CGFloat) -> Color? {\n UIColor(self).darkened(by: percent)?.color\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\Color+Helpers.swift
Color+Helpers.swift
Swift
363
0.95
0
0.571429
node-utils
860
2025-01-06T19:48:38.318508
MIT
false
9d1af6bbb5cd322d8f78364142e55103
//\n// Coordinator+Router.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-08-24.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport Routing\n\nextension Coordinator {\n var applicationRouter: ApplicationRouter<AppRoute>? {\n var appCoordinator = self\n\n while let parentCoordinator = appCoordinator.parent {\n appCoordinator = parentCoordinator\n }\n\n return (appCoordinator as? ApplicationCoordinator)?.router\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\Coordinator+Router.swift
Coordinator+Router.swift
Swift
503
0.95
0.045455
0.388889
python-kit
738
2024-07-27T09:30:09.300900
MIT
false
f17ac74efbc31f575a3562997f0a33f4
//\n// NEVPNStatus+Debug.swift\n// MullvadVPN\n//\n// Created by pronebird on 28/11/2019.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport NetworkExtension\n\nextension NEVPNStatus: Swift.CustomStringConvertible {\n public var description: String {\n switch self {\n case .connected:\n return "connected"\n case .connecting:\n return "connecting"\n case .disconnected:\n return "disconnected"\n case .disconnecting:\n return "disconnecting"\n case .invalid:\n return "invalid"\n case .reasserting:\n return "reasserting"\n @unknown default:\n return "unknown value (\(rawValue))"\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\NEVPNStatus+Debug.swift
NEVPNStatus+Debug.swift
Swift
736
0.95
0.033333
0.25
awesome-app
311
2024-03-19T05:03:01.425788
GPL-3.0
false
420d03f2a8090ccd6d73673c63c97f22
//\n// NSAttributedString+Markdown.swift\n// MullvadVPN\n//\n// Created by pronebird on 19/11/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nextension NSAttributedString {\n enum MarkdownElement {\n case bold\n }\n\n convenience init(\n markdownString: String,\n options: MarkdownStylingOptions,\n applyEffect: ((MarkdownElement, String) -> [NSAttributedString.Key: Any])? = nil\n ) {\n let attributedString = NSMutableAttributedString()\n let components = markdownString.components(separatedBy: "**")\n\n for (stringIndex, string) in components.enumerated() {\n var attributes: [NSAttributedString.Key: Any] = [:]\n\n if stringIndex % 2 == 0 {\n attributes[.font] = options.font\n } else {\n attributes[.font] = options.boldFont\n attributes.merge(applyEffect?(.bold, string) ?? [:], uniquingKeysWith: { $1 })\n }\n\n attributedString.append(NSAttributedString(string: string, attributes: attributes))\n }\n\n attributedString.addAttribute(\n .paragraphStyle,\n value: options.paragraphStyle,\n range: NSRange(location: 0, length: attributedString.length)\n )\n\n self.init(attributedString: attributedString)\n }\n}\n\nextension NSMutableAttributedString {\n func apply(paragraphStyle: NSParagraphStyle) {\n let attributeRange = NSRange(location: 0, length: length)\n addAttribute(.paragraphStyle, value: paragraphStyle, range: attributeRange)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\NSAttributedString+Extensions.swift
NSAttributedString+Extensions.swift
Swift
1,592
0.95
0.038462
0.162791
react-lib
640
2023-09-05T19:16:46.782485
MIT
false
ef0eaf11c84a9613a9a7518e89c81492
//\n// NSLayoutConstraint+Helpers.swift\n// MullvadVPN\n//\n// Created by pronebird on 21/07/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nextension NSLayoutConstraint {\n /// Sets constraint priority and returns `self`\n func withPriority(_ priority: UILayoutPriority) -> Self {\n self.priority = priority\n return self\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\NSLayoutConstraint+Helpers.swift
NSLayoutConstraint+Helpers.swift
Swift
381
0.95
0
0.533333
vue-tools
711
2024-02-08T01:24:01.967736
BSD-3-Clause
false
730d7e6060eac39263089adcc27fae39
//\n// NSParagraphStyle+Extensions.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-06-27.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nextension NSParagraphStyle {\n static var alert: NSParagraphStyle {\n let style = NSMutableParagraphStyle()\n\n style.paragraphSpacing = 16\n style.lineBreakMode = .byWordWrapping\n\n return style\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\NSParagraphStyle+Extensions.swift
NSParagraphStyle+Extensions.swift
Swift
409
0.95
0
0.4375
python-kit
145
2025-03-18T06:48:25.606992
GPL-3.0
false
b94051c21e388ce89222f61f3dad2b02
//\n// NSRegularExpression+IPAddress.swift\n// MullvadVPN\n//\n// Created by pronebird on 30/10/2020.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nextension NSRegularExpression {\n static var ipv4RegularExpression: NSRegularExpression {\n // Regular expression obtained from:\n // https://www.regular-expressions.info/ip.html\n let pattern = #"""\n \b(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.\n (25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.\n (25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.\n (25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\b\n """#\n // swiftlint:disable:next force_try\n return try! NSRegularExpression(pattern: pattern, options: [.allowCommentsAndWhitespace])\n }\n\n // swiftlint:disable line_length\n static var ipv6RegularExpression: NSRegularExpression {\n // Regular expression obtained from:\n // https://stackoverflow.com/a/17871737\n let pattern = #"""\n # IPv6 RegEx\n (\n ([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}| # 1:2:3:4:5:6:7:8\n ([0-9a-fA-F]{1,4}:){1,7}:| # 1:: 1:2:3:4:5:6:7::\n ([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}| # 1::8 1:2:3:4:5:6::8 1:2:3:4:5:6::8\n ([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}| # 1::7:8 1:2:3:4:5::7:8 1:2:3:4:5::8\n ([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}| # 1::6:7:8 1:2:3:4::6:7:8 1:2:3:4::8\n ([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}| # 1::5:6:7:8 1:2:3::5:6:7:8 1:2:3::8\n ([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}| # 1::4:5:6:7:8 1:2::4:5:6:7:8 1:2::8\n [0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})| # 1::3:4:5:6:7:8 1::3:4:5:6:7:8 1::8\n :((:[0-9a-fA-F]{1,4}){1,7}|:)| # ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::\n fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}| # fe80::7:8%eth0 fe80::7:8%1 (link-local IPv6 addresses with zone index)\n ::(ffff(:0{1,4}){0,1}:){0,1}\n ((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}\n (25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])| # ::255.255.255.255 ::ffff:255.255.255.255 ::ffff:0:255.255.255.255 (IPv4-mapped IPv6 addresses and IPv4-translated addresses)\n ([0-9a-fA-F]{1,4}:){1,4}:\n ((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}\n (25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]) # 2001:db8:3:4::192.0.2.33 64:ff9b::192.0.2.33 (IPv4-Embedded IPv6 Address)\n )\n """#\n // swiftlint:disable:next force_try\n return try! NSRegularExpression(pattern: pattern, options: [.allowCommentsAndWhitespace])\n }\n // swiftlint:enable line_length\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\NSRegularExpression+IPAddress.swift
NSRegularExpression+IPAddress.swift
Swift
2,899
0.95
0.037037
0.313725
react-lib
477
2025-05-04T01:13:33.306040
Apache-2.0
false
82a2cc7a6a406f2ff535b6f41c99a450
//\n// RESTCreateApplePaymentResponse.swift\n// MullvadVPN\n//\n// Created by Andreas Lif on 2022-08-04.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadREST\n\nextension REST.CreateApplePaymentResponse {\n enum Context {\n case purchase\n case restoration\n }\n\n func alertTitle(context: Context) -> String {\n switch context {\n case .purchase:\n return NSLocalizedString(\n "TIME_ADDED_ALERT_SUCCESS_TITLE",\n tableName: "REST",\n value: "Thanks for your purchase",\n comment: ""\n )\n case .restoration:\n return NSLocalizedString(\n "RESTORE_PURCHASES_ALERT_TITLE",\n tableName: "REST",\n value: "Restore purchases",\n comment: ""\n )\n }\n }\n\n func alertMessage(context: Context) -> String {\n switch context {\n case .purchase:\n return String(\n format: NSLocalizedString(\n "TIME_ADDED_ALERT_SUCCESS_MESSAGE",\n tableName: "REST",\n value: "%@ have been added to your account",\n comment: ""\n ),\n formattedTimeAdded ?? ""\n )\n case .restoration:\n switch self {\n case .noTimeAdded:\n return NSLocalizedString(\n "RESTORE_PURCHASES_ALERT_NO_TIME_ADDED_MESSAGE",\n tableName: "REST",\n value: "Your previous purchases have already been added to this account.",\n comment: ""\n )\n case .timeAdded:\n return String(\n format: NSLocalizedString(\n "RESTORE_PURCHASES_ALERT_TIME_ADDED_MESSAGE",\n tableName: "REST",\n value: "%@ have been added to your account",\n comment: ""\n ),\n formattedTimeAdded ?? ""\n )\n }\n }\n }\n}\n\nextension REST.CreateApplePaymentResponse.Context {\n var errorTitle: String {\n switch self {\n case .purchase:\n return NSLocalizedString(\n "CANNOT_COMPLETE_PURCHASE_ALERT_TITLE",\n tableName: "Payment",\n value: "Cannot complete the purchase",\n comment: ""\n )\n case .restoration:\n return NSLocalizedString(\n "RESTORE_PURCHASES_FAILURE_ALERT_TITLE",\n tableName: "Payment",\n value: "Cannot restore purchases",\n comment: ""\n )\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\RESTCreateApplePaymentResponse+Localization.swift
RESTCreateApplePaymentResponse+Localization.swift
Swift
2,758
0.95
0.054945
0.081395
node-utils
296
2024-05-12T14:38:34.749970
GPL-3.0
false
c1fa1d709f6caf844d574d59695bc1e3
//\n// RESTError+Display.swift\n// MullvadVPN\n//\n// Created by pronebird on 04/06/2020.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\nimport MullvadTypes\n\nextension REST.Error: MullvadTypes.DisplayError {\n public var displayErrorDescription: String? {\n switch self {\n case let .network(urlError):\n return String(\n format: NSLocalizedString(\n "NETWORK_ERROR",\n tableName: "REST",\n value: "Network error: %@",\n comment: ""\n ),\n urlError.localizedDescription\n )\n\n case let .unhandledResponse(statusCode, serverResponse):\n guard let serverResponse else {\n return String(format: NSLocalizedString(\n "UNEXPECTED_RESPONSE",\n tableName: "REST",\n value: "Unexpected server response: %d",\n comment: ""\n ), statusCode)\n }\n\n switch serverResponse.code {\n case .invalidAccount:\n return NSLocalizedString(\n "INVALID_ACCOUNT_ERROR",\n tableName: "REST",\n value: "Invalid account",\n comment: ""\n )\n\n case .maxDevicesReached:\n return NSLocalizedString(\n "MAX_DEVICES_REACHED_ERROR",\n tableName: "REST",\n value: "Too many devices registered with account",\n comment: ""\n )\n\n case .serviceUnavailable:\n return NSLocalizedString(\n "SERVICE_UNAVAILABLE",\n tableName: "REST",\n value: "We are having some issues, please try again later",\n comment: ""\n )\n\n case .tooManyRequests:\n return NSLocalizedString(\n "TOO_MANY_REQUESTS",\n tableName: "REST",\n value: "We are having some issues, please try again later",\n comment: ""\n )\n\n default:\n return String(\n format: NSLocalizedString(\n "SERVER_ERROR",\n tableName: "REST",\n value: "Unexpected server response: %1$@ (HTTP status: %2$d)",\n comment: ""\n ),\n serverResponse.code.rawValue,\n statusCode\n )\n }\n\n default:\n return NSLocalizedString(\n "INTERNAL_ERROR",\n tableName: "REST",\n value: "Internal error.",\n comment: ""\n )\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\RESTError+Display.swift
RESTError+Display.swift
Swift
2,898
0.95
0.043478
0.084337
react-lib
205
2024-03-06T09:40:16.710003
Apache-2.0
false
1042beac5bbc133175126d8a7a72e07c
//\n// SKError+Localized.swift\n// MullvadVPN\n//\n// Created by pronebird on 17/01/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport StoreKit\n\nextension SKError: Foundation.LocalizedError {\n public var errorDescription: String? {\n switch code {\n case .unknown:\n return NSLocalizedString(\n "UNKNOWN_ERROR",\n tableName: "StoreKitErrors",\n value: "Unknown error.",\n comment: ""\n )\n case .clientInvalid:\n return NSLocalizedString(\n "CLIENT_INVALID",\n tableName: "StoreKitErrors",\n value: "Client is not allowed to issue the request.",\n comment: ""\n )\n case .paymentCancelled:\n return NSLocalizedString(\n "PAYMENT_CANCELLED",\n tableName: "StoreKitErrors",\n value: "The payment request was cancelled.",\n comment: ""\n )\n case .paymentInvalid:\n return NSLocalizedString(\n "PAYMENT_INVALID",\n tableName: "StoreKitErrors",\n value: "Invalid purchase identifier.",\n comment: ""\n )\n case .paymentNotAllowed:\n return NSLocalizedString(\n "PAYMENT_NOT_ALLOWED",\n tableName: "StoreKitErrors",\n value: "This device is not allowed to make the payment.",\n comment: ""\n )\n default:\n return localizedDescription\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\SKError+Localized.swift
SKError+Localized.swift
Swift
1,607
0.95
0.018868
0.137255
vue-tools
189
2025-01-08T16:22:02.804053
Apache-2.0
false
4f9a5d0e759f4563047997b4d0c6e433
//\n// SKProduct+Formatting.swift\n// MullvadVPN\n//\n// Created by pronebird on 19/03/2020.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport StoreKit\n\nextension SKProduct {\n var localizedPrice: String? {\n let formatter = NumberFormatter()\n formatter.locale = priceLocale\n formatter.numberStyle = .currency\n\n return formatter.string(from: price)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\SKProduct+Formatting.swift
SKProduct+Formatting.swift
Swift
423
0.95
0
0.411765
vue-tools
160
2025-03-19T11:55:37.596954
MIT
false
d49b9cd3e6300ffc61a7a8ce1f807d0b
//\n// SKProduct+Sorting.swift\n// MullvadVPN\n//\n// Created by Steffen Ernst on 2025-01-14.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport StoreKit\n\nextension Array where Element == SKProduct {\n func sortedByPrice() -> [SKProduct] {\n sorted { ($0.price as Decimal) < ($1.price as Decimal) }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\SKProduct+Sorting.swift
SKProduct+Sorting.swift
Swift
333
0.95
0
0.538462
react-lib
652
2023-08-06T14:02:43.610388
GPL-3.0
false
a0529d1d1ff09f8318696ec7502563f0
//\n// StorePaymentManagerError+Display.swift\n// MullvadVPN\n//\n// Created by pronebird on 17/01/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\nimport StoreKit\n\nextension StorePaymentManagerError: DisplayError {\n var displayErrorDescription: String? {\n switch self {\n case .noAccountSet:\n return NSLocalizedString(\n "INTERNAL_ERROR",\n tableName: "StorePaymentManager",\n value: "Internal error.",\n comment: ""\n )\n\n case let .validateAccount(error):\n let reason = (error as? DisplayError)?.displayErrorDescription ?? ""\n\n return String(\n format: NSLocalizedString(\n "VALIDATE_ACCOUNT_ERROR",\n tableName: "StorePaymentManager",\n value: "Failed to validate account number: %@",\n comment: ""\n ), reason\n )\n\n case let .readReceipt(readReceiptError):\n if readReceiptError is StoreReceiptNotFound {\n return NSLocalizedString(\n "RECEIPT_NOT_FOUND_ERROR",\n tableName: "StorePaymentManager",\n value: "AppStore receipt is not found on disk.",\n comment: ""\n )\n } else if let storeError = readReceiptError as? SKError {\n return String(\n format: NSLocalizedString(\n "REFRESH_RECEIPT_ERROR",\n tableName: "StorePaymentManager",\n value: "Cannot refresh the AppStore receipt: %@",\n comment: ""\n ),\n storeError.localizedDescription\n )\n } else {\n return NSLocalizedString(\n "READ_RECEIPT_ERROR",\n tableName: "StorePaymentManager",\n value: "Cannot read the AppStore receipt from disk",\n comment: ""\n )\n }\n\n case let .sendReceipt(error):\n let reason = (error as? DisplayError)?.displayErrorDescription ?? ""\n let errorFormat = NSLocalizedString(\n "SEND_RECEIPT_ERROR",\n tableName: "StorePaymentManager",\n value: "Failed to send the receipt to server: %@",\n comment: ""\n )\n let recoverySuggestion = NSLocalizedString(\n "SEND_RECEIPT_RECOVERY_SUGGESTION",\n tableName: "StorePaymentManager",\n value: "Please retry by using the \"Restore purchases\" button.",\n comment: ""\n )\n var errorString = String(format: errorFormat, reason)\n errorString.append("\n\n")\n errorString.append(recoverySuggestion)\n return errorString\n\n case let .storePayment(storeError):\n guard let error = storeError as? SKError else { return storeError.localizedDescription }\n if error.code.rawValue == 0, error.underlyingErrorChain.map({ $0 as NSError }).first?.code == 825 {\n return SKError(.paymentCancelled).errorDescription\n }\n return SKError(error.code).errorDescription\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\StorePaymentManagerError+Display.swift
StorePaymentManagerError+Display.swift
Swift
3,379
0.95
0.044444
0.084337
python-kit
718
2024-03-11T14:31:19.489511
BSD-3-Clause
false
3f09a3cdcda7b500a004d98977d189a8
//\n// String+AccountFormatting.swift\n// MullvadVPN\n//\n// Created by Andreas Lif on 2022-06-10.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nextension String {\n var formattedAccountNumber: String {\n split(every: 4).joined(separator: " ")\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\String+AccountFormatting.swift
String+AccountFormatting.swift
Swift
295
0.95
0
0.538462
python-kit
236
2024-12-05T12:22:32.410280
Apache-2.0
false
db6206695fb19ca8c68d41f49b111eaa