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// OutgoingConnectionService.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2023-10-27.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadLogging\nimport Network\n\nprotocol OutgoingConnectionServiceHandling {\n func getOutgoingConnectionInfo() async throws -> OutgoingConnectionInfo\n}\n\nfinal class OutgoingConnectionService: OutgoingConnectionServiceHandling {\n private let outgoingConnectionProxy: OutgoingConnectionHandling\n\n init(outgoingConnectionProxy: OutgoingConnectionHandling) {\n self.outgoingConnectionProxy = outgoingConnectionProxy\n }\n\n func getOutgoingConnectionInfo() async throws -> OutgoingConnectionInfo {\n let ipv4ConnectionInfo = try await outgoingConnectionProxy.getIPV4(retryStrategy: .default)\n let ipv6ConnectionInfo = try? await outgoingConnectionProxy.getIPV6(retryStrategy: .noRetry)\n return OutgoingConnectionInfo(ipv4: ipv4ConnectionInfo, ipv6: ipv6ConnectionInfo)\n }\n}\n\nstruct OutgoingConnectionInfo {\n /// IPv4 exit connection.\n let ipv4: IPV4ConnectionData\n\n /// IPv6 exit connection.\n let ipv6: IPV6ConnectionData?\n\n var outAddress: String? {\n let ipv4String = ipv4.exitIP ? "\(ipv4.ip)" : nil\n\n var ipv6String: String?\n if let ipv6 = ipv6, ipv6.exitIP {\n ipv6String = "\(ipv6.ip)"\n }\n\n let outAddress = [ipv4String, ipv6String].compactMap { $0 }.joined(separator: "\n")\n return outAddress.isEmpty ? nil : outAddress\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Tunnel\OutgoingConnectionService.swift
OutgoingConnectionService.swift
Swift
1,520
0.95
0.081633
0.230769
node-utils
377
2024-08-08T16:53:42.167039
Apache-2.0
false
6e15e3b3825f98d252a2c6f1e0abf340
//\n// TunnelViewController.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-12-10.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport MapKit\nimport MullvadLogging\nimport MullvadREST\nimport MullvadSettings\nimport MullvadTypes\nimport SwiftUI\n\nclass TunnelViewController: UIViewController, RootContainment {\n private let logger = Logger(label: "TunnelViewController")\n private let interactor: TunnelViewControllerInteractor\n private var tunnelState: TunnelState = .disconnected\n private var connectionViewViewModel: ConnectionViewViewModel\n private var indicatorsViewViewModel: FeatureIndicatorsViewModel\n private var connectionView: ConnectionView\n private var connectionController: UIHostingController<ConnectionView>?\n\n var shouldShowSelectLocationPicker: (() -> Void)?\n var shouldShowCancelTunnelAlert: (() -> Void)?\n\n let activityIndicator: SpinnerActivityIndicatorView = {\n let activityIndicator = SpinnerActivityIndicatorView(style: .large)\n activityIndicator.translatesAutoresizingMaskIntoConstraints = false\n activityIndicator.tintColor = .white\n activityIndicator.setContentHuggingPriority(.defaultHigh, for: .horizontal)\n activityIndicator.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)\n return activityIndicator\n }()\n\n private let mapViewController = MapViewController()\n\n override var preferredStatusBarStyle: UIStatusBarStyle {\n .lightContent\n }\n\n var preferredHeaderBarPresentation: HeaderBarPresentation {\n switch interactor.deviceState {\n case .loggedIn, .revoked:\n return HeaderBarPresentation(\n style: tunnelState.isSecured ? .secured : .unsecured,\n showsDivider: false\n )\n case .loggedOut:\n return HeaderBarPresentation(style: .default, showsDivider: true)\n }\n }\n\n var prefersHeaderBarHidden: Bool {\n false\n }\n\n var prefersNotificationBarHidden: Bool {\n false\n }\n\n init(interactor: TunnelViewControllerInteractor) {\n self.interactor = interactor\n\n tunnelState = interactor.tunnelStatus.state\n connectionViewViewModel = ConnectionViewViewModel(\n tunnelStatus: interactor.tunnelStatus,\n relayConstraints: interactor.tunnelSettings.relayConstraints,\n relayCache: RelayCache(cacheDirectory: ApplicationConfiguration.containerURL),\n customListRepository: CustomListRepository()\n )\n indicatorsViewViewModel = FeatureIndicatorsViewModel(\n tunnelSettings: interactor.tunnelSettings,\n ipOverrides: interactor.ipOverrides,\n tunnelStatus: interactor.tunnelStatus\n )\n\n connectionView = ConnectionView(\n connectionViewModel: connectionViewViewModel,\n indicatorsViewModel: indicatorsViewViewModel\n )\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 interactor.didUpdateDeviceState = { [weak self] _, _ in\n self?.setNeedsHeaderBarStyleAppearanceUpdate()\n }\n\n interactor.didUpdateTunnelStatus = { [weak self] tunnelStatus in\n self?.connectionViewViewModel.update(tunnelStatus: tunnelStatus)\n self?.setTunnelState(tunnelStatus.state, animated: true)\n self?.indicatorsViewViewModel.tunnelState = tunnelStatus.state\n self?.indicatorsViewViewModel.observedState = tunnelStatus.observedState\n self?.view.setNeedsLayout()\n }\n\n interactor.didGetOutgoingAddress = { [weak self] outgoingConnectionInfo in\n self?.connectionViewViewModel.outgoingConnectionInfo = outgoingConnectionInfo\n }\n\n interactor.didUpdateTunnelSettings = { [weak self] tunnelSettings in\n self?.indicatorsViewViewModel.tunnelSettings = tunnelSettings\n self?.connectionViewViewModel.relayConstraints = tunnelSettings.relayConstraints\n }\n\n interactor.didUpdateIpOverrides = { [weak self] overrides in\n self?.indicatorsViewViewModel.ipOverrides = overrides\n }\n\n connectionView.action = { [weak self] action in\n switch action {\n case .connect:\n self?.interactor.startTunnel()\n\n case .cancel:\n if case .waitingForConnectivity(.noConnection) = self?.interactor.tunnelStatus.state {\n self?.shouldShowCancelTunnelAlert?()\n } else {\n self?.interactor.stopTunnel()\n }\n\n case .disconnect:\n self?.interactor.stopTunnel()\n\n case .reconnect:\n self?.interactor.reconnectTunnel(selectNewRelay: true)\n\n case .selectLocation:\n self?.shouldShowSelectLocationPicker?()\n }\n }\n\n addMapController()\n addActivityIndicator()\n addConnectionView()\n updateMap(animated: false)\n }\n\n func setMainContentHidden(_ isHidden: Bool, animated: Bool) {\n let actions = {\n _ = self.connectionView.opacity(isHidden ? 0 : 1)\n }\n\n if animated {\n UIView.animate(withDuration: 0.25, animations: actions)\n } else {\n actions()\n }\n }\n\n // MARK: - Private\n\n private func setTunnelState(_ tunnelState: TunnelState, animated: Bool) {\n self.tunnelState = tunnelState\n\n setNeedsHeaderBarStyleAppearanceUpdate()\n\n guard isViewLoaded else { return }\n\n updateMap(animated: animated)\n }\n\n private func updateMap(animated: Bool) {\n switch tunnelState {\n case let .connecting(tunnelRelays, _, _):\n mapViewController.removeLocationMarker()\n mapViewController.setCenter(tunnelRelays?.exit.location.geoCoordinate, animated: animated)\n activityIndicator.startAnimating()\n\n case let .reconnecting(tunnelRelays, _, _), let .negotiatingEphemeralPeer(tunnelRelays, _, _, _):\n activityIndicator.startAnimating()\n mapViewController.removeLocationMarker()\n mapViewController.setCenter(tunnelRelays.exit.location.geoCoordinate, animated: animated)\n\n case let .connected(tunnelRelays, _, _):\n let center = tunnelRelays.exit.location.geoCoordinate\n mapViewController.setCenter(center, animated: animated)\n activityIndicator.stopAnimating()\n mapViewController.addLocationMarker(coordinate: center)\n\n case .pendingReconnect:\n activityIndicator.startAnimating()\n mapViewController.removeLocationMarker()\n\n case .waitingForConnectivity, .error:\n activityIndicator.stopAnimating()\n mapViewController.removeLocationMarker()\n\n case .disconnected, .disconnecting:\n activityIndicator.stopAnimating()\n mapViewController.removeLocationMarker()\n mapViewController.setCenter(nil, animated: animated)\n }\n }\n\n private func addMapController() {\n let mapView = mapViewController.view!\n\n addChild(mapViewController)\n mapViewController.alignmentView = activityIndicator\n mapViewController.didMove(toParent: self)\n\n view.addConstrainedSubviews([mapView]) {\n mapView.pinEdgesToSuperview()\n }\n }\n\n /// Computes a constraint multiplier based on the screen size\n private func computeHeightBreakpointMultiplier() -> CGFloat {\n let screenBounds = UIWindow().screen.coordinateSpace.bounds\n return screenBounds.height < 700 ? 2.0 : 1.5\n }\n\n private func addActivityIndicator() {\n // If the device doesn't have a lot of vertical screen estate, center the progress view higher on the map\n // so the connection view details do not shadow it unless fully expanded if possible\n let heightConstraintMultiplier = computeHeightBreakpointMultiplier()\n\n let verticalCenteredAnchor = activityIndicator.centerYAnchor.anchorWithOffset(to: view.centerYAnchor)\n view.addConstrainedSubviews([activityIndicator]) {\n activityIndicator.centerXAnchor.constraint(equalTo: view.centerXAnchor)\n verticalCenteredAnchor.constraint(\n equalTo: activityIndicator.heightAnchor,\n multiplier: heightConstraintMultiplier\n )\n }\n }\n\n private func addConnectionView() {\n let connectionController = UIHostingController(rootView: connectionView)\n self.connectionController = connectionController\n\n let connectionViewProxy = connectionController.view!\n connectionViewProxy.backgroundColor = .clear\n\n addChild(connectionController)\n connectionController.didMove(toParent: self)\n view.addConstrainedSubviews([activityIndicator, connectionViewProxy]) {\n connectionViewProxy.pinEdgesToSuperview(.all())\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Tunnel\TunnelViewController.swift
TunnelViewController.swift
Swift
9,119
0.95
0.035714
0.053922
react-lib
637
2023-10-20T11:28:53.414748
BSD-3-Clause
false
2871562777aad4d19d6016a59947179b
//\n// TunnelViewControllerInteractor.swift\n// MullvadVPN\n//\n// Created by pronebird on 26/10/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport MullvadSettings\nimport MullvadTypes\n\nfinal class TunnelViewControllerInteractor: @unchecked Sendable {\n private let tunnelManager: TunnelManager\n private let outgoingConnectionService: OutgoingConnectionServiceHandling\n private var tunnelObserver: TunnelObserver?\n private var outgoingConnectionTask: Task<Void, Error>?\n private var ipOverrideRepository: IPOverrideRepositoryProtocol\n private var cancellables: Set<Combine.AnyCancellable> = []\n\n var didUpdateTunnelStatus: ((TunnelStatus) -> Void)?\n var didUpdateDeviceState: ((_ deviceState: DeviceState, _ previousDeviceState: DeviceState) -> Void)?\n var didUpdateTunnelSettings: ((LatestTunnelSettings) -> Void)?\n var didUpdateIpOverrides: (([IPOverride]) -> Void)?\n var didGetOutgoingAddress: (@MainActor (OutgoingConnectionInfo) -> Void)?\n\n var tunnelStatus: TunnelStatus {\n tunnelManager.tunnelStatus\n }\n\n var deviceState: DeviceState {\n tunnelManager.deviceState\n }\n\n var tunnelSettings: LatestTunnelSettings {\n tunnelManager.settings\n }\n\n var ipOverrides: [IPOverride] {\n ipOverrideRepository.fetchAll()\n }\n\n deinit {\n outgoingConnectionTask?.cancel()\n }\n\n init(\n tunnelManager: TunnelManager,\n outgoingConnectionService: OutgoingConnectionServiceHandling,\n ipOverrideRepository: IPOverrideRepositoryProtocol\n ) {\n self.tunnelManager = tunnelManager\n self.outgoingConnectionService = outgoingConnectionService\n self.ipOverrideRepository = ipOverrideRepository\n\n let tunnelObserver = TunnelBlockObserver(\n didUpdateTunnelStatus: { [weak self] _, tunnelStatus in\n guard let self else { return }\n outgoingConnectionTask?.cancel()\n didUpdateTunnelStatus?(tunnelStatus)\n if case .connected = tunnelStatus.state {\n outgoingConnectionTask = Task(priority: .high) { [weak self] in\n guard let outgoingConnectionInfo = try await self?.outgoingConnectionService\n .getOutgoingConnectionInfo() else {\n return\n }\n await self?.didGetOutgoingAddress?(outgoingConnectionInfo)\n }\n }\n },\n didUpdateDeviceState: { [weak self] _, deviceState, previousDeviceState in\n self?.didUpdateDeviceState?(deviceState, previousDeviceState)\n },\n didUpdateTunnelSettings: { [weak self] _, tunnelSettings in\n self?.didUpdateTunnelSettings?(tunnelSettings)\n }\n )\n\n tunnelManager.addObserver(tunnelObserver)\n\n self.tunnelObserver = tunnelObserver\n\n ipOverrideRepository.overridesPublisher\n .sink { [weak self] overrides in\n self?.didUpdateIpOverrides?(overrides)\n }\n .store(in: &cancellables)\n }\n\n func startTunnel() {\n tunnelManager.startTunnel()\n }\n\n func stopTunnel() {\n tunnelManager.stopTunnel()\n }\n\n func reconnectTunnel(selectNewRelay: Bool) {\n tunnelManager.reconnectTunnel(selectNewRelay: selectNewRelay)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Tunnel\TunnelViewControllerInteractor.swift
TunnelViewControllerInteractor.swift
Swift
3,430
0.95
0.029703
0.082353
awesome-app
326
2023-08-25T10:08:28.358602
GPL-3.0
false
557c5691b7948003cd88024fad93ae03
//\n// ButtonPanel.swift\n// MullvadVPN\n//\n// Created by Andrew Bulhak on 2025-01-03.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport SwiftUI\n\nextension ConnectionView {\n internal struct ButtonPanel: View {\n typealias Action = (ConnectionViewViewModel.TunnelAction) -> Void\n\n @ObservedObject var viewModel: ConnectionViewViewModel\n var action: Action?\n\n var body: some View {\n VStack(spacing: 16) {\n locationButton(with: action)\n .disabled(viewModel.disableButtons)\n actionButton(with: action)\n .disabled(viewModel.disableButtons)\n }\n }\n\n @ViewBuilder\n private func locationButton(with action: Action?) -> some View {\n switch viewModel.tunnelStatus.state {\n case .connecting, .connected, .reconnecting, .waitingForConnectivity, .negotiatingEphemeralPeer, .error:\n SplitMainButton(\n text: viewModel.localizedTitleForSelectLocationButton,\n image: .iconReload,\n style: .default,\n accessibilityId: .selectLocationButton,\n primaryAction: { action?(.selectLocation) },\n secondaryAction: { action?(.reconnect) }\n )\n case .disconnecting, .pendingReconnect, .disconnected:\n MainButton(\n text: viewModel.localizedTitleForSelectLocationButton,\n style: .default,\n action: { action?(.selectLocation) }\n )\n .accessibilityIdentifier(AccessibilityIdentifier.selectLocationButton.asString)\n }\n }\n\n @ViewBuilder\n private func actionButton(with action: Action?) -> some View {\n switch viewModel.actionButton {\n case .connect:\n MainButton(\n text: LocalizedStringKey("Connect"),\n style: .success,\n action: { action?(.connect) }\n )\n .accessibilityIdentifier(AccessibilityIdentifier.connectButton.asString)\n case .disconnect:\n MainButton(\n text: LocalizedStringKey("Disconnect"),\n style: .danger,\n action: { action?(.disconnect) }\n )\n .accessibilityIdentifier(AccessibilityIdentifier.disconnectButton.asString)\n case .cancel:\n MainButton(\n text: LocalizedStringKey(\n viewModel.tunnelStatus.state == .waitingForConnectivity(.noConnection)\n ? "Disconnect"\n : "Cancel"\n ),\n style: .danger,\n action: { action?(.cancel) }\n )\n .accessibilityIdentifier(\n viewModel.tunnelStatus.state == .waitingForConnectivity(.noConnection)\n ? AccessibilityIdentifier.disconnectButton.asString\n : AccessibilityIdentifier.cancelButton.asString\n )\n }\n }\n }\n}\n\n#Preview {\n ConnectionViewComponentPreview(showIndicators: true) { _, vm, _ in\n ConnectionView.ButtonPanel(viewModel: vm, action: nil)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Tunnel\ConnectionView\ButtonPanel.swift
ButtonPanel.swift
Swift
3,389
0.95
0.022222
0.096386
awesome-app
979
2023-08-21T22:48:22.737713
BSD-3-Clause
false
885548a0293c430a4970e690a745e227
//\n// ConnectionView.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-12-03.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport SwiftUI\n\nstruct ConnectionView: View {\n @ObservedObject var connectionViewModel: ConnectionViewViewModel\n @ObservedObject var indicatorsViewModel: FeatureIndicatorsViewModel\n\n @State private(set) var isExpanded = false\n\n @State private(set) var scrollViewHeight: CGFloat = 0\n var hasFeatureIndicators: Bool { !indicatorsViewModel.chips.isEmpty }\n var action: ButtonPanel.Action?\n\n var body: some View {\n VStack {\n Spacer()\n .accessibilityIdentifier(AccessibilityIdentifier.connectionView.asString)\n VStack(spacing: 16) {\n VStack(alignment: .leading, spacing: 0) {\n HeaderView(viewModel: connectionViewModel, isExpanded: $isExpanded)\n .padding(.bottom, 8)\n Divider()\n .background(UIColor.secondaryTextColor.color)\n .padding(.bottom, 16)\n .showIf(isExpanded)\n\n ScrollView {\n HStack {\n VStack(alignment: .leading, spacing: 0) {\n Text(LocalizedStringKey("Active features"))\n .font(.footnote.weight(.semibold))\n .foregroundStyle(UIColor.primaryTextColor.color.opacity(0.6))\n .showIf(isExpanded && hasFeatureIndicators)\n\n ChipContainerView(\n viewModel: indicatorsViewModel,\n tunnelState: connectionViewModel.tunnelStatus.state,\n isExpanded: $isExpanded\n )\n .padding(.bottom, isExpanded ? 16 : 0)\n .showIf(hasFeatureIndicators)\n\n DetailsView(viewModel: connectionViewModel)\n .padding(.bottom, 8)\n .showIf(isExpanded)\n }\n Spacer()\n }\n .sizeOfView { size in\n withAnimation {\n scrollViewHeight = size.height\n }\n }\n }\n .frame(maxHeight: scrollViewHeight)\n .apply {\n if #available(iOS 16.4, *) {\n $0.scrollBounceBehavior(.basedOnSize)\n } else {\n $0\n }\n }\n }\n .transformEffect(.identity)\n .animation(.default, value: hasFeatureIndicators)\n ButtonPanel(viewModel: connectionViewModel, action: action)\n }\n .padding(16)\n .background(BlurView(style: .dark))\n .cornerRadius(12)\n .padding(EdgeInsets(top: 16, leading: 16, bottom: 24, trailing: 16))\n .onChange(of: connectionViewModel.showsConnectionDetails) { showsConnectionDetails in\n if !showsConnectionDetails {\n withAnimation {\n isExpanded = false\n }\n }\n }\n }\n }\n}\n\n#Preview("ConnectionView (Indicators)") {\n ConnectionViewComponentPreview(showIndicators: true) { indicatorModel, viewModel, _ in\n ConnectionView(connectionViewModel: viewModel, indicatorsViewModel: indicatorModel)\n }\n}\n\n#Preview("ConnectionView (No indicators)") {\n ConnectionViewComponentPreview(showIndicators: false) { indicatorModel, viewModel, _ in\n ConnectionView(connectionViewModel: viewModel, indicatorsViewModel: indicatorModel)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Tunnel\ConnectionView\ConnectionView.swift
ConnectionView.swift
Swift
4,023
0.95
0.02
0.1
node-utils
263
2025-05-05T16:02:38.659565
MIT
false
e3d94b83a923d09ae7d9449b54e4a457
//\n// ConnectionViewComponentPreview.swift\n// MullvadVPN\n//\n// Created by Andrew Bulhak on 2025-01-03.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadMockData\nimport MullvadREST\nimport MullvadSettings\nimport MullvadTypes\nimport PacketTunnelCore\nimport SwiftUI\n\nstruct ConnectionViewComponentPreview<Content: View>: View {\n let showIndicators: Bool\n let connectedTunnelStatus = TunnelStatus(\n observedState: .connected(ObservedConnectionState(\n selectedRelays: SelectedRelaysStub.selectedRelays,\n relayConstraints: RelayConstraints(entryLocations: .any, exitLocations: .any, port: .any, filter: .any),\n networkReachability: .reachable,\n connectionAttemptCount: 0,\n transportLayer: .udp,\n remotePort: 80,\n isPostQuantum: true,\n isDaitaEnabled: true\n )),\n state: .connected(SelectedRelaysStub.selectedRelays, isPostQuantum: true, isDaita: true)\n )\n\n private var tunnelSettings: LatestTunnelSettings {\n LatestTunnelSettings(\n wireGuardObfuscation: WireGuardObfuscationSettings(state: showIndicators ? .udpOverTcp : .off),\n tunnelQuantumResistance: showIndicators ? .on : .off,\n tunnelMultihopState: showIndicators ? .on : .off,\n daita: DAITASettings(daitaState: showIndicators ? .on : .off)\n )\n }\n\n private let viewModel: ConnectionViewViewModel\n\n var content: (FeatureIndicatorsViewModel, ConnectionViewViewModel, Binding<Bool>) -> Content\n\n @State var isExpanded = false\n\n init(\n showIndicators: Bool,\n content: @escaping (FeatureIndicatorsViewModel, ConnectionViewViewModel, Binding<Bool>) -> Content\n ) {\n self.showIndicators = showIndicators\n self.content = content\n viewModel = ConnectionViewViewModel(\n tunnelStatus: connectedTunnelStatus,\n relayConstraints: RelayConstraints(),\n relayCache: RelayCache(cacheDirectory: ApplicationConfiguration.containerURL),\n customListRepository: CustomListRepository()\n )\n viewModel.outgoingConnectionInfo = OutgoingConnectionInfo(\n ipv4: .init(ip: .allHostsGroup, exitIP: true),\n ipv6: IPV6ConnectionData(\n ip: .broadcast,\n exitIP: true\n )\n )\n }\n\n var body: some View {\n content(\n FeatureIndicatorsViewModel(\n tunnelSettings: tunnelSettings,\n ipOverrides: [],\n tunnelStatus: connectedTunnelStatus\n ),\n viewModel,\n $isExpanded\n )\n .background(UIColor.secondaryColor.color)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Tunnel\ConnectionView\ConnectionViewComponentPreview.swift
ConnectionViewComponentPreview.swift
Swift
2,729
0.95
0
0.097222
vue-tools
108
2023-11-04T05:24:23.285690
BSD-3-Clause
false
b1c227cb9bff7a457e408f09d9be2a0e
//\n// ConnectionViewViewModel.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-12-09.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport MullvadREST\nimport MullvadSettings\nimport MullvadTypes\nimport SwiftUI\n\nclass ConnectionViewViewModel: ObservableObject {\n enum TunnelActionButton {\n case connect\n case disconnect\n case cancel\n }\n\n enum TunnelAction {\n case connect\n case disconnect\n case cancel\n case reconnect\n case selectLocation\n }\n\n @Published private(set) var tunnelStatus: TunnelStatus\n @Published var outgoingConnectionInfo: OutgoingConnectionInfo?\n @Published var showsActivityIndicator = false\n\n @Published var relayConstraints: RelayConstraints\n let destinationDescriber: DestinationDescribing\n\n var tunnelIsConnected: Bool {\n if case .connected = tunnelStatus.state {\n true\n } else {\n false\n }\n }\n\n var connectionName: String? {\n if case let .only(loc) = relayConstraints.exitLocations {\n return destinationDescriber.describe(loc)\n }\n return nil\n }\n\n init(\n tunnelStatus: TunnelStatus,\n relayConstraints: RelayConstraints,\n relayCache: RelayCacheProtocol,\n customListRepository: CustomListRepositoryProtocol\n ) {\n self.tunnelStatus = tunnelStatus\n self.relayConstraints = relayConstraints\n self.destinationDescriber = DestinationDescriber(\n relayCache: relayCache,\n customListRepository: customListRepository\n )\n }\n\n func update(tunnelStatus: TunnelStatus) {\n self.tunnelStatus = tunnelStatus\n }\n}\n\nextension ConnectionViewViewModel {\n var showsConnectionDetails: Bool {\n switch tunnelStatus.state {\n case .connecting, .reconnecting, .negotiatingEphemeralPeer,\n .connected, .pendingReconnect:\n true\n case .disconnecting, .disconnected, .waitingForConnectivity, .error:\n false\n }\n }\n\n var textColorForSecureLabel: UIColor {\n switch tunnelStatus.state {\n case .connecting, .reconnecting, .waitingForConnectivity(.noConnection), .negotiatingEphemeralPeer,\n .pendingReconnect, .disconnecting:\n .white\n case .connected:\n .successColor\n case .disconnected, .waitingForConnectivity(.noNetwork), .error:\n .dangerColor\n }\n }\n\n var disableButtons: Bool {\n if case .waitingForConnectivity(.noNetwork) = tunnelStatus.state {\n true\n } else {\n false\n }\n }\n\n var localizedTitleForSecureLabel: LocalizedStringKey {\n switch tunnelStatus.state {\n case .connecting, .reconnecting, .negotiatingEphemeralPeer:\n LocalizedStringKey("Connecting...")\n case .connected:\n LocalizedStringKey("Connected")\n case .disconnecting(.nothing):\n LocalizedStringKey("Disconnecting...")\n case .disconnecting(.reconnect), .pendingReconnect:\n LocalizedStringKey("Reconnecting")\n case .disconnected:\n LocalizedStringKey("Disconnected")\n case .waitingForConnectivity(.noConnection), .error:\n LocalizedStringKey("Blocked connection")\n case .waitingForConnectivity(.noNetwork):\n LocalizedStringKey("No network")\n }\n }\n\n var accessibilityIdForSecureLabel: AccessibilityIdentifier {\n switch tunnelStatus.state {\n case .connected:\n .connectionStatusConnectedLabel\n case .connecting:\n .connectionStatusConnectingLabel\n default:\n .connectionStatusNotConnectedLabel\n }\n }\n\n var localizedAccessibilityLabelForSecureLabel: LocalizedStringKey {\n switch tunnelStatus.state {\n case .disconnected, .waitingForConnectivity, .disconnecting, .pendingReconnect, .error:\n localizedTitleForSecureLabel\n case let .connected(tunnelInfo, _, _):\n LocalizedStringKey("Connected to \(tunnelInfo.exit.location.city), \(tunnelInfo.exit.location.country)")\n case let .connecting(tunnelInfo, _, _):\n if let tunnelInfo {\n LocalizedStringKey(\n "Connecting to \(tunnelInfo.exit.location.city), \(tunnelInfo.exit.location.country)"\n )\n } else {\n localizedTitleForSecureLabel\n }\n case let .reconnecting(tunnelInfo, _, _), let .negotiatingEphemeralPeer(tunnelInfo, _, _, _):\n LocalizedStringKey("Reconnecting to \(tunnelInfo.exit.location.city), \(tunnelInfo.exit.location.country)")\n }\n }\n\n var localizedTitleForSelectLocationButton: LocalizedStringKey {\n switch tunnelStatus.state {\n case .disconnecting, .pendingReconnect, .disconnected, .waitingForConnectivity(.noNetwork):\n LocalizedStringKey(connectionName ?? "Select location")\n case .connecting, .connected, .reconnecting, .waitingForConnectivity(.noConnection),\n .negotiatingEphemeralPeer, .error:\n LocalizedStringKey("Switch location")\n }\n }\n\n var actionButton: TunnelActionButton {\n switch tunnelStatus.state {\n case .disconnected, .disconnecting(.nothing), .waitingForConnectivity(.noNetwork):\n .connect\n case .connecting, .pendingReconnect, .disconnecting(.reconnect), .waitingForConnectivity(.noConnection),\n .negotiatingEphemeralPeer:\n .cancel\n case .connected, .reconnecting, .error:\n .disconnect\n }\n }\n\n var titleForCountryAndCity: LocalizedStringKey? {\n guard let tunnelRelays = tunnelStatus.state.relays else {\n return nil\n }\n\n return LocalizedStringKey("\(tunnelRelays.exit.location.country), \(tunnelRelays.exit.location.city)")\n }\n\n var titleForServer: LocalizedStringKey? {\n guard let tunnelRelays = tunnelStatus.state.relays else {\n return nil\n }\n\n let exitName = tunnelRelays.exit.hostname\n let entryName = tunnelRelays.entry?.hostname\n\n return if let entryName {\n LocalizedStringKey("\(exitName) via \(entryName)")\n } else {\n LocalizedStringKey("\(exitName)")\n }\n }\n\n var inAddress: String? {\n guard let tunnelRelays = tunnelStatus.state.relays else {\n return nil\n }\n\n let observedTunnelState = tunnelStatus.observedState\n\n var portAndTransport = ""\n if let inPort = observedTunnelState.connectionState?.remotePort {\n let protocolLayer = observedTunnelState.connectionState?.transportLayer == .tcp ? "TCP" : "UDP"\n portAndTransport = ":\(inPort) \(protocolLayer)"\n }\n\n guard\n let address = tunnelRelays.entry?.endpoint.ipv4Relay.ip\n ?? tunnelStatus.state.relays?.exit.endpoint.ipv4Relay.ip\n else {\n return nil\n }\n\n return "\(address)\(portAndTransport)"\n }\n\n var outAddressIpv4: String? {\n guard\n let outgoingConnectionInfo,\n let address = outgoingConnectionInfo.ipv4.exitIP ? outgoingConnectionInfo.ipv4.ip : nil\n else {\n return nil\n }\n\n return "\(address)"\n }\n\n var outAddressIpv6: String? {\n guard\n let outgoingConnectionInfo,\n let ipv6 = outgoingConnectionInfo.ipv6,\n let address = ipv6.exitIP ? ipv6.ip : nil\n else {\n return nil\n }\n\n return "\(address)"\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Tunnel\ConnectionView\ConnectionViewViewModel.swift
ConnectionViewViewModel.swift
Swift
7,661
0.95
0.058091
0.033333
node-utils
210
2025-02-06T14:39:05.204941
Apache-2.0
false
240e9a01ba2c9e18a5007ad24bfbdcf8
//\n// DestinationDescriber.swift\n// MullvadVPN\n//\n// Created by Andrew Bulhak on 2025-01-20.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n// A source of truth for converting an exit relay destination (i.e., a relay or list) into a name\n\nimport MullvadREST\nimport MullvadSettings\nimport MullvadTypes\n\nprotocol DestinationDescribing {\n func describe(_ destination: UserSelectedRelays) -> String?\n}\n\nstruct DestinationDescriber: DestinationDescribing {\n let relayCache: RelayCacheProtocol\n let customListRepository: CustomListRepositoryProtocol\n\n public init(\n relayCache: RelayCacheProtocol,\n customListRepository: CustomListRepositoryProtocol\n ) {\n self.relayCache = relayCache\n self.customListRepository = customListRepository\n }\n\n private func customListDescription(_ destination: UserSelectedRelays) -> String? {\n // We only return a description for the list if the user has selected the\n // entire list. If they have only selected relays/locations from it,\n // we show those as if they selected them from elsewhere.\n guard\n let customListSelection = destination.customListSelection,\n customListSelection.isList,\n let customList = customListRepository.fetch(by: customListSelection.listId)\n else { return nil }\n return customList.name\n }\n\n private func describeRelayLocation(\n _ locationSpec: RelayLocation,\n usingRelayWithLocation serverLocation: Location\n ) -> String {\n switch locationSpec {\n case .country: serverLocation.country\n case .city: serverLocation.city\n case let .hostname(_, _, hostname):\n "\(serverLocation.city) (\(hostname))"\n }\n }\n\n private func relayDescription(_ destination: UserSelectedRelays) -> String? {\n guard\n let location = destination.locations.first,\n let cachedRelays = try? relayCache.read().relays\n else { return nil }\n let locatedRelays = RelayWithLocation.locateRelays(\n relays: cachedRelays.wireguard.relays,\n locations: cachedRelays.locations\n )\n\n guard let matchingRelay = (locatedRelays.first { $0.matches(location: location)\n }) else { return nil }\n\n return describeRelayLocation(location, usingRelayWithLocation: matchingRelay.serverLocation)\n }\n\n func describe(_ destination: UserSelectedRelays) -> String? {\n customListDescription(destination) ?? relayDescription(destination)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Tunnel\ConnectionView\DestinationDescriber.swift
DestinationDescriber.swift
Swift
2,557
0.95
0.082192
0.174603
react-lib
613
2025-03-21T19:11:45.464572
GPL-3.0
false
cedb3a2ac9c7b89f609abb4fa9f6f358
//\n// DetailsView.swift\n// MullvadVPN\n//\n// Created by Andrew Bulhak on 2025-01-03.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport SwiftUI\n\nextension ConnectionView {\n internal struct DetailsView: View {\n @ObservedObject var viewModel: ConnectionViewViewModel\n @State private var columnWidth: CGFloat = 0\n\n var body: some View {\n VStack(alignment: .leading, spacing: 8) {\n HStack {\n Text(LocalizedStringKey("Connection details"))\n .font(.footnote.weight(.semibold))\n .foregroundStyle(UIColor.primaryTextColor.color.opacity(0.6))\n Spacer()\n }\n\n VStack(alignment: .leading, spacing: 0) {\n if let inAddress = viewModel.inAddress {\n connectionDetailRow(\n title: LocalizedStringKey("In"),\n value: inAddress,\n accessibilityId: .connectionPanelInAddressRow\n )\n }\n if viewModel.tunnelIsConnected {\n if let outAddressIpv4 = viewModel.outAddressIpv4 {\n connectionDetailRow(\n title: LocalizedStringKey("Out IPv4"),\n value: outAddressIpv4,\n accessibilityId: .connectionPanelOutAddressRow\n )\n }\n if let outAddressIpv6 = viewModel.outAddressIpv6 {\n connectionDetailRow(\n title: LocalizedStringKey("Out IPv6"),\n value: outAddressIpv6,\n accessibilityId: .connectionPanelOutIpv6AddressRow\n )\n }\n }\n }\n }\n .animation(.default, value: viewModel.inAddress)\n .animation(.default, value: viewModel.tunnelIsConnected)\n }\n\n @ViewBuilder\n private func connectionDetailRow(\n title: LocalizedStringKey,\n value: String,\n accessibilityId: AccessibilityIdentifier\n ) -> some View {\n HStack(alignment: .top, spacing: 8) {\n Text(title)\n .font(.subheadline)\n .foregroundStyle(UIColor.primaryTextColor.color.opacity(0.6))\n .frame(minWidth: columnWidth, alignment: .leading)\n .sizeOfView { columnWidth = max(columnWidth, $0.width) }\n Text(value)\n .font(.subheadline)\n .foregroundStyle(UIColor.primaryTextColor.color)\n .accessibilityIdentifier(accessibilityId.asString)\n }\n }\n }\n}\n\n#Preview {\n ConnectionViewComponentPreview(showIndicators: true) { _, vm, _ in\n ConnectionView.DetailsView(viewModel: vm)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Tunnel\ConnectionView\DetailsView.swift
DetailsView.swift
Swift
3,069
0.95
0.05
0.108108
node-utils
647
2023-09-26T04:49:59.385377
GPL-3.0
false
fe261cf055443359cdba01ddb97f2d3d
//\n// FeatureIndicatorsViewModel.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2024-12-05.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\nimport PacketTunnelCore\nimport SwiftUI\n\nclass FeatureIndicatorsViewModel: ChipViewModelProtocol {\n @Published var tunnelSettings: LatestTunnelSettings\n @Published var ipOverrides: [IPOverride]\n @Published var tunnelState: TunnelState\n @Published var observedState: ObservedState\n\n init(\n tunnelSettings: LatestTunnelSettings,\n ipOverrides: [IPOverride],\n tunnelStatus: TunnelStatus\n ) {\n self.tunnelSettings = tunnelSettings\n self.ipOverrides = ipOverrides\n self.tunnelState = tunnelStatus.state\n self.observedState = tunnelStatus.observedState\n }\n\n var chips: [ChipModel] {\n // Here can be a check if a feature indicator should show in other connection states\n // e.g. Access local network in blocked state\n switch tunnelState {\n case .connecting, .reconnecting, .negotiatingEphemeralPeer,\n .connected, .pendingReconnect:\n let features: [ChipFeature] = [\n DaitaFeature(state: tunnelState),\n QuantumResistanceFeature(state: tunnelState),\n MultihopFeature(state: tunnelState),\n ObfuscationFeature(settings: tunnelSettings, state: observedState),\n DNSFeature(settings: tunnelSettings),\n IPOverrideFeature(overrides: ipOverrides),\n ]\n\n return features\n .filter { $0.isEnabled }\n .map { ChipModel(name: $0.name) }\n default:\n return []\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Tunnel\ConnectionView\FeatureIndicatorsViewModel.swift
FeatureIndicatorsViewModel.swift
Swift
1,714
0.95
0.057692
0.191489
node-utils
826
2024-02-06T20:22:17.837735
Apache-2.0
false
7a592bfc1b7d62ee37d7e286606b11b0
//\n// HeaderView.swift\n// MullvadVPN\n//\n// Created by Andrew Bulhak on 2025-01-03.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport SwiftUI\n\nextension ConnectionView {\n internal struct HeaderView: View {\n @ObservedObject var viewModel: ConnectionViewViewModel\n @Binding var isExpanded: Bool\n\n @State var titleForCountryAndCity: LocalizedStringKey?\n @State var titleForServer: LocalizedStringKey?\n\n var body: some View {\n Button {\n withAnimation {\n isExpanded.toggle()\n }\n } label: {\n HStack(alignment: .top) {\n VStack(alignment: .leading, spacing: 0) {\n Text(viewModel.localizedTitleForSecureLabel)\n .textCase(.uppercase)\n .font(.title3.weight(.semibold))\n .foregroundStyle(viewModel.textColorForSecureLabel.color)\n .accessibilityIdentifier(viewModel.accessibilityIdForSecureLabel.asString)\n .accessibilityLabel(viewModel.localizedAccessibilityLabelForSecureLabel)\n if let titleForCountryAndCity {\n Text(titleForCountryAndCity)\n .font(.title3.weight(.semibold))\n .foregroundStyle(UIColor.primaryTextColor.color)\n .padding(.top, 4)\n }\n if let titleForServer {\n Text(titleForServer)\n .font(.body)\n .foregroundStyle(UIColor.primaryTextColor.color.opacity(0.6))\n .padding(.top, 2)\n .accessibilityIdentifier(AccessibilityIdentifier.connectionPanelServerLabel.asString)\n }\n }\n\n Group {\n Spacer()\n Button {\n withAnimation {\n isExpanded.toggle()\n }\n } label: {\n Image(.iconChevronUp)\n .renderingMode(.template)\n .rotationEffect(isExpanded ? .degrees(-180) : .degrees(0))\n .foregroundStyle(.white)\n .accessibilityIdentifier(AccessibilityIdentifier.relayStatusCollapseButton.asString)\n }\n }\n .showIf(viewModel.showsConnectionDetails)\n }\n .onAppear {\n titleForServer = viewModel.titleForServer\n titleForCountryAndCity = viewModel.titleForCountryAndCity\n }\n .onChange(of: viewModel.titleForCountryAndCity, perform: { newValue in\n withAnimation {\n titleForCountryAndCity = newValue\n }\n })\n .onChange(of: viewModel.titleForServer, perform: { newValue in\n withAnimation {\n titleForServer = newValue\n }\n })\n }\n .disabled(!viewModel.showsConnectionDetails)\n }\n }\n}\n\n#Preview {\n ConnectionViewComponentPreview(showIndicators: true) { _, vm, isExpanded in\n ConnectionView.HeaderView(viewModel: vm, isExpanded: isExpanded)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Tunnel\ConnectionView\HeaderView.swift
HeaderView.swift
Swift
3,610
0.95
0.022727
0.097561
node-utils
525
2025-04-08T23:01:16.088698
GPL-3.0
false
b32113ad5e9d993b0dac09cf542a6097
//\n// ChipContainerView.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2024-12-05.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport SwiftUI\n\nstruct ChipContainerView<ViewModel>: View where ViewModel: ChipViewModelProtocol {\n @ObservedObject var viewModel: ViewModel\n let tunnelState: TunnelState\n @Binding var isExpanded: Bool\n\n @State private var chipContainerHeight: CGFloat = .zero\n private let verticalPadding: CGFloat = 8\n\n var body: some View {\n GeometryReader { geo in\n let containerWidth = geo.size.width\n\n let (chipsToAdd, showMoreButton) = if isExpanded {\n (viewModel.chips, false)\n } else {\n viewModel.chipsToAdd(forContainerWidth: containerWidth)\n }\n\n HStack {\n ZStack(alignment: .topLeading) {\n createChipViews(chips: chipsToAdd, containerWidth: containerWidth)\n }\n\n Button(LocalizedStringKey("\(viewModel.chips.count - chipsToAdd.count) more...")) {\n withAnimation {\n isExpanded.toggle()\n }\n }\n .font(.subheadline)\n .lineLimit(1)\n .foregroundStyle(UIColor.primaryTextColor.color)\n .showIf(showMoreButton)\n .transition(.move(edge: .bottom).combined(with: .opacity))\n\n Spacer()\n }\n .sizeOfView { size in\n withAnimation {\n chipContainerHeight = size.height\n }\n }\n }\n .frame(height: chipContainerHeight)\n }\n\n private func createChipViews(chips: [ChipModel], containerWidth: CGFloat) -> some View {\n nonisolated(unsafe) var width = CGFloat.zero\n nonisolated(unsafe) var height = CGFloat.zero\n\n return ForEach(chips) { data in\n ChipView(item: data)\n .padding(\n EdgeInsets(\n top: verticalPadding,\n leading: 0,\n bottom: verticalPadding,\n trailing: UIMetrics.FeatureIndicators.chipViewTrailingMargin\n )\n )\n .alignmentGuide(.leading) { dimension in\n if abs(width - dimension.width) > containerWidth {\n width = 0\n height -= dimension.height\n }\n let result = width\n if data.id == chips.last?.id {\n width = 0\n } else {\n width -= dimension.width\n }\n return result\n }\n .alignmentGuide(.top) { _ in\n let result = height\n if data.id == chips.last?.id {\n height = 0\n }\n return result\n }\n }\n }\n}\n\n#Preview("Tap to expand") {\n StatefulPreviewWrapper(false) { isExpanded in\n ChipContainerView(\n viewModel: MockFeatureIndicatorsViewModel(),\n tunnelState: .connected(\n .init(\n entry: nil,\n exit: .init(\n endpoint: .init(\n ipv4Relay: .init(ip: .allHostsGroup, port: 1234),\n ipv4Gateway: .allHostsGroup,\n ipv6Gateway: .broadcast,\n publicKey: Data()\n ),\n hostname: "hostname",\n location: .init(\n country: "Sweden",\n countryCode: "SE",\n city: "Gothenburg",\n cityCode: "gbg",\n latitude: 1234,\n longitude: 1234\n )\n ),\n retryAttempt: 0\n ),\n isPostQuantum: false,\n isDaita: false\n ),\n isExpanded: isExpanded\n )\n .background(UIColor.secondaryColor.color)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Tunnel\ConnectionView\ChipView\ChipContainerView.swift
ChipContainerView.swift
Swift
4,286
0.95
0.031496
0.068966
vue-tools
819
2024-10-10T17:43:03.845277
MIT
false
2520df39c30248c0cd8da1a408d9f02a
//\n// ChipFeature.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2024-12-06.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\nimport MullvadSettings\nimport PacketTunnelCore\nimport SwiftUI\n\n// Opting to use NSLocalizedString instead of LocalizedStringKey here in order\n// to be able to fetch the string value at a later point (eg. in ChipViewModelProtocol,\n// when calculating the text widths of the chips).\n\nprotocol ChipFeature {\n var isEnabled: Bool { get }\n var name: String { get }\n}\n\nstruct DaitaFeature: ChipFeature {\n let state: TunnelState\n\n var isEnabled: Bool {\n state.isDaita ?? false\n }\n\n var name: String {\n NSLocalizedString(\n "FEATURE_INDICATORS_CHIP_DAITA",\n tableName: "FeatureIndicatorsChip",\n value: "DAITA",\n comment: ""\n )\n }\n}\n\nstruct QuantumResistanceFeature: ChipFeature {\n let state: TunnelState\n\n var isEnabled: Bool {\n state.isPostQuantum ?? false\n }\n\n var name: String {\n NSLocalizedString(\n "FEATURE_INDICATORS_CHIP_QUANTUM_RESISTANCE",\n tableName: "FeatureIndicatorsChip",\n value: "Quantum resistance",\n comment: ""\n )\n }\n}\n\nstruct MultihopFeature: ChipFeature {\n let state: TunnelState\n var isEnabled: Bool {\n state.isMultihop\n }\n\n var name: String {\n NSLocalizedString(\n "FEATURE_INDICATORS_CHIP_MULTIHOP",\n tableName: "FeatureIndicatorsChip",\n value: "Multihop",\n comment: ""\n )\n }\n}\n\nstruct ObfuscationFeature: ChipFeature {\n let settings: LatestTunnelSettings\n let state: ObservedState\n\n var actualObfuscationMethod: WireGuardObfuscationState {\n state.connectionState.map { $0.obfuscationMethod } ?? .off\n }\n\n var isEnabled: Bool {\n actualObfuscationMethod != .off\n }\n\n var isAutomatic: Bool {\n settings.wireGuardObfuscation.state == .automatic\n }\n\n var name: String {\n // This just currently says "Obfuscation".\n // To add an automaticity indicator (a trailing " (automatic)"\n // or a colour/border style or whatever), use the `isAutomatic` field.\n // To say what type of obfuscation it is,\n // we can look at `actualObfuscationMethod`\n NSLocalizedString(\n "FEATURE_INDICATORS_CHIP_OBFUSCATION",\n tableName: "FeatureIndicatorsChip",\n value: "Obfuscation",\n comment: ""\n )\n }\n}\n\nstruct DNSFeature: ChipFeature {\n let settings: LatestTunnelSettings\n\n var isEnabled: Bool {\n settings.dnsSettings.enableCustomDNS || !settings.dnsSettings.blockingOptions.isEmpty\n }\n\n var name: String {\n if !settings.dnsSettings.blockingOptions.isEmpty {\n NSLocalizedString(\n "FEATURE_INDICATORS_CHIP_CONTENT_BLOCKERS",\n tableName: "FeatureIndicatorsChip",\n value: "DNS content blockers",\n comment: ""\n )\n } else {\n NSLocalizedString(\n "FEATURE_INDICATORS_CHIP_CUSTOM_DNS",\n tableName: "FeatureIndicatorsChip",\n value: "Custom DNS",\n comment: ""\n )\n }\n }\n}\n\nstruct IPOverrideFeature: ChipFeature {\n let overrides: [IPOverride]\n\n var isEnabled: Bool {\n !overrides.isEmpty\n }\n\n var name: String {\n NSLocalizedString(\n "FEATURE_INDICATORS_CHIP_IP_OVERRIDE",\n tableName: "FeatureIndicatorsChip",\n value: "Server IP Override",\n comment: ""\n )\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Tunnel\ConnectionView\ChipView\ChipFeature.swift
ChipFeature.swift
Swift
3,651
0.95
0.006993
0.122951
python-kit
902
2024-09-12T00:55:49.584898
GPL-3.0
false
e93caaae6140465771acd44f108cc194
//\n// FeatureChipModel.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2024-12-05.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport SwiftUI\n\nstruct ChipModel: Identifiable {\n var id: String { name }\n let name: String\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Tunnel\ConnectionView\ChipView\ChipModel.swift
ChipModel.swift
Swift
266
0.95
0
0.538462
awesome-app
733
2024-10-13T16:10:24.797848
Apache-2.0
false
a646eebc52d4f3d0e4bb653cf7024c2a
//\n// FeatureChipView.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2024-12-05.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport SwiftUI\n\nstruct ChipView: View {\n let item: ChipModel\n private let borderWidth: CGFloat = 1\n\n var body: some View {\n Text(item.name)\n .font(.subheadline)\n .lineLimit(1)\n .foregroundStyle(UIColor.primaryTextColor.color)\n .padding(.horizontal, UIMetrics.FeatureIndicators.chipViewHorisontalPadding)\n .padding(.vertical, 4)\n .background(\n RoundedRectangle(cornerRadius: 8)\n .stroke(\n UIColor.primaryColor.color,\n lineWidth: borderWidth\n )\n .background(\n RoundedRectangle(cornerRadius: 8)\n .fill(UIColor.secondaryColor.color)\n )\n .padding(borderWidth)\n )\n }\n}\n\n#Preview {\n ZStack {\n ChipView(item: ChipModel(name: "Example"))\n }\n .frame(maxWidth: .infinity, maxHeight: .infinity)\n .background(UIColor.secondaryColor.color)\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Tunnel\ConnectionView\ChipView\ChipView.swift
ChipView.swift
Swift
1,196
0.95
0
0.205128
python-kit
939
2023-12-27T10:59:38.699838
GPL-3.0
false
0c8fc0d35ec0fa249ce94f9917c4c3fd
//\n// ChipViewModelProtocol.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2024-12-05.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport SwiftUI\n\nprotocol ChipViewModelProtocol: ObservableObject {\n var chips: [ChipModel] { get }\n}\n\nextension ChipViewModelProtocol {\n func chipsToAdd(forContainerWidth containerWidth: CGFloat) -> (chips: [ChipModel], isOverflowing: Bool) {\n var chipsToAdd = [ChipModel]()\n var isOverflowing = false\n\n let moreTextWidth = String(\n format: NSLocalizedString(\n "CONNECTION_VIEW_CHIPS_MORE",\n tableName: "ConnectionView",\n value: "@d more...",\n comment: ""\n ), arguments: [chips.count]\n )\n .width(using: .preferredFont(forTextStyle: .subheadline)) + 4 // Some extra to be safe.\n var totalChipsWidth: CGFloat = 0\n\n for (index, chip) in chips.enumerated() {\n let textWidth = chip.name.width(using: .preferredFont(forTextStyle: .subheadline))\n let chipWidth = textWidth\n + UIMetrics.FeatureIndicators.chipViewHorisontalPadding * 2\n + UIMetrics.FeatureIndicators.chipViewTrailingMargin\n let isLastChip = index == chips.count - 1\n\n totalChipsWidth += chipWidth\n\n let chipWillFitWithMoreText = (totalChipsWidth + moreTextWidth) <= containerWidth\n let chipWillFit = totalChipsWidth <= containerWidth\n\n guard (chipWillFit && isLastChip) || chipWillFitWithMoreText else {\n isOverflowing = true\n break\n }\n\n chipsToAdd.append(chip)\n }\n\n return (chipsToAdd, isOverflowing)\n }\n}\n\nclass MockFeatureIndicatorsViewModel: ChipViewModelProtocol {\n @Published var chips: [ChipModel] = [\n ChipModel(name: "DAITA"),\n ChipModel(name: "Obfuscation"),\n ChipModel(name: "Quantum resistance"),\n ChipModel(name: "Multihop"),\n ChipModel(name: "DNS content blockers"),\n ChipModel(name: "Custom DNS"),\n ChipModel(name: "Server IP override"),\n ]\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Tunnel\ConnectionView\ChipView\ChipViewModelProtocol.swift
ChipViewModelProtocol.swift
Swift
2,137
0.95
0.030769
0.12963
react-lib
112
2024-10-01T14:56:31.707942
Apache-2.0
false
fb2771c69a5f085e506387e307436a01
//\n// CustomDNSCellFactory.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-11-09.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\nimport UIKit\n\nprotocol CustomDNSCellEventHandler {\n func addDNSEntry()\n func didChangeDNSEntry(with identifier: UUID, inputString: String) -> Bool\n func didChangeState(for preference: CustomDNSDataSource.Item, isOn: Bool)\n func showInfo(for button: VPNSettingsInfoButtonItem)\n}\n\n@MainActor\nfinal class CustomDNSCellFactory: @preconcurrency CellFactoryProtocol {\n let tableView: UITableView\n var viewModel: VPNSettingsViewModel\n var delegate: CustomDNSCellEventHandler?\n var isEditing = false\n\n init(tableView: UITableView, viewModel: VPNSettingsViewModel) {\n self.tableView = tableView\n self.viewModel = viewModel\n }\n\n func makeCell(for item: CustomDNSDataSource.Item, indexPath: IndexPath) -> UITableViewCell {\n let cell = tableView.dequeueReusableCell(withIdentifier: item.reuseIdentifier.rawValue, for: indexPath)\n\n configureCell(cell, item: item, indexPath: indexPath)\n\n return cell\n }\n\n func configure(\n _ cell: UITableViewCell,\n toggleSetting: Bool,\n title: String,\n for preference: CustomDNSDataSource.Item\n ) {\n guard let cell = cell as? SettingsSwitchCell else { return }\n\n cell.titleLabel.text = title\n cell.setAccessibilityIdentifier(preference.accessibilityIdentifier)\n cell.applySubCellStyling()\n cell.setOn(toggleSetting, animated: true)\n cell.action = { [weak self] isOn in\n self?.delegate?.didChangeState(\n for: preference,\n isOn: isOn\n )\n }\n }\n\n // swiftlint:disable:next function_body_length\n func configureCell(_ cell: UITableViewCell, item: CustomDNSDataSource.Item, indexPath: IndexPath) {\n switch item {\n case .blockAll:\n let localizedString = NSLocalizedString(\n "BLOCK_ALL_CELL_LABEL",\n tableName: "VPNSettings",\n value: "All",\n comment: ""\n )\n\n configure(\n cell,\n toggleSetting: viewModel.blockAll,\n title: localizedString,\n for: .blockAll\n )\n\n case .blockAdvertising:\n let localizedString = NSLocalizedString(\n "BLOCK_ADS_CELL_LABEL",\n tableName: "VPNSettings",\n value: "Ads",\n comment: ""\n )\n\n configure(\n cell,\n toggleSetting: viewModel.blockAdvertising,\n title: localizedString,\n for: .blockAdvertising\n )\n\n case .blockTracking:\n let localizedString = NSLocalizedString(\n "BLOCK_TRACKERS_CELL_LABEL",\n tableName: "VPNSettings",\n value: "Trackers",\n comment: ""\n )\n configure(\n cell,\n toggleSetting: viewModel.blockTracking,\n title: localizedString,\n for: .blockTracking\n )\n\n case .blockMalware:\n guard let cell = cell as? SettingsSwitchCell else { return }\n\n let localizedString = NSLocalizedString(\n "BLOCK_MALWARE_CELL_LABEL",\n tableName: "VPNSettings",\n value: "Malware",\n comment: ""\n )\n configure(\n cell,\n toggleSetting: viewModel.blockMalware,\n title: localizedString,\n for: .blockMalware\n )\n cell.infoButtonHandler = { [weak self] in\n self?.delegate?.showInfo(for: .blockMalware)\n }\n\n case .blockAdultContent:\n let localizedString = NSLocalizedString(\n "BLOCK_ADULT_CELL_LABEL",\n tableName: "VPNSettings",\n value: "Adult content",\n comment: ""\n )\n configure(\n cell,\n toggleSetting: viewModel.blockAdultContent,\n title: localizedString,\n for: .blockAdultContent\n )\n\n case .blockGambling:\n let localizedString = NSLocalizedString(\n "BLOCK_GAMBLING_CELL_LABEL",\n tableName: "VPNSettings",\n value: "Gambling",\n comment: ""\n )\n configure(\n cell,\n toggleSetting: viewModel.blockGambling,\n title: localizedString,\n for: .blockGambling\n )\n\n case .blockSocialMedia:\n let localizedString = NSLocalizedString(\n "BLOCK_SOCIAL_MEDIA_CELL_LABEL",\n tableName: "VPNSettings",\n value: "Social media",\n comment: ""\n )\n configure(\n cell,\n toggleSetting: viewModel.blockSocialMedia,\n title: localizedString,\n for: .blockSocialMedia\n )\n\n case .useCustomDNS:\n guard let cell = cell as? SettingsSwitchCell else { return }\n\n cell.titleLabel.text = NSLocalizedString(\n "CUSTOM_DNS_CELL_LABEL",\n tableName: "VPNSettings",\n value: "Use custom DNS server",\n comment: ""\n )\n cell.setSwitchEnabled(viewModel.customDNSPrecondition == .satisfied)\n cell.setOn(viewModel.effectiveEnableCustomDNS, animated: false)\n cell.accessibilityHint = viewModel.customDNSPrecondition\n .localizedDescription(isEditing: isEditing)\n cell.setAccessibilityIdentifier(.dnsSettingsUseCustomDNSCell)\n cell.action = { [weak self] isOn in\n self?.delegate?.didChangeState(for: .useCustomDNS, isOn: isOn)\n }\n\n case .addDNSServer:\n guard let cell = cell as? SettingsAddDNSEntryCell else { return }\n\n cell.titleLabel.text = NSLocalizedString(\n "ADD_CUSTOM_DNS_SERVER_CELL_LABEL",\n tableName: "VPNSettings",\n value: "Add a server",\n comment: ""\n )\n cell.setAccessibilityIdentifier(.dnsSettingsAddServerCell)\n cell.tapAction = { [weak self] in\n self?.delegate?.addDNSEntry()\n }\n\n case let .dnsServer(entryIdentifier):\n guard let cell = cell as? SettingsDNSTextCell else { return }\n\n let dnsServerEntry = viewModel.dnsEntry(entryIdentifier: entryIdentifier)!\n\n cell.textField.text = dnsServerEntry.address\n cell.isValidInput = dnsEntryIsValid(identifier: entryIdentifier, cell: cell)\n cell.accessibilityIdentifier = "\(item.accessibilityIdentifier) (\(entryIdentifier))"\n\n cell.onTextChange = { [weak self] cell in\n cell.isValidInput = self?\n .dnsEntryIsValid(identifier: entryIdentifier, cell: cell) ?? false\n }\n\n cell.onReturnKey = { cell in\n cell.endEditing(false)\n }\n\n case .dnsServerInfo:\n guard let cell = cell as? SettingsDNSInfoCell else { return }\n\n cell.titleLabel.attributedText = viewModel.customDNSPrecondition.attributedLocalizedDescription(\n isEditing: isEditing,\n preferredFont: .systemFont(ofSize: 14)\n )\n }\n }\n\n private func dnsEntryIsValid(identifier: UUID, cell: SettingsDNSTextCell) -> Bool {\n delegate?.didChangeDNSEntry(\n with: identifier,\n inputString: cell.textField.text ?? ""\n ) ?? false\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\VPNSettings\CustomDNSCellFactory.swift
CustomDNSCellFactory.swift
Swift
7,863
0.95
0.072961
0.039604
node-utils
531
2024-04-24T11:16:34.465866
Apache-2.0
false
9c9fc90e189cd7b790ca74140f9e43e7
//\n// CustomDNSDataSource.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-11-09.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\nimport UIKit\n\nfinal class CustomDNSDataSource: UITableViewDiffableDataSource<\n CustomDNSDataSource.Section,\n CustomDNSDataSource.Item\n>, UITableViewDelegate {\n typealias InfoButtonHandler = (Item) -> Void\n\n enum CellReuseIdentifiers: String, CaseIterable {\n case settingSwitch\n case dnsServer\n case dnsServerInfo\n case addDNSServer\n\n var reusableViewClass: AnyClass {\n switch self {\n case .settingSwitch:\n return SettingsSwitchCell.self\n case .dnsServer:\n return SettingsDNSTextCell.self\n case .dnsServerInfo:\n return SettingsDNSInfoCell.self\n case .addDNSServer:\n return SettingsAddDNSEntryCell.self\n }\n }\n }\n\n private enum HeaderFooterReuseIdentifiers: String, CaseIterable {\n case contentBlockerHeader\n\n var reusableViewClass: AnyClass {\n return SettingsHeaderView.self\n }\n }\n\n enum Section: String, Hashable, CaseIterable {\n case contentBlockers\n case customDNS\n }\n\n enum Item: Hashable {\n case blockAll\n case blockAdvertising\n case blockTracking\n case blockMalware\n case blockAdultContent\n case blockGambling\n case blockSocialMedia\n case useCustomDNS\n case addDNSServer\n case dnsServer(_ uniqueID: UUID)\n case dnsServerInfo\n\n static var contentBlockers: [Item] {\n [\n .blockAll,\n .blockAdvertising,\n .blockTracking,\n .blockMalware,\n .blockGambling,\n .blockAdultContent,\n .blockSocialMedia,\n ]\n }\n\n var accessibilityIdentifier: AccessibilityIdentifier {\n switch self {\n case .blockAll:\n return .blockAll\n case .blockAdvertising:\n return .blockAdvertising\n case .blockTracking:\n return .blockTracking\n case .blockMalware:\n return .blockMalware\n case .blockGambling:\n return .blockGambling\n case .blockAdultContent:\n return .blockAdultContent\n case .blockSocialMedia:\n return .blockSocialMedia\n case .useCustomDNS:\n return .useCustomDNS\n case .addDNSServer:\n return .addDNSServer\n case .dnsServer:\n return .dnsServer\n case .dnsServerInfo:\n return .dnsServerInfo\n }\n }\n\n static func isDNSServerItem(_ item: Item) -> Bool {\n if case .dnsServer = item {\n return true\n } else {\n return false\n }\n }\n\n var reuseIdentifier: CellReuseIdentifiers {\n switch self {\n case .addDNSServer:\n return .addDNSServer\n case .dnsServer:\n return .dnsServer\n case .dnsServerInfo:\n return .dnsServerInfo\n default:\n return .settingSwitch\n }\n }\n }\n\n private var isEditing = false\n\n private(set) var viewModel = VPNSettingsViewModel() { didSet {\n cellFactory.viewModel = viewModel\n }}\n private(set) var viewModelBeforeEditing = VPNSettingsViewModel()\n private let cellFactory: CustomDNSCellFactory\n private weak var tableView: UITableView?\n\n weak var delegate: DNSSettingsDataSourceDelegate?\n\n init(tableView: UITableView) {\n self.tableView = tableView\n\n let cellFactory = CustomDNSCellFactory(\n tableView: tableView,\n viewModel: viewModel\n )\n self.cellFactory = cellFactory\n\n super.init(tableView: tableView) { _, indexPath, item in\n cellFactory.makeCell(for: item, indexPath: indexPath)\n }\n\n tableView.delegate = self\n cellFactory.delegate = self\n\n registerClasses()\n }\n\n func setAvailablePortRanges(_ ranges: [[UInt16]]) {\n viewModel.availableWireGuardPortRanges = ranges\n }\n\n func setEditing(_ editing: Bool, animated: Bool) {\n guard isEditing != editing else { return }\n\n isEditing = editing\n cellFactory.isEditing = isEditing\n\n if editing {\n viewModelBeforeEditing = viewModel\n } else {\n viewModel.sanitizeCustomDNSEntries()\n }\n\n updateSnapshot(animated: true)\n\n viewModel.customDNSDomains.forEach { entry in\n reload(item: .dnsServer(entry.identifier))\n }\n\n if !editing, viewModelBeforeEditing != viewModel {\n delegate?.didChangeViewModel(viewModel)\n }\n }\n\n func update(from tunnelSettings: LatestTunnelSettings) {\n let newViewModel = VPNSettingsViewModel(from: tunnelSettings)\n let mergedViewModel = viewModel.merged(newViewModel)\n\n if viewModel != mergedViewModel {\n viewModel = mergedViewModel\n }\n\n updateSnapshot()\n }\n\n // MARK: - UITableViewDataSource\n\n override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {\n // Disable swipe to delete when not editing the table view\n guard isEditing else { return false }\n\n let item = itemIdentifier(for: indexPath)\n\n switch item {\n case .dnsServer, .addDNSServer:\n return true\n default:\n return false\n }\n }\n\n override func tableView(\n _ tableView: UITableView,\n commit editingStyle: UITableViewCell.EditingStyle,\n forRowAt indexPath: IndexPath\n ) {\n let item = itemIdentifier(for: indexPath)\n\n if case .addDNSServer = item, editingStyle == .insert {\n addDNSServerEntry()\n }\n\n if case let .dnsServer(entryIdentifier) = item, editingStyle == .delete {\n deleteDNSServerEntry(entryIdentifier: entryIdentifier)\n }\n }\n\n override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {\n let item = itemIdentifier(for: indexPath)\n\n switch item {\n case .dnsServer:\n return true\n default:\n return false\n }\n }\n\n override func tableView(\n _ tableView: UITableView,\n moveRowAt sourceIndexPath: IndexPath,\n to destinationIndexPath: IndexPath\n ) {\n let sourceItem = itemIdentifier(for: sourceIndexPath)!\n let destinationItem = itemIdentifier(for: destinationIndexPath)!\n\n guard case let .dnsServer(sourceIdentifier) = sourceItem,\n case let .dnsServer(targetIdentifier) = destinationItem,\n let sourceIndex = viewModel.indexOfDNSEntry(entryIdentifier: sourceIdentifier),\n let destinationIndex = viewModel.indexOfDNSEntry(entryIdentifier: targetIdentifier)\n else { return }\n\n let removedEntry = viewModel.customDNSDomains.remove(at: sourceIndex)\n viewModel.customDNSDomains.insert(removedEntry, at: destinationIndex)\n\n updateSnapshot()\n }\n\n // MARK: - UITableViewDelegate\n\n func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {\n false\n }\n\n // Disallow selection for tapping on a selected setting\n func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {\n let sectionIdentifier = snapshot().sectionIdentifiers[section]\n\n guard let view = tableView\n .dequeueReusableHeaderFooterView(\n withIdentifier: HeaderFooterReuseIdentifiers.contentBlockerHeader\n .rawValue\n ) as? SettingsHeaderView else { return nil }\n\n switch sectionIdentifier {\n case .contentBlockers:\n configureContentBlockersHeader(view)\n return view\n default:\n return nil\n }\n }\n\n func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {\n nil\n }\n\n func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {\n let sectionIdentifier = snapshot().sectionIdentifiers[section]\n\n switch sectionIdentifier {\n case .customDNS:\n return 0\n\n default:\n return UITableView.automaticDimension\n }\n }\n\n func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {\n 0\n }\n\n func tableView(\n _ tableView: UITableView,\n editingStyleForRowAt indexPath: IndexPath\n ) -> UITableViewCell.EditingStyle {\n let item = itemIdentifier(for: indexPath)\n\n switch item {\n case .dnsServer:\n return .delete\n case .addDNSServer:\n return .insert\n default:\n return .none\n }\n }\n\n func tableView(\n _ tableView: UITableView,\n targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath,\n toProposedIndexPath proposedDestinationIndexPath: IndexPath\n ) -> IndexPath {\n let sectionIdentifier = snapshot().sectionIdentifiers[sourceIndexPath.section]\n guard case .customDNS = sectionIdentifier else { return sourceIndexPath }\n\n let items = snapshot().itemIdentifiers(inSection: sectionIdentifier)\n\n let indexPathForFirstRow = items.first(where: Item.isDNSServerItem).flatMap { item in\n indexPath(for: item)\n }\n\n let indexPathForLastRow = items.last(where: Item.isDNSServerItem).flatMap { item in\n indexPath(for: item)\n }\n\n guard let indexPathForFirstRow,\n let indexPathForLastRow else { return sourceIndexPath }\n\n if proposedDestinationIndexPath.section == sourceIndexPath.section {\n return min(max(proposedDestinationIndexPath, indexPathForFirstRow), indexPathForLastRow)\n } else {\n if proposedDestinationIndexPath.section > sourceIndexPath.section {\n return indexPathForLastRow\n } else {\n return indexPathForFirstRow\n }\n }\n }\n\n // MARK: - Private\n\n private func registerClasses() {\n CellReuseIdentifiers.allCases.forEach { enumCase in\n tableView?.register(\n enumCase.reusableViewClass,\n forCellReuseIdentifier: enumCase.rawValue\n )\n }\n\n HeaderFooterReuseIdentifiers.allCases.forEach { enumCase in\n tableView?.register(\n enumCase.reusableViewClass,\n forHeaderFooterViewReuseIdentifier: enumCase.rawValue\n )\n }\n }\n\n private func updateSnapshot(animated: Bool = false, completion: (() -> Void)? = nil) {\n var newSnapshot = NSDiffableDataSourceSnapshot<Section, Item>()\n let oldSnapshot = snapshot()\n\n // Append sections\n newSnapshot.appendSections(Section.allCases)\n\n if oldSnapshot.sectionIdentifiers.contains(.contentBlockers) {\n newSnapshot.appendItems(\n oldSnapshot.itemIdentifiers(inSection: .contentBlockers),\n toSection: .contentBlockers\n )\n }\n\n // Append DNS settings\n newSnapshot.appendItems([.useCustomDNS], toSection: .customDNS)\n\n let dnsServerItems = viewModel.customDNSDomains.map { entry in\n Item.dnsServer(entry.identifier)\n }\n newSnapshot.appendItems(dnsServerItems, toSection: .customDNS)\n\n if isEditing, viewModel.customDNSDomains.count < DNSSettings.maxAllowedCustomDNSDomains {\n newSnapshot.appendItems([.addDNSServer], toSection: .customDNS)\n }\n\n // Append/update DNS server info.\n newSnapshot = updateDNSInfoItems(in: newSnapshot)\n\n // Apply snapshot.\n applySnapshot(newSnapshot, animated: animated, completion: completion)\n }\n\n private func applySnapshot(\n _ snapshot: NSDiffableDataSourceSnapshot<Section, Item>,\n animated: Bool,\n completion: (() -> Void)? = nil\n ) {\n apply(snapshot, animatingDifferences: animated) {\n completion?()\n }\n }\n\n private func reload(item: Item) {\n if let indexPath = indexPath(for: item),\n let cell = tableView?.cellForRow(at: indexPath) {\n cellFactory.configureCell(cell, item: item, indexPath: indexPath)\n }\n }\n\n private func setBlockAll(_ isEnabled: Bool) {\n let oldViewModel = viewModel\n viewModel.setBlockAll(isEnabled)\n reloadBlockerData(isEnabled, oldViewModel: oldViewModel)\n\n [\n .blockAdvertising,\n .blockTracking,\n .blockMalware,\n .blockAdultContent,\n .blockGambling,\n .blockSocialMedia,\n ].forEach { item in\n reload(item: item)\n }\n }\n\n private func setBlockAdvertising(_ isEnabled: Bool) {\n let oldViewModel = viewModel\n viewModel.setBlockAdvertising(isEnabled)\n reloadBlockerData(isEnabled, oldViewModel: oldViewModel)\n }\n\n private func setBlockTracking(_ isEnabled: Bool) {\n let oldViewModel = viewModel\n viewModel.setBlockTracking(isEnabled)\n reloadBlockerData(isEnabled, oldViewModel: oldViewModel)\n }\n\n private func setBlockMalware(_ isEnabled: Bool) {\n let oldViewModel = viewModel\n viewModel.setBlockMalware(isEnabled)\n reloadBlockerData(isEnabled, oldViewModel: oldViewModel)\n }\n\n private func setBlockAdultContent(_ isEnabled: Bool) {\n let oldViewModel = viewModel\n viewModel.setBlockAdultContent(isEnabled)\n reloadBlockerData(isEnabled, oldViewModel: oldViewModel)\n }\n\n private func setBlockGambling(_ isEnabled: Bool) {\n let oldViewModel = viewModel\n viewModel.setBlockGambling(isEnabled)\n reloadBlockerData(isEnabled, oldViewModel: oldViewModel)\n }\n\n private func setBlockSocialMedia(_ isEnabled: Bool) {\n let oldViewModel = viewModel\n viewModel.setBlockSocialMedia(isEnabled)\n reloadBlockerData(isEnabled, oldViewModel: oldViewModel)\n }\n\n private func reloadBlockerData(_ isEnabled: Bool, oldViewModel: VPNSettingsViewModel) {\n if oldViewModel.customDNSPrecondition != viewModel.customDNSPrecondition {\n reloadDnsServerInfo()\n }\n\n if !isEnabled || viewModel.allBlockersEnabled {\n reload(item: .blockAll)\n }\n\n if\n let index = snapshot().sectionIdentifiers.firstIndex(of: .contentBlockers),\n let headerView = tableView?.headerView(forSection: index) as? SettingsHeaderView {\n configureContentBlockersHeader(headerView)\n }\n\n if !isEditing {\n delegate?.didChangeViewModel(viewModel)\n }\n }\n\n private func setEnableCustomDNS(_ isEnabled: Bool) {\n let oldViewModel = viewModel\n\n viewModel.setEnableCustomDNS(isEnabled)\n\n if oldViewModel.customDNSPrecondition != viewModel.customDNSPrecondition {\n reloadDnsServerInfo()\n }\n\n if !isEditing {\n delegate?.didChangeViewModel(viewModel)\n }\n }\n\n private func handleDNSEntryChange(with identifier: UUID, inputString: String) -> Bool {\n let oldViewModel = viewModel\n\n viewModel.updateDNSEntry(entryIdentifier: identifier, newAddress: inputString)\n\n if oldViewModel.customDNSPrecondition != viewModel.customDNSPrecondition {\n reloadDnsServerInfo()\n }\n\n return viewModel.isDNSDomainUserInputValid(inputString)\n }\n\n private func addDNSServerEntry() {\n let newDNSEntry = DNSServerEntry(address: "")\n viewModel.customDNSDomains.append(newDNSEntry)\n\n updateSnapshot(animated: true) { [weak self] in\n // Focus on the new entry text field.\n let lastDNSEntry = self?.snapshot().itemIdentifiers(inSection: .customDNS)\n .last { item in\n if case let .dnsServer(entryIdentifier) = item {\n return entryIdentifier == newDNSEntry.identifier\n } else {\n return false\n }\n }\n\n if let lastDNSEntry,\n let indexPath = self?.indexPath(for: lastDNSEntry) {\n let cell = self?.tableView?.cellForRow(at: indexPath) as? SettingsDNSTextCell\n\n self?.tableView?.scrollToRow(at: indexPath, at: .bottom, animated: true)\n cell?.textField.becomeFirstResponder()\n }\n }\n }\n\n private func deleteDNSServerEntry(entryIdentifier: UUID) {\n let entryIndex = viewModel.customDNSDomains.firstIndex { entry in\n entry.identifier == entryIdentifier\n }\n\n guard let entryIndex else { return }\n\n viewModel.customDNSDomains.remove(at: entryIndex)\n\n reload(item: .useCustomDNS)\n updateSnapshot(animated: true)\n }\n\n private func reloadDnsServerInfo() {\n reload(item: .useCustomDNS)\n\n let snapshot = updateDNSInfoItems(in: snapshot())\n apply(snapshot, animatingDifferences: true)\n }\n\n private func updateDNSInfoItems(\n in snapshot: NSDiffableDataSourceSnapshot<Section, Item>\n ) -> NSDiffableDataSourceSnapshot<Section, Item> {\n var snapshot = snapshot\n\n if viewModel.customDNSPrecondition == .satisfied {\n snapshot.deleteItems([.dnsServerInfo])\n } else {\n if snapshot.itemIdentifiers(inSection: .customDNS).contains(.dnsServerInfo) {\n snapshot.reloadItems([.dnsServerInfo])\n } else {\n snapshot.appendItems([.dnsServerInfo], toSection: .customDNS)\n }\n }\n\n return snapshot\n }\n\n private func configureContentBlockersHeader(_ header: SettingsHeaderView) {\n let title = NSLocalizedString(\n "CONTENT_BLOCKERS_HEADER_LABEL",\n tableName: "VPNSettings",\n value: "DNS content blockers",\n comment: ""\n )\n\n let enabledBlockersCount = viewModel.enabledBlockersCount\n let attributedTitle = NSMutableAttributedString(string: title)\n let blockerCountText = NSAttributedString(string: " (\(enabledBlockersCount))", attributes: [\n .foregroundColor: UIColor.primaryTextColor.withAlphaComponent(0.6),\n ])\n\n if enabledBlockersCount > 0 {\n attributedTitle.append(blockerCountText)\n }\n\n UIView.transition(with: header.titleLabel, duration: 0.2, options: .transitionCrossDissolve) {\n header.titleLabel.attributedText = attributedTitle\n }\n header.titleLabel.sizeToFit()\n\n header.accessibilityCustomActionName = title\n header.accessibilityValue = "\(enabledBlockersCount)"\n header.setAccessibilityIdentifier(.dnsContentBlockersHeaderView)\n\n header.infoButtonHandler = { [weak self] in\n self?.delegate?.showInfo(for: .contentBlockers)\n }\n\n header.didCollapseHandler = { [weak self] headerView in\n guard let self else { return }\n\n var snapshot = self.snapshot()\n\n if headerView.isExpanded {\n snapshot.deleteItems(Item.contentBlockers)\n } else {\n snapshot.appendItems(Item.contentBlockers, toSection: .contentBlockers)\n }\n\n headerView.isExpanded.toggle()\n self.apply(snapshot, animatingDifferences: true)\n }\n }\n}\n\nextension CustomDNSDataSource: @preconcurrency CustomDNSCellEventHandler {\n func didChangeState(for preference: Item, isOn: Bool) {\n switch preference {\n case .blockAll:\n setBlockAll(isOn)\n\n case .blockAdvertising:\n setBlockAdvertising(isOn)\n\n case .blockTracking:\n setBlockTracking(isOn)\n\n case .blockMalware:\n setBlockMalware(isOn)\n\n case .blockAdultContent:\n setBlockAdultContent(isOn)\n\n case .blockGambling:\n setBlockGambling(isOn)\n\n case .blockSocialMedia:\n setBlockSocialMedia(isOn)\n\n case .useCustomDNS:\n setEnableCustomDNS(isOn)\n\n default:\n break\n }\n }\n\n func addDNSEntry() {\n addDNSServerEntry()\n }\n\n func didChangeDNSEntry(\n with identifier: UUID,\n inputString: String\n ) -> Bool {\n handleDNSEntryChange(with: identifier, inputString: inputString)\n }\n\n func showInfo(for button: VPNSettingsInfoButtonItem) {\n delegate?.showInfo(for: button)\n }\n}\n\n// swiftlint:disable:this file_length\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\VPNSettings\CustomDNSDataSource.swift
CustomDNSDataSource.swift
Swift
20,928
0.95
0.074074
0.033028
awesome-app
265
2025-05-03T15:57:14.531134
BSD-3-Clause
false
f36c08d11802d83b029b6e304d677aa2
//\n// CustomDNSViewController.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-11-09.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\nimport UIKit\n\nclass CustomDNSViewController: UITableViewController {\n private let interactor: VPNSettingsInteractor\n private var dataSource: CustomDNSDataSource?\n private let alertPresenter: AlertPresenter\n\n override var preferredStatusBarStyle: UIStatusBarStyle {\n .lightContent\n }\n\n init(interactor: VPNSettingsInteractor, alertPresenter: AlertPresenter) {\n self.interactor = interactor\n self.alertPresenter = alertPresenter\n\n super.init(style: .grouped)\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n override func viewDidLoad() {\n super.viewDidLoad()\n\n tableView.setAccessibilityIdentifier(.dnsSettingsTableView)\n tableView.backgroundColor = .secondaryColor\n tableView.separatorColor = .secondaryColor\n tableView.rowHeight = UITableView.automaticDimension\n tableView.estimatedRowHeight = 60\n tableView.estimatedSectionHeaderHeight = tableView.estimatedRowHeight\n\n dataSource = CustomDNSDataSource(tableView: tableView)\n dataSource?.delegate = self\n\n navigationItem.title = NSLocalizedString(\n "NAVIGATION_TITLE",\n tableName: "VPNSettings",\n value: "DNS settings",\n comment: ""\n )\n\n navigationItem.rightBarButtonItem = editButtonItem\n navigationItem.rightBarButtonItem?.setAccessibilityIdentifier(.dnsSettingsEditButton)\n\n interactor.tunnelSettingsDidChange = { [weak self] newSettings in\n self?.dataSource?.update(from: newSettings)\n }\n dataSource?.update(from: interactor.tunnelSettings)\n\n tableView.tableHeaderView = UIView(frame: CGRect(\n origin: .zero,\n size: CGSize(width: 0, height: UIMetrics.TableView.sectionSpacing)\n ))\n }\n\n override func setEditing(_ editing: Bool, animated: Bool) {\n super.setEditing(editing, animated: animated)\n\n dataSource?.setEditing(editing, animated: animated)\n\n navigationItem.setHidesBackButton(editing, animated: animated)\n\n // Disable swipe to dismiss when editing\n isModalInPresentation = editing\n }\n\n private func showInfo(with message: NSAttributedString) {\n let presentation = AlertPresentation(\n id: "vpn-settings-content-blockers-alert",\n icon: .info,\n attributedMessage: message,\n buttons: [\n AlertAction(\n title: NSLocalizedString(\n "VPN_SETTINGS_DNS_SETTINGS_OK_ACTION",\n tableName: "ContentBlockers",\n value: "Got it!",\n comment: ""\n ),\n style: .default\n ),\n ]\n )\n\n alertPresenter.showAlert(presentation: presentation, animated: true)\n }\n}\n\nextension CustomDNSViewController: @preconcurrency DNSSettingsDataSourceDelegate {\n func didChangeViewModel(_ viewModel: VPNSettingsViewModel) {\n interactor.updateSettings([.dnsSettings(viewModel.asDNSSettings())])\n }\n\n func showInfo(for item: VPNSettingsInfoButtonItem) {\n showInfo(with: NSAttributedString(\n markdownString: item.description,\n options: MarkdownStylingOptions(font: .preferredFont(forTextStyle: .body))\n ))\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\VPNSettings\CustomDNSViewController.swift
CustomDNSViewController.swift
Swift
3,584
0.95
0.018182
0.089888
node-utils
440
2024-12-31T05:27:22.224563
GPL-3.0
false
52685caff760ea878b6c67809f96cd5c
//\n// VPNSettingsCellFactory.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-03-09.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\nimport UIKit\n\nprotocol VPNSettingsCellEventHandler {\n func showInfo(for button: VPNSettingsInfoButtonItem)\n func showDetails(for button: VPNSettingsDetailsButtonItem)\n func addCustomPort(_ port: UInt16)\n func selectCustomPortEntry(_ port: UInt16) -> Bool\n func selectObfuscationState(_ state: WireGuardObfuscationState)\n func switchMultihop(_ state: MultihopState)\n func setLocalNetworkSharing(_ enabled: Bool, onCancel: @escaping () -> Void)\n func setIncludeAllNetworks(_ enabled: Bool, onCancel: @escaping () -> Void)\n}\n\n@MainActor\nfinal class VPNSettingsCellFactory: @preconcurrency CellFactoryProtocol {\n let tableView: UITableView\n var viewModel: VPNSettingsViewModel\n var delegate: VPNSettingsCellEventHandler?\n var isEditing = false\n\n init(tableView: UITableView, viewModel: VPNSettingsViewModel) {\n self.tableView = tableView\n self.viewModel = viewModel\n }\n\n func makeCell(for item: VPNSettingsDataSource.Item, indexPath: IndexPath) -> UITableViewCell {\n let cell = tableView.dequeueReusableCell(withIdentifier: item.reuseIdentifier.rawValue, for: indexPath)\n configureCell(cell, item: item, indexPath: indexPath)\n\n return cell\n }\n\n // swiftlint:disable:next cyclomatic_complexity function_body_length\n func configureCell(_ cell: UITableViewCell, item: VPNSettingsDataSource.Item, indexPath: IndexPath) {\n (cell as? SettingsCell)?.detailTitleLabel.accessibilityIdentifier = nil\n switch item {\n case .includeAllNetworks:\n guard let cell = cell as? SettingsSwitchCell else { return }\n cell.action = { enable in\n self.delegate?.setIncludeAllNetworks(enable) {\n cell.setOn(self.viewModel.includeAllNetworks, animated: true)\n }\n }\n\n cell.titleLabel.text = NSLocalizedString(\n "LOCAL_NETWORK_SHARING_CELL_LABEL",\n tableName: "VPNSettings",\n value: "Include all networks",\n comment: ""\n )\n cell.setAccessibilityIdentifier(item.accessibilityIdentifier)\n cell.setOn(viewModel.includeAllNetworks, animated: true)\n case .localNetworkSharing:\n guard let cell = cell as? SettingsSwitchCell else { return }\n cell.infoButtonHandler = { self.delegate?.showInfo(for: .localNetworkSharing) }\n cell.action = { enable in\n self.delegate?.setLocalNetworkSharing(enable) {\n cell.setOn(self.viewModel.localNetworkSharing, animated: true)\n }\n }\n\n cell.titleLabel.text = NSLocalizedString(\n "LOCAL_NETWORK_SHARING_CELL_LABEL",\n tableName: "VPNSettings",\n value: "Local network sharing",\n comment: ""\n )\n cell.setAccessibilityIdentifier(item.accessibilityIdentifier)\n cell.setOn(viewModel.localNetworkSharing, animated: true)\n cell.setSwitchEnabled(viewModel.includeAllNetworks)\n\n case .dnsSettings:\n guard let cell = cell as? SettingsCell else { return }\n\n cell.titleLabel.text = NSLocalizedString(\n "DNS_SETTINGS_CELL_LABEL",\n tableName: "VPNSettings",\n value: "DNS settings",\n comment: ""\n )\n\n cell.disclosureType = .chevron\n cell.setAccessibilityIdentifier(item.accessibilityIdentifier)\n\n case .ipOverrides:\n guard let cell = cell as? SettingsCell else { return }\n\n cell.titleLabel.text = NSLocalizedString(\n "IP_OVERRIDE_CELL_LABEL",\n tableName: "VPNSettings",\n value: "Server IP override",\n comment: ""\n )\n\n cell.disclosureType = .chevron\n cell.setAccessibilityIdentifier(item.accessibilityIdentifier)\n\n case let .wireGuardPort(port):\n guard let cell = cell as? SelectableSettingsCell else { return }\n\n var portString = NSLocalizedString(\n "WIREGUARD_PORT_CELL_LABEL",\n tableName: "VPNSettings",\n value: "Automatic",\n comment: ""\n )\n if let port {\n portString = String(port)\n }\n\n cell.titleLabel.text = portString\n cell.accessibilityIdentifier = "\(item.accessibilityIdentifier.asString)"\n cell.applySubCellStyling()\n\n case .wireGuardCustomPort:\n guard let cell = cell as? SettingsInputCell else { return }\n\n cell.titleLabel.text = NSLocalizedString(\n "WIREGUARD_CUSTOM_PORT_CELL_LABEL",\n tableName: "VPNSettings",\n value: "Custom",\n comment: ""\n )\n cell.textField.placeholder = NSLocalizedString(\n "WIREGUARD_CUSTOM_PORT_CELL_INPUT_PLACEHOLDER",\n tableName: "VPNSettings",\n value: "Port",\n comment: ""\n )\n\n cell.textField.setAccessibilityIdentifier(.customWireGuardPortTextField)\n cell.setAccessibilityIdentifier(item.accessibilityIdentifier)\n cell.applySubCellStyling()\n\n cell.inputDidChange = { [weak self] text in\n let port = UInt16(text) ?? UInt16()\n cell.isValidInput = self?.delegate?.selectCustomPortEntry(port) ?? false\n }\n cell.inputWasConfirmed = { [weak self] text in\n if let port = UInt16(text), cell.isValidInput {\n self?.delegate?.addCustomPort(port)\n }\n }\n\n if let port = viewModel.customWireGuardPort {\n cell.textField.text = String(port)\n\n // Only update validity if input is invalid. Otherwise the textcolor will be wrong\n // (active text field color rather than the expected inactive color).\n let isValidInput = delegate?.selectCustomPortEntry(port) ?? false\n if !isValidInput {\n cell.isValidInput = false\n }\n }\n\n case .wireGuardObfuscationAutomatic:\n guard let cell = cell as? SelectableSettingsCell else { return }\n\n cell.titleLabel.text = NSLocalizedString(\n "WIREGUARD_OBFUSCATION_AUTOMATIC_LABEL",\n tableName: "VPNSettings",\n value: "Automatic",\n comment: ""\n )\n cell.setAccessibilityIdentifier(item.accessibilityIdentifier)\n cell.applySubCellStyling()\n\n case .wireGuardObfuscationUdpOverTcp:\n guard let cell = cell as? SelectableSettingsDetailsCell else { return }\n\n cell.titleLabel.text = NSLocalizedString(\n "WIREGUARD_OBFUSCATION_UDP_TCP_LABEL",\n tableName: "VPNSettings",\n value: "UDP-over-TCP",\n comment: ""\n )\n\n cell.detailTitleLabel.text = String(format: NSLocalizedString(\n "WIREGUARD_OBFUSCATION_UDP_TCP_PORT",\n tableName: "VPNSettings",\n value: "Port: %@",\n comment: ""\n ), viewModel.obfuscationUpdOverTcpPort.description)\n\n cell.setAccessibilityIdentifier(item.accessibilityIdentifier)\n cell.detailTitleLabel.setAccessibilityIdentifier(.wireGuardObfuscationUdpOverTcpPort)\n cell.applySubCellStyling()\n\n cell.buttonAction = { [weak self] in\n self?.delegate?.showDetails(for: .udpOverTcp)\n }\n\n case .wireGuardObfuscationShadowsocks:\n guard let cell = cell as? SelectableSettingsDetailsCell else { return }\n\n cell.titleLabel.text = NSLocalizedString(\n "WIREGUARD_OBFUSCATION_SHADOWSOCKS_LABEL",\n tableName: "VPNSettings",\n value: "Shadowsocks",\n comment: ""\n )\n\n cell.detailTitleLabel.text = String(format: NSLocalizedString(\n "WIREGUARD_OBFUSCATION_SHADOWSOCKS_PORT",\n tableName: "VPNSettings",\n value: "Port: %@",\n comment: ""\n ), viewModel.obfuscationShadowsocksPort.description)\n\n cell.setAccessibilityIdentifier(item.accessibilityIdentifier)\n cell.detailTitleLabel.setAccessibilityIdentifier(.wireGuardObfuscationShadowsocksPort)\n cell.applySubCellStyling()\n\n cell.buttonAction = { [weak self] in\n self?.delegate?.showDetails(for: .wireguardOverShadowsocks)\n }\n\n case .wireGuardObfuscationOff:\n guard let cell = cell as? SelectableSettingsCell else { return }\n\n cell.titleLabel.text = NSLocalizedString(\n "WIREGUARD_OBFUSCATION_OFF_LABEL",\n tableName: "VPNSettings",\n value: "Off",\n comment: ""\n )\n cell.setAccessibilityIdentifier(item.accessibilityIdentifier)\n cell.applySubCellStyling()\n\n case let .wireGuardObfuscationPort(port):\n guard let cell = cell as? SelectableSettingsCell else { return }\n\n let portString = port.description\n cell.titleLabel.text = NSLocalizedString(\n "WIREGUARD_OBFUSCATION_PORT_LABEL",\n tableName: "VPNSettings",\n value: portString,\n comment: ""\n )\n cell.accessibilityIdentifier = "\(item.accessibilityIdentifier)\(portString)"\n cell.applySubCellStyling()\n\n case .quantumResistanceAutomatic:\n guard let cell = cell as? SelectableSettingsCell else { return }\n\n cell.titleLabel.text = NSLocalizedString(\n "QUANTUM_RESISTANCE_AUTOMATIC_LABEL",\n tableName: "VPNSettings",\n value: "Automatic",\n comment: ""\n )\n cell.setAccessibilityIdentifier(item.accessibilityIdentifier)\n cell.applySubCellStyling()\n\n case .quantumResistanceOn:\n guard let cell = cell as? SelectableSettingsCell else { return }\n\n cell.titleLabel.text = NSLocalizedString(\n "QUANTUM_RESISTANCE_ON_LABEL",\n tableName: "VPNSettings",\n value: "On",\n comment: ""\n )\n cell.setAccessibilityIdentifier(item.accessibilityIdentifier)\n cell.applySubCellStyling()\n\n case .quantumResistanceOff:\n guard let cell = cell as? SelectableSettingsCell else { return }\n\n cell.titleLabel.text = NSLocalizedString(\n "QUANTUM_RESISTANCE_OFF_LABEL",\n tableName: "VPNSettings",\n value: "Off",\n comment: ""\n )\n cell.setAccessibilityIdentifier(item.accessibilityIdentifier)\n cell.applySubCellStyling()\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\VPNSettings\VPNSettingsCellFactory.swift
VPNSettingsCellFactory.swift
Swift
11,235
0.95
0.048443
0.041152
react-lib
809
2025-05-05T04:12:25.327559
Apache-2.0
false
b7edbf3813d4053076a7fafff937398a
//\n// VPNSettingsDataSource.swift\n// MullvadVPN\n//\n// Created by pronebird on 05/10/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\nimport UIKit\n\nfinal class VPNSettingsDataSource: UITableViewDiffableDataSource<\n VPNSettingsDataSource.Section,\n VPNSettingsDataSource.Item\n>, UITableViewDelegate {\n typealias InfoButtonHandler = (Item) -> Void\n\n enum CellReuseIdentifiers: String, CaseIterable {\n case localNetworkSharing\n case dnsSettings\n case ipOverrides\n case wireGuardPort\n case wireGuardCustomPort\n case wireGuardObfuscation\n case wireGuardObfuscationOption\n case wireGuardObfuscationPort\n case quantumResistance\n case includeAllNetworks\n\n var reusableViewClass: AnyClass {\n switch self {\n case .localNetworkSharing:\n return SettingsSwitchCell.self\n case .dnsSettings:\n return SettingsCell.self\n case .ipOverrides:\n return SettingsCell.self\n case .wireGuardPort:\n return SelectableSettingsCell.self\n case .wireGuardCustomPort:\n return SettingsInputCell.self\n case .wireGuardObfuscationOption:\n return SelectableSettingsDetailsCell.self\n case .wireGuardObfuscation:\n return SelectableSettingsCell.self\n case .wireGuardObfuscationPort:\n return SelectableSettingsCell.self\n case .quantumResistance:\n return SelectableSettingsCell.self\n case .includeAllNetworks:\n return SettingsSwitchCell.self\n }\n }\n }\n\n private enum HeaderFooterReuseIdentifiers: String, CaseIterable {\n case settingsHeaderView\n\n var reusableViewClass: AnyClass {\n return SettingsHeaderView.self\n }\n }\n\n enum Section: String, Hashable, CaseIterable {\n #if DEBUG\n case localNetworkSharing\n #endif\n case dnsSettings\n case ipOverrides\n case wireGuardPorts\n case wireGuardObfuscation\n case quantumResistance\n case privacyAndSecurity\n }\n\n enum Item: Hashable {\n case includeAllNetworks(_ enabled: Bool)\n case localNetworkSharing(_ enabled: Bool)\n case dnsSettings\n case ipOverrides\n case wireGuardPort(_ port: UInt16?)\n case wireGuardCustomPort\n case wireGuardObfuscationAutomatic\n case wireGuardObfuscationUdpOverTcp\n case wireGuardObfuscationShadowsocks\n case wireGuardObfuscationOff\n case wireGuardObfuscationPort(_ port: WireGuardObfuscationUdpOverTcpPort)\n case quantumResistanceAutomatic\n case quantumResistanceOn\n case quantumResistanceOff\n\n static var wireGuardPorts: [Item] {\n let defaultPorts = VPNSettingsViewModel.defaultWireGuardPorts.map {\n Item.wireGuardPort($0)\n }\n return [.wireGuardPort(nil)] + defaultPorts + [.wireGuardCustomPort]\n }\n\n static var wireGuardObfuscation: [Item] {\n [\n .wireGuardObfuscationAutomatic,\n .wireGuardObfuscationShadowsocks,\n .wireGuardObfuscationUdpOverTcp,\n .wireGuardObfuscationOff,\n ]\n }\n\n static var wireGuardObfuscationPort: [Item] {\n [\n .wireGuardObfuscationPort(.automatic),\n .wireGuardObfuscationPort(.port80),\n .wireGuardObfuscationPort(.port5001),\n ]\n }\n\n static var quantumResistance: [Item] {\n [.quantumResistanceAutomatic, .quantumResistanceOn, .quantumResistanceOff]\n }\n\n var accessibilityIdentifier: AccessibilityIdentifier {\n switch self {\n case .includeAllNetworks:\n return .includeAllNetworks\n case .localNetworkSharing:\n return .localNetworkSharing\n case .dnsSettings:\n return .dnsSettings\n case .ipOverrides:\n return .ipOverrides\n case let .wireGuardPort(port):\n return .wireGuardPort(port)\n case .wireGuardCustomPort:\n return .wireGuardCustomPort\n case .wireGuardObfuscationAutomatic:\n return .wireGuardObfuscationAutomatic\n case .wireGuardObfuscationUdpOverTcp:\n return .wireGuardObfuscationUdpOverTcp\n case .wireGuardObfuscationShadowsocks:\n return .wireGuardObfuscationShadowsocks\n case .wireGuardObfuscationOff:\n return .wireGuardObfuscationOff\n case .wireGuardObfuscationPort:\n return .wireGuardObfuscationPort\n case .quantumResistanceAutomatic:\n return .quantumResistanceAutomatic\n case .quantumResistanceOn:\n return .quantumResistanceOn\n case .quantumResistanceOff:\n return .quantumResistanceOff\n }\n }\n\n var reuseIdentifier: CellReuseIdentifiers {\n switch self {\n case .includeAllNetworks:\n return .includeAllNetworks\n case .localNetworkSharing:\n return .localNetworkSharing\n case .dnsSettings:\n return .dnsSettings\n case .ipOverrides:\n return .ipOverrides\n case .wireGuardPort:\n return .wireGuardPort\n case .wireGuardCustomPort:\n return .wireGuardCustomPort\n case .wireGuardObfuscationAutomatic, .wireGuardObfuscationOff:\n return .wireGuardObfuscation\n case .wireGuardObfuscationUdpOverTcp, .wireGuardObfuscationShadowsocks:\n return .wireGuardObfuscationOption\n case .wireGuardObfuscationPort:\n return .wireGuardObfuscationPort\n case .quantumResistanceAutomatic, .quantumResistanceOn, .quantumResistanceOff:\n return .quantumResistance\n }\n }\n }\n\n private(set) var viewModel = VPNSettingsViewModel() { didSet {\n vpnSettingsCellFactory.viewModel = viewModel\n }}\n private let vpnSettingsCellFactory: VPNSettingsCellFactory\n private weak var tableView: UITableView?\n\n private var obfuscationSettings: WireGuardObfuscationSettings {\n WireGuardObfuscationSettings(\n state: viewModel.obfuscationState,\n udpOverTcpPort: viewModel.obfuscationUpdOverTcpPort,\n shadowsocksPort: viewModel.obfuscationShadowsocksPort\n )\n }\n\n weak var delegate: VPNSettingsDataSourceDelegate?\n\n var selectedIndexPaths: [IndexPath] {\n var wireGuardPortItem: Item = .wireGuardPort(viewModel.wireGuardPort)\n if let customPort = indexPath(for: .wireGuardCustomPort) {\n if tableView?.indexPathsForSelectedRows?.contains(customPort) ?? false {\n wireGuardPortItem = .wireGuardCustomPort\n }\n }\n\n let obfuscationStateItem: Item = switch viewModel.obfuscationState {\n case .automatic: .wireGuardObfuscationAutomatic\n case .off: .wireGuardObfuscationOff\n case .on, .udpOverTcp: .wireGuardObfuscationUdpOverTcp\n case .shadowsocks: .wireGuardObfuscationShadowsocks\n }\n\n let quantumResistanceItem: Item = switch viewModel.quantumResistance {\n case .automatic: .quantumResistanceAutomatic\n case .off: .quantumResistanceOff\n case .on: .quantumResistanceOn\n }\n\n let obfuscationPortItem: Item = .wireGuardObfuscationPort(viewModel.obfuscationUpdOverTcpPort)\n\n return [\n wireGuardPortItem,\n obfuscationStateItem,\n obfuscationPortItem,\n quantumResistanceItem,\n ].compactMap { indexPath(for: $0) }\n }\n\n init(tableView: UITableView) {\n self.tableView = tableView\n\n let vpnSettingsCellFactory = VPNSettingsCellFactory(\n tableView: tableView,\n viewModel: viewModel\n )\n self.vpnSettingsCellFactory = vpnSettingsCellFactory\n\n super.init(tableView: tableView) { _, indexPath, itemIdentifier in\n vpnSettingsCellFactory.makeCell(for: itemIdentifier, indexPath: indexPath)\n }\n\n tableView.delegate = self\n vpnSettingsCellFactory.delegate = self\n\n registerClasses()\n }\n\n func setAvailablePortRanges(_ ranges: [[UInt16]]) {\n viewModel.availableWireGuardPortRanges = ranges\n }\n\n func revertWireGuardPortCellToLastSelection() {\n guard let customPortCell = getCustomPortCell(), customPortCell.textField.isEditing else {\n return\n }\n\n customPortCell.textField.resignFirstResponder()\n\n if customPortCell.isValidInput {\n customPortCell.confirmInput()\n } else if let port = viewModel.customWireGuardPort {\n customPortCell.setInput(String(port))\n customPortCell.confirmInput()\n } else {\n customPortCell.reset()\n\n Item.wireGuardPorts.forEach { item in\n if case let .wireGuardPort(port) = item, port == viewModel.wireGuardPort {\n if let indexPath = indexPath(for: item) {\n deselectAllRowsInSectionExceptRowAt(indexPath)\n }\n selectRow(at: item)\n return\n }\n }\n }\n }\n\n func update(from tunnelSettings: LatestTunnelSettings) {\n updateViewModel(from: tunnelSettings)\n updateSnapshot()\n }\n\n func reload(from tunnelSettings: LatestTunnelSettings) {\n updateViewModel(from: tunnelSettings)\n\n var snapshot = snapshot()\n snapshot.reconfigureItems(snapshot.itemIdentifiers)\n applySnapshot(snapshot, animated: false)\n }\n\n // MARK: - UITableViewDelegate\n\n func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {\n if selectedIndexPaths.contains(indexPath) {\n cell.setSelected(true, animated: false)\n }\n }\n\n func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {\n let item = itemIdentifier(for: indexPath)\n\n switch item {\n case .includeAllNetworks, .localNetworkSharing:\n return nil\n default: return indexPath\n }\n }\n\n func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {\n let item = itemIdentifier(for: indexPath)\n\n deselectAllRowsInSectionExceptRowAt(indexPath)\n\n switch item {\n case .dnsSettings:\n tableView.deselectRow(at: indexPath, animated: false)\n delegate?.showDNSSettings()\n\n case .ipOverrides:\n tableView.deselectRow(at: indexPath, animated: false)\n delegate?.showIPOverrides()\n\n case let .wireGuardPort(port):\n viewModel.setWireGuardPort(port)\n\n if let cell = getCustomPortCell() {\n cell.reset()\n cell.textField.resignFirstResponder()\n }\n\n delegate?.didSelectWireGuardPort(port)\n\n case .wireGuardCustomPort:\n getCustomPortCell()?.textField.becomeFirstResponder()\n\n case .wireGuardObfuscationAutomatic:\n selectObfuscationState(.automatic)\n delegate?.didUpdateTunnelSettings(TunnelSettingsUpdate.obfuscation(obfuscationSettings))\n case .wireGuardObfuscationUdpOverTcp:\n selectObfuscationState(.udpOverTcp)\n delegate?.didUpdateTunnelSettings(TunnelSettingsUpdate.obfuscation(obfuscationSettings))\n case .wireGuardObfuscationShadowsocks:\n selectObfuscationState(.shadowsocks)\n delegate?.didUpdateTunnelSettings(TunnelSettingsUpdate.obfuscation(obfuscationSettings))\n case .wireGuardObfuscationOff:\n selectObfuscationState(.off)\n delegate?.didUpdateTunnelSettings(TunnelSettingsUpdate.obfuscation(obfuscationSettings))\n case let .wireGuardObfuscationPort(port):\n selectObfuscationPort(port)\n delegate?.didUpdateTunnelSettings(TunnelSettingsUpdate.obfuscation(obfuscationSettings))\n case .quantumResistanceAutomatic:\n selectQuantumResistance(.automatic)\n delegate?.didUpdateTunnelSettings(TunnelSettingsUpdate.quantumResistance(viewModel.quantumResistance))\n case .quantumResistanceOn:\n selectQuantumResistance(.on)\n delegate?.didUpdateTunnelSettings(TunnelSettingsUpdate.quantumResistance(viewModel.quantumResistance))\n case .quantumResistanceOff:\n selectQuantumResistance(.off)\n delegate?.didUpdateTunnelSettings(TunnelSettingsUpdate.quantumResistance(viewModel.quantumResistance))\n default:\n break\n }\n }\n\n // Disallow selection for tapping on a selectable setting.\n func tableView(_ tableView: UITableView, willDeselectRowAt indexPath: IndexPath) -> IndexPath? {\n let item = itemIdentifier(for: indexPath)\n\n switch item {\n case .dnsSettings, .ipOverrides:\n return indexPath\n default:\n return nil\n }\n }\n\n func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {\n let sectionIdentifier = snapshot().sectionIdentifiers[section]\n\n guard let view = tableView\n .dequeueReusableHeaderFooterView(\n withIdentifier: HeaderFooterReuseIdentifiers.settingsHeaderView.rawValue\n ) as? SettingsHeaderView else { return nil }\n\n switch sectionIdentifier {\n case .wireGuardPorts:\n configureWireguardPortsHeader(view)\n return view\n\n case .wireGuardObfuscation:\n configureObfuscationHeader(view)\n return view\n case .quantumResistance:\n configureQuantumResistanceHeader(view)\n return view\n default:\n return nil\n }\n }\n\n func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {\n let view = UIView()\n view.backgroundColor = tableView.backgroundColor\n return view\n }\n\n func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {\n let sectionIdentifier = snapshot().sectionIdentifiers[section]\n\n switch sectionIdentifier {\n case .dnsSettings, .ipOverrides, .privacyAndSecurity:\n return .leastNonzeroMagnitude\n #if DEBUG\n case .localNetworkSharing: return .leastNonzeroMagnitude\n #endif\n default:\n return tableView.estimatedRowHeight\n }\n }\n\n func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {\n let sectionIdentifier = snapshot().sectionIdentifiers[section]\n\n return switch sectionIdentifier {\n // 0 due to there already being a separator between .dnsSettings and .ipOverrides.\n case .dnsSettings: 0\n case .ipOverrides, .quantumResistance: UITableView.automaticDimension\n #if DEBUG\n case .localNetworkSharing: UITableView.automaticDimension\n #endif\n default: 0.5\n }\n }\n\n func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {\n let sectionIdentifier = snapshot().sectionIdentifiers[indexPath.section]\n\n return switch sectionIdentifier {\n case .privacyAndSecurity: false\n default: true\n }\n }\n\n // MARK: - Private\n\n func updateViewModel(from tunnelSettings: LatestTunnelSettings) {\n let newViewModel = VPNSettingsViewModel(from: tunnelSettings)\n let mergedViewModel = viewModel.merged(newViewModel)\n\n if viewModel != mergedViewModel {\n viewModel = mergedViewModel\n }\n }\n\n private func registerClasses() {\n CellReuseIdentifiers.allCases.forEach { enumCase in\n tableView?.register(\n enumCase.reusableViewClass,\n forCellReuseIdentifier: enumCase.rawValue\n )\n }\n\n tableView?.register(\n SettingsHeaderView.self,\n forHeaderFooterViewReuseIdentifier: HeaderFooterReuseIdentifiers.settingsHeaderView.rawValue\n )\n }\n\n private func deselectAllRowsInSectionExceptRowAt(_ indexPath: IndexPath) {\n guard let indexPaths = tableView?.indexPathsForSelectedRows else { return }\n let rowsToDeselect = indexPaths.filter { $0.section == indexPath.section && $0.row != indexPath.row }\n\n rowsToDeselect.forEach {\n tableView?.deselectRow(at: $0, animated: false)\n }\n }\n\n private func updateSnapshot(animated: Bool = false, completion: (() -> Void)? = nil) {\n var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()\n\n snapshot.appendSections(Section.allCases)\n snapshot.appendItems([.dnsSettings], toSection: .dnsSettings)\n snapshot.appendItems([.ipOverrides], toSection: .ipOverrides)\n #if DEBUG\n snapshot.appendItems(\n [.localNetworkSharing(viewModel.localNetworkSharing)],\n toSection: .localNetworkSharing\n )\n snapshot\n .appendItems(\n [.includeAllNetworks(viewModel.includeAllNetworks)],\n toSection: .localNetworkSharing\n )\n #endif\n\n applySnapshot(snapshot, animated: animated, completion: completion)\n }\n\n private func applySnapshot(\n _ snapshot: NSDiffableDataSourceSnapshot<Section, Item>,\n animated: Bool,\n completion: (() -> Void)? = nil\n ) {\n apply(snapshot, animatingDifferences: animated) { [weak self] in\n self?.selectedIndexPaths.forEach { self?.selectRow(at: $0) }\n completion?()\n }\n }\n\n private func reload(item: Item) {\n if let indexPath = indexPath(for: item),\n let cell = tableView?.cellForRow(at: indexPath) {\n vpnSettingsCellFactory.configureCell(cell, item: item, indexPath: indexPath)\n }\n }\n\n private func configureWireguardPortsHeader(_ header: SettingsHeaderView) {\n let title = NSLocalizedString(\n "WIREGUARD_PORTS_HEADER_LABEL",\n tableName: "VPNSettings",\n value: "WireGuard ports",\n comment: ""\n )\n\n header.setAccessibilityIdentifier(.wireGuardPortsCell)\n header.titleLabel.text = title\n header.accessibilityCustomActionName = title\n header.isExpanded = isExpanded(.wireGuardPorts)\n header.infoButtonHandler = { [weak self] in\n if let self, let humanReadablePortRepresentation = delegate?.humanReadablePortRepresentation() {\n self.delegate?.showInfo(for: .wireGuardPorts(humanReadablePortRepresentation))\n }\n }\n\n header.didCollapseHandler = { [weak self] headerView in\n guard let self else { return }\n\n var snapshot = self.snapshot()\n var updateTimeDelay = 0.0\n\n if headerView.isExpanded {\n if let customPortCell = getCustomPortCell(), customPortCell.textField.isEditing {\n revertWireGuardPortCellToLastSelection()\n updateTimeDelay = 0.5\n }\n\n snapshot.deleteItems(Item.wireGuardPorts)\n } else {\n snapshot.appendItems(Item.wireGuardPorts, toSection: .wireGuardPorts)\n }\n\n // The update should be delayed when we're reverting an ongoing change, to give the\n // user just enough time to notice it.\n DispatchQueue.main.asyncAfter(deadline: .now() + updateTimeDelay) { [weak self] in\n headerView.isExpanded.toggle()\n self?.applySnapshot(snapshot, animated: true)\n }\n }\n }\n\n private func configureObfuscationHeader(_ header: SettingsHeaderView) {\n let title = NSLocalizedString(\n "OBFUSCATION_HEADER_LABEL",\n tableName: "VPNSettings",\n value: "WireGuard Obfuscation",\n comment: ""\n )\n\n header.setAccessibilityIdentifier(.wireGuardObfuscationCell)\n header.titleLabel.text = title\n header.accessibilityCustomActionName = title\n header.isExpanded = isExpanded(.wireGuardObfuscation)\n header.didCollapseHandler = { [weak self] header in\n guard let self else { return }\n\n var snapshot = snapshot()\n if header.isExpanded {\n snapshot.deleteItems(Item.wireGuardObfuscation)\n } else {\n snapshot.appendItems(Item.wireGuardObfuscation, toSection: .wireGuardObfuscation)\n }\n header.isExpanded.toggle()\n applySnapshot(snapshot, animated: true)\n }\n\n header.infoButtonHandler = { [weak self] in\n self.map { $0.delegate?.showInfo(for: .wireGuardObfuscation) }\n }\n }\n\n private func configureQuantumResistanceHeader(_ header: SettingsHeaderView) {\n let title = NSLocalizedString(\n "QUANTUM_RESISTANCE_HEADER_LABEL",\n tableName: "VPNSettings",\n value: "Quantum-resistant tunnel",\n comment: ""\n )\n\n header.setAccessibilityIdentifier(.quantumResistantTunnelCell)\n header.titleLabel.text = title\n header.accessibilityCustomActionName = title\n header.isExpanded = isExpanded(.quantumResistance)\n header.didCollapseHandler = { [weak self] header in\n guard let self else { return }\n\n var snapshot = snapshot()\n if header.isExpanded {\n snapshot.deleteItems(Item.quantumResistance)\n } else {\n snapshot.appendItems(Item.quantumResistance, toSection: .quantumResistance)\n }\n header.isExpanded.toggle()\n applySnapshot(snapshot, animated: true)\n }\n\n header.infoButtonHandler = { [weak self] in\n self.map { $0.delegate?.showInfo(for: .quantumResistance) }\n }\n }\n\n private func selectRow(at indexPath: IndexPath?, animated: Bool = false) {\n tableView?.selectRow(at: indexPath, animated: animated, scrollPosition: .none)\n }\n\n private func selectRow(at item: Item?, animated: Bool = false) {\n guard let item else { return }\n\n tableView?.selectRow(at: indexPath(for: item), animated: false, scrollPosition: .none)\n }\n\n private func getCustomPortCell() -> SettingsInputCell? {\n if let customPortIndexPath = indexPath(for: .wireGuardCustomPort) {\n return tableView?.cellForRow(at: customPortIndexPath) as? SettingsInputCell\n }\n\n return nil\n }\n\n /*\n Since we are dequeuing headers, it's crucial to maintain the state of expansion.\n Using screenshots as a single source of truth to capture the state allows us to\n determine whether headers are expanded or not.\n */\n private func isExpanded(_ section: Section) -> Bool {\n let snapshot = snapshot()\n return snapshot.numberOfItems(inSection: section) != 0\n }\n}\n\nextension VPNSettingsDataSource: @preconcurrency VPNSettingsCellEventHandler {\n func setIncludeAllNetworks(_ enabled: Bool, onCancel: @escaping () -> Void) {\n self.viewModel.setIncludeAllNetworks(enabled)\n self.delegate?.didUpdateTunnelSettings(.includeAllNetworks(enabled))\n }\n\n func setLocalNetworkSharing(_ enabled: Bool, onCancel: @escaping () -> Void) {\n delegate?.showLocalNetworkSharingWarning(enabled) { accepted in\n if accepted {\n self.delegate?.didUpdateTunnelSettings(.localNetworkSharing(enabled))\n self.viewModel.setLocalNetworkSharing(enabled)\n } else {\n onCancel()\n }\n }\n }\n\n func showInfo(for button: VPNSettingsInfoButtonItem) {\n delegate?.showInfo(for: button)\n }\n\n func showDetails(for button: VPNSettingsDetailsButtonItem) {\n delegate?.showDetails(for: button)\n }\n\n func addCustomPort(_ port: UInt16) {\n viewModel.setWireGuardPort(port)\n delegate?.didSelectWireGuardPort(port)\n }\n\n func selectCustomPortEntry(_ port: UInt16) -> Bool {\n if let indexPath = indexPath(for: .wireGuardCustomPort), !selectedIndexPaths.contains(indexPath) {\n deselectAllRowsInSectionExceptRowAt(indexPath)\n selectRow(at: indexPath)\n }\n\n return viewModel.isPortWithinValidWireGuardRanges(port)\n }\n\n func selectObfuscationState(_ state: WireGuardObfuscationState) {\n viewModel.setWireGuardObfuscationState(state)\n }\n\n func selectObfuscationPort(_ port: WireGuardObfuscationUdpOverTcpPort) {\n viewModel.setWireGuardObfuscationUdpOverTcpPort(port)\n }\n\n func selectQuantumResistance(_ state: TunnelQuantumResistance) {\n viewModel.setQuantumResistance(state)\n }\n\n func switchMultihop(_ state: MultihopState) {\n viewModel.setMultihop(state)\n delegate?.didUpdateTunnelSettings(.multihop(viewModel.multihopState))\n }\n}\n\n// swiftlint:disable:this file_length\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\VPNSettings\VPNSettingsDataSource.swift
VPNSettingsDataSource.swift
Swift
25,363
0.95
0.076596
0.040067
awesome-app
363
2024-09-19T12:04:51.064990
BSD-3-Clause
false
4c25b3d022e93b59809ce093621a18d6
//\n// VPNSettingsDataSourceDelegate.swift\n// MullvadVPN\n//\n// Created by pronebird on 11/10/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadSettings\n\nprotocol DNSSettingsDataSourceDelegate: AnyObject {\n func didChangeViewModel(_ viewModel: VPNSettingsViewModel)\n func showInfo(for: VPNSettingsInfoButtonItem)\n}\n\nprotocol VPNSettingsDataSourceDelegate: AnyObject {\n func didUpdateTunnelSettings(_ update: TunnelSettingsUpdate)\n func showInfo(for: VPNSettingsInfoButtonItem)\n func showDetails(for: VPNSettingsDetailsButtonItem)\n func showDNSSettings()\n func showIPOverrides()\n func didSelectWireGuardPort(_ port: UInt16?)\n func humanReadablePortRepresentation() -> String\n func showLocalNetworkSharingWarning(_ enable: Bool, completion: @escaping (Bool) -> Void)\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\VPNSettings\VPNSettingsDataSourceDelegate.swift
VPNSettingsDataSourceDelegate.swift
Swift
849
0.95
0.115385
0.304348
react-lib
121
2024-03-20T10:03:18.885333
BSD-3-Clause
false
90a2d8154c0b8fc4f8e98965bd55e750
//\n// VPNSettingsDetailsButtonItem.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-10-18.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nenum VPNSettingsDetailsButtonItem {\n case udpOverTcp\n case wireguardOverShadowsocks\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\VPNSettings\VPNSettingsDetailsButtonItem.swift
VPNSettingsDetailsButtonItem.swift
Swift
259
0.8
0
0.636364
vue-tools
404
2023-10-25T06:44:41.134352
Apache-2.0
false
adf741032a4ea8422523e5d0cb21ebfb
//\n// VPNSettingsInfoButtonItem.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-11-10.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nenum VPNSettingsInfoButtonItem: CustomStringConvertible {\n case localNetworkSharing\n case contentBlockers\n case blockMalware\n case wireGuardPorts(String)\n case wireGuardObfuscation\n case wireGuardObfuscationPort\n case quantumResistance\n case multihop\n\n var description: String {\n switch self {\n case .localNetworkSharing:\n NSLocalizedString(\n "VPN_SETTINGS_LOCAL_NETWORK_SHARING",\n tableName: "LocalNetworkSharing",\n value: """\n This feature allows access to other devices on the local network, such as for sharing, printing, \\n streaming, etc.\n Attention: toggling “Local network sharing” requires restarting the VPN connection.\n """,\n comment: ""\n )\n case .contentBlockers:\n NSLocalizedString(\n "VPN_SETTINGS_CONTENT_BLOCKERS_GENERAL",\n tableName: "ContentBlockers",\n value: """\n When this feature is enabled it stops the device from contacting certain \\n domains or websites known for distributing ads, malware, trackers and more. \\n\n This might cause issues on certain websites, services, and apps.\n Attention: this setting cannot be used in combination with **Use custom DNS server**.\n """,\n comment: ""\n )\n case .blockMalware:\n NSLocalizedString(\n "VPN_SETTINGS_CONTENT_BLOCKERS_MALWARE",\n tableName: "ContentBlockers",\n value: """\n Warning: The malware blocker is not an anti-virus and should not \\n be treated as such, this is just an extra layer of protection.\n """,\n comment: ""\n )\n case let .wireGuardPorts(portsString):\n String(\n format: NSLocalizedString(\n "VPN_SETTINGS_WIREGUARD_PORTS_GENERAL",\n tableName: "WireGuardPorts",\n value: """\n The automatic setting will randomly choose from the valid port ranges shown below.\n The custom port can be any value inside the valid ranges:\n %@\n """,\n comment: ""\n ),\n portsString\n )\n case .wireGuardObfuscation:\n NSLocalizedString(\n "VPN_SETTINGS_WIREGUARD_OBFUSCATION_GENERAL",\n tableName: "WireGuardObfuscation",\n value: """\n Obfuscation hides the WireGuard traffic inside another protocol. \\n It can be used to help circumvent censorship and other types of filtering, \\n where a plain WireGuard connection would be blocked.\n """,\n comment: ""\n )\n case .wireGuardObfuscationPort:\n NSLocalizedString(\n "VPN_SETTINGS_WIREGUARD_OBFUSCATION_PORT_GENERAL",\n tableName: "WireGuardObfuscation",\n value: "Which TCP port the UDP-over-TCP obfuscation protocol should connect to on the VPN server.",\n comment: ""\n )\n case .quantumResistance:\n NSLocalizedString(\n "VPN_SETTINGS_QUANTUM_RESISTANCE_GENERAL",\n tableName: "QuantumResistance",\n value: """\n This feature makes the WireGuard tunnel resistant to potential attacks from quantum computers.\n It does this by performing an extra key exchange using a quantum safe algorithm and mixing \\n the result into WireGuard’s regular encryption.\n This extra step uses approximately 500 kiB of traffic every time a new tunnel is established.\n """,\n comment: ""\n )\n case .multihop:\n NSLocalizedString(\n "MULTIHOP_INFORMATION_TEXT",\n tableName: "Multihop",\n value: """\n Multihop routes your traffic into one WireGuard server and out another, making it harder to trace.\n This results in increased latency but increases anonymity online.\n """,\n comment: ""\n )\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\VPNSettings\VPNSettingsInfoButtonItem.swift
VPNSettingsInfoButtonItem.swift
Swift
4,595
0.95
0.026549
0.06422
vue-tools
467
2024-07-14T20:13:10.857971
Apache-2.0
false
f5f4f6266a56d18d044e568e3ef34390
//\n// VPNSettingsInteractor.swift\n// MullvadVPN\n//\n// Created by pronebird on 31/10/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\nimport MullvadSettings\n\nfinal class VPNSettingsInteractor {\n let tunnelManager: TunnelManager\n private var tunnelObserver: TunnelObserver?\n private let relayCacheTracker: RelayCacheTracker\n\n var tunnelSettingsDidChange: ((LatestTunnelSettings) -> Void)?\n var cachedRelaysDidChange: ((CachedRelays) -> Void)?\n\n var tunnelSettings: LatestTunnelSettings {\n tunnelManager.settings\n }\n\n var cachedRelays: CachedRelays? {\n try? relayCacheTracker.getCachedRelays()\n }\n\n init(tunnelManager: TunnelManager, relayCacheTracker: RelayCacheTracker) {\n self.tunnelManager = tunnelManager\n self.relayCacheTracker = relayCacheTracker\n\n let tunnelObserver =\n TunnelBlockObserver(didUpdateTunnelSettings: { [weak self] _, newSettings in\n self?.tunnelSettingsDidChange?(newSettings)\n })\n self.tunnelObserver = tunnelObserver\n tunnelManager.addObserver(tunnelObserver)\n }\n\n func updateSettings(_ changes: [TunnelSettingsUpdate], completion: (@Sendable () -> Void)? = nil) {\n tunnelManager.updateSettings(changes, completionHandler: completion)\n }\n\n func setPort(_ port: UInt16?, completion: (@Sendable () -> Void)? = nil) {\n var relayConstraints = tunnelManager.settings.relayConstraints\n\n if let port {\n relayConstraints.port = .only(port)\n } else {\n relayConstraints.port = .any\n }\n\n tunnelManager.updateSettings([.relayConstraints(relayConstraints)], completionHandler: completion)\n }\n}\n\nextension VPNSettingsInteractor: RelayCacheTrackerObserver {\n func relayCacheTracker(_ tracker: RelayCacheTracker, didUpdateCachedRelays cachedRelays: CachedRelays) {\n cachedRelaysDidChange?(cachedRelays)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\VPNSettings\VPNSettingsInteractor.swift
VPNSettingsInteractor.swift
Swift
1,982
0.95
0.048387
0.14
node-utils
697
2025-03-11T10:05:46.683625
BSD-3-Clause
false
2dbdb2f056053795fe2b18f6ac8f76b8
//\n// VPNSettingsViewController.swift\n// MullvadVPN\n//\n// Created by pronebird on 19/05/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\nimport SwiftUI\nimport UIKit\n\nprotocol VPNSettingsViewControllerDelegate: AnyObject {\n func showIPOverrides()\n}\n\nclass VPNSettingsViewController: UITableViewController {\n private let interactor: VPNSettingsInteractor\n private var dataSource: VPNSettingsDataSource?\n private let alertPresenter: AlertPresenter\n\n weak var delegate: VPNSettingsViewControllerDelegate?\n\n override var preferredStatusBarStyle: UIStatusBarStyle {\n .lightContent\n }\n\n init(interactor: VPNSettingsInteractor, alertPresenter: AlertPresenter) {\n self.interactor = interactor\n self.alertPresenter = alertPresenter\n\n super.init(style: .grouped)\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n override func viewDidLoad() {\n super.viewDidLoad()\n\n tableView.setAccessibilityIdentifier(.vpnSettingsTableView)\n tableView.backgroundColor = .secondaryColor\n tableView.separatorColor = .secondaryColor\n tableView.rowHeight = UITableView.automaticDimension\n tableView.estimatedRowHeight = 60\n tableView.estimatedSectionHeaderHeight = tableView.estimatedRowHeight\n tableView.allowsMultipleSelection = true\n\n dataSource = VPNSettingsDataSource(tableView: tableView)\n dataSource?.delegate = self\n\n navigationItem.title = NSLocalizedString(\n "NAVIGATION_TITLE",\n tableName: "VPNSettings",\n value: "VPN settings",\n comment: ""\n )\n\n interactor.tunnelSettingsDidChange = { [weak self] newSettings in\n self?.dataSource?.reload(from: newSettings)\n }\n dataSource?.update(from: interactor.tunnelSettings)\n\n dataSource?.setAvailablePortRanges(interactor.cachedRelays?.relays.wireguard.portRanges ?? [])\n interactor.cachedRelaysDidChange = { [weak self] cachedRelays in\n self?.dataSource?.setAvailablePortRanges(cachedRelays.relays.wireguard.portRanges)\n }\n\n tableView.tableHeaderView = UIView(frame: CGRect(\n origin: .zero,\n size: CGSize(width: 0, height: UIMetrics.TableView.sectionSpacing)\n ))\n }\n}\n\nextension VPNSettingsViewController: @preconcurrency VPNSettingsDataSourceDelegate {\n func humanReadablePortRepresentation() -> String {\n let ranges = interactor.cachedRelays?.relays.wireguard.portRanges ?? []\n return ranges\n .compactMap { range in\n if let minPort = range.first, let maxPort = range.last {\n return minPort == maxPort ? String(minPort) : "\(minPort)-\(maxPort)"\n } else {\n return nil\n }\n }\n .joined(separator: ", ")\n }\n\n func didUpdateTunnelSettings(_ update: TunnelSettingsUpdate) {\n interactor.updateSettings([update])\n }\n\n func showInfo(for item: VPNSettingsInfoButtonItem) {\n let presentation = AlertPresentation(\n id: "vpn-settings-content-blockers-alert",\n icon: .info,\n message: item.description,\n buttons: [\n AlertAction(\n title: NSLocalizedString(\n "VPN_SETTINGS_VPN_SETTINGS_OK_ACTION",\n tableName: "ContentBlockers",\n value: "Got it!",\n comment: ""\n ),\n style: .default\n ),\n ]\n )\n\n alertPresenter.showAlert(presentation: presentation, animated: true)\n }\n\n func showDetails(for item: VPNSettingsDetailsButtonItem) {\n switch item {\n case .udpOverTcp:\n showUDPOverTCPObfuscationSettings()\n case .wireguardOverShadowsocks:\n showShadowsocksObfuscationSettings()\n }\n }\n\n func showDNSSettings() {\n let viewController = CustomDNSViewController(interactor: interactor, alertPresenter: alertPresenter)\n navigationController?.pushViewController(viewController, animated: true)\n }\n\n func showIPOverrides() {\n delegate?.showIPOverrides()\n }\n\n private func showUDPOverTCPObfuscationSettings() {\n let viewModel = TunnelUDPOverTCPObfuscationSettingsViewModel(tunnelManager: interactor.tunnelManager)\n let view = UDPOverTCPObfuscationSettingsView(viewModel: viewModel)\n let vc = UIHostingController(rootView: view)\n vc.title = NSLocalizedString(\n "UDP_OVER_TCP_TITLE",\n tableName: "VPNSettings",\n value: "UDP-over-TCP",\n comment: ""\n )\n navigationController?.pushViewController(vc, animated: true)\n }\n\n private func showShadowsocksObfuscationSettings() {\n let viewModel = TunnelShadowsocksObfuscationSettingsViewModel(tunnelManager: interactor.tunnelManager)\n let view = ShadowsocksObfuscationSettingsView(viewModel: viewModel)\n let vc = UIHostingController(rootView: view)\n vc.title = NSLocalizedString(\n "SHADOWSOCKS_TITLE",\n tableName: "VPNSettings",\n value: "Shadowsocks",\n comment: ""\n )\n navigationController?.pushViewController(vc, animated: true)\n }\n\n func didSelectWireGuardPort(_ port: UInt16?) {\n interactor.setPort(port)\n }\n\n func showLocalNetworkSharingWarning(_ enable: Bool, completion: @escaping (Bool) -> Void) {\n if interactor.tunnelManager.tunnelStatus.state.isSecured {\n let description = NSLocalizedString(\n "VPN_SETTINGS_LOCAL_NETWORK_SHARING_WARNING",\n tableName: "LocalNetworkSharing",\n value: """\n \(\n enable\n ? "Enabling"\n : "Disabling"\n ) “Local network sharing” requires restarting the VPN connection, which will disconnect you and briefly expose your traffic. \n To prevent this, manually enable Airplane Mode and turn off Wi-Fi before continuing. \n Would you like to continue to enable “Local network sharing”?\n """,\n comment: ""\n )\n\n let presentation = AlertPresentation(\n id: "vpn-settings-local-network-sharing-warning",\n icon: .info,\n message: description,\n buttons: [\n AlertAction(\n title: NSLocalizedString(\n "VPN_SETTINGS_LOCAL_NETWORK_SHARING_OK_ACTION",\n tableName: "ContentBlockers",\n value: "Yes, continue",\n comment: ""\n ),\n style: .destructive,\n accessibilityId: .acceptLocalNetworkSharingButton,\n handler: {\n completion(true)\n }\n ),\n AlertAction(\n title: NSLocalizedString(\n "VPN_SETTINGS_LOCAL_NETWORK_SHARING_CANCEL_ACTION",\n tableName: "ContentBlockers",\n value: "Cancel",\n comment: ""\n ),\n style: .default,\n handler: { completion(false) }\n ),\n ]\n )\n\n alertPresenter.showAlert(presentation: presentation, animated: true)\n } else {\n completion(true)\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\VPNSettings\VPNSettingsViewController.swift
VPNSettingsViewController.swift
Swift
7,819
0.95
0.02765
0.037037
python-kit
82
2024-06-06T13:05:47.722002
BSD-3-Clause
false
53a030953531c6b34017a9ec4bad5d5c
//\n// VPNSettingsViewModel.swift\n// MullvadVPN\n//\n// Created by pronebird on 11/10/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\nimport MullvadTypes\nimport UIKit\n\nenum CustomDNSPrecondition {\n /// Custom DNS can be enabled\n case satisfied\n\n /// Custom DNS cannot be enabled as it would conflict with other settings.\n case conflictsWithOtherSettings\n\n /// No valid DNS server entries.\n case emptyDNSDomains\n\n /// Returns localized description explaining how to enable Custom DNS.\n func localizedDescription(isEditing: Bool) -> String? {\n attributedLocalizedDescription(\n isEditing: isEditing,\n preferredFont: UIFont.systemFont(ofSize: UIFont.systemFontSize)\n )?.string\n }\n\n /// Returns attributed localized description explaining how to enable Custom DNS.\n func attributedLocalizedDescription(\n isEditing: Bool,\n preferredFont: UIFont\n ) -> NSAttributedString? {\n switch self {\n case .satisfied:\n return nil\n\n case .emptyDNSDomains:\n if isEditing {\n return NSAttributedString(\n string: NSLocalizedString(\n "CUSTOM_DNS_NO_DNS_ENTRIES_EDITING_ON_FOOTNOTE",\n tableName: "VPNSettings",\n value: "To enable this setting, add at least one server.",\n comment: "Foot note displayed if there are no DNS entries and table view is in editing mode."\n ),\n attributes: [.font: preferredFont]\n )\n } else {\n return NSAttributedString(\n markdownString: NSLocalizedString(\n "CUSTOM_DNS_NO_DNS_ENTRIES_EDITING_OFF_FOOTNOTE",\n tableName: "VPNSettings",\n value: "Tap **Edit** to add at least one DNS server.",\n comment:\n "Foot note displayed if there are no DNS entries, but table view is not in editing mode."\n ),\n options: MarkdownStylingOptions(font: preferredFont)\n )\n }\n\n case .conflictsWithOtherSettings:\n return NSAttributedString(\n string: NSLocalizedString(\n "CUSTOM_DNS_DISABLE_CONTENT_BLOCKERS_FOOTNOTE",\n tableName: "VPNSettings",\n value: "Disable all content blockers to activate this setting.",\n comment: """\n Foot note displayed when custom DNS cannot be enabled, because content blockers should be \\n disabled first.\n """\n ),\n attributes: [.font: preferredFont]\n )\n }\n }\n}\n\nstruct DNSServerEntry: Equatable, Hashable {\n var identifier = UUID()\n var address: String\n}\n\nstruct VPNSettingsViewModel: Equatable {\n private(set) var blockAll: Bool\n private(set) var blockAdvertising: Bool\n private(set) var blockTracking: Bool\n private(set) var blockMalware: Bool\n private(set) var blockAdultContent: Bool\n private(set) var blockGambling: Bool\n private(set) var blockSocialMedia: Bool\n private(set) var enableCustomDNS: Bool\n private(set) var wireGuardPort: UInt16?\n var customDNSDomains: [DNSServerEntry]\n var availableWireGuardPortRanges: [[UInt16]] = []\n\n private(set) var obfuscationState: WireGuardObfuscationState\n private(set) var obfuscationUpdOverTcpPort: WireGuardObfuscationUdpOverTcpPort\n private(set) var obfuscationShadowsocksPort: WireGuardObfuscationShadowsocksPort\n\n private(set) var quantumResistance: TunnelQuantumResistance\n private(set) var multihopState: MultihopState\n\n private(set) var includeAllNetworks: Bool\n private(set) var localNetworkSharing: Bool\n\n static let defaultWireGuardPorts: [UInt16] = [51820, 53]\n\n var enabledBlockersCount: Int {\n [\n blockAdvertising,\n blockTracking,\n blockMalware,\n blockAdultContent,\n blockGambling,\n blockSocialMedia,\n ].filter { $0 }.count\n }\n\n var allBlockersEnabled: Bool {\n enabledBlockersCount == CustomDNSDataSource.Item.contentBlockers.filter { $0 != .blockAll }.count\n }\n\n mutating func setBlockAll(_ newValue: Bool) {\n blockAll = newValue\n blockAdvertising = newValue\n blockTracking = newValue\n blockMalware = newValue\n blockAdultContent = newValue\n blockGambling = newValue\n blockSocialMedia = newValue\n enableCustomDNS = false\n }\n\n mutating func setBlockAdvertising(_ newValue: Bool) {\n blockAdvertising = newValue\n blockAll = allBlockersEnabled\n enableCustomDNS = false\n }\n\n mutating func setBlockTracking(_ newValue: Bool) {\n blockTracking = newValue\n blockAll = allBlockersEnabled\n enableCustomDNS = false\n }\n\n mutating func setBlockMalware(_ newValue: Bool) {\n blockMalware = newValue\n blockAll = allBlockersEnabled\n enableCustomDNS = false\n }\n\n mutating func setBlockAdultContent(_ newValue: Bool) {\n blockAdultContent = newValue\n blockAll = allBlockersEnabled\n enableCustomDNS = false\n }\n\n mutating func setBlockGambling(_ newValue: Bool) {\n blockGambling = newValue\n blockAll = allBlockersEnabled\n enableCustomDNS = false\n }\n\n mutating func setBlockSocialMedia(_ newValue: Bool) {\n blockSocialMedia = newValue\n blockAll = allBlockersEnabled\n enableCustomDNS = false\n }\n\n mutating func setEnableCustomDNS(_ newValue: Bool) {\n enableCustomDNS = newValue\n }\n\n mutating func setWireGuardPort(_ newValue: UInt16?) {\n wireGuardPort = newValue\n }\n\n mutating func setWireGuardObfuscationState(_ newState: WireGuardObfuscationState) {\n obfuscationState = newState\n }\n\n mutating func setWireGuardObfuscationShadowsockPort(_ newPort: WireGuardObfuscationShadowsocksPort) {\n obfuscationShadowsocksPort = newPort\n }\n\n mutating func setWireGuardObfuscationUdpOverTcpPort(_ newPort: WireGuardObfuscationUdpOverTcpPort) {\n obfuscationUpdOverTcpPort = newPort\n }\n\n mutating func setQuantumResistance(_ newState: TunnelQuantumResistance) {\n quantumResistance = newState\n }\n\n mutating func setMultihop(_ newState: MultihopState) {\n multihopState = newState\n }\n\n mutating func setIncludeAllNetworks(_ newState: Bool) {\n includeAllNetworks = newState\n }\n\n mutating func setLocalNetworkSharing(_ newState: Bool) {\n localNetworkSharing = newState\n }\n\n /// Precondition for enabling Custom DNS.\n var customDNSPrecondition: CustomDNSPrecondition {\n if blockAdvertising || blockTracking || blockMalware ||\n blockAdultContent || blockGambling || blockSocialMedia {\n return .conflictsWithOtherSettings\n } else {\n let hasValidDNSDomains = customDNSDomains.contains { entry in\n AnyIPAddress(entry.address) != nil\n }\n\n if hasValidDNSDomains {\n return .satisfied\n } else {\n return .emptyDNSDomains\n }\n }\n }\n\n /// Effective state of the custom DNS setting.\n var effectiveEnableCustomDNS: Bool {\n customDNSPrecondition == .satisfied && enableCustomDNS\n }\n\n var customWireGuardPort: UInt16? {\n wireGuardPort.flatMap { port in\n Self.defaultWireGuardPorts.contains(port) ? nil : port\n }\n }\n\n init(from tunnelSettings: LatestTunnelSettings = LatestTunnelSettings()) {\n let dnsSettings = tunnelSettings.dnsSettings\n\n blockAdvertising = dnsSettings.blockingOptions.contains(.blockAdvertising)\n blockTracking = dnsSettings.blockingOptions.contains(.blockTracking)\n blockMalware = dnsSettings.blockingOptions.contains(.blockMalware)\n blockAdultContent = dnsSettings.blockingOptions.contains(.blockAdultContent)\n blockGambling = dnsSettings.blockingOptions.contains(.blockGambling)\n blockSocialMedia = dnsSettings.blockingOptions.contains(.blockSocialMedia)\n blockAll = blockAdvertising\n && blockTracking\n && blockMalware\n && blockAdultContent\n && blockGambling\n && blockSocialMedia\n\n enableCustomDNS = dnsSettings.enableCustomDNS\n customDNSDomains = dnsSettings.customDNSDomains.map { ipAddress in\n DNSServerEntry(identifier: UUID(), address: "\(ipAddress)")\n }\n wireGuardPort = tunnelSettings.relayConstraints.port.value\n\n obfuscationState = tunnelSettings.wireGuardObfuscation.state\n obfuscationUpdOverTcpPort = tunnelSettings.wireGuardObfuscation.udpOverTcpPort\n obfuscationShadowsocksPort = tunnelSettings.wireGuardObfuscation.shadowsocksPort\n\n quantumResistance = tunnelSettings.tunnelQuantumResistance\n multihopState = tunnelSettings.tunnelMultihopState\n\n includeAllNetworks = tunnelSettings.includeAllNetworks\n localNetworkSharing = tunnelSettings.localNetworkSharing\n }\n\n /// Produce merged view model, keeping entry `identifier` for matching DNS entries and\n /// retaining available Wireguard port ranges.\n func merged(_ other: VPNSettingsViewModel) -> VPNSettingsViewModel {\n var mergedViewModel = other\n mergedViewModel.customDNSDomains = merge(customDNSDomains, with: other.customDNSDomains)\n mergedViewModel.availableWireGuardPortRanges = availableWireGuardPortRanges\n\n return mergedViewModel\n }\n\n /// Sanitize custom DNS entries.\n mutating func sanitizeCustomDNSEntries() {\n // Sanitize DNS domains, drop invalid entries.\n customDNSDomains = customDNSDomains.compactMap { entry in\n if let canonicalAddress = AnyIPAddress(entry.address) {\n var newEntry = entry\n newEntry.address = "\(canonicalAddress)"\n return newEntry\n } else {\n return nil\n }\n }\n\n // Toggle off custom DNS when no domains specified.\n if customDNSDomains.isEmpty {\n enableCustomDNS = false\n }\n }\n\n func dnsEntry(entryIdentifier: UUID) -> DNSServerEntry? {\n customDNSDomains.first { entry in\n entry.identifier == entryIdentifier\n }\n }\n\n /// Returns an index of entry in `customDNSDomains`, otherwise `nil`.\n func indexOfDNSEntry(entryIdentifier: UUID) -> Int? {\n customDNSDomains.firstIndex { entry in\n entry.identifier == entryIdentifier\n }\n }\n\n /// Update the address for the DNS entry with the given UUID.\n mutating func updateDNSEntry(entryIdentifier: UUID, newAddress: String) {\n guard let index = indexOfDNSEntry(entryIdentifier: entryIdentifier) else { return }\n\n var entry = customDNSDomains[index]\n entry.address = newAddress\n customDNSDomains[index] = entry\n }\n\n /// Converts view model into `DNSSettings`.\n func asDNSSettings() -> DNSSettings {\n var blockingOptions = DNSBlockingOptions()\n if blockAdvertising {\n blockingOptions.insert(.blockAdvertising)\n }\n\n if blockTracking {\n blockingOptions.insert(.blockTracking)\n }\n\n if blockMalware {\n blockingOptions.insert(.blockMalware)\n }\n\n if blockAdultContent {\n blockingOptions.insert(.blockAdultContent)\n }\n\n if blockGambling {\n blockingOptions.insert(.blockGambling)\n }\n\n if blockSocialMedia {\n blockingOptions.insert(.blockSocialMedia)\n }\n\n var dnsSettings = DNSSettings()\n dnsSettings.blockingOptions = blockingOptions\n dnsSettings.enableCustomDNS = enableCustomDNS\n dnsSettings.customDNSDomains = customDNSDomains.compactMap { entry in\n AnyIPAddress(entry.address)\n }\n return dnsSettings\n }\n\n /// Returns true if the given string is empty or a valid IP address.\n func isDNSDomainUserInputValid(_ string: String) -> Bool {\n string.isEmpty || AnyIPAddress(string) != nil\n }\n\n /// Returns true if the given port is in within the supported ranges.\n func isPortWithinValidWireGuardRanges(_ port: UInt16) -> Bool {\n availableWireGuardPortRanges.contains { range in\n if let minPort = range.first, let maxPort = range.last {\n return (minPort ... maxPort).contains(port)\n }\n\n return false\n }\n }\n\n /// Replaces all old domains with new, keeping only those that share the same id and updating their content.\n private func merge(_ oldDomains: [DNSServerEntry], with newDomains: [DNSServerEntry]) -> [DNSServerEntry] {\n var oldDomains = oldDomains\n\n return newDomains.map { otherEntry in\n let sameEntryIndex = oldDomains.firstIndex { entry in\n entry.address == otherEntry.address\n }\n\n if let sameEntryIndex {\n let sourceEntry = oldDomains[sameEntryIndex]\n\n oldDomains.remove(at: sameEntryIndex)\n\n return sourceEntry\n } else {\n return otherEntry\n }\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\VPNSettings\VPNSettingsViewModel.swift
VPNSettingsViewModel.swift
Swift
13,480
0.95
0.053299
0.075988
node-utils
260
2023-10-07T18:19:24.831627
MIT
false
682bdb5562521cb43b7f92ab3d25866b
//\n// AppButton.swift\n// MullvadVPN\n//\n// Created by pronebird on 23/05/2019.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\n/// A subclass that implements action buttons used across the app\nclass AppButton: CustomButton {\n /// Default content insets based on current trait collection.\n var defaultContentInsets: NSDirectionalEdgeInsets {\n switch traitCollection.userInterfaceIdiom {\n case .phone:\n return NSDirectionalEdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 10)\n case .pad:\n return NSDirectionalEdgeInsets(top: 15, leading: 15, bottom: 15, trailing: 15)\n default:\n return .zero\n }\n }\n\n enum Style: Int {\n /// Default blue appearance.\n case `default`\n\n /// Destructive appearance.\n case danger\n\n /// Positive appearance suitable for actions that provide security.\n case success\n\n /// Translucent destructive appearance.\n case translucentDanger\n\n /// Translucent neutral appearance.\n case translucentNeutral\n\n /// Translucent destructive appearance for the left-hand side of a two component split button.\n case translucentDangerSplitLeft\n\n /// Translucent destructive appearance for the right-hand side of a two component split button.\n case translucentDangerSplitRight\n\n /// Default blue rounded button suitable for presentation in table view using `.insetGrouped` style.\n case tableInsetGroupedDefault\n\n /// Positive appearance for presentation in table view using `.insetGrouped` style.\n case tableInsetGroupedSuccess\n\n /// Destructive style suitable for presentation in table view using `.insetGrouped` style.\n case tableInsetGroupedDanger\n\n /// Returns a background image for the button.\n var backgroundImage: UIImage {\n switch self {\n case .default:\n UIImage(resource: .defaultButton)\n case .danger:\n UIImage(resource: .dangerButton)\n case .success:\n UIImage(resource: .successButton)\n case .translucentDanger:\n UIImage(resource: .translucentDangerButton)\n case .translucentNeutral:\n UIImage(resource: .translucentNeutralButton)\n case .translucentDangerSplitLeft:\n UIImage(resource: .translucentDangerSplitLeftButton).imageFlippedForRightToLeftLayoutDirection()\n case .translucentDangerSplitRight:\n UIImage(resource: .translucentDangerSplitRightButton).imageFlippedForRightToLeftLayoutDirection()\n case .tableInsetGroupedDefault:\n UIImage(resource: .defaultButton)\n case .tableInsetGroupedSuccess:\n UIImage(resource: .successButton)\n case .tableInsetGroupedDanger:\n UIImage(resource: .dangerButton)\n }\n }\n }\n\n /// Button style.\n var style: Style {\n didSet {\n updateButtonBackground()\n }\n }\n\n init(style: Style) {\n self.style = style\n super.init(frame: .zero)\n commonInit()\n }\n\n override init(frame: CGRect) {\n self.style = .default\n super.init(frame: frame)\n commonInit()\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n private func commonInit() {\n imageAlignment = .trailing\n titleAlignment = .leading\n\n var config = super.configuration ?? .plain()\n config.title = title(for: state)\n config.contentInsets = defaultContentInsets\n config.background.image = style.backgroundImage\n config.background.imageContentMode = .scaleAspectFill\n config.titleTextAttributesTransformer =\n UIConfigurationTextAttributesTransformer { [weak self] attributeContainer in\n var updatedAttributeContainer = attributeContainer\n updatedAttributeContainer.font = UIFont.systemFont(ofSize: 18, weight: .semibold)\n updatedAttributeContainer.foregroundColor = self?.state.customButtonTitleColor\n return updatedAttributeContainer\n }\n\n let configurationHandler: UIButton.ConfigurationUpdateHandler = { [weak self] _ in\n guard let self else { return }\n updateButtonBackground()\n }\n configuration = config\n configurationUpdateHandler = configurationHandler\n }\n\n /// Set background image based on current style.\n private func updateButtonBackground() {\n if isEnabled {\n // Load the normal image and set it as the background\n configuration?.background.image = style.backgroundImage\n } else {\n // Adjust the image for the disabled state\n configuration?.background.image = style.backgroundImage.withAlpha(0.5)\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Views\AppButton.swift
AppButton.swift
Swift
4,978
0.95
0.092199
0.2
awesome-app
890
2024-05-16T02:43:18.219016
GPL-3.0
false
eabb42d0b5a47853b77693b8266bd6f3
//\n// BlurView.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\n/// Blurred (background) view using a `UIBlurEffect`.\nstruct BlurView: View {\n var style: UIBlurEffect.Style\n\n var body: some View {\n VisualEffectView(effect: UIBlurEffect(style: style))\n .opacity(0.8)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Views\BlurView.swift
BlurView.swift
Swift
397
0.95
0
0.5
vue-tools
810
2023-09-17T12:50:12.860559
MIT
false
950fc93804bedfcc78f88a1d8ecd9bc8
//\n// CheckboxView.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-06-05.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass CheckboxView: UIView {\n private let backgroundView: UIView = {\n let view = UIView()\n view.backgroundColor = .white\n view.layer.cornerRadius = 4\n return view\n }()\n\n private let checkmarkView: UIImageView = {\n let imageView = UIImageView(image: UIImage.tick)\n imageView.tintColor = .successColor\n imageView.contentMode = .scaleAspectFit\n imageView.alpha = 0\n return imageView\n }()\n\n var isChecked = false {\n didSet {\n checkmarkView.alpha = isChecked ? 1 : 0\n }\n }\n\n init() {\n super.init(frame: .zero)\n\n directionalLayoutMargins = .init(top: 4, leading: 4, bottom: 4, trailing: 4)\n\n addConstrainedSubviews([backgroundView, checkmarkView]) {\n backgroundView.pinEdgesToSuperview()\n checkmarkView.pinEdgesToSuperviewMargins()\n }\n }\n\n required init?(coder aDecoder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Views\CheckboxView.swift
CheckboxView.swift
Swift
1,174
0.95
0.021277
0.179487
vue-tools
826
2023-07-15T11:45:59.755744
BSD-3-Clause
false
03c049942f9c99c2437e6df010a9e589
//\n// CustomButton.swift\n// MullvadVPN\n//\n// Created by pronebird on 23/05/2019.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nextension UIControl.State {\n var customButtonTitleColor: UIColor? {\n switch self {\n case .normal:\n return UIColor.AppButton.normalTitleColor\n case .disabled:\n return UIColor.AppButton.disabledTitleColor\n case .highlighted:\n return UIColor.AppButton.highlightedTitleColor\n default:\n return nil\n }\n }\n}\n\n/// A custom `UIButton` subclass that implements additional layouts for the image\nclass CustomButton: UIButton, Sendable {\n var imageAlignment: NSDirectionalRectEdge = .leading {\n didSet {\n self.configuration?.imagePlacement = imageAlignment\n }\n }\n\n var inlineImageSpacing: CGFloat = 4 {\n didSet {\n self.configuration?.imagePadding = inlineImageSpacing\n }\n }\n\n var titleAlignment: UIButton.Configuration.TitleAlignment = .center {\n didSet {\n self.configuration?.titleAlignment = titleAlignment\n }\n }\n\n var inlineTitleSpacing: CGFloat = 4 {\n didSet {\n self.configuration?.titlePadding = inlineTitleSpacing\n }\n }\n\n override init(frame: CGRect) {\n super.init(frame: frame)\n commonInit()\n }\n\n required init?(coder: NSCoder) {\n super.init(coder: coder)\n commonInit()\n }\n\n private func commonInit() {\n var config = UIButton.Configuration.plain()\n config.imagePadding = inlineImageSpacing\n config.imagePlacement = imageAlignment\n config.titleAlignment = titleAlignment\n config.titleLineBreakMode = .byWordWrapping\n config.titlePadding = inlineTitleSpacing\n config.baseForegroundColor = state.customButtonTitleColor\n self.configuration = config\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Views\CustomButton.swift
CustomButton.swift
Swift
1,923
0.95
0.041667
0.126984
vue-tools
607
2024-06-03T06:07:18.822712
MIT
false
38d44db93927b2dcf0817670bff359ff
//\n// CustomSwitch.swift\n// MullvadVPN\n//\n// Created by pronebird on 20/05/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass CustomSwitch: UISwitch {\n /// Returns the private `UISwitch` background view\n private var backgroundView: UIView? {\n // Go two levels deep only\n let subviewsToExamine = subviews.flatMap { view -> [UIView] in\n [view] + view.subviews\n }\n\n // Find the first subview that has background color set.\n let backgroundView = subviewsToExamine.first { subview in\n subview.backgroundColor != nil\n }\n\n return backgroundView\n }\n\n override init(frame: CGRect) {\n super.init(frame: frame)\n\n tintColor = .clear\n onTintColor = .clear\n overrideUserInterfaceStyle = .light\n\n setAccessibilityIdentifier(.customSwitch)\n\n updateThumbColor(isOn: isOn, animated: false)\n\n addTarget(self, action: #selector(valueChanged(_:)), for: .valueChanged)\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n override func setOn(_ on: Bool, animated: Bool) {\n super.setOn(on, animated: animated)\n\n updateThumbColor(isOn: on, animated: animated)\n }\n\n private func updateThumbColor(isOn: Bool, animated: Bool) {\n let actions = {\n self.thumbTintColor = isOn ? UIColor.Switch.onThumbColor : UIColor.Switch.offThumbColor\n self.backgroundView?.backgroundColor = .clear\n }\n\n if animated {\n UIView.animate(withDuration: 0.25, animations: actions)\n } else {\n actions()\n }\n }\n\n @objc private func valueChanged(_ sender: Any) {\n updateThumbColor(isOn: isOn, animated: true)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Views\CustomSwitch.swift
CustomSwitch.swift
Swift
1,809
0.95
0.044776
0.192308
awesome-app
926
2025-03-21T01:57:27.722242
MIT
false
00d9a3c070f23d0694953783252ad6b1
//\n// CustomSwitchContainer.swift\n// MullvadVPN\n//\n// Created by pronebird on 20/05/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass CustomSwitchContainer: UIView {\n static let borderEdgeInsets = UIEdgeInsets(top: 3, left: 3, bottom: 3, right: 3)\n\n private let borderShape: CAShapeLayer = {\n let shapeLayer = CAShapeLayer()\n shapeLayer.borderColor = UIColor.Switch.borderColor.cgColor\n shapeLayer.borderWidth = 2\n shapeLayer.cornerCurve = .continuous\n return shapeLayer\n }()\n\n let control = CustomSwitch()\n\n var isEnabled: Bool {\n get {\n control.isEnabled\n }\n set {\n control.isEnabled = newValue\n updateBorderOpacity()\n }\n }\n\n override var accessibilityIdentifier: String? {\n didSet {\n control.accessibilityIdentifier = accessibilityIdentifier\n }\n }\n\n override var intrinsicContentSize: CGSize {\n controlSize()\n }\n\n override func sizeThatFits(_ size: CGSize) -> CGSize {\n controlSize()\n }\n\n override init(frame: CGRect) {\n super.init(frame: frame)\n\n addSubview(control)\n layer.addSublayer(borderShape)\n\n control.sizeToFit()\n sizeToFit()\n\n borderShape.cornerRadius = bounds.height * 0.5\n borderShape.frame = bounds\n\n updateBorderOpacity()\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n override func layoutSubviews() {\n super.layoutSubviews()\n\n control.frame.origin = CGPoint(x: Self.borderEdgeInsets.left, y: Self.borderEdgeInsets.top)\n }\n\n // MARK: - Private\n\n private func controlSize() -> CGSize {\n var size = control.bounds.size\n size.width += Self.borderEdgeInsets.left + Self.borderEdgeInsets.right\n size.height += Self.borderEdgeInsets.top + Self.borderEdgeInsets.bottom\n return size\n }\n\n private func updateBorderOpacity() {\n CATransaction.begin()\n CATransaction.setDisableActions(true)\n\n borderShape.opacity = control.isEnabled ? 1 : 0.2\n\n CATransaction.commit()\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Views\CustomSwitchContainer.swift
CustomSwitchContainer.swift
Swift
2,206
0.95
0.011111
0.115942
react-lib
102
2025-04-06T11:26:40.053815
BSD-3-Clause
false
7188fc8720c9dc53498c57f043d0b3e7
//\n// CustomTextField.swift\n// MullvadVPN\n//\n// Created by pronebird on 16/09/2020.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport UIKit\n\nclass CustomTextField: UITextField {\n var cornerRadius: CGFloat = UIMetrics.controlCornerRadius {\n didSet {\n layer.cornerRadius = cornerRadius\n }\n }\n\n var textMargins = UIMetrics.textFieldMargins {\n didSet {\n setNeedsLayout()\n }\n }\n\n var placeholderTextColor = UIColor.TextField.placeholderTextColor {\n didSet {\n updatePlaceholderTextColor()\n }\n }\n\n override var placeholder: String? {\n didSet {\n updatePlaceholderTextColor()\n }\n }\n\n override init(frame: CGRect) {\n super.init(frame: frame)\n\n textColor = UIColor.TextField.textColor\n layer.cornerRadius = cornerRadius\n clipsToBounds = true\n }\n\n override func didAddSubview(_ subview: UIView) {\n super.didAddSubview(subview)\n\n // Internally `UITextField` adds the placeholder label to its view hierarchy.\n // Intercept it here and update the text color.\n if let placeholderLabel = subview as? UILabel {\n placeholderLabel.textColor = placeholderTextColor\n }\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n override func textRect(forBounds bounds: CGRect) -> CGRect {\n bounds.inset(by: textMargins)\n }\n\n override func editingRect(forBounds bounds: CGRect) -> CGRect {\n textRect(forBounds: bounds)\n }\n\n private func updatePlaceholderTextColor() {\n for case let placeholderLabel as UILabel in subviews {\n placeholderLabel.textColor = placeholderTextColor\n break\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Views\CustomTextField.swift
CustomTextField.swift
Swift
1,836
0.95
0.041096
0.15
awesome-app
910
2025-05-25T12:03:43.218887
BSD-3-Clause
false
15f8860593a169d31d5e1f043efa44d7
//\n// CustomTextView.swift\n// MullvadVPN\n//\n// Created by pronebird on 16/09/2020.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass CustomTextView: UITextView {\n private static let textViewCornerRadius: CGFloat = 4\n\n var roundCorners = true {\n didSet {\n layer.cornerRadius = roundCorners ? Self.textViewCornerRadius : 0\n }\n }\n\n /// Placeholder string\n var placeholder: String? {\n get {\n placeholderTextLabel.text\n }\n set {\n placeholderTextLabel.text = newValue\n }\n }\n\n /// Placeholder text label\n private let placeholderTextLabel = UILabel()\n\n /// Placeholder label constraints\n private var placeholderConstraints = [NSLayoutConstraint]()\n\n override var textContainerInset: UIEdgeInsets {\n didSet {\n setNeedsUpdateConstraints()\n }\n }\n\n override var font: UIFont? {\n didSet {\n placeholderTextLabel.font = font ?? UIFont.preferredFont(forTextStyle: .body)\n }\n }\n\n /// Placeholder text inset derived from `textContainerInset`\n private var placeholderTextInset: UIEdgeInsets {\n var placeholderInset = textContainerInset\n\n // Offset the placeholder label to match with text view rendering.\n placeholderInset.top += 0.5\n\n return placeholderInset\n }\n\n override var accessibilityLabel: String? {\n get {\n if self.text.isEmpty {\n return placeholderTextLabel.text\n } else {\n return super.accessibilityLabel\n }\n }\n set {\n super.accessibilityLabel = newValue\n }\n }\n\n override var accessibilityPath: UIBezierPath? {\n get {\n if roundCorners {\n return UIBezierPath(\n roundedRect: accessibilityFrame,\n cornerRadius: Self.textViewCornerRadius\n )\n } else {\n return UIBezierPath(rect: accessibilityFrame)\n }\n }\n set {\n super.accessibilityPath = newValue\n }\n }\n\n nonisolated(unsafe) private var notificationObserver: Any?\n\n override init(frame: CGRect, textContainer: NSTextContainer?) {\n super.init(frame: frame, textContainer: textContainer)\n\n placeholderTextLabel.isAccessibilityElement = false\n placeholderTextLabel.accessibilityTraits = []\n placeholderTextLabel.textColor = UIColor.TextField.placeholderTextColor\n placeholderTextLabel.highlightedTextColor = UIColor.TextField.placeholderTextColor\n placeholderTextLabel.translatesAutoresizingMaskIntoConstraints = false\n placeholderTextLabel.numberOfLines = 0\n addSubview(placeholderTextLabel)\n\n // Create placeholder constraints\n placeholderConstraints = [\n placeholderTextLabel.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor),\n placeholderTextLabel.leadingAnchor\n .constraint(equalTo: safeAreaLayoutGuide.leadingAnchor),\n placeholderTextLabel.trailingAnchor\n .constraint(equalTo: safeAreaLayoutGuide.trailingAnchor),\n placeholderTextLabel.bottomAnchor\n .constraint(lessThanOrEqualTo: safeAreaLayoutGuide.bottomAnchor),\n ]\n NSLayoutConstraint.activate(placeholderConstraints)\n\n // Set visual appearance\n textColor = UIColor.TextField.textColor\n layer.cornerRadius = Self.textViewCornerRadius\n clipsToBounds = true\n\n // Set content padding\n contentInset = .zero\n textContainerInset = UIEdgeInsets(top: 12, left: 14, bottom: 12, right: 14)\n self.textContainer.lineFragmentPadding = 0\n\n // Handle placeholder visibility\n notificationObserver = NotificationCenter.default.addObserver(\n forName: NSTextStorage.didProcessEditingNotification,\n object: textStorage,\n queue: OperationQueue.main\n ) { [weak self] _ in\n MainActor.assumeIsolated {\n self?.updatePlaceholderVisibility()\n }\n }\n\n updatePlaceholderVisibility()\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n deinit {\n if let notificationObserver {\n NotificationCenter.default.removeObserver(notificationObserver)\n }\n }\n\n override func updateConstraints() {\n let textInset = placeholderTextInset\n\n for constraint in placeholderConstraints {\n switch constraint.firstAttribute {\n case .top:\n constraint.constant = textInset.top\n case .leading:\n constraint.constant = textInset.left\n case .trailing:\n constraint.constant = -textInset.right\n case .bottom:\n constraint.constant = -textInset.bottom\n default:\n break\n }\n }\n\n super.updateConstraints()\n }\n\n private func updatePlaceholderVisibility() {\n placeholderTextLabel.isHidden = textStorage.length > 0\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Views\CustomTextView.swift
CustomTextView.swift
Swift
5,196
0.95
0.035294
0.111888
vue-tools
661
2024-03-13T14:45:25.126132
BSD-3-Clause
false
161679fd57a59fb87ac1d6e5b50ca2b9
//\n// CustomToggle.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\n/// Custom (default) toggle style used for switches.\nstruct CustomToggleStyle: ToggleStyle {\n private let width: CGFloat = 48\n private let height: CGFloat = 30\n private let circleRadius: CGFloat = 23\n\n var disabled = false\n let accessibilityId: AccessibilityIdentifier?\n var infoButtonAction: (() -> Void)?\n\n func makeBody(configuration: Configuration) -> some View {\n HStack {\n configuration.label\n .opacity(disabled ? 0.2 : 1)\n\n if let infoButtonAction {\n Button(action: infoButtonAction) {\n Image(.iconInfo)\n }\n .adjustingTapAreaSize()\n .tint(.white)\n }\n\n Spacer()\n\n ZStack(alignment: configuration.isOn ? .trailing : .leading) {\n Capsule(style: .circular)\n .frame(width: width, height: height)\n .foregroundColor(.clear)\n .overlay(\n RoundedRectangle(cornerRadius: circleRadius)\n .stroke(\n Color(.white.withAlphaComponent(0.8)),\n lineWidth: 2\n )\n )\n .opacity(disabled ? 0.2 : 1)\n\n Circle()\n .frame(width: circleRadius, height: circleRadius)\n .padding(3)\n .foregroundColor(\n configuration.isOn\n ? Color(uiColor: UIColor.Switch.onThumbColor)\n : Color(uiColor: UIColor.Switch.offThumbColor)\n )\n .opacity(disabled ? 0.4 : 1)\n }\n .accessibilityIdentifier(accessibilityId?.asString ?? "")\n .onTapGesture {\n toggle(configuration)\n }\n .adjustingTapAreaSize()\n }\n }\n\n private func toggle(_ configuration: Configuration) {\n withAnimation(.easeInOut(duration: 0.25)) {\n configuration.isOn.toggle()\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Views\CustomToggleStyle.swift
CustomToggleStyle.swift
Swift
2,288
0.95
0.027778
0.126984
python-kit
887
2024-11-05T11:21:40.762469
Apache-2.0
false
bc50c0d188450fc3c876d03c4ea3f50c
//\n// EmptyTableViewHeaderFooterView.swift\n// MullvadVPN\n//\n// Created by pronebird on 27/05/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass EmptyTableViewHeaderFooterView: UITableViewHeaderFooterView {\n override init(reuseIdentifier: String?) {\n super.init(reuseIdentifier: reuseIdentifier)\n\n textLabel?.isHidden = true\n contentView.backgroundColor = .clear\n backgroundView?.backgroundColor = .clear\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Views\EmptyTableViewHeaderFooterView.swift
EmptyTableViewHeaderFooterView.swift
Swift
588
0.95
0.043478
0.368421
awesome-app
911
2024-01-02T18:48:24.322472
Apache-2.0
false
99e7d31b1272be76fa68df98f79d6177
//\n// InAppPurchaseButton.swift\n// MullvadVPN\n//\n// Created by pronebird on 23/03/2020.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport UIKit\n\nclass InAppPurchaseButton: AppButton {\n let activityIndicator = SpinnerActivityIndicatorView(style: .medium)\n\n var isLoading = false {\n didSet {\n if isLoading {\n activityIndicator.startAnimating()\n } else {\n activityIndicator.stopAnimating()\n }\n\n setNeedsLayout()\n }\n }\n\n init() {\n super.init(style: .success)\n\n addSubview(activityIndicator)\n\n // Make sure the buy button scales down the font size to fit the long labels.\n // Changing baseline adjustment helps to prevent the text from being misaligned after\n // being scaled down.\n titleLabel?.adjustsFontSizeToFitWidth = true\n titleLabel?.baselineAdjustment = .alignCenters\n }\n\n required init?(coder aDecoder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n override func layoutSubviews() {\n super.layoutSubviews()\n\n // Calculate the content size after insets\n let contentSize = frame\n let contentEdgeInsets = configuration?.contentInsets ?? .zero\n let finalWidth = contentSize.width - (contentEdgeInsets.leading + contentEdgeInsets.trailing)\n let finalHeight = contentSize.height - (contentEdgeInsets.top + contentEdgeInsets.bottom)\n let contentRect = CGRect(\n origin: frame.origin,\n size: CGSize(width: finalWidth, height: finalHeight)\n )\n self.titleLabel?.frame = getTitleRect(forContentRect: contentRect)\n self.activityIndicator.frame = activityIndicatorRect(forContentRect: contentRect)\n }\n\n private func getTitleRect(forContentRect contentRect: CGRect) -> CGRect {\n var titleRect = titleLabel?.frame ?? .zero\n let activityIndicatorRect = activityIndicatorRect(forContentRect: contentRect)\n\n // Adjust the title frame in case if it overlaps the activity indicator\n let intersection = titleRect.intersection(activityIndicatorRect)\n if !intersection.isNull {\n if case .leftToRight = effectiveUserInterfaceLayoutDirection {\n titleRect.origin.x = max(contentRect.minX, titleRect.minX - intersection.width)\n titleRect.size.width = intersection.minX - titleRect.minX\n } else {\n titleRect.origin.x = titleRect.minX + intersection.width\n titleRect.size.width = min(contentRect.maxX, titleRect.maxX) - intersection.maxX\n }\n }\n\n return titleRect\n }\n\n private func activityIndicatorRect(forContentRect contentRect: CGRect) -> CGRect {\n var frame = activityIndicator.frame\n\n if case .leftToRight = effectiveUserInterfaceLayoutDirection {\n frame.origin.x = contentRect.maxX - frame.width\n } else {\n frame.origin.x = contentRect.minX\n }\n\n frame.origin.y = contentRect.midY\n return frame\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Views\InAppPurchaseButton.swift
InAppPurchaseButton.swift
Swift
3,123
0.95
0.066667
0.162162
node-utils
732
2025-06-02T22:57:53.053007
MIT
false
cfcd868d0010bb1ae0be6b44215d6ea1
//\n// IncreasedHitButton.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2023-05-16.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport SwiftUI\nimport UIKit\n\nfinal class IncreasedHitButton: UIButton {\n private let defaultSize = UIMetrics.Button.minimumTappableAreaSize.width\n\n override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {\n let width = bounds.width\n let height = bounds.height\n let dx = (max(defaultSize, width) - width) * 0.5\n let dy = (max(defaultSize, height) - height) * 0.5\n return bounds.insetBy(dx: -dx, dy: -dy).contains(point)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Views\IncreasedHitButton.swift
IncreasedHitButton.swift
Swift
635
0.95
0.045455
0.368421
awesome-app
886
2024-07-16T00:41:14.754151
Apache-2.0
false
e625ba717c69b414c3272647fcdd1457
//\n// InfoHeaderView.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-10-01.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\nimport UIKit\n\n/// Header view pinned at the top of a ``ViewController``.\nclass InfoHeaderView: UIView, UITextViewDelegate {\n /// Event handler invoked when user taps on the link.\n var onAbout: (() -> Void)?\n\n private let infoLabel = UILabel()\n private let config: InfoHeaderConfig\n\n init(config: InfoHeaderConfig) {\n self.config = config\n\n super.init(frame: .zero)\n\n infoLabel.backgroundColor = .clear\n infoLabel.attributedText = makeAttributedString()\n infoLabel.numberOfLines = 0\n infoLabel.accessibilityTraits = .link\n\n directionalLayoutMargins = .zero\n\n addSubviews()\n addTapGestureRecognizer()\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n private let defaultTextAttributes: [NSAttributedString.Key: Any] = [\n .font: UIFont.systemFont(ofSize: 13),\n .foregroundColor: UIColor.ContentHeading.textColor,\n ]\n\n private let defaultLinkAttributes: [NSAttributedString.Key: Any] = [\n .font: UIFont.boldSystemFont(ofSize: 13),\n .foregroundColor: UIColor.ContentHeading.linkColor,\n .attachment: "#",\n ]\n\n private func makeAttributedString() -> NSAttributedString {\n let paragraphStyle = NSMutableParagraphStyle()\n paragraphStyle.lineBreakMode = .byWordWrapping\n\n let attributedString = NSMutableAttributedString()\n attributedString.append(NSAttributedString(string: config.body, attributes: defaultTextAttributes))\n attributedString.append(NSAttributedString(string: " ", attributes: defaultTextAttributes))\n attributedString.append(NSAttributedString(string: config.link, attributes: defaultLinkAttributes))\n attributedString.addAttribute(\n .paragraphStyle,\n value: paragraphStyle,\n range: NSRange(location: 0, length: attributedString.length)\n )\n return attributedString\n }\n\n private func addSubviews() {\n addConstrainedSubviews([infoLabel]) {\n infoLabel.pinEdgesToSuperviewMargins()\n }\n }\n\n private func addTapGestureRecognizer() {\n let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTextViewTap))\n addGestureRecognizer(tapGesture)\n }\n\n @objc\n private func handleTextViewTap() {\n onAbout?()\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Views\InfoHeaderView.swift
InfoHeaderView.swift
Swift
2,557
0.95
0.012195
0.136364
react-lib
771
2025-01-20T02:55:37.384103
Apache-2.0
false
710047d97a5cac793caea99c9fa200c4
//\n// LinkButton.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-12-20.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\n/// A subclass that implements the button that visually look like URL links on the web\nclass LinkButton: CustomButton {\n override init(frame: CGRect) {\n super.init(frame: frame)\n commonInit()\n }\n\n required init?(coder: NSCoder) {\n super.init(coder: coder)\n commonInit()\n }\n\n var titleString: String? {\n didSet {\n updateAttributedTitle(string: titleString)\n }\n }\n\n private func commonInit() {\n imageAlignment = .trailing\n contentHorizontalAlignment = .leading\n configuration?.contentInsets = .zero\n accessibilityTraits.insert(.link)\n }\n\n private func updateAttributedTitle(string: String?) {\n let states: [UIControl.State] = [.normal, .highlighted, .disabled]\n states.forEach { state in\n let attributedTitle = string.flatMap { makeAttributedTitle($0, for: state) }\n self.setAttributedTitle(attributedTitle, for: state)\n }\n }\n\n private func makeAttributedTitle(\n _ title: String,\n for state: UIControl.State\n ) -> NSAttributedString {\n var attributes: [NSAttributedString.Key: Any] = [\n .underlineStyle: NSUnderlineStyle.single.rawValue,\n ]\n\n if let titleColor = state.customButtonTitleColor {\n attributes[.foregroundColor] = titleColor\n }\n\n return NSAttributedString(string: title, attributes: attributes)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Views\LinkButton.swift
LinkButton.swift
Swift
1,607
0.95
0.086207
0.163265
awesome-app
986
2024-05-21T08:41:14.292808
Apache-2.0
false
5faea231603c8f6d2a2f95bdd55b32ee
//\n// MainButton.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-12-04.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport SwiftUI\nenum MainButtonImagePosition {\n case leading\n case trailing\n}\n\nstruct MainButton: View {\n var text: LocalizedStringKey\n var style: MainButtonStyle.Style\n\n var image: Image?\n var imagePosition: MainButtonImagePosition = .leading\n var action: () -> Void\n\n @State private var imageHeight: CGFloat = 24.0\n\n var body: some View {\n Button(action: action, label: {\n ZStack {\n // Centered Text\n Text(text)\n .lineLimit(nil)\n .multilineTextAlignment(.center)\n .if(image != nil) { view in\n // Reserve space for image if present\n view.padding(.horizontal, imageHeight)\n }\n\n // Image on Leading or Trailing\n HStack {\n if imagePosition == .leading, let image = image {\n image\n .resizable()\n .scaledToFit()\n .frame(height: imageHeight)\n .padding(.leading, 8.0)\n Spacer()\n }\n Spacer()\n if imagePosition == .trailing, let image = image {\n Spacer() // Push the text to center\n image\n .resizable()\n .scaledToFit()\n .frame(height: imageHeight)\n .padding(.trailing, 8.0)\n }\n }\n }\n })\n .sizeOfView { size in\n let actualHeight = size.height - 16.0\n let baseHeight = max(actualHeight, 24.0)\n imageHeight = baseHeight * 0.8\n }\n .buttonStyle(MainButtonStyle(style))\n .cornerRadius(UIMetrics.MainButton.cornerRadius)\n }\n}\n\n#Preview {\n MainButton(text: "Connect", style: .success) {\n print("Tapped")\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Views\MainButton.swift
MainButton.swift
Swift
2,181
0.95
0.068493
0.166667
python-kit
872
2023-08-11T11:54:20.938494
Apache-2.0
false
6ce4d97a21c5c05bb5ebd4ef73594c8c
//\n// MainButtonStyle.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-12-05.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport SwiftUI\n\nstruct MainButtonStyle: ButtonStyle {\n var style: Style\n @Environment(\.isEnabled) private var isEnabled: Bool\n\n init(_ style: Style) {\n self.style = style\n }\n\n func makeBody(configuration: Configuration) -> some View {\n return configuration.label\n .frame(minHeight: 44)\n .foregroundColor(\n isEnabled\n ? UIColor.primaryTextColor.color\n : UIColor.primaryTextColor.withAlphaComponent(0.2).color\n )\n .background(\n isEnabled\n ? configuration.isPressed\n ? style.pressedColor\n : style.color\n : style.disabledColor\n )\n .font(.body.weight(.semibold))\n }\n}\n\nextension MainButtonStyle {\n enum Style {\n case `default`\n case danger\n case success\n\n var color: Color {\n switch self {\n case .default:\n UIColor.primaryColor.color\n case .danger:\n UIColor.dangerColor.color\n case .success:\n UIColor.successColor.color\n }\n }\n\n var pressedColor: Color {\n color.darkened(by: 0.4)!\n }\n\n var disabledColor: Color {\n color.darkened(by: 0.6)!\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Views\MainButtonStyle.swift
MainButtonStyle.swift
Swift
1,537
0.95
0.015873
0.127273
vue-tools
715
2024-04-21T06:24:49.886728
GPL-3.0
false
f86c4f5af447a9c03515fd1428c88642
//\n// Separator.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-11-20.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport SwiftUI\n\nstruct RowSeparator: View {\n var color = Color(.secondaryColor)\n\n var body: some View {\n color\n .frame(height: UIMetrics.TableView.separatorHeight)\n .padding(.leading, 16)\n }\n}\n\n#Preview {\n RowSeparator(color: Color(.primaryColor))\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Views\RowSeparator.swift
RowSeparator.swift
Swift
439
0.95
0
0.421053
awesome-app
171
2023-10-04T18:47:16.093285
BSD-3-Clause
false
10d9039e9724154d3bc052b141ac1a56
//\n// SpinnerActivityIndicatorView.swift\n// MullvadVPN\n//\n// Created by pronebird on 15/05/2019.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\n@MainActor\nclass SpinnerActivityIndicatorView: UIView {\n private static let rotationAnimationKey = "rotation"\n private static let animationDuration = 0.6\n\n @MainActor\n enum Style: Sendable {\n case small, medium, large, custom\n\n var intrinsicSize: CGSize {\n switch self {\n case .small:\n return CGSize(width: 16, height: 16)\n case .medium:\n return CGSize(width: 20, height: 20)\n case .large:\n return CGSize(width: 60, height: 60)\n case .custom:\n return CGSize(width: UIView.noIntrinsicMetric, height: UIView.noIntrinsicMetric)\n }\n }\n }\n\n private let imageView = UIImageView(image: .spinner)\n\n private(set) var isAnimating = false\n private(set) var style = Style.large\n\n private var sceneActivationObserver: Any?\n\n override var intrinsicContentSize: CGSize {\n style.intrinsicSize\n }\n\n init(style: Style) {\n self.style = style\n\n let size = style == .custom ? .zero : style.intrinsicSize\n\n super.init(frame: CGRect(origin: .zero, size: size))\n\n addSubview(imageView)\n isHidden = true\n backgroundColor = UIColor.clear\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n deinit {\n MainActor.assumeIsolated {\n unregisterSceneActivationObserver()\n }\n }\n\n override func didMoveToWindow() {\n super.didMoveToWindow()\n\n if window == nil {\n unregisterSceneActivationObserver()\n } else {\n registerSceneActivationObserver()\n restartAnimationIfNeeded()\n }\n }\n\n override func layoutSubviews() {\n super.layoutSubviews()\n\n let size = style == .custom ? frame.size : style.intrinsicSize\n\n imageView.frame = CGRect(origin: .zero, size: size)\n }\n\n func startAnimating() {\n guard !isAnimating else { return }\n isAnimating = true\n\n isHidden = false\n addAnimation()\n }\n\n func stopAnimating() {\n guard isAnimating else { return }\n isAnimating = false\n\n isHidden = true\n removeAnimation()\n }\n\n private func addAnimation() {\n layer.add(createAnimation(), forKey: Self.rotationAnimationKey)\n }\n\n private func removeAnimation() {\n layer.removeAnimation(forKey: Self.rotationAnimationKey)\n }\n\n private func registerSceneActivationObserver() {\n unregisterSceneActivationObserver()\n\n sceneActivationObserver = NotificationCenter.default.addObserver(\n forName: UIScene.willEnterForegroundNotification,\n object: window?.windowScene,\n queue: .main, using: { [weak self] _ in\n MainActor.assumeIsolated {\n self?.restartAnimationIfNeeded()\n }\n }\n )\n }\n\n private func unregisterSceneActivationObserver() {\n if let sceneActivationObserver {\n NotificationCenter.default.removeObserver(sceneActivationObserver)\n self.sceneActivationObserver = nil\n }\n }\n\n private func restartAnimationIfNeeded() {\n let animation = layer.animation(forKey: Self.rotationAnimationKey)\n\n if isAnimating, animation == nil {\n removeAnimation()\n addAnimation()\n }\n }\n\n private func createAnimation() -> CABasicAnimation {\n let animation = CABasicAnimation(keyPath: "transform.rotation")\n animation.toValue = NSNumber(value: Double.pi * 2)\n animation.duration = Self.animationDuration\n animation.repeatCount = Float.infinity\n animation.timingFunction = CAMediaTimingFunction(name: .linear)\n animation.timeOffset = layer.convertTime(CACurrentMediaTime(), from: nil)\n\n return animation\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Views\SpinnerActivityIndicatorView.swift
SpinnerActivityIndicatorView.swift
Swift
4,074
0.95
0.033333
0.059322
python-kit
29
2025-06-19T15:35:32.611503
GPL-3.0
false
4a4f605affa3a0c844376f79dc802fee
//\n// SplitMainButton.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-12-05.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport SwiftUI\n\nstruct SplitMainButton: View {\n var text: LocalizedStringKey\n var image: ImageResource\n var style: MainButtonStyle.Style\n var accessibilityId: AccessibilityIdentifier?\n\n @State private var secondaryButtonWidth: CGFloat = 0\n\n var primaryAction: () -> Void\n var secondaryAction: () -> Void\n\n var body: some View {\n HStack(spacing: 1) {\n Button(action: primaryAction, label: {\n HStack {\n Spacer()\n Text(text)\n Spacer()\n }\n .padding(.trailing, -secondaryButtonWidth)\n })\n .ifLet(accessibilityId) { view, value in\n view.accessibilityIdentifier(value.asString)\n }\n\n Button(action: secondaryAction, label: {\n Image(image)\n .resizable()\n .scaledToFit()\n .frame(width: 24, height: 24)\n .padding(10)\n })\n .aspectRatio(1, contentMode: .fit)\n .sizeOfView { secondaryButtonWidth = $0.width }\n }\n .buttonStyle(MainButtonStyle(style))\n .cornerRadius(UIMetrics.MainButton.cornerRadius)\n }\n}\n\n#Preview {\n SplitMainButton(\n text: "Select location",\n image: .iconReload,\n style: .default,\n primaryAction: {\n print("Tapped primary")\n },\n secondaryAction: {\n print("Tapped secondary")\n }\n )\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Views\SplitMainButton.swift
SplitMainButton.swift
Swift
1,670
0.95
0
0.142857
node-utils
489
2024-10-02T17:10:44.745493
MIT
false
d53d6554fbbd4e52f3e7acf10f14e46c
//\n// StatusActivityView.swift\n// MullvadVPN\n//\n// Created by Andreas Lif on 2022-08-15.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport UIKit\n\nclass StatusActivityView: UIView {\n enum State {\n case hidden, activity, success, failure\n }\n\n var state: State = .hidden {\n didSet {\n updateView()\n }\n }\n\n private let statusImageView: StatusImageView = {\n let imageView = StatusImageView(style: .failure)\n imageView.translatesAutoresizingMaskIntoConstraints = false\n imageView.contentMode = .scaleAspectFit\n return imageView\n }()\n\n private let activityIndicator: SpinnerActivityIndicatorView = {\n let view = SpinnerActivityIndicatorView(style: .large)\n view.tintColor = .white\n view.translatesAutoresizingMaskIntoConstraints = false\n return view\n }()\n\n init(state: State) {\n super.init(frame: .zero)\n\n self.state = state\n addSubview(statusImageView)\n addSubview(activityIndicator)\n\n NSLayoutConstraint.activate([\n activityIndicator.widthAnchor.constraint(equalTo: statusImageView.widthAnchor),\n activityIndicator.heightAnchor.constraint(equalTo: statusImageView.heightAnchor),\n statusImageView.topAnchor.constraint(equalTo: topAnchor),\n statusImageView.bottomAnchor.constraint(equalTo: bottomAnchor),\n\n statusImageView.centerXAnchor.constraint(equalTo: centerXAnchor),\n statusImageView.centerYAnchor.constraint(equalTo: centerYAnchor),\n activityIndicator.centerXAnchor.constraint(equalTo: centerXAnchor),\n activityIndicator.centerYAnchor.constraint(equalTo: centerYAnchor),\n ])\n\n updateView()\n }\n\n required init?(coder: NSCoder) {\n super.init(coder: coder)\n }\n\n private func updateView() {\n switch state {\n case .hidden:\n statusImageView.alpha = 0\n activityIndicator.stopAnimating()\n case .activity:\n statusImageView.alpha = 0\n activityIndicator.startAnimating()\n case .success:\n statusImageView.alpha = 1\n statusImageView.style = .success\n activityIndicator.stopAnimating()\n case .failure:\n statusImageView.alpha = 1\n statusImageView.style = .failure\n activityIndicator.stopAnimating()\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Views\StatusActivityView.swift
StatusActivityView.swift
Swift
2,458
0.95
0.024691
0.101449
react-lib
26
2024-10-06T16:29:54.914717
GPL-3.0
false
cb5ec5821cbba8d12de3b1ca2fdedb93
//\n// StatusImageView.swift\n// MullvadVPN\n//\n// Created by pronebird on 12/02/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass StatusImageView: UIImageView {\n enum Style: Int {\n case success\n case failure\n\n fileprivate var image: UIImage? {\n switch self {\n case .success:\n return UIImage.Status.success\n case .failure:\n return UIImage.Status.failure\n }\n }\n }\n\n var style: Style = .success {\n didSet {\n self.image = style.image\n }\n }\n\n override var accessibilityValue: String? {\n get {\n switch style {\n case .success:\n return "success"\n case .failure:\n return "fail"\n }\n }\n\n // swiftlint:disable:next unused_setter_value\n set {\n fatalError("This accessibilityValue property is get only")\n }\n }\n\n override var intrinsicContentSize: CGSize {\n CGSize(width: 60, height: 60)\n }\n\n override init(frame: CGRect) {\n super.init(frame: frame)\n image = style.image\n }\n\n init(style: Style) {\n self.style = style\n super.init(image: style.image)\n image = style.image\n setAccessibilityIdentifier(.statusImageView)\n }\n\n required init?(coder: NSCoder) {\n super.init(coder: coder)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Views\StatusImageView.swift
StatusImageView.swift
Swift
1,455
0.95
0.044776
0.140351
node-utils
172
2023-12-13T21:05:13.891835
Apache-2.0
false
45a8bd84877a39a99a8f72720b07ad78
//\n// VisualEffectView.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-12-04.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport SwiftUI\n\nstruct VisualEffectView: UIViewRepresentable {\n var effect: UIVisualEffect?\n\n func makeUIView(context: UIViewRepresentableContext<Self>) -> UIVisualEffectView {\n let view = UIVisualEffectView(effect: effect)\n view.translatesAutoresizingMaskIntoConstraints = false\n return view\n }\n\n func updateUIView(_ uiView: UIVisualEffectView, context: UIViewRepresentableContext<Self>) {\n uiView.effect = effect\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Views\VisualEffectView.swift
VisualEffectView.swift
Swift
618
0.95
0
0.368421
node-utils
815
2023-11-23T15:29:00.301663
BSD-3-Clause
false
058b9326b4ae8f653bc093bfa3f13207
//\n// MockCustomListsRepository.swift\n// MullvadVPNTests\n//\n// Created by Jon Petersson on 2024-02-29.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport MullvadSettings\nimport MullvadTypes\n\nstruct CustomListsRepositoryStub: CustomListRepositoryProtocol {\n let customLists: [CustomList]\n\n func save(list: CustomList) throws {}\n\n func delete(id: UUID) {}\n\n func fetch(by id: UUID) -> CustomList? {\n nil\n }\n\n func fetchAll() -> [CustomList] {\n customLists\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNTests\MullvadSettings\CustomListsRepositoryStub.swift
CustomListsRepositoryStub.swift
Swift
531
0.95
0
0.333333
vue-tools
46
2024-06-02T09:07:28.395413
BSD-3-Clause
true
ed2a9a44747951bc5cd9b2566e0219d9
//\n// InMemorySettingsStore.swift\n// MullvadVPNTests\n//\n// Created by Marco Nikic on 2023-10-17.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadSettings\n\nprotocol Instantiable {\n init()\n}\n\nclass InMemorySettingsStore<ThrownError: Error>: SettingsStore, @unchecked Sendable where ThrownError: Instantiable {\n private var settings = [SettingsKey: Data]()\n\n func read(key: SettingsKey) throws -> Data {\n guard settings.keys.contains(key), let value = settings[key] else { throw ThrownError() }\n return value\n }\n\n func write(_ data: Data, for key: SettingsKey) throws {\n settings[key] = data\n }\n\n func delete(key: SettingsKey) throws {\n settings.removeValue(forKey: key)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNTests\MullvadSettings\InMemorySettingsStore.swift
InMemorySettingsStore.swift
Swift
775
0.95
0.064516
0.28
node-utils
969
2024-09-17T01:02:42.708811
Apache-2.0
true
dabe45afbb240459aec2e5a95510ccfe
//\n// IPOverrideRepositoryStub.swift\n// MullvadVPNTests\n//\n// Created by Jon Petersson on 2024-01-31.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport MullvadSettings\n\nstruct IPOverrideRepositoryStub: IPOverrideRepositoryProtocol {\n let passthroughSubject: CurrentValueSubject<[IPOverride], Never> = CurrentValueSubject([])\n var overridesPublisher: AnyPublisher<[IPOverride], Never> {\n passthroughSubject.eraseToAnyPublisher()\n }\n\n let overrides: [IPOverride]\n\n init(overrides: [IPOverride] = []) {\n self.overrides = overrides\n }\n\n func add(_ overrides: [IPOverride]) {}\n\n func fetchAll() -> [IPOverride] {\n overrides\n }\n\n func fetchByHostname(_ hostname: String) -> IPOverride? {\n nil\n }\n\n func deleteAll() {}\n\n func parse(data: Data) throws -> [IPOverride] {\n overrides\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNTests\MullvadSettings\IPOverrideRepositoryStub.swift
IPOverrideRepositoryStub.swift
Swift
893
0.95
0
0.233333
python-kit
855
2024-02-04T16:49:18.313404
MIT
true
890f92fb243759ea1fa7736aab953817
//\n// MockFileCache.swift\n// MullvadVPNTests\n//\n// Created by pronebird on 13/06/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\n\n/// File cache implementation that simulates file state and uses internal lock to synchronize access to it.\nfinal class MockFileCache<Content: Codable & Equatable>: FileCacheProtocol {\n private var state: State\n private let stateLock = NSLock()\n\n init(initialState: State = .fileNotFound) {\n state = initialState\n }\n\n /// Returns internal state.\n func getState() -> State {\n stateLock.lock()\n defer { stateLock.unlock() }\n\n return state\n }\n\n func read() throws -> Content {\n stateLock.lock()\n defer { stateLock.unlock() }\n\n switch state {\n case .fileNotFound:\n throw CocoaError(.fileReadNoSuchFile)\n case let .exists(content):\n return content\n }\n }\n\n func write(_ content: Content) throws {\n stateLock.lock()\n defer { stateLock.unlock() }\n\n state = .exists(content)\n }\n\n func clear() throws {\n stateLock.lock()\n defer { stateLock.unlock() }\n\n state = .fileNotFound\n }\n\n enum State: Equatable {\n /// File does not exist yet.\n case fileNotFound\n\n /// File exists with the given contents.\n case exists(Content)\n\n var isExists: Bool {\n if case .exists = self {\n return true\n } else {\n return false\n }\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNTests\MullvadTypes\MockFileCache.swift
MockFileCache.swift
Swift
1,581
0.95
0.042857
0.196429
vue-tools
352
2023-12-11T08:19:49.522325
Apache-2.0
true
6deb9f6b50f07b4e86ac9ed319f14976
//\n// File.swift\n// MullvadVPNTests\n//\n// Created by Mojgan on 2023-10-25.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadREST\n\nstruct OutgoingConnectionProxyStub: OutgoingConnectionHandling {\n var ipV4: IPV4ConnectionData\n var ipV6: IPV6ConnectionData\n var error: Error?\n\n func getIPV6(retryStrategy: MullvadREST.REST.RetryStrategy) async throws -> IPV6ConnectionData {\n if let error {\n throw error\n } else {\n return ipV6\n }\n }\n\n func getIPV4(retryStrategy: MullvadREST.REST.RetryStrategy) async throws -> IPV4ConnectionData {\n if let error {\n throw error\n } else {\n return ipV4\n }\n }\n}\n\nextension IPV4ConnectionData {\n static let mock = IPV4ConnectionData(ip: .loopback, exitIP: true)\n}\n\nextension IPV6ConnectionData {\n static let mock = IPV6ConnectionData(ip: .loopback, exitIP: true)\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNTests\MullvadVPN\GeneralAPIs\OutgoingConnectionProxy+Stub.swift
OutgoingConnectionProxy+Stub.swift
Swift
936
0.95
0.051282
0.212121
node-utils
148
2024-08-14T00:47:27.547581
Apache-2.0
true
74c15653d0e7c83853f745f57bec335d
//\n// URLSessionStub.swift\n// MullvadVPNTests\n//\n// Created by Mojgan on 2023-10-25.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nclass URLSessionStub: URLSessionProtocol {\n var response: (Data, URLResponse)\n\n init(response: (Data, URLResponse)) {\n self.response = response\n }\n\n func data(for request: URLRequest) async throws -> (Data, URLResponse) {\n return response\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNTests\MullvadVPN\Protocols\URLSessionStub.swift
URLSessionStub.swift
Swift
443
0.95
0.095238
0.411765
node-utils
577
2024-05-29T23:35:02.767148
BSD-3-Clause
true
2511c02f11ffc5f7b2e7eb8914774447
//\n// RelayCacheTracker+Stubs.swift\n// MullvadVPNTests\n//\n// Created by Marco Nikic on 2023-10-03.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadMockData\n@testable import MullvadREST\n@testable import MullvadTypes\n\nstruct RelayCacheTrackerStub: RelayCacheTrackerProtocol {\n func startPeriodicUpdates() {}\n\n func stopPeriodicUpdates() {}\n\n func updateRelays(completionHandler: ((sending Result<RelaysFetchResult, Error>) -> Void)?) -> Cancellable {\n AnyCancellable()\n }\n\n func getCachedRelays() throws -> CachedRelays {\n CachedRelays(relays: ServerRelaysResponseStubs.sampleRelays, updatedAt: Date())\n }\n\n func getNextUpdateDate() -> Date {\n Date()\n }\n\n func addObserver(_ observer: RelayCacheTrackerObserver) {}\n\n func removeObserver(_ observer: RelayCacheTrackerObserver) {}\n\n func refreshCachedRelays() throws {}\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNTests\MullvadVPN\RelayCacheTracker\RelayCacheTracker+Stubs.swift
RelayCacheTracker+Stubs.swift
Swift
922
0.95
0
0.259259
node-utils
700
2025-01-12T07:11:04.285331
GPL-3.0
true
3ce465c5a4c9863edd1d67ba89ceb62b
//\n// MockTunnel.swift\n// MullvadVPNTests\n//\n// Created by Andrew Bulhak on 2024-02-05.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\nimport NetworkExtension\n\nclass MockTunnel: TunnelProtocol, @unchecked Sendable {\n typealias TunnelManagerProtocol = SimulatorTunnelProviderManager\n\n var status: NEVPNStatus\n\n var isOnDemandEnabled: Bool\n\n var startDate: Date?\n\n var backgroundTaskProvider: BackgroundTaskProviding\n\n required init(tunnelProvider: TunnelManagerProtocol, backgroundTaskProvider: BackgroundTaskProviding) {\n status = .disconnected\n isOnDemandEnabled = false\n startDate = nil\n self.backgroundTaskProvider = backgroundTaskProvider\n }\n\n // Observers are currently unimplemented\n func addObserver(_ observer: TunnelStatusObserver) {}\n\n func removeObserver(_ observer: TunnelStatusObserver) {}\n\n func addBlockObserver(\n queue: DispatchQueue?,\n handler: @escaping (any TunnelProtocol, NEVPNStatus) -> Void\n ) -> TunnelStatusBlockObserver {\n fatalError("MockTunnel.addBlockObserver Not implemented")\n }\n\n func logFormat() -> String {\n ""\n }\n\n func saveToPreferences(_ completion: @escaping (Error?) -> Void) {\n completion(nil)\n }\n\n func removeFromPreferences(completion: @escaping (Error?) -> Void) {\n completion(nil)\n }\n\n func setConfiguration(_ configuration: TunnelConfiguration) {}\n\n func start(options: [String: NSObject]?) throws {\n startDate = Date()\n }\n\n func stop() {}\n\n func sendProviderMessage(_ messageData: Data, responseHandler: ((Data?) -> Void)?) throws {}\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNTests\MullvadVPN\TunnelManager\MockTunnel.swift
MockTunnel.swift
Swift
1,688
0.95
0.015625
0.170213
node-utils
475
2023-11-24T18:52:51.491147
BSD-3-Clause
true
3d11acb5d692758ce2524d129dda9d22
//\n// MockTunnelInteractor.swift\n// MullvadVPNTests\n//\n// Created by Andrew Bulhak on 2024-02-02.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\nimport MullvadSettings\nimport MullvadTypes\n\n// this is still very minimal, and will be fleshed out as needed.\nfinal class MockTunnelInteractor: TunnelInteractor, @unchecked Sendable {\n var isConfigurationLoaded: Bool\n\n var settings: LatestTunnelSettings\n\n var deviceState: DeviceState\n\n var onUpdateTunnelStatus: ((TunnelStatus) -> Void)?\n\n var tunnel: (any TunnelProtocol)?\n\n var backgroundTaskProvider: BackgroundTaskProviding {\n UIApplicationStub()\n }\n\n init(\n isConfigurationLoaded: Bool,\n settings: LatestTunnelSettings,\n deviceState: DeviceState,\n onUpdateTunnelStatus: ((TunnelStatus) -> Void)? = nil\n ) {\n self.isConfigurationLoaded = isConfigurationLoaded\n self.settings = settings\n self.deviceState = deviceState\n self.onUpdateTunnelStatus = onUpdateTunnelStatus\n self.tunnel = nil\n self.tunnelStatus = TunnelStatus()\n }\n\n func getPersistentTunnels() -> [any TunnelProtocol] {\n return []\n }\n\n func createNewTunnel() -> any TunnelProtocol {\n return MockTunnel(\n tunnelProvider: SimulatorTunnelProviderManager(),\n backgroundTaskProvider: backgroundTaskProvider\n )\n }\n\n func setTunnel(_ tunnel: (any TunnelProtocol)?, shouldRefreshTunnelState: Bool) {\n self.tunnel = tunnel\n }\n\n var tunnelStatus: TunnelStatus\n\n func updateTunnelStatus(_ block: (inout TunnelStatus) -> Void) -> TunnelStatus {\n var tunnelStatus = self.tunnelStatus\n block(&tunnelStatus)\n onUpdateTunnelStatus?(tunnelStatus)\n return tunnelStatus\n }\n\n func setConfigurationLoaded() {}\n\n func setSettings(_ settings: LatestTunnelSettings, persist: Bool) {}\n\n func setDeviceState(_ deviceState: DeviceState, persist: Bool) {}\n\n func removeLastUsedAccount() {}\n\n func handleRestError(_ error: Error) {}\n\n func startTunnel() {}\n\n func prepareForVPNConfigurationDeletion() {}\n\n struct NotImplementedError: Error {}\n\n func selectRelays() throws -> SelectedRelays {\n throw NotImplementedError()\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNTests\MullvadVPN\TunnelManager\MockTunnelInteractor.swift
MockTunnelInteractor.swift
Swift
2,314
0.95
0.011494
0.123077
vue-tools
934
2025-05-29T20:00:43.192934
Apache-2.0
true
41c3743c53a1b4bfbfbb1d2c320a0d1b
//\n// TunnelStore+Stubs.swift\n// MullvadVPNTests\n//\n// Created by Marco Nikic on 2023-10-03.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\nimport NetworkExtension\n\nstruct TunnelStoreStub: TunnelStoreProtocol, Sendable {\n typealias TunnelType = TunnelStub\n let backgroundTaskProvider: any BackgroundTaskProviding\n func getPersistentTunnels() -> [TunnelType] {\n []\n }\n\n func createNewTunnel() -> TunnelType {\n TunnelStub(backgroundTaskProvider: backgroundTaskProvider, status: .invalid, isOnDemandEnabled: false)\n }\n}\n\nclass DummyTunnelStatusObserver: TunnelStatusObserver {\n func tunnel(_ tunnel: any TunnelProtocol, didReceiveStatus status: NEVPNStatus) {}\n}\n\nfinal class TunnelStub: TunnelProtocol, Equatable, @unchecked Sendable {\n typealias TunnelManagerProtocol = SimulatorTunnelProviderManager\n\n static func == (lhs: TunnelStub, rhs: TunnelStub) -> Bool {\n ObjectIdentifier(lhs) == ObjectIdentifier(rhs)\n }\n\n convenience init(\n tunnelProvider: SimulatorTunnelProviderManager,\n backgroundTaskProvider: any BackgroundTaskProviding\n ) {\n self.init(backgroundTaskProvider: backgroundTaskProvider, status: .invalid, isOnDemandEnabled: false)\n }\n\n init(\n backgroundTaskProvider: any BackgroundTaskProviding,\n status: NEVPNStatus,\n isOnDemandEnabled: Bool,\n startDate: Date? = nil\n ) {\n self.status = status\n self.isOnDemandEnabled = isOnDemandEnabled\n self.startDate = startDate\n self.backgroundTaskProvider = backgroundTaskProvider\n }\n\n func addObserver(_ observer: TunnelStatusObserver) {}\n\n func removeObserver(_ observer: TunnelStatusObserver) {}\n\n var backgroundTaskProvider: any BackgroundTaskProviding\n\n var status: NEVPNStatus\n\n var isOnDemandEnabled: Bool\n\n var startDate: Date?\n\n func addBlockObserver(\n queue: DispatchQueue?,\n handler: @escaping (any TunnelProtocol, NEVPNStatus) -> Void\n ) -> TunnelStatusBlockObserver {\n TunnelStatusBlockObserver(tunnel: self, queue: queue, handler: handler)\n }\n\n func logFormat() -> String {\n ""\n }\n\n func saveToPreferences(_ completion: @escaping (Error?) -> Void) {}\n\n func removeFromPreferences(completion: @escaping (Error?) -> Void) {}\n\n func setConfiguration(_ configuration: TunnelConfiguration) {}\n\n func start(options: [String: NSObject]?) throws {}\n\n func stop() {}\n\n func sendProviderMessage(_ messageData: Data, responseHandler: ((Data?) -> Void)?) throws {}\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNTests\MullvadVPN\TunnelManager\TunnelStore+Stubs.swift
TunnelStore+Stubs.swift
Swift
2,603
0.95
0.022472
0.104478
python-kit
910
2024-06-14T12:40:07.025261
GPL-3.0
true
399ec47516de8100c8122476667d27f9
//\n// UIApplication+Stubs.swift\n// MullvadVPNTests\n//\n// Created by Marco Nikic on 2023-10-02.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport UIKit\n\n@testable import MullvadTypes\n\nstruct UIApplicationStub: BackgroundTaskProviding {\n var backgroundTimeRemaining: TimeInterval { .infinity }\n\n func endBackgroundTask(_ identifier: UIBackgroundTaskIdentifier) {}\n\n #if compiler(>=6)\n func beginBackgroundTask(\n withName taskName: String?,\n expirationHandler handler: (@MainActor @Sendable () -> Void)?\n )\n -> UIBackgroundTaskIdentifier {\n .invalid\n }\n #else\n func beginBackgroundTask(\n withName taskName: String?,\n expirationHandler handler: (() -> Void)?\n ) -> UIBackgroundTaskIdentifier {\n .invalid\n }\n #endif\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNTests\MullvadVPN\TunnelManager\UIApplication+Stubs.swift
UIApplication+Stubs.swift
Swift
836
0.95
0.028571
0.333333
react-lib
71
2024-11-30T03:29:20.136414
BSD-3-Clause
true
80ce5cdd865d0c96ecccbad9e2a39450
//\n// MullvadApi.swift\n// MullvadVPNUITests\n//\n// Created by Emils on 31/01/2024.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nstruct ApiError: Error {\n let description: String\n let kind: MullvadApiErrorKind\n init(_ result: MullvadApiError) {\n kind = result.kind\n if result.description != nil {\n description = String(cString: result.description)\n } else {\n description = "No error"\n }\n mullvad_api_error_drop(result)\n }\n\n func throwIfErr() throws {\n if self.kind.rawValue != 0 {\n throw self\n }\n }\n}\n\nstruct InitMutableBufferError: Error {\n let description = "Failed to allocate memory for mutable buffer"\n}\n\nstruct Device {\n let name: String\n let id: UUID\n\n init(device_struct: MullvadApiDevice) {\n name = String(cString: device_struct.name_ptr)\n id = UUID(uuid: device_struct.id)\n }\n}\n\n/// - Warning: Do not change the `apiAddress` or the `hostname` after the time `MullvadApi.init` has been invoked\n/// The Mullvad API crate is using a global static variable to store those. They will be initialized only once.\n///\nclass MullvadApi {\n private var clientContext = MullvadApiClient()\n\n /// Initialize the Mullvad API client\n /// - Parameters:\n /// - apiAddress: Address of the Mullvad API server in the format \<IP-address\>:\<port\>\n /// - hostname: Hostname of the Mullvad API server\n init(apiAddress: String, hostname: String) throws {\n let result = mullvad_api_client_initialize(\n &clientContext,\n apiAddress,\n hostname,\n false\n )\n try ApiError(result).throwIfErr()\n }\n\n /// Removes all devices assigned to the specified account\n func removeAllDevices(forAccount: String) throws {\n let result = mullvad_api_remove_all_devices(\n clientContext,\n forAccount\n )\n\n try ApiError(result).throwIfErr()\n }\n\n /// Public key must be at least 32 bytes long - only 32 bytes of it will be read\n func addDevice(forAccount: String, publicKey: Data) throws {\n var device = MullvadApiDevice()\n let result = mullvad_api_add_device(\n clientContext,\n forAccount,\n (publicKey as NSData).bytes,\n &device\n )\n\n try ApiError(result).throwIfErr()\n }\n\n /// Returns a unix timestamp of the expiry date for the specified account.\n func getExpiry(forAccount: String) throws -> UInt64 {\n var expiry = UInt64(0)\n let result = mullvad_api_get_expiry(clientContext, forAccount, &expiry)\n\n try ApiError(result).throwIfErr()\n\n return expiry\n }\n\n func createAccount() throws -> String {\n var newAccountPtr: UnsafePointer<CChar>?\n let result = mullvad_api_create_account(\n clientContext,\n &newAccountPtr\n )\n try ApiError(result).throwIfErr()\n\n let newAccount = String(cString: newAccountPtr!)\n return newAccount\n }\n\n func listDevices(forAccount: String) throws -> [Device] {\n var iterator = MullvadApiDeviceIterator()\n let result = mullvad_api_list_devices(clientContext, forAccount, &iterator)\n try ApiError(result).throwIfErr()\n\n return DeviceIterator(iter: iterator).collect()\n }\n\n func delete(account: String) throws {\n let result = mullvad_api_delete_account(clientContext, account)\n try ApiError(result).throwIfErr()\n }\n\n deinit {\n mullvad_api_client_drop(clientContext)\n }\n\n class DeviceIterator {\n private let backingIter: MullvadApiDeviceIterator\n\n init(iter: MullvadApiDeviceIterator) {\n backingIter = iter\n }\n\n func collect() -> [Device] {\n var nextDevice = MullvadApiDevice()\n var devices: [Device] = []\n while mullvad_api_device_iter_next(backingIter, &nextDevice) {\n devices.append(Device(device_struct: nextDevice))\n mullvad_api_device_drop(nextDevice)\n }\n return devices\n }\n\n deinit {\n mullvad_api_device_iter_drop(backingIter)\n }\n }\n}\n\nprivate extension String {\n func lengthOfBytes() -> UInt {\n return UInt(self.lengthOfBytes(using: String.Encoding.utf8))\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\MullvadApi.swift
MullvadApi.swift
Swift
4,385
0.95
0.090909
0.132813
react-lib
160
2024-10-22T16:06:48.212650
BSD-3-Clause
true
006b339c1dc508fc59bb4649d3fc4c58
//\n// XCUIElement+Extensions.swift\n// MullvadVPNUITests\n//\n// Created by Niklas Berglund on 2024-03-25.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport XCTest\n\nextension XCUIElement {\n func waitForNonExistence(timeout: TimeInterval) -> Bool {\n let predicate = NSPredicate(format: "exists == FALSE")\n let expectation = XCTNSPredicateExpectation(predicate: predicate, object: self)\n\n _ = XCTWaiter().wait(for: [expectation], timeout: timeout)\n return !exists\n }\n\n func scrollDownToElement(element: XCUIElement, maxScrolls: UInt = 5) {\n var count = 0\n while !element.isVisible && count < maxScrolls {\n swipeUp(velocity: .slow)\n count += 1\n }\n }\n\n func scrollUpToElement(element: XCUIElement, maxScrolls: UInt = 5) {\n var count = 0\n while !element.isVisible && count < maxScrolls {\n swipeDown(velocity: .slow)\n count += 1\n }\n }\n\n var isVisible: Bool {\n guard self.exists && !self.frame.isEmpty else { return false }\n return XCUIApplication().windows.element(boundBy: 0).frame.contains(self.frame)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\XCUIElement+Extensions.swift
XCUIElement+Extensions.swift
Swift
1,175
0.95
0.075
0.205882
awesome-app
737
2024-05-23T02:29:16.863541
MIT
true
3bdb743399485414f23dbe245ecd4342
//\n// XCUIElementQuery+Extensions.swift\n// MullvadVPNUITests\n//\n// Created by Niklas Berglund on 2024-01-19.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport XCTest\n\nextension XCUIElementQuery {\n subscript(key: any RawRepresentable<String>) -> XCUIElement {\n self[key.rawValue]\n }\n\n subscript(key: AccessibilityIdentifier) -> XCUIElement {\n self[key.asString]\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\XCUIElementQuery+Extensions.swift
XCUIElementQuery+Extensions.swift
Swift
433
0.95
0
0.411765
vue-tools
675
2025-03-30T01:12:47.259857
Apache-2.0
true
a2362e7c9b4284dbe61e0989db58f82c
//\n// FirewallClient.swift\n// MullvadVPNUITests\n//\n// Created by Niklas Berglund on 2024-01-18.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport SystemConfiguration\nimport UIKit\nimport XCTest\n\nclass FirewallClient: TestRouterAPIClient {\n // swiftlint:disable force_cast\n let testDeviceIdentifier = Bundle(for: FirewallClient.self).infoDictionary?["TestDeviceIdentifier"] as! String\n // swiftlint:enable force_cast\n\n lazy var sessionIdentifier = "urn:uuid:" + testDeviceIdentifier\n\n /// Create a new rule associated to the device under test\n public func createRule(_ firewallRule: FirewallRule) {\n let createRuleURL = TestRouterAPIClient.baseURL.appendingPathComponent("rule")\n\n var request = URLRequest(url: createRuleURL)\n request.httpMethod = "POST"\n request.setValue("application/json", forHTTPHeaderField: "Content-Type")\n\n let dataDictionary: [String: Any] = [\n "label": sessionIdentifier,\n "from": firewallRule.fromIPAddress, // Deprecated, replaced by "src"\n "to": firewallRule.toIPAddress, // Deprectated, replaced by "dst"\n "src": firewallRule.fromIPAddress,\n "dst": firewallRule.toIPAddress,\n "protocols": firewallRule.protocolsAsStringArray(),\n ]\n\n var requestError: Error?\n var requestResponse: URLResponse?\n let completionHandlerInvokedExpectation = XCTestExpectation(\n description: "Completion handler for the request is invoked"\n )\n\n do {\n let jsonData = try JSONSerialization.data(withJSONObject: dataDictionary)\n request.httpBody = jsonData\n\n let dataTask = URLSession.shared.dataTask(with: request) { _, response, error in\n requestError = error\n requestResponse = response\n completionHandlerInvokedExpectation.fulfill()\n }\n\n dataTask.resume()\n\n let waitResult = XCTWaiter.wait(for: [completionHandlerInvokedExpectation], timeout: 30)\n\n if waitResult != .completed {\n XCTFail("Failed to create firewall rule - timeout")\n } else {\n if let response = requestResponse as? HTTPURLResponse {\n if response.statusCode != 201 {\n XCTFail(\n "Failed to create firewall rule - unexpected response status code \(response.statusCode)"\n )\n }\n }\n\n if let error = requestError {\n XCTFail("Failed to create firewall rule - encountered error \(error.localizedDescription)")\n }\n }\n } catch {\n XCTFail("Failed to create firewall rule - couldn't serialize JSON")\n }\n }\n\n /// Remove all firewall rules associated to this device under test\n public func removeRules() {\n let removeRulesURL = TestRouterAPIClient.baseURL.appendingPathComponent("remove-rules/\(sessionIdentifier)")\n\n var request = URLRequest(url: removeRulesURL)\n request.httpMethod = "DELETE"\n\n var requestResponse: URLResponse?\n var requestError: Error?\n let completionHandlerInvokedExpectation = XCTestExpectation(\n description: "Completion handler for the request is invoked"\n )\n\n let dataTask = URLSession.shared.dataTask(with: request) { _, response, error in\n requestResponse = response\n requestError = error\n completionHandlerInvokedExpectation.fulfill()\n }\n\n dataTask.resume()\n\n let waitResult = XCTWaiter.wait(for: [completionHandlerInvokedExpectation], timeout: 30)\n\n if waitResult != .completed {\n XCTFail("Failed to remove firewall rules - timeout")\n } else {\n if let response = requestResponse as? HTTPURLResponse, response.statusCode != 200 {\n XCTFail("Failed to remove firewall rules - unexpected server response")\n }\n\n if let error = requestError {\n XCTFail("Failed to remove firewall rules - encountered error \(error.localizedDescription)")\n }\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Networking\FirewallClient.swift
FirewallClient.swift
Swift
4,255
0.95
0.132743
0.119565
awesome-app
236
2025-03-07T15:48:57.711785
Apache-2.0
true
2d5d037fcdbe83ff673affa5742c23cf
//\n// FirewallRule.swift\n// MullvadVPNUITests\n//\n// Created by Niklas Berglund on 2024-01-18.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport XCTest\n\nstruct FirewallRule {\n let fromIPAddress: String\n let toIPAddress: String\n let protocols: [NetworkTransportProtocol]\n\n /// - Parameters:\n /// - fromIPAddress: Block traffic originating from this source IP address.\n /// - toIPAddress: Block traffic to this destination IP address.\n /// - protocols: Protocols which should be blocked. If none is specified all will be blocked.\n private init(fromIPAddress: String, toIPAddress: String, protocols: [NetworkTransportProtocol]) {\n self.fromIPAddress = fromIPAddress\n self.toIPAddress = toIPAddress\n self.protocols = protocols\n }\n\n public func protocolsAsStringArray() -> [String] {\n return protocols.map { $0.rawValue }\n }\n\n /// Make a firewall rule blocking API access for the current device under test\n public static func makeBlockAPIAccessFirewallRule() throws -> FirewallRule {\n let deviceIPAddress = try FirewallClient().getDeviceIPAddress()\n let apiIPAddress = try MullvadAPIWrapper.getAPIIPAddress()\n return FirewallRule(\n fromIPAddress: deviceIPAddress,\n toIPAddress: apiIPAddress,\n protocols: [.TCP]\n )\n }\n\n public static func makeBlockAllTrafficRule(toIPAddress: String) throws -> FirewallRule {\n let deviceIPAddress = try FirewallClient().getDeviceIPAddress()\n\n return FirewallRule(\n fromIPAddress: deviceIPAddress,\n toIPAddress: toIPAddress,\n protocols: [.ICMP, .TCP, .UDP]\n )\n }\n\n public static func makeBlockUDPTrafficRule(toIPAddress: String) throws -> FirewallRule {\n let deviceIPAddress = try FirewallClient().getDeviceIPAddress()\n\n return FirewallRule(\n fromIPAddress: deviceIPAddress,\n toIPAddress: toIPAddress,\n protocols: [.UDP]\n )\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Networking\FirewallRule.swift
FirewallRule.swift
Swift
2,058
0.95
0.081967
0.230769
react-lib
659
2024-10-03T21:16:10.843862
BSD-3-Clause
true
097326f33b109f197cc61a759799c5a8
//\n// LeakCheck.swift\n// MullvadVPN\n//\n// Created by Niklas Berglund on 2024-12-16.\n// Copyright © 2024 Mullvad VPN AB. All rights reserved.\n//\n\nimport XCTest\n\nclass LeakCheck {\n static func assertNoLeaks(streams: [Stream], rules: [NoTrafficToHostLeakRule]) {\n XCTAssertFalse(streams.isEmpty, "No streams to leak check")\n XCTAssertFalse(rules.isEmpty, "No leak rules to check")\n\n for rule in rules where rule.isViolated(streams: streams) {\n XCTFail("Leaked traffic destined to \(rule.host) outside of the tunnel connection")\n }\n }\n\n static func assertLeaks(streams: [Stream], rules: [NoTrafficToHostLeakRule]) {\n XCTAssertFalse(streams.isEmpty, "No streams to leak check")\n XCTAssertFalse(rules.isEmpty, "No leak rules to check")\n\n for rule in rules where rule.isViolated(streams: streams) == false {\n XCTFail("Expected to leak traffic to \(rule.host) outside of tunnel")\n }\n }\n}\n\nclass NoTrafficToHostLeakRule {\n let host: String\n\n init(host: String) {\n self.host = host\n }\n\n func isViolated(streams: [Stream]) -> Bool {\n streams.filter { $0.destinationAddress == host }.isEmpty == false\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Networking\LeakCheck.swift
LeakCheck.swift
Swift
1,218
0.95
0.097561
0.212121
vue-tools
371
2024-06-04T08:11:26.393866
GPL-3.0
true
4bae065d7f7588ecbde94d3ad272c328
//\n// MullvadAPIWrapper.swift\n// MullvadVPNUITests\n//\n// Created by Niklas Berglund on 2024-01-18.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport CryptoKit\nimport Foundation\nimport XCTest\n\nenum MullvadAPIError: Error {\n case invalidEndpointFormatError\n case requestError\n}\n\nclass MullvadAPIWrapper {\n private var mullvadAPI: MullvadApi\n private let throttleQueue = DispatchQueue(label: "MullvadAPIWrapperThrottleQueue", qos: .userInitiated)\n private var lastCallDate: Date?\n private let throttleDelay: TimeInterval = 0.25\n private let throttleWaitTimeout: TimeInterval = 5.0\n\n // swiftlint:disable force_cast\n static let hostName = Bundle(for: MullvadAPIWrapper.self)\n .infoDictionary?["ApiHostName"] as! String\n\n /// API endpoint configuration value in the format <IP-address>:<port>\n static let endpoint = Bundle(for: MullvadAPIWrapper.self)\n .infoDictionary?["ApiEndpoint"] as! String\n // swiftlint:enable force_cast\n\n init() throws {\n let apiAddress = try Self.getAPIIPAddress() + ":" + Self.getAPIPort()\n let hostname = Self.hostName\n mullvadAPI = try MullvadApi(apiAddress: apiAddress, hostname: hostname)\n }\n\n /// Throttle what's in the callback. This is used for throttling requests to the app API. All requests should be throttled or else we might be rate limited. The API allows maximum 5 requests per second. Note that the implementation assumes what is being throttled is synchronous.\n private func throttle(callback: @escaping () -> Void) {\n throttleQueue.async {\n let now = Date()\n var delay: TimeInterval = 0\n\n if let lastCallDate = self.lastCallDate {\n let timeSinceLastCall = now.timeIntervalSince(lastCallDate)\n\n if timeSinceLastCall < self.throttleDelay {\n delay = self.throttleDelay - timeSinceLastCall\n }\n }\n\n // Note that this is not really throttling, but it works because the API client implementation is synchronous, and we wait for each request to return.\n self.throttleQueue.asyncAfter(deadline: .now() + delay) {\n callback()\n self.lastCallDate = Date()\n }\n }\n }\n\n public static func getAPIIPAddress() throws -> String {\n guard let ipAddress = endpoint.components(separatedBy: ":").first else {\n throw MullvadAPIError.invalidEndpointFormatError\n }\n\n return ipAddress\n }\n\n public static func getAPIPort() throws -> String {\n guard let port = endpoint.components(separatedBy: ":").last else {\n throw MullvadAPIError.invalidEndpointFormatError\n }\n\n return port\n }\n\n /// Generate a mock public WireGuard key\n private func generateMockWireGuardKey() -> Data {\n let privateKey = Curve25519.KeyAgreement.PrivateKey()\n let publicKey = privateKey.publicKey\n let publicKeyData = publicKey.rawRepresentation\n\n return publicKeyData\n }\n\n func createAccount() -> String {\n var accountNumber = String()\n let requestCompletedExpectation = XCTestExpectation(description: "Create account request completed")\n\n throttle {\n do {\n accountNumber = try self.mullvadAPI.createAccount()\n } catch {\n XCTFail("Failed to create account with error: \(error.localizedDescription)")\n }\n\n requestCompletedExpectation.fulfill()\n }\n\n let waitResult = XCTWaiter().wait(for: [requestCompletedExpectation], timeout: throttleWaitTimeout)\n XCTAssertEqual(waitResult, .completed, "Create account request completed")\n\n return accountNumber\n }\n\n func deleteAccount(_ accountNumber: String) {\n let requestCompletedExpectation = XCTestExpectation(description: "Delete account request completed")\n\n throttle {\n do {\n try self.mullvadAPI.delete(account: accountNumber)\n } catch {\n XCTFail("Failed to delete account with error: \(error.localizedDescription)")\n }\n\n requestCompletedExpectation.fulfill()\n }\n\n let waitResult = XCTWaiter().wait(for: [requestCompletedExpectation], timeout: throttleWaitTimeout)\n XCTAssertEqual(waitResult, .completed, "Delete account request completed")\n }\n\n /// Add another device to specified account. A dummy WireGuard key will be generated.\n func addDevice(_ account: String) {\n let requestCompletedExpectation = XCTestExpectation(description: "Add device request completed")\n\n throttle {\n let devicePublicKey = self.generateMockWireGuardKey()\n\n do {\n try self.mullvadAPI.addDevice(forAccount: account, publicKey: devicePublicKey)\n } catch {\n XCTFail("Failed to add device with error: \(error.localizedDescription)")\n }\n\n requestCompletedExpectation.fulfill()\n }\n\n let waitResult = XCTWaiter().wait(for: [requestCompletedExpectation], timeout: throttleWaitTimeout)\n XCTAssertEqual(waitResult, .completed, "Add device request completed")\n }\n\n /// Add multiple devices to specified account. Dummy WireGuard keys will be generated.\n func addDevices(_ numberOfDevices: Int, account: String) {\n for i in 0 ..< numberOfDevices {\n self.addDevice(account)\n print("Created \(i + 1) devices")\n }\n }\n\n func getAccountExpiry(_ account: String) throws -> Date {\n var accountExpiryDate: Date = .distantPast\n let requestCompletedExpectation = XCTestExpectation(description: "Get account expiry request completed")\n\n throttle {\n do {\n let accountExpiryTimestamp = Double(try self.mullvadAPI.getExpiry(forAccount: account))\n accountExpiryDate = Date(timeIntervalSince1970: accountExpiryTimestamp)\n } catch {\n XCTFail("Failed to get account expiry with error: \(error.localizedDescription)")\n }\n\n requestCompletedExpectation.fulfill()\n }\n\n let waitResult = XCTWaiter().wait(for: [requestCompletedExpectation], timeout: throttleWaitTimeout)\n XCTAssertEqual(waitResult, .completed, "Get account expiry request completed")\n\n return accountExpiryDate\n }\n\n func getDevices(_ account: String) throws -> [Device] {\n var devices: [Device] = []\n let requestCompletedExpectation = XCTestExpectation(description: "Get devices request completed")\n\n throttle {\n do {\n devices = try self.mullvadAPI.listDevices(forAccount: account)\n } catch {\n XCTFail("Failed to get devices with error: \(error.localizedDescription)")\n }\n\n requestCompletedExpectation.fulfill()\n }\n\n let waitResult = XCTWaiter.wait(for: [requestCompletedExpectation], timeout: throttleWaitTimeout)\n XCTAssertEqual(waitResult, .completed, "Get devices request completed")\n\n return devices\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Networking\MullvadAPIWrapper.swift
MullvadAPIWrapper.swift
Swift
7,143
0.95
0.130208
0.099338
node-utils
272
2023-09-05T04:50:46.065700
MIT
true
331e6577bc6a7aec015bd78eb60ab920
//\n// Networking.swift\n// MullvadVPNUITests\n//\n// Created by Niklas Berglund on 2024-02-05.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport Network\nimport XCTest\n\nenum NetworkTransportProtocol: String, Codable {\n case TCP = "tcp"\n case UDP = "udp"\n case ICMP = "icmp"\n}\n\nenum NetworkingError: Error {\n case notConfiguredError\n case internalError(reason: String)\n}\n\nstruct DNSServerEntry: Decodable {\n let organization: String\n let mullvad_dns: Bool\n}\n\n/// Class with methods for verifying network connectivity\nclass Networking {\n /// Get configured ad serving domain\n private static func getAdServingDomain() throws -> String {\n guard let adServingDomain = Bundle(for: Networking.self)\n .infoDictionary?["AdServingDomain"] as? String else {\n throw NetworkingError.notConfiguredError\n }\n\n return adServingDomain\n }\n\n /// Check whether host and port is reachable by attempting to connect a socket\n private static func canConnectSocket(host: String, port: String) throws -> Bool {\n let socketHost = NWEndpoint.Host(host)\n let socketPort = try XCTUnwrap(NWEndpoint.Port(port))\n let connection = NWConnection(host: socketHost, port: socketPort, using: .tcp)\n var connectionError: Error?\n\n let connectionStateDeterminedExpectation = XCTestExpectation(\n description: "Completion handler for the reach ad serving domain request is invoked"\n )\n\n connection.stateUpdateHandler = { state in\n print("State: \(state)")\n\n switch state {\n case let .failed(error):\n connection.cancel()\n connectionError = error\n connectionStateDeterminedExpectation.fulfill()\n case .ready:\n connection.cancel()\n connectionStateDeterminedExpectation.fulfill()\n default:\n break\n }\n }\n\n connection.start(queue: .global())\n let waitResult = XCTWaiter.wait(for: [connectionStateDeterminedExpectation], timeout: 15)\n\n if waitResult != .completed || connectionError != nil {\n return false\n }\n\n return true\n }\n\n /// Get configured domain to use for Internet connectivity checks\n public static func getAlwaysReachableDomain() throws -> String {\n guard let shouldBeReachableDomain = Bundle(for: Networking.self)\n .infoDictionary?["ShouldBeReachableDomain"] as? String else {\n throw NetworkingError.notConfiguredError\n }\n\n return shouldBeReachableDomain\n }\n\n public static func getAlwaysReachableIPAddress() -> String {\n guard let shouldBeReachableIPAddress = Bundle(for: Networking.self)\n .infoDictionary?["ShouldBeReachableIPAddress"] as? String else {\n XCTFail("Should be reachable IP address not configured")\n return String()\n }\n\n return shouldBeReachableIPAddress\n }\n\n /// Verify API can be accessed by attempting to connect a socket to the configured API host and port\n public static func verifyCanAccessAPI() throws {\n let apiIPAddress = try MullvadAPIWrapper.getAPIIPAddress()\n let apiPort = try MullvadAPIWrapper.getAPIPort()\n XCTAssertTrue(\n try canConnectSocket(host: apiIPAddress, port: apiPort),\n "Failed to verify that API can be accessed"\n )\n }\n\n /// Verify API cannot be accessed by attempting to connect a socket to the configured API host and port\n public static func verifyCannotAccessAPI() throws {\n let apiIPAddress = try MullvadAPIWrapper.getAPIIPAddress()\n let apiPort = try MullvadAPIWrapper.getAPIPort()\n XCTAssertFalse(\n try canConnectSocket(host: apiIPAddress, port: apiPort),\n "Failed to verify that API cannot be accessed"\n )\n }\n\n /// Verify that the device has Internet connectivity\n public static func verifyCanAccessInternet() throws {\n XCTAssertTrue(\n try canConnectSocket(host: getAlwaysReachableDomain(), port: "80"),\n "Failed to verify that the Internet can be acccessed"\n )\n }\n\n /// Verify that the device does not have Internet connectivity\n public static func verifyCannotAccessInternet() throws {\n XCTAssertFalse(\n try canConnectSocket(host: getAlwaysReachableDomain(), port: "80"),\n "Failed to verify that the Internet cannot be accessed"\n )\n }\n\n /// Verify that an ad serving domain is reachable by making sure a connection can be established on port 80\n public static func verifyCanReachAdServingDomain() throws {\n XCTAssertTrue(\n try Self.canConnectSocket(host: try Self.getAdServingDomain(), port: "80"),\n "Failed to verify that ad serving domain can be accessed"\n )\n }\n\n /// Verify that an ad serving domain is NOT reachable by making sure a connection can not be established on port 80\n public static func verifyCannotReachAdServingDomain() throws {\n XCTAssertFalse(\n try Self.canConnectSocket(host: try Self.getAdServingDomain(), port: "80"),\n "Failed to verify that ad serving domain cannot be accessed"\n )\n }\n\n /// Verify that the expected DNS server is used by verifying provider name and whether it is a Mullvad DNS server or not\n public static func verifyDNSServerProvider(_ providerName: String, isMullvad: Bool) throws {\n guard let mullvadDNSLeakURL = URL(string: "https://am.i.mullvad.net/dnsleak") else {\n throw NetworkingError.internalError(reason: "Failed to create URL object")\n }\n\n var request = URLRequest(url: mullvadDNSLeakURL)\n request.setValue("application/json", forHTTPHeaderField: "accept")\n\n var requestData: Data?\n var requestResponse: URLResponse?\n var requestError: Error?\n let completionHandlerInvokedExpectation = XCTestExpectation(\n description: "Completion handler for the request is invoked"\n )\n\n do {\n let dataTask = URLSession.shared.dataTask(with: request) { data, response, error in\n requestData = data\n requestResponse = response\n requestError = error\n completionHandlerInvokedExpectation.fulfill()\n }\n\n dataTask.resume()\n\n let waitResult = XCTWaiter.wait(for: [completionHandlerInvokedExpectation], timeout: 30)\n\n if waitResult != .completed {\n XCTFail("Failed to verify DNS server provider - timeout")\n } else {\n if let response = requestResponse as? HTTPURLResponse {\n if response.statusCode != 200 {\n XCTFail("Failed to verify DNS server provider - unexpected server response")\n }\n }\n\n if let error = requestError {\n XCTFail("Failed to verify DNS server provider - encountered error \(error.localizedDescription)")\n }\n\n if let requestData = requestData {\n let dnsServerEntries = try JSONDecoder().decode([DNSServerEntry].self, from: requestData)\n XCTAssertGreaterThanOrEqual(dnsServerEntries.count, 1)\n\n for dnsServerEntry in dnsServerEntries {\n XCTAssertEqual(dnsServerEntry.organization, providerName, "Expected organization name")\n XCTAssertEqual(\n dnsServerEntry.mullvad_dns,\n isMullvad,\n "Verifying that it is or isn't a Mullvad DNS server"\n )\n }\n }\n }\n } catch {\n XCTFail("Failed to verify DNS server provider - couldn't serialize JSON")\n }\n }\n\n public static func verifyConnectedThroughMullvad() throws {\n let mullvadConnectionJsonEndpoint = try XCTUnwrap(\n Bundle(for: Networking.self)\n .infoDictionary?["AmIJSONUrl"] as? String,\n "Read am I JSON URL from Info"\n )\n guard let url = URL(string: mullvadConnectionJsonEndpoint) else {\n XCTFail("Failed to unwrap URL")\n return\n }\n\n let request = URLRequest(url: url)\n let completionHandlerInvokedExpectation = XCTestExpectation(\n description: "Completion handler for the request is invoked"\n )\n\n let dataTask = URLSession.shared.dataTask(with: request) { data, response, error in\n if let response = response as? HTTPURLResponse {\n if response.statusCode != 200 {\n XCTFail("Request to connection check API failed - unexpected server response")\n }\n }\n\n if let error = error {\n XCTFail("Request to connection check API failed - encountered error \(error.localizedDescription)")\n }\n\n guard let data = data else {\n XCTFail("Didn't receive any data")\n return\n }\n\n do {\n let jsonObject = try JSONSerialization.jsonObject(with: data)\n\n if let dictionary = jsonObject as? [String: Any] {\n guard let isConnectedThroughMullvad = dictionary["mullvad_exit_ip"] as? Bool else {\n XCTFail("Unexpected JSON format")\n return\n }\n\n XCTAssertTrue(isConnectedThroughMullvad)\n }\n } catch {\n XCTFail("Failed to verify whether connected through Mullvad or not")\n }\n\n completionHandlerInvokedExpectation.fulfill()\n }\n\n dataTask.resume()\n\n let waitResult = XCTWaiter.wait(for: [completionHandlerInvokedExpectation], timeout: 30)\n\n if waitResult != .completed {\n XCTFail("Request to connection check API failed - timeout")\n }\n }\n\n public static func verifyCanAccessLocalNetwork() throws {\n let apiIPAddress = "192.168.105.1"\n let apiPort = "80"\n XCTAssertTrue(\n try canConnectSocket(host: apiIPAddress, port: apiPort),\n "Failed to verify that local network can be accessed"\n )\n }\n\n public static func verifyCannotAccessLocalNetwork() throws {\n let apiIPAddress = "192.168.105.1"\n let apiPort = "80"\n XCTAssertFalse(\n try canConnectSocket(host: apiIPAddress, port: apiPort),\n "Failed to verify that local network cannot be accessed"\n )\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Networking\Networking.swift
Networking.swift
Swift
10,744
0.95
0.160839
0.075314
react-lib
597
2025-07-02T09:16:39.128936
GPL-3.0
true
ffd4c8c4439643ff839a0f3e1469432b
//\n// PacketCapture.swift\n// MullvadVPNUITests\n//\n// Created by Niklas Berglund on 2024-04-30.\n// Copyright © 2024 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport XCTest\n\nstruct PacketCaptureSession {\n var identifier: String\n\n init(identifier: String = UUID().uuidString) {\n self.identifier = identifier\n\n print("Current Packet Capture session identifier is: \(identifier)")\n }\n}\n\n/// Represents a stream in packet capture\nclass Stream: Codable, Equatable {\n static func == (lhs: Stream, rhs: Stream) -> Bool {\n return lhs.sourceAddress == rhs.sourceAddress &&\n lhs.destinationAddress == rhs.destinationAddress &&\n lhs.flowID == rhs.flowID &&\n lhs.transportProtocol == rhs.transportProtocol\n }\n\n let sourceAddress: String\n let sourcePort: Int\n let destinationAddress: String\n let destinationPort: Int\n let flowID: String?\n let transportProtocol: NetworkTransportProtocol\n var packets: [Packet] {\n didSet {\n determineDateInterval()\n }\n }\n\n /// Date interval from first to last packet of this stream\n var dateInterval: DateInterval\n\n /// Date interval from first to last tx(sent from test device) packet of this stream\n var txInterval: DateInterval?\n\n /// Date interval from frist to last rx(sent to test device) packet of this stream\n var rxInterval: DateInterval?\n\n enum CodingKeys: String, CodingKey {\n case sourceAddress = "peer_addr"\n case destinationAddress = "other_addr"\n case flowID = "flow_id"\n case transportProtocol = "transport_protocol"\n case packets\n }\n\n required init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n self.flowID = try container.decodeIfPresent(String.self, forKey: .flowID)\n self.transportProtocol = try container.decode(NetworkTransportProtocol.self, forKey: .transportProtocol)\n self.packets = try container.decode([Packet].self, forKey: .packets)\n dateInterval = DateInterval()\n\n // Separate source address and port\n let sourceValue = try container.decode(String.self, forKey: .sourceAddress)\n let sourceSplit = sourceValue.components(separatedBy: ":")\n self.sourceAddress = try XCTUnwrap(sourceSplit.first)\n self.sourcePort = try XCTUnwrap(Int(try XCTUnwrap(sourceSplit.last)))\n\n // Separate destination address and port\n let destinationValue = try container.decode(String.self, forKey: .destinationAddress)\n let destinationSplit = destinationValue.components(separatedBy: ":")\n self.destinationAddress = try XCTUnwrap(destinationSplit.first)\n self.destinationPort = try XCTUnwrap(Int(try XCTUnwrap(destinationSplit.last)))\n\n // Set date interval based on packets' time window\n determineDateInterval()\n }\n\n /// Determine the stream's date interval from the time between first to the last packet\n private func determineDateInterval() {\n guard packets.isEmpty == false else {\n XCTFail("Stream unexpectedly have no packets")\n return\n }\n\n // Identify first tx and rx packets to set as initial values\n let txPackets = packets.filter { $0.fromPeer == true }.sorted { $0.date < $1.date }\n let rxPackets = packets.filter { $0.fromPeer == false }.sorted { $0.date < $1.date }\n let allPackets = packets.sorted { $0.date < $1.date }\n\n if let firstTxPacket = txPackets.first, let lastTxPacket = txPackets.last {\n txInterval = DateInterval(start: firstTxPacket.date, end: lastTxPacket.date)\n }\n\n if let firstRxPacket = rxPackets.first, let lastRxPacket = rxPackets.last {\n rxInterval = DateInterval(start: firstRxPacket.date, end: lastRxPacket.date)\n }\n\n if let firstPacket = allPackets.first, let lastPacket = allPackets.last {\n dateInterval = DateInterval(start: firstPacket.date, end: lastPacket.date)\n }\n }\n}\n\n/// Represents a packet in packet capture\nclass Packet: Codable, Equatable {\n /// True when packet is sent from device under test, false if from another host\n public let fromPeer: Bool\n\n /// Timestamp in microseconds\n private var timestamp: Int64\n\n public var date: Date\n\n enum CodingKeys: String, CodingKey {\n case fromPeer = "from_peer"\n case timestamp\n }\n\n required init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n fromPeer = try container.decode(Bool.self, forKey: .fromPeer)\n timestamp = try container.decode(Int64.self, forKey: .timestamp) / 1000000\n date = Date(timeIntervalSince1970: TimeInterval(timestamp))\n }\n\n static func == (lhs: Packet, rhs: Packet) -> Bool {\n return lhs.fromPeer == rhs.fromPeer &&\n lhs.timestamp == rhs.timestamp &&\n lhs.date == rhs.date\n }\n}\n\nclass PacketCaptureClient: TestRouterAPIClient {\n /// Start a new capture session\n func startCapture() -> PacketCaptureSession {\n let session = PacketCaptureSession()\n\n let jsonDictionary = [\n "label": session.identifier,\n ]\n\n _ = sendRequest(\n httpMethod: "POST",\n endpoint: "capture",\n contentType: "application/json",\n jsonData: jsonDictionary\n )\n\n return session\n }\n\n /// Stop capture for session\n func stopCapture(session: PacketCaptureSession) {\n _ = sendJSONRequest(httpMethod: "POST", endpoint: "stop-capture/\(session.identifier)", jsonData: nil)\n }\n\n /// Cut specified number of seconds from the beginning and end of data capture\n static func trimPackets(streams: [Stream], secondsStart: Double, secondsEnd: Double) -> [Stream] {\n var collectionStartDate: Date?\n var collectionEndDate: Date?\n\n XCTAssertTrue(streams.count >= 1, "Captured streams are empty, expected at least 1")\n\n for stream in streams {\n if collectionStartDate != nil {\n collectionStartDate = min(collectionStartDate!, stream.dateInterval.start)\n } else {\n collectionStartDate = stream.dateInterval.start\n }\n\n if collectionEndDate != nil {\n collectionEndDate = max(collectionEndDate!, stream.dateInterval.end)\n } else {\n collectionEndDate = stream.dateInterval.end\n }\n }\n\n let cutStartDate = collectionStartDate!.addingTimeInterval(secondsStart)\n let cutEndDate = collectionEndDate!.addingTimeInterval(-secondsEnd)\n\n var trimmedStreams: [Stream] = []\n for stream in streams {\n let packetsWithinTimeframe = stream.packets.filter { packet in\n return packet.date >= cutStartDate && packet.date <= cutEndDate\n }\n\n if packetsWithinTimeframe.isEmpty == false {\n stream.packets = packetsWithinTimeframe\n trimmedStreams.append(stream)\n }\n }\n\n return trimmedStreams\n }\n\n /// Get captured traffic from this session parsed to objects\n func getParsedCaptureObjects(session: PacketCaptureSession) -> [Stream] {\n let parsedData = getParsedCapture(session: session)\n let decoder = JSONDecoder()\n\n do {\n let streams = try decoder.decode([Stream].self, from: parsedData)\n return streams\n } catch {\n XCTFail("Failed to decode parsed capture")\n return []\n }\n }\n\n /// Get captured traffic from this session parsed to JSON\n func getParsedCapture(session: PacketCaptureSession) -> Data {\n var deviceIPAddress: String\n\n do {\n deviceIPAddress = try getDeviceIPAddress()\n } catch {\n XCTFail("Failed to get device IP address")\n return Data()\n }\n\n let responseData = sendJSONRequest(\n httpMethod: "PUT",\n endpoint: "parse-capture/\(session.identifier)",\n jsonData: [deviceIPAddress]\n )\n\n return responseData\n }\n\n /// Get PCAP file contents for the capture of this session\n func getPCAP(session: PacketCaptureSession) -> Data {\n let response = sendPCAPRequest(httpMethod: "GET", endpoint: "last-capture/\(session.identifier)", jsonData: nil)\n return response\n }\n\n private func sendJSONRequest(httpMethod: String, endpoint: String, jsonData: Any?) -> Data {\n let responseData = sendRequest(\n httpMethod: httpMethod,\n endpoint: endpoint,\n contentType: "application/json",\n jsonData: jsonData\n )\n\n guard let responseData else {\n XCTFail("Unexpectedly didn't get any data from JSON request")\n return Data()\n }\n\n return responseData\n }\n\n private func sendPCAPRequest(httpMethod: String, endpoint: String, jsonData: Any?) -> Data {\n let responseData = sendRequest(\n httpMethod: httpMethod,\n endpoint: endpoint,\n contentType: "application/pcap",\n jsonData: jsonData\n )\n\n guard let responseData else {\n XCTFail("Unexpectedly didn't get any data from response")\n return Data()\n }\n\n XCTAssertFalse(responseData.isEmpty, "PCAP response data should not be empty")\n\n return responseData\n }\n\n private func sendRequest(httpMethod: String, endpoint: String, contentType: String?, jsonData: Any?) -> Data? {\n let url = TestRouterAPIClient.baseURL.appendingPathComponent(endpoint)\n\n var request = URLRequest(url: url)\n request.httpMethod = httpMethod\n\n if let contentType {\n request.setValue(contentType, forHTTPHeaderField: "Content-Type")\n }\n\n if let jsonData = jsonData {\n do {\n request.httpBody = try JSONSerialization.data(withJSONObject: jsonData)\n } catch {\n XCTFail("Failed to serialize JSON data")\n }\n }\n\n var requestResponse: URLResponse?\n var requestError: Error?\n var responseData: Data?\n\n let completionHandlerInvokedExpectation = XCTestExpectation(\n description: "Completion handler for the request is invoked"\n )\n\n let dataTask = URLSession.shared.dataTask(with: request) { data, response, error in\n requestResponse = response\n requestError = error\n\n guard let data = data,\n let response = response as? HTTPURLResponse,\n error == nil else {\n XCTFail("Error: \(error?.localizedDescription ?? "Unknown error")")\n return\n }\n\n if 200 ... 204 ~= response.statusCode && error == nil {\n responseData = data\n } else {\n XCTFail("Request failed")\n }\n\n completionHandlerInvokedExpectation.fulfill()\n }\n\n dataTask.resume()\n\n let waitResult = XCTWaiter.wait(for: [completionHandlerInvokedExpectation], timeout: 30)\n\n if waitResult != .completed {\n XCTFail("Failed to send packet capture API request - timeout")\n } else {\n if let response = requestResponse as? HTTPURLResponse {\n if (200 ... 201 ~= response.statusCode) == false {\n XCTFail("Packet capture API request failed - unexpected server response")\n }\n }\n\n if let error = requestError {\n XCTFail("Packet capture API request failed - encountered error \(error.localizedDescription)")\n }\n }\n\n return responseData\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Networking\PacketCapture.swift
PacketCapture.swift
Swift
11,810
0.95
0.129032
0.091241
python-kit
914
2025-01-06T08:33:28.648863
BSD-3-Clause
true
826dca2d086e586d5b60c9dd8a6f5152
//\n// PartnerAPIClient.swift\n// MullvadVPNUITests\n//\n// Created by Niklas Berglund on 2024-04-19.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport XCTest\n\nclass PartnerAPIClient {\n let baseURL = URL(string: "https://partner.stagemole.eu/v1/")!\n\n lazy var accessToken: String = {\n guard let token = Bundle(for: BaseUITestCase.self).infoDictionary?["PartnerApiToken"] as? String else {\n fatalError("Failed to retrieve partner API token from config")\n }\n return token\n }()\n\n /// Add time to an account\n /// - Parameters:\n /// - accountNumber: Account number\n /// - days: Number of days to add. Needs to be between 1 and 31.\n func addTime(accountNumber: String, days: Int) -> Date {\n let jsonResponse = sendRequest(\n method: "POST",\n endpoint: "accounts/\(accountNumber)/extend",\n jsonObject: ["days": "\(days)"]\n )\n\n guard let newExpiryString = jsonResponse["new_expiry"] as? String else {\n XCTFail("Failed to read new account expiry from response")\n return Date()\n }\n\n let dateFormatter = ISO8601DateFormatter()\n guard let newExpiryDate = dateFormatter.date(from: newExpiryString) else {\n XCTFail("Failed to create Date object from date string")\n return Date()\n }\n\n return newExpiryDate\n }\n\n func createAccount() -> String {\n let jsonResponse = sendRequest(method: "POST", endpoint: "accounts", jsonObject: nil)\n\n guard let accountNumber = jsonResponse["id"] as? String else {\n XCTFail("Failed to read created account number")\n return String()\n }\n\n return accountNumber\n }\n\n func deleteAccount(accountNumber: String) {\n _ = sendRequest(method: "DELETE", endpoint: "accounts/\(accountNumber)", jsonObject: nil)\n }\n\n private func sendRequest(method: String, endpoint: String, jsonObject: [String: Any]?) -> [String: Any] {\n let url = baseURL.appendingPathComponent(endpoint)\n var request = URLRequest(url: url)\n request.httpMethod = method\n request.setValue("Basic \(accessToken)", forHTTPHeaderField: "Authorization")\n\n var jsonResponse: [String: Any] = [:]\n\n do {\n if let jsonObject = jsonObject {\n request.setValue("application/json", forHTTPHeaderField: "Content-Type")\n request.httpBody = try JSONSerialization.data(withJSONObject: jsonObject, options: [])\n }\n } catch {\n XCTFail("Failed to serialize JSON object")\n return [:]\n }\n\n let completionHandlerInvokedExpectation = XCTestExpectation(\n description: "Completion handler for the request is invoked"\n )\n\n var requestError: Error?\n\n let task = URLSession.shared.dataTask(with: request) { data, response, error in\n requestError = error\n\n guard let data = data,\n let response = response as? HTTPURLResponse,\n error == nil else {\n XCTFail("Error: \(error?.localizedDescription ?? "Unknown error")")\n completionHandlerInvokedExpectation.fulfill()\n return\n }\n\n if 200 ... 204 ~= response.statusCode {\n print("Request successful")\n do {\n if data.isEmpty {\n // Not all requests return JSON data\n jsonResponse = [:]\n } else {\n jsonResponse = try JSONSerialization.jsonObject(with: data) as? [String: Any] ?? [:]\n }\n } catch {\n XCTFail("Failed to deserialize JSON response")\n }\n } else {\n XCTFail("Request failed with status code \(response.statusCode)")\n }\n\n completionHandlerInvokedExpectation.fulfill()\n }\n\n task.resume()\n let waitResult = XCTWaiter().wait(for: [completionHandlerInvokedExpectation], timeout: 10)\n XCTAssertEqual(waitResult, .completed, "Waiting for partner API request expectation completed")\n XCTAssertNil(requestError)\n\n return jsonResponse\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Networking\PartnerAPIClient.swift
PartnerAPIClient.swift
Swift
4,315
0.95
0.097561
0.118812
python-kit
914
2025-04-16T02:33:18.705578
BSD-3-Clause
true
1aad5637f7a7f427907b99ec47488b41
//\n// TrafficGenerator.swift\n// MullvadVPNUITests\n//\n// Created by Niklas Berglund on 2024-06-25.\n// Copyright © 2024 Mullvad VPN AB. All rights reserved.\n//\n\nimport Network\nimport XCTest\n\nclass TrafficGenerator {\n let destinationHost: String\n let port: Int\n var connection: NWConnection\n let dispatchQueue = DispatchQueue(label: "TrafficGeneratorDispatchQueue")\n var sendDataTimer: DispatchSourceTimer\n\n init(destinationHost: String, port: Int) {\n self.destinationHost = destinationHost\n self.port = port\n\n sendDataTimer = DispatchSource.makeTimerSource(queue: dispatchQueue)\n let params = NWParameters.udp\n connection = NWConnection(\n host: NWEndpoint.Host(destinationHost),\n port: NWEndpoint.Port(integerLiteral: UInt16(port)),\n using: params\n )\n setupOtherHandlers()\n }\n\n func reconnect() {\n print("Attempting to reconnect")\n connection.forceCancel()\n\n connection = createConnection()\n setupConnection()\n setupOtherHandlers()\n }\n\n func createConnection() -> NWConnection {\n let params = NWParameters.udp\n return NWConnection(\n host: NWEndpoint.Host(destinationHost),\n port: NWEndpoint.Port(integerLiteral: UInt16(port)),\n using: params\n )\n }\n\n func setupOtherHandlers() {\n connection.pathUpdateHandler = { newPath in\n let availableInterfaces = newPath.availableInterfaces.map { $0.customDebugDescription }\n let availableGateways = newPath.gateways.map { $0.customDebugDescription }\n\n print("New interfaces available: \(availableInterfaces)")\n print("New gateways available: \(availableGateways)")\n }\n\n connection.viabilityUpdateHandler = { newViability in\n print("Connection is viable: \(newViability)")\n }\n\n connection.betterPathUpdateHandler = { betterPathAvailable in\n print("A better path is available: \(betterPathAvailable)")\n }\n }\n\n func setupConnection() {\n print("Setting up connection...")\n let doneAttemptingConnectExpecation = XCTestExpectation(description: "Done attemping to connect")\n\n connection.stateUpdateHandler = { state in\n switch state {\n case .ready:\n print("Ready")\n self.sendDataTimer.resume()\n doneAttemptingConnectExpecation.fulfill()\n case let .failed(error):\n print("Failed to connect: \(error)")\n self.sendDataTimer.cancel()\n self.reconnect()\n case .preparing:\n print("Preparing connection...")\n case .setup:\n print("Setting upp connection...")\n case let .waiting(error):\n print("Waiting to connect: \(error)")\n case .cancelled:\n self.sendDataTimer.suspend()\n print("Cancelled connection")\n self.reconnect()\n default:\n break\n }\n }\n connection.start(queue: dispatchQueue)\n\n XCTWaiter().wait(for: [doneAttemptingConnectExpecation], timeout: 10.0)\n }\n\n func stopConnection() {\n connection.stateUpdateHandler = { @Sendable _ in }\n connection.cancel()\n }\n\n public func startGeneratingUDPTraffic(interval: TimeInterval) {\n setupConnection()\n sendDataTimer.schedule(deadline: .now(), repeating: interval)\n\n sendDataTimer.setEventHandler {\n let data = Data("dGhpcyBpcyBqdXN0IHNvbWUgZHVtbXkgZGF0YSB0aGlzIGlzIGp1c3Qgc29tZSBkdW".utf8)\n\n print("Attempting to send data...")\n\n if self.connection.state != .ready {\n print("Not connected, won't send data")\n } else {\n self.connection.send(content: data, completion: .contentProcessed { error in\n if let error = error {\n print("Failed to send data: \(error)")\n } else {\n print("Data sent")\n }\n })\n }\n }\n\n sendDataTimer.activate()\n }\n\n public func stopGeneratingUDPTraffic() {\n sendDataTimer.setEventHandler(handler: {})\n sendDataTimer.cancel()\n stopConnection()\n }\n}\n\nextension NWInterface {\n var customDebugDescription: String {\n "type: \(type) name: \(self.name) index: \(index)"\n }\n}\n\nextension NWInterface.InterfaceType: @retroactive CustomDebugStringConvertible {\n public var debugDescription: String {\n switch self {\n case .cellular: "Cellular"\n case .loopback: "Loopback"\n case .other: "Other"\n case .wifi: "Wifi"\n case .wiredEthernet: "Wired Ethernet"\n @unknown default: "Unknown interface type"\n }\n }\n}\n\nextension NWEndpoint {\n var customDebugDescription: String {\n switch self {\n case let .hostPort(host, port): "host: \(host.customDebugDescription) port: \(port)"\n case let .opaque(endpoint): "opaque: \(endpoint.description)"\n case let .url(url): "url: \(url)"\n case let .service(\n name,\n type,\n domain,\n interface\n ): "service named:\(name), type:\(type), domain:\(domain), interface:\(interface?.customDebugDescription ?? "[No interface]")"\n case let .unix(path): "unix: \(path)"\n @unknown default: "Unknown NWEndpoint type"\n }\n }\n}\n\nextension NWEndpoint.Host {\n var customDebugDescription: String {\n switch self {\n case let .ipv4(IPv4Address): "IPv4: \(IPv4Address)"\n case let .ipv6(IPv6Address): "IPv6: \(IPv6Address)"\n case let .name(name, interface): "named: \(name), \(interface?.customDebugDescription ?? "[No interface]")"\n @unknown default: "Unknown host"\n }\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Networking\TrafficGenerator.swift
TrafficGenerator.swift
Swift
5,946
0.95
0.043243
0.04375
python-kit
328
2024-08-06T15:31:14.614247
MIT
true
2f9c162c2fd3fa0c64903a139e81211b
//\n// AccountDeletionPage.swift\n// MullvadVPNUITests\n//\n// Created by Niklas Berglund on 2024-01-30.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport XCTest\n\nclass AccountDeletionPage: Page {\n @discardableResult override init(_ app: XCUIApplication) {\n super.init(app)\n\n self.pageElement = app.otherElements[.deleteAccountView]\n waitForPageToBeShown()\n }\n\n @discardableResult func tapTextField() -> Self {\n app.textFields[AccessibilityIdentifier.deleteAccountTextField].tap()\n return self\n }\n\n @discardableResult func tapDeleteAccountButton() -> Self {\n app.otherElements[.deleteAccountView].buttons[AccessibilityIdentifier.deleteButton].tap()\n return self\n }\n\n @discardableResult func tapCancelButton() -> Self {\n app.buttons[AccessibilityIdentifier.cancelButton].tap()\n return self\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Pages\AccountDeletionPage.swift
AccountDeletionPage.swift
Swift
918
0.95
0.029412
0.25
react-lib
689
2024-06-23T08:09:48.071065
MIT
true
aa5e1a741c2118e722bc40a91d83fba5
//\n// AccountPage.swift\n// MullvadVPNUITests\n//\n// Created by Niklas Berglund on 2024-01-23.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport XCTest\n\nclass AccountPage: Page {\n @discardableResult override init(_ app: XCUIApplication) {\n super.init(app)\n\n self.pageElement = app.otherElements[.accountView]\n waitForPageToBeShown()\n }\n\n @discardableResult func tapRedeemVoucherButton() -> Self {\n app.buttons[AccessibilityIdentifier.redeemVoucherButton.asString].tap()\n return self\n }\n\n @discardableResult func tapAdd30DaysTimeButton() -> Self {\n app.buttons[AccessibilityIdentifier.purchaseButton.asString].tap()\n return self\n }\n\n @discardableResult func tapRestorePurchasesButton() -> Self {\n app.buttons[AccessibilityIdentifier.restorePurchasesButton.asString].tap()\n return self\n }\n\n @discardableResult func tapLogOutButton() -> Self {\n app.buttons[AccessibilityIdentifier.logoutButton.asString].tap()\n return self\n }\n\n @discardableResult func tapDeleteAccountButton() -> Self {\n app.buttons[AccessibilityIdentifier.deleteButton.asString].tap()\n return self\n }\n\n func getDeviceName() throws -> String {\n let deviceNameLabel = app.otherElements[AccessibilityIdentifier.accountPageDeviceNameLabel]\n return try XCTUnwrap(deviceNameLabel.value as? String, "Failed to read device name from label")\n }\n\n @discardableResult func verifyPaidUntil(_ date: Date) -> Self {\n // Strip seconds from date, since the app don't display seconds\n let calendar = Calendar.current\n var components = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: date)\n components.second = 0\n guard let strippedDate = calendar.date(from: components) else {\n XCTFail("Failed to remove seconds from date")\n return self\n }\n\n let paidUntilLabelText = app.staticTexts[AccessibilityIdentifier.accountPagePaidUntilLabel].label\n let dateFormatter = DateFormatter()\n dateFormatter.dateStyle = .medium\n dateFormatter.timeStyle = .short\n\n guard let paidUntilLabelDate = dateFormatter.date(from: paidUntilLabelText) else {\n XCTFail("Failed to convert presented date to Date object")\n return self\n }\n\n XCTAssertEqual(strippedDate, paidUntilLabelDate, "Paid until date correct")\n return self\n }\n\n func waitForLogoutSpinnerToDisappear() {\n let spinnerDisappeared = app.otherElements[.logOutSpinnerAlertView]\n .waitForNonExistence(timeout: BaseUITestCase.extremelyLongTimeout)\n XCTAssertTrue(spinnerDisappeared, "Log out spinner disappeared")\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Pages\AccountPage.swift
AccountPage.swift
Swift
2,786
0.95
0.025316
0.123077
vue-tools
585
2023-08-31T23:38:08.779343
Apache-2.0
true
cde41dce6a8ed9e61d470c8ba83defc5
//\n// AddAccessMethodPage.swift\n// MullvadVPNUITests\n//\n// Created by Niklas Berglund on 2024-04-08.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport XCTest\n\nclass AddAccessMethodPage: Page {\n override init(_ app: XCUIApplication) {\n super.init(app)\n self.pageElement = app.tables[.addAccessMethodTableView]\n waitForPageToBeShown()\n }\n\n @discardableResult func tapNameCell() -> Self {\n app.cells[AccessibilityIdentifier.accessMethodNameTextField]\n .tap()\n return self\n }\n\n @discardableResult func tapTypeCell() -> Self {\n app.cells[AccessibilityIdentifier.accessMethodProtocolSelectionCell]\n .tap()\n return self\n }\n\n @discardableResult func tapShadowsocksTypeValueCell() -> Self {\n app.tables[AccessibilityIdentifier.accessMethodProtocolPickerView].staticTexts["Shadowsocks"].tap()\n return self\n }\n\n @discardableResult func tapSOCKS5TypeValueCell() -> Self {\n app.tables[AccessibilityIdentifier.accessMethodProtocolPickerView].staticTexts["SOCKS5"].tap()\n return self\n }\n\n @discardableResult func tapServerCell() -> Self {\n app.cells[AccessibilityIdentifier.socks5ServerCell]\n .tap()\n return self\n }\n\n @discardableResult func tapPortCell() -> Self {\n app.cells[AccessibilityIdentifier.socks5PortCell]\n .tap()\n return self\n }\n\n @discardableResult func tapAuthenticationSwitch() -> Self {\n app.switches[AccessibilityIdentifier.socks5AuthenticationSwitch]\n .tap()\n return self\n }\n\n @discardableResult func tapAddButton() -> Self {\n app.buttons[AccessibilityIdentifier.accessMethodAddButton]\n .tap()\n return self\n }\n\n @discardableResult func waitForAPIUnreachableLabel() -> Self {\n XCTAssertTrue(\n app.staticTexts[AccessibilityIdentifier.addAccessMethodTestStatusUnreachableLabel]\n .waitForExistence(timeout: BaseUITestCase.longTimeout)\n )\n return self\n }\n}\n\nclass AddAccessMethodAPIUnreachableAlert: Page {\n override init(_ app: XCUIApplication) {\n super.init(app)\n self.pageElement = app.otherElements[.accessMethodUnreachableAlert]\n waitForPageToBeShown()\n }\n\n @discardableResult func tapSaveButton() -> Self {\n app.buttons[AccessibilityIdentifier.accessMethodUnreachableSaveButton].tap()\n return self\n }\n\n @discardableResult func tapBackButton() -> Self {\n app.buttons[AccessibilityIdentifier.accessMethodUnreachableBackButton].tap()\n return self\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Pages\AddAccessMethodPage.swift
AddAccessMethodPage.swift
Swift
2,667
0.95
0.022222
0.092105
python-kit
452
2024-12-25T11:50:56.833570
BSD-3-Clause
true
73b7c35bfcf909dddb05db63343b7bd9
//\n// AddCustomListLocationsPage.swift\n// MullvadVPNUITests\n//\n// Created by Jon Petersson on 2024-06-03.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport XCTest\n\nclass AddCustomListLocationsPage: EditCustomListLocationsPage {\n @discardableResult override func tapBackButton() -> Self {\n app.navigationBars["Add locations"].buttons.firstMatch.tap()\n return self\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Pages\AddCustomListLocationsPage.swift
AddCustomListLocationsPage.swift
Swift
411
0.95
0.0625
0.5
node-utils
188
2025-01-10T19:54:12.230680
MIT
true
ee1c0236c637f2c9b289b48d5279249e
//\n// Alert.swift\n// MullvadVPNUITests\n//\n// Created by Niklas Berglund on 2024-01-10.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport XCTest\n\n/// Generic alert "page"\nclass Alert: Page {\n @discardableResult override init(_ app: XCUIApplication) {\n super.init(app)\n\n self.pageElement = app.otherElements[.alertContainerView]\n waitForPageToBeShown()\n }\n\n @discardableResult func tapOkay() -> Self {\n app.buttons[AccessibilityIdentifier.alertOkButton].tap()\n return self\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Pages\Alert.swift
Alert.swift
Swift
564
0.95
0.04
0.380952
awesome-app
957
2024-03-11T22:13:02.893750
GPL-3.0
true
6ee75e511aa1ee7e67b8f74ca568ad9a
//\n// APIAccessPage.swift\n// MullvadVPNUITests\n//\n// Created by Niklas Berglund on 2024-04-08.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport XCTest\n\nclass APIAccessPage: Page {\n override init(_ app: XCUIApplication) {\n super.init(app)\n self.pageElement = app.otherElements[.apiAccessView]\n waitForPageToBeShown()\n }\n\n @discardableResult func tapAddButton() -> Self {\n app.buttons[AccessibilityIdentifier.addAccessMethodButton]\n .tap()\n return self\n }\n\n func getAccessMethodCells() -> [XCUIElement] {\n app.otherElements[AccessibilityIdentifier.apiAccessView].cells.allElementsBoundByIndex\n }\n\n func getAccessMethodCell(accessibilityId: AccessibilityIdentifier) -> XCUIElement {\n app.otherElements[AccessibilityIdentifier.apiAccessView].cells[accessibilityId]\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Pages\APIAccessPage.swift
APIAccessPage.swift
Swift
892
0.95
0.03125
0.259259
react-lib
727
2024-07-17T18:53:38.266588
GPL-3.0
true
000017c239d3b4806e3e41375a18d1b5
//\n// AppLogsPage.swift\n// MullvadVPNUITests\n//\n// Created by Niklas Berglund on 2024-04-26.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport XCTest\n\nclass AppLogsPage: Page {\n override init(_ app: XCUIApplication) {\n super.init(app)\n self.pageElement = app.otherElements[.appLogsView]\n waitForPageToBeShown()\n }\n\n @discardableResult func tapShareButton() -> Self {\n app.buttons[.appLogsShareButton].tap()\n return self\n }\n\n @discardableResult func tapDoneButton() -> Self {\n app.buttons[.appLogsDoneButton].tap()\n return self\n }\n\n func getAppLogText() -> String {\n guard let logText = app.textViews[.problemReportAppLogsTextView].value as? String else {\n XCTFail("Failed to extract app log text")\n return String()\n }\n\n return logText\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Pages\AppLogsPage.swift
AppLogsPage.swift
Swift
879
0.95
0.027778
0.233333
react-lib
179
2024-01-29T13:41:07.277832
MIT
true
1413360432e9d4c006559e8cc47b1ff8
//\n// ChangeLogAlert.swift\n// MullvadVPNUITests\n//\n// Created by Niklas Berglund on 2024-02-20.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport XCTest\n\nclass ChangeLogAlert: Page {\n @discardableResult override init(_ app: XCUIApplication) {\n super.init(app)\n\n self.pageElement = app.otherElements[.changeLogAlert]\n waitForPageToBeShown()\n }\n\n @discardableResult func tapOkay() -> Self {\n app.buttons[AccessibilityIdentifier.alertOkButton].tap()\n return self\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Pages\ChangeLogAlert.swift
ChangeLogAlert.swift
Swift
553
0.95
0.041667
0.35
node-utils
119
2023-12-10T16:48:53.577045
Apache-2.0
true
0e22dcd5c84ecfc838c2efa74655848d
//\n// CustomListPage.swift\n// MullvadVPNUITests\n//\n// Created by Marco Nikic on 2024-04-17.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport XCTest\n\nclass CustomListPage: Page {\n @discardableResult override init(_ app: XCUIApplication) {\n super.init(app)\n\n self.pageElement = app.otherElements[.newCustomListView]\n waitForPageToBeShown()\n }\n\n @discardableResult func verifyCreateButtonIs(enabled: Bool) -> Self {\n let saveOrCreateButton = app.buttons[.saveCreateCustomListButton]\n XCTAssertTrue(saveOrCreateButton.isEnabled == enabled, "Verify state of create button")\n return self\n }\n\n @discardableResult func tapCreateListButton() -> Self {\n let saveOrCreateButton = app.buttons[.saveCreateCustomListButton]\n saveOrCreateButton.tap()\n return self\n }\n\n // It's the same button, the difference is just for semantics\n @discardableResult func tapSaveListButton() -> Self {\n tapCreateListButton()\n }\n\n @discardableResult func renameCustomList(name: String) -> Self {\n let editCustomListNameCell = app.cells[.customListEditNameFieldCell]\n // Activate the text field\n editCustomListNameCell.tap()\n // Select the entire text with a triple tap\n editCustomListNameCell.tap(withNumberOfTaps: 3, numberOfTouches: 1)\n // Tap the "delete" key on the on-screen keyboard, the case is sensitive.\n // However, on a simulator the keyboard isn't visible by default, so we\n // need to take that into consideration.\n if app.keys["delete"].isHittable {\n app.keys["delete"].tap()\n }\n editCustomListNameCell.typeText(name)\n return self\n }\n\n @discardableResult func deleteCustomList(named customListName: String) -> Self {\n let deleteCustomListCell = app.cells[.customListEditDeleteListCell]\n deleteCustomListCell.tap()\n app.buttons[.confirmDeleteCustomListButton].tap()\n return self\n }\n\n @discardableResult func addOrEditLocations() -> Self {\n app.cells[.customListEditAddOrEditLocationCell].tap()\n return self\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Pages\CustomListPage.swift
CustomListPage.swift
Swift
2,169
0.95
0.047619
0.240741
python-kit
888
2025-05-08T05:00:37.818361
Apache-2.0
true
184fb6e5df77b07ff5b093dcef87909b
//\n// DAITAPage.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-11-25.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport XCTest\n\nclass DAITAPage: Page {\n @discardableResult override init(_ app: XCUIApplication) {\n super.init(app)\n\n self.pageElement = app.otherElements[.daitaView]\n waitForPageToBeShown()\n }\n\n @discardableResult func tapBackButton() -> Self {\n // Workaround for setting accessibility identifier on navigation bar button being non-trivial\n app.buttons.matching(identifier: "Settings").allElementsBoundByIndex.last?.tap()\n return self\n }\n\n @discardableResult func tapEnableDirectOnlyDialogButtonIfPresent() -> Self {\n let buttonElement = app.buttons[AccessibilityIdentifier.daitaConfirmAlertEnableButton]\n if buttonElement.exists {\n buttonElement.tap()\n }\n return self\n }\n\n @discardableResult func verifyTwoPages() -> Self {\n XCTAssertEqual(app.pageIndicators.firstMatch.value as? String, "page 1 of 2")\n return self\n }\n\n @discardableResult func tapEnableSwitch() -> Self {\n app.switches[AccessibilityIdentifier.daitaSwitch].tap()\n return self\n }\n\n @discardableResult func tapEnableSwitchIfOn() -> Self {\n let switchElement = app.switches[AccessibilityIdentifier.daitaSwitch]\n\n if switchElement.value as? String == "1" {\n tapEnableSwitch()\n }\n return self\n }\n\n @discardableResult func tapEnableSwitchIfOff() -> Self {\n let switchElement = app.switches[AccessibilityIdentifier.daitaSwitch]\n\n if switchElement.value as? String == "0" {\n tapEnableSwitch()\n }\n return self\n }\n\n @discardableResult func verifyDirectOnlySwitchIsEnabled() -> Self {\n XCTAssertTrue(app.switches[AccessibilityIdentifier.daitaDirectOnlySwitch].isEnabled)\n return self\n }\n\n @discardableResult func verifyDirectOnlySwitchIsDisabled() -> Self {\n XCTAssertFalse(app.switches[AccessibilityIdentifier.daitaDirectOnlySwitch].isEnabled)\n return self\n }\n\n @discardableResult func tapDirectOnlySwitch() -> Self {\n app.switches[AccessibilityIdentifier.daitaDirectOnlySwitch].tap()\n return self\n }\n\n @discardableResult func tapDirectOnlySwitchIfOn() -> Self {\n let switchElement = app.switches[AccessibilityIdentifier.daitaDirectOnlySwitch]\n\n if switchElement.value as? String == "1" {\n tapDirectOnlySwitch()\n }\n return self\n }\n\n @discardableResult func tapDirectOnlySwitchIfOff() -> Self {\n let switchElement = app.switches[AccessibilityIdentifier.daitaDirectOnlySwitch]\n\n if switchElement.value as? String == "0" {\n tapDirectOnlySwitch()\n }\n return self\n }\n\n @discardableResult func verifyDirectOnlySwitchOn() -> Self {\n let switchElement = app.switches[AccessibilityIdentifier.daitaDirectOnlySwitch]\n\n guard let switchValue = switchElement.value as? String else {\n XCTFail("Failed to read switch state")\n return self\n }\n\n XCTAssertEqual(switchValue, "1")\n return self\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Pages\DAITAPage.swift
DAITAPage.swift
Swift
3,228
0.95
0.07619
0.095238
node-utils
696
2025-05-25T02:47:31.463643
BSD-3-Clause
true
2197c66ecd4dafd0697d1c52c1c03ced
//\n// DaitaPromptAlert.swift\n// MullvadVPNUITests\n//\n// Created by Mojgan on 2024-08-15.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\nimport Foundation\nimport XCTest\n\nclass DaitaPromptAlert: Page {\n @discardableResult override init(_ app: XCUIApplication) {\n super.init(app)\n\n self.pageElement = app.otherElements[.daitaPromptAlert]\n waitForPageToBeShown()\n }\n\n @discardableResult func tapEnableAnyway() -> Self {\n app.buttons[AccessibilityIdentifier.daitaConfirmAlertEnableButton].tap()\n return self\n }\n\n @discardableResult func tapBack() -> Self {\n app.buttons[AccessibilityIdentifier.daitaConfirmAlertBackButton].tap()\n return self\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Pages\DaitaPromptAlert.swift
DaitaPromptAlert.swift
Swift
727
0.95
0.035714
0.291667
vue-tools
647
2024-05-18T14:40:43.456165
GPL-3.0
true
75e1f59624f6f7f1cb5dcd8bf29ad812
//\n// DeviceManagementPage.swift\n// MullvadVPNUITests\n//\n// Created by Niklas Berglund on 2024-03-27.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport XCTest\n\n/// Page class for the "too many devices" page shown when logging on to an account with too many devices\nclass DeviceManagementPage: Page {\n override init(_ app: XCUIApplication) {\n super.init(app)\n\n self.pageElement = app.otherElements[.deviceManagementView]\n waitForPageToBeShown()\n }\n\n @discardableResult func tapRemoveDeviceButton(cellIndex: Int) -> Self {\n app\n .otherElements.matching(identifier: AccessibilityIdentifier.deviceCell.asString).element(boundBy: cellIndex)\n .buttons[AccessibilityIdentifier.deviceCellRemoveButton]\n .tap()\n\n return self\n }\n\n @discardableResult func tapContinueWithLoginButton() -> Self {\n app.buttons[AccessibilityIdentifier.continueWithLoginButton].tap()\n return self\n }\n}\n\n/// Confirmation alert displayed when removing a device\nclass DeviceManagementLogOutDeviceConfirmationAlert: Page {\n override init(_ app: XCUIApplication) {\n super.init(app)\n self.pageElement = app.otherElements[.alertContainerView]\n waitForPageToBeShown()\n }\n\n @discardableResult func tapYesLogOutDeviceButton() -> Self {\n app.buttons[AccessibilityIdentifier.logOutDeviceConfirmButton]\n .tap()\n return self\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Pages\DeviceManagementPage.swift
DeviceManagementPage.swift
Swift
1,465
0.95
0.083333
0.225
vue-tools
556
2024-03-09T13:15:13.788899
MIT
true
08b08acb91b6e0aa69b238abdcd84153
//\n// DNSSettingsPage.swift\n// MullvadVPNUITests\n//\n// Created by Niklas Berglund on 2024-03-19.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport XCTest\n\nclass DNSSettingsPage: Page {\n @discardableResult override init(_ app: XCUIApplication) {\n super.init(app)\n\n self.pageElement = app.tables[.dnsSettingsTableView]\n waitForPageToBeShown()\n }\n\n private func assertSwitchOn(accessibilityIdentifier: AccessibilityIdentifier) -> Self {\n let switchElement = app.cells[accessibilityIdentifier]\n .switches[AccessibilityIdentifier.customSwitch]\n\n guard let switchValue = switchElement.value as? String else {\n XCTFail("Failed to read switch state")\n return self\n }\n\n XCTAssertEqual(switchValue, "1")\n\n return self\n }\n\n @discardableResult func tapBackButton() -> Self {\n // Workaround for setting accessibility identifier on navigation bar button being non-trivial\n app.buttons.matching(identifier: "VPN settings").allElementsBoundByIndex.last?.tap()\n return self\n }\n\n @discardableResult func tapDNSContentBlockersHeaderExpandButton() -> Self {\n let headerView = app.otherElements[AccessibilityIdentifier.dnsContentBlockersHeaderView]\n let expandButton = headerView.buttons[AccessibilityIdentifier.expandButton]\n expandButton.tap()\n\n return self\n }\n\n @discardableResult func tapUseCustomDNSSwitch() -> Self {\n app.cells[AccessibilityIdentifier.dnsSettingsUseCustomDNSCell]\n .switches[AccessibilityIdentifier.customSwitch]\n .tap()\n\n return self\n }\n\n @discardableResult func tapBlockAdsSwitch() -> Self {\n app.cells[AccessibilityIdentifier.blockAdvertising]\n .switches[AccessibilityIdentifier.customSwitch]\n .tap()\n\n return self\n }\n\n @discardableResult func tapBlockAdsSwitchIfOn() -> Self {\n let blockAdsSwitch = app.cells[AccessibilityIdentifier.blockAdvertising]\n .switches[AccessibilityIdentifier.customSwitch]\n\n if blockAdsSwitch.value as? String == "1" {\n tapBlockAdsSwitch()\n }\n return self\n }\n\n @discardableResult func tapBlockTrackerSwitch() -> Self {\n app.cells[AccessibilityIdentifier.blockTracking]\n .switches[AccessibilityIdentifier.customSwitch]\n .tap()\n\n return self\n }\n\n @discardableResult func tapBlockMalwareSwitch() -> Self {\n app.cells[AccessibilityIdentifier.blockMalware]\n .switches[AccessibilityIdentifier.customSwitch]\n .tap()\n\n return self\n }\n\n @discardableResult func tapBlockAdultContentSwitch() -> Self {\n app.cells[AccessibilityIdentifier.blockAdultContent]\n .switches[AccessibilityIdentifier.customSwitch]\n .tap()\n\n return self\n }\n\n @discardableResult func tapBlockGamblingSwitch() -> Self {\n app.cells[AccessibilityIdentifier.blockGambling]\n .switches[AccessibilityIdentifier.customSwitch]\n .tap()\n\n return self\n }\n\n @discardableResult func tapBlockSocialMediaSwitch() -> Self {\n app.cells[AccessibilityIdentifier.blockSocialMedia]\n .switches[AccessibilityIdentifier.customSwitch]\n .tap()\n\n return self\n }\n\n @discardableResult func tapEditButton() -> Self {\n app.buttons[AccessibilityIdentifier.dnsSettingsEditButton]\n .tap()\n return self\n }\n\n @discardableResult func tapDoneButton() -> Self {\n return self.tapEditButton()\n }\n\n @discardableResult func tapAddAServer() -> Self {\n app.cells[AccessibilityIdentifier.dnsSettingsAddServerCell]\n .tap()\n return self\n }\n\n @discardableResult func tapEnterIPAddressTextField() -> Self {\n app.textFields[AccessibilityIdentifier.dnsSettingsEnterIPAddressTextField]\n .tap()\n return self\n }\n\n @discardableResult func verifyBlockAdsSwitchOn() -> Self {\n return assertSwitchOn(accessibilityIdentifier: .blockAdvertising)\n }\n\n @discardableResult func verifyBlockTrackerSwitchOn() -> Self {\n return assertSwitchOn(accessibilityIdentifier: .blockTracking)\n }\n\n @discardableResult func verifyBlockMalwareSwitchOn() -> Self {\n return assertSwitchOn(accessibilityIdentifier: .blockMalware)\n }\n\n @discardableResult func verifyBlockAdultContentSwitchOn() -> Self {\n return assertSwitchOn(accessibilityIdentifier: .blockAdultContent)\n }\n\n @discardableResult func verifyBlockGamblingSwitchOn() -> Self {\n return assertSwitchOn(accessibilityIdentifier: .blockGambling)\n }\n\n @discardableResult func verifyBlockSocialMediaSwitchOn() -> Self {\n return assertSwitchOn(accessibilityIdentifier: .blockSocialMedia)\n }\n\n @discardableResult func verifyUseCustomDNSSwitchOn() -> Self {\n return assertSwitchOn(accessibilityIdentifier: .dnsSettingsUseCustomDNSCell)\n }\n\n /// Verify that the UI shows stored DNS server IP address same as `ipAddress`. Note that this function assumes there is only one custom DNS server IP address stored.\n @discardableResult func verifyCustomDNSIPAddress(_ ipAddress: String) -> Self {\n let textField = app.textFields[AccessibilityIdentifier.dnsSettingsEnterIPAddressTextField]\n\n guard let settingIPAddress = textField.value as? String else {\n XCTFail("Failed to read configured DNS IP address")\n return self\n }\n\n XCTAssertEqual(ipAddress, settingIPAddress)\n return self\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Pages\DNSSettingsPage.swift
DNSSettingsPage.swift
Swift
5,658
0.95
0.028409
0.066176
vue-tools
788
2024-06-14T09:56:20.486970
BSD-3-Clause
true
6e2f7cffefa0a750a83df3570c1581bf
//\n// EditAccessMethodPage.swift\n// MullvadVPNUITests\n//\n// Created by Niklas Berglund on 2024-04-10.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport XCTest\n\nclass EditAccessMethodPage: Page {\n enum TestStatus {\n case reachable, unreachable, testing\n }\n\n override init(_ app: XCUIApplication) {\n super.init(app)\n self.pageElement = app.tables[.editAccessMethodView]\n waitForPageToBeShown()\n }\n\n @discardableResult func tapEnableMethodSwitch() -> Self {\n app.switches[AccessibilityIdentifier.accessMethodEnableSwitch].tap()\n return self\n }\n\n @discardableResult func tapEnableMethodSwitchIfOff() -> Self {\n let enableMethodSwitch = app.switches[AccessibilityIdentifier.accessMethodEnableSwitch]\n\n if enableMethodSwitch.value as? String == "0" {\n tapEnableMethodSwitch()\n }\n\n return self\n }\n\n @discardableResult func verifyTestStatus(_ status: TestStatus) -> Self {\n switch status {\n case .reachable:\n XCTAssertTrue(app.staticTexts["API reachable"].waitForExistence(timeout: BaseUITestCase.longTimeout))\n case .unreachable:\n XCTAssertTrue(app.staticTexts["API unreachable"].waitForExistence(timeout: BaseUITestCase.longTimeout))\n case .testing:\n XCTAssertTrue(app.staticTexts["Testing..."].waitForExistence(timeout: BaseUITestCase.longTimeout))\n }\n\n return self\n }\n\n @discardableResult func tapTestMethodButton() -> Self {\n app.buttons[AccessibilityIdentifier.accessMethodTestButton].tap()\n return self\n }\n\n @discardableResult func tapBackButton() -> Self {\n // Workaround due to the way automatically managed back buttons work. Back button needs to be nil for the automatic back button behaviour in iOS, and since its nil we cannot set accessibilityIdentifier for it\n let backButton = app.navigationBars.firstMatch.buttons.firstMatch\n backButton.tap()\n return self\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Pages\EditAccessMethodPage.swift
EditAccessMethodPage.swift
Swift
2,051
0.95
0.080645
0.156863
awesome-app
121
2023-08-21T00:11:33.552271
MIT
true
50cc847bf4b78e12535e1d40370caf87
//\n// EditCustomListLocationsPage.swift\n// MullvadVPNUITests\n//\n// Created by Marco Nikic on 2024-04-19.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport XCTest\n\nclass EditCustomListLocationsPage: Page {\n enum Action {\n case add, edit\n }\n\n @discardableResult override init(_ app: XCUIApplication) {\n super.init(app)\n\n self.pageElement = app.otherElements[.editCustomListEditLocationsView]\n waitForPageToBeShown()\n }\n\n @discardableResult func scrollToLocationWith(identifier: String) -> Self {\n let tableView = app.tables[.editCustomListEditLocationsTableView]\n tableView.cells[identifier].tap()\n return self\n }\n\n @discardableResult func toggleLocationCheckmarkWith(identifier: String) -> Self {\n let locationCell = app.tables[.editCustomListEditLocationsTableView].cells[identifier]\n locationCell.buttons[.customListLocationCheckmarkButton].tap()\n return self\n }\n\n @discardableResult func unfoldLocationwith(identifier: String) -> Self {\n let locationCell = app.tables[.editCustomListEditLocationsTableView].cells[identifier]\n let expandCellButton = locationCell.buttons["expandButton"]\n if expandCellButton.exists {\n expandCellButton.tap()\n }\n return self\n }\n\n @discardableResult func collapseLocationwith(identifier: String) -> Self {\n let locationCell = app.tables[.editCustomListEditLocationsTableView].cells[identifier]\n let collapseCellButton = locationCell.buttons["collapseButton"]\n if collapseCellButton.exists {\n collapseCellButton.tap()\n }\n return self\n }\n\n @discardableResult func tapBackButton() -> Self {\n app.navigationBars["Edit locations"].buttons.firstMatch.tap()\n return self\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Pages\EditCustomListLocationsPage.swift
EditCustomListLocationsPage.swift
Swift
1,842
0.95
0.052632
0.145833
python-kit
473
2024-01-22T00:33:17.581989
MIT
true
8c668495c027bc761d2fd3cae5a2313a
//\n// HeaderBar.swift\n// MullvadVPNUITests\n//\n// Created by Niklas Berglund on 2024-01-23.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport XCTest\n\nclass HeaderBar: Page {\n lazy var accountButton = app.buttons[AccessibilityIdentifier.accountButton]\n lazy var settingsButton = app.buttons[AccessibilityIdentifier.settingsButton]\n\n @discardableResult override init(_ app: XCUIApplication) {\n super.init(app)\n\n self.pageElement = app.otherElements[.headerBarView]\n waitForPageToBeShown()\n }\n\n @discardableResult func tapAccountButton() -> Self {\n accountButton.tap()\n return self\n }\n\n @discardableResult func tapSettingsButton() -> Self {\n settingsButton.tap()\n return self\n }\n\n @discardableResult public func verifyDeviceLabelShown() -> Self {\n XCTAssertTrue(\n app.staticTexts[AccessibilityIdentifier.headerDeviceNameLabel]\n .waitForExistence(timeout: BaseUITestCase.defaultTimeout), "Device name displayed in header"\n )\n\n return self\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Pages\HeaderBar.swift
HeaderBar.swift
Swift
1,106
0.95
0.02439
0.212121
python-kit
506
2023-12-07T01:10:52.037978
Apache-2.0
true
8ee6d6242fe0f31fd2976f3b412217cf
//\n// ListCustomListsPage.swift\n// MullvadVPNUITests\n//\n// Created by Marco Nikic on 2024-04-18.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport XCTest\n\nclass ListCustomListsPage: Page {\n @discardableResult override init(_ app: XCUIApplication) {\n super.init(app)\n\n self.pageElement = app.otherElements[.listCustomListsView]\n waitForPageToBeShown()\n }\n\n /// This function taps on a given custom list in the Edit Custom List page.\n ///\n /// This functions assumes that all the custom lists are visible on a single page\n /// No scrolling will be attempted to scroll to find a custom list\n /// - Parameter customListName: The custom list to edit\n @discardableResult func selectCustomListToEdit(named customListName: String) -> Self {\n app.tables[.listCustomListsTableView].staticTexts[customListName].tap()\n return self\n }\n\n @discardableResult func tapDoneButton() -> Self {\n app.buttons[.listCustomListDoneButton].tap()\n return self\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Pages\ListCustomListsPage.swift
ListCustomListsPage.swift
Swift
1,043
0.95
0.060606
0.428571
python-kit
639
2024-04-21T23:34:31.962243
GPL-3.0
true
cbb5b2b33190f6e4028f204be3cc5c30
//\n// LoginPage.swift\n// MullvadVPNUITests\n//\n// Created by Niklas Berglund on 2024-01-10.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport XCTest\n\nclass LoginPage: Page {\n @discardableResult override init(_ app: XCUIApplication) {\n super.init(app)\n\n self.pageElement = app.otherElements[.loginView]\n waitForPageToBeShown()\n }\n\n @discardableResult public func tapAccountNumberTextField() -> Self {\n app.textFields[AccessibilityIdentifier.loginTextField].tap()\n return self\n }\n\n @discardableResult public func waitForAccountNumberSubmitButton() -> Self {\n let submitButtonExist = app.buttons[AccessibilityIdentifier.loginTextFieldButton]\n .waitForExistence(timeout: BaseUITestCase.defaultTimeout)\n XCTAssertTrue(submitButtonExist, "Account number submit button shown")\n return self\n }\n\n @discardableResult public func tapAccountNumberSubmitButton() -> Self {\n app.buttons[AccessibilityIdentifier.loginTextFieldButton].tap()\n return self\n }\n\n @discardableResult public func tapCreateAccountButton() -> Self {\n app.buttons[AccessibilityIdentifier.createAccountButton].tap()\n return self\n }\n\n @discardableResult public func verifySuccessIconShown() -> Self {\n // Success icon is only shown very briefly, since another view is presented after success icon is shown.\n // Therefore we need to poll faster than waitForElement function.\n let successIconDisplayedExpectation = XCTestExpectation(description: "Success icon shown")\n let timer = Timer.scheduledTimer(withTimeInterval: 0.2, repeats: true) { [self] _ in\n let statusImageView = self.app.images[.statusImageView]\n\n if statusImageView.exists {\n if statusImageView.value as? String == "success" {\n successIconDisplayedExpectation.fulfill()\n }\n }\n }\n\n let waitResult = XCTWaiter.wait(for: [successIconDisplayedExpectation], timeout: BaseUITestCase.longTimeout)\n XCTAssertEqual(waitResult, .completed, "Success icon shown")\n timer.invalidate()\n\n return self\n }\n\n @discardableResult public func verifyFailIconShown() -> Self {\n let predicate = NSPredicate(format: "identifier == 'statusImageView' AND value == 'fail'")\n let elementQuery = app.images.containing(predicate)\n let elementExists = elementQuery.firstMatch.waitForExistence(timeout: BaseUITestCase.longTimeout)\n XCTAssertTrue(elementExists, "Fail icon shown")\n return self\n }\n\n /// Checks whether success icon is being shown\n func getSuccessIconShown() -> Bool {\n let predicate = NSPredicate(format: "identifier == 'statusImageView' AND value == 'success'")\n let elementQuery = app.images.containing(predicate)\n let elementExists = elementQuery.firstMatch.waitForExistence(timeout: BaseUITestCase.defaultTimeout)\n return elementExists\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Pages\LoginPage.swift
LoginPage.swift
Swift
3,041
0.95
0.064103
0.153846
node-utils
760
2024-01-30T23:59:36.403129
Apache-2.0
true
96fe8a462b15095779e63f003f03e93d
//\n// MultihopPage.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-11-25.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport XCTest\n\nclass MultihopPage: Page {\n @discardableResult override init(_ app: XCUIApplication) {\n super.init(app)\n\n self.pageElement = app.otherElements[.multihopView]\n waitForPageToBeShown()\n }\n\n @discardableResult func tapBackButton() -> Self {\n // Workaround for setting accessibility identifier on navigation bar button being non-trivial\n app.buttons.matching(identifier: "Settings").allElementsBoundByIndex.last?.tap()\n return self\n }\n\n @discardableResult func verifyOnePage() -> Self {\n XCTAssertEqual(app.pageIndicators.firstMatch.value as? String, "page 1 of 1")\n return self\n }\n\n @discardableResult func tapEnableSwitch() -> Self {\n app.switches[AccessibilityIdentifier.multihopSwitch].tap()\n return self\n }\n\n @discardableResult func tapEnableSwitchIfOn() -> Self {\n let switchElement = app.switches[AccessibilityIdentifier.multihopSwitch]\n\n if switchElement.value as? String == "1" {\n tapEnableSwitch()\n }\n return self\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Pages\MultihopPage.swift
MultihopPage.swift
Swift
1,229
0.95
0.069767
0.228571
react-lib
923
2024-07-28T03:00:39.636034
BSD-3-Clause
true
80fa7640a24a630711da10021464f1c7
//\n// OutOfTimePage.swift\n// MullvadVPNUITests\n//\n// Created by Niklas Berglund on 2024-02-20.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport XCTest\n\nclass OutOfTimePage: Page {\n @discardableResult override init(_ app: XCUIApplication) {\n super.init(app)\n\n self.pageElement = app.otherElements[.outOfTimeView]\n waitForPageToBeShown()\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Pages\OutOfTimePage.swift
OutOfTimePage.swift
Swift
410
0.95
0.052632
0.4375
node-utils
264
2025-05-18T02:34:03.646696
MIT
true
6d0cf0881b0ce0b3269f013fba5529db
//\n// Page.swift\n// MullvadVPNUITests\n//\n// Created by Niklas Berglund on 2024-01-10.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport XCTest\n\nclass Page {\n let app: XCUIApplication\n\n /// Element in the page used to verify that the page is currently being shown, usually accessibilityIdentifier of the view controller's main view\n var pageElement: XCUIElement?\n\n @discardableResult init(_ app: XCUIApplication) {\n self.app = app\n }\n\n func waitForPageToBeShown() {\n if let pageElement {\n XCTAssertTrue(\n pageElement.waitForExistence(timeout: BaseUITestCase.defaultTimeout),\n "Page is shown"\n )\n }\n }\n\n @discardableResult func enterText(_ text: String) -> Self {\n app.typeText(text)\n return self\n }\n\n @discardableResult func dismissKeyboard() -> Self {\n self.enterText("\n")\n return self\n }\n\n /// Fast swipe down action to dismiss a modal view. Will swipe on the middle of the screen.\n @discardableResult func swipeDownToDismissModal() -> Self {\n app.swipeDown(velocity: .fast)\n return self\n }\n\n @discardableResult func tapKeyboardDoneButton() -> Self {\n app.toolbars.buttons["Done"].tap()\n return self\n }\n\n @discardableResult func tapWhereStatusBarShouldBeToScrollToTopMostPosition() -> Self {\n // Tapping but not at center x coordinate because on iPad there's an ellipsis button in the center of the status bar\n app.coordinate(withNormalizedOffset: CGVector(dx: 0.75, dy: 0)).tap()\n return self\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Pages\Page.swift
Page.swift
Swift
1,646
0.95
0.035088
0.212766
python-kit
398
2024-12-11T11:03:51.440652
MIT
true
c094548b2907d3e42f8d4a5e75573bb5
//\n// ProblemReportPage.swift\n// MullvadVPNUITests\n//\n// Created by Niklas Berglund on 2024-01-26.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport XCTest\n\nclass ProblemReportPage: Page {\n @discardableResult override init(_ app: XCUIApplication) {\n super.init(app)\n\n self.pageElement = app.otherElements[.problemReportView]\n waitForPageToBeShown()\n }\n\n @discardableResult func tapEmailTextField() -> Self {\n app.textFields[AccessibilityIdentifier.problemReportEmailTextField]\n .tap()\n\n return self\n }\n\n @discardableResult func tapMessageTextView() -> Self {\n app.textViews[AccessibilityIdentifier.problemReportMessageTextView]\n .tap()\n\n return self\n }\n\n @discardableResult func tapViewAppLogsButton() -> Self {\n app.buttons[AccessibilityIdentifier.problemReportAppLogsButton]\n .tap()\n\n return self\n }\n\n @discardableResult func tapSendButton() -> Self {\n app.buttons[AccessibilityIdentifier.problemReportSendButton]\n .tap()\n\n return self\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Pages\ProblemReportPage.swift
ProblemReportPage.swift
Swift
1,135
0.95
0.021277
0.194444
react-lib
728
2025-02-28T15:38:22.641104
BSD-3-Clause
true
59bfdd07b511b326727111f014cacc34
//\n// ProblemReportSubmittedPage.swift\n// MullvadVPNUITests\n//\n// Created by Niklas Berglund on 2024-02-26.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport XCTest\n\nclass ProblemReportSubmittedPage: Page {\n @discardableResult override init(_ app: XCUIApplication) {\n super.init(app)\n\n self.pageElement = app.otherElements[.problemReportSubmittedView]\n waitForPageToBeShown()\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Pages\ProblemReportSubmittedPage.swift
ProblemReportSubmittedPage.swift
Swift
449
0.95
0.052632
0.4375
awesome-app
453
2024-02-09T11:15:28.776907
Apache-2.0
true
57a463f1d3ccce6b36cd41b0df77f2d3
//\n// RevokedDevicePage.swift\n// MullvadVPNUITests\n//\n// Created by Niklas Berglund on 2024-03-08.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport XCTest\n\nclass RevokedDevicePage: Page {\n @discardableResult override init(_ app: XCUIApplication) {\n super.init(app)\n\n self.pageElement = app.otherElements[.revokedDeviceView]\n waitForPageToBeShown()\n }\n\n @discardableResult func tapGoToLogin() -> Self {\n app.buttons[AccessibilityIdentifier.revokedDeviceLoginButton]\n .tap()\n\n return self\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Pages\RevokedDevicePage.swift
RevokedDevicePage.swift
Swift
592
0.95
0.038462
0.333333
python-kit
730
2025-03-29T05:55:45.463934
MIT
true
57b957bfe608e6c0483b34d2338af9c9
//\n// SelectLocationFilterPage.swift\n// MullvadVPNUITests\n//\n// Created by Niklas Berglund on 2024-04-17.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport XCTest\n\nclass SelectLocationFilterPage: Page {\n override init(_ app: XCUIApplication) {\n super.init(app)\n }\n\n @discardableResult func tapOwnershipCellExpandButton() -> Self {\n app.otherElements[AccessibilityIdentifier.locationFilterOwnershipHeaderCell]\n .buttons[AccessibilityIdentifier.expandButton].tap()\n return self\n }\n\n @discardableResult func tapProvidersCellExpandButton() -> Self {\n app.otherElements[AccessibilityIdentifier.locationFilterProvidersHeaderCell]\n .buttons[AccessibilityIdentifier.expandButton].tap()\n return self\n }\n\n @discardableResult func tapAnyOwnershipCell() -> Self {\n app.cells[AccessibilityIdentifier.ownershipAnyCell].tap()\n return self\n }\n\n @discardableResult func tapMullvadOwnershipCell() -> Self {\n app.cells[AccessibilityIdentifier.ownershipMullvadOwnedCell].tap()\n return self\n }\n\n @discardableResult func tapRentedOwnershipCell() -> Self {\n app.cells[AccessibilityIdentifier.ownershipRentedCell].tap()\n return self\n }\n\n @discardableResult func tapApplyButton() -> Self {\n app.buttons[AccessibilityIdentifier.applyButton].tap()\n return self\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Pages\SelectLocationFilterPage.swift
SelectLocationFilterPage.swift
Swift
1,435
0.95
0.020833
0.175
awesome-app
925
2025-07-02T15:16:28.031121
MIT
true
6915aa8e19aa04498644878af3bd6563
//\n// SelectLocationPage.swift\n// MullvadVPNUITests\n//\n// Created by Niklas Berglund on 2024-01-11.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport XCTest\n\nclass SelectLocationPage: Page {\n @discardableResult override init(_ app: XCUIApplication) {\n super.init(app)\n\n self.pageElement = app.otherElements[.selectLocationView]\n waitForPageToBeShown()\n }\n\n @discardableResult func tapLocationCell(withName name: String) -> Self {\n app.tables[AccessibilityIdentifier.selectLocationTableView].cells.staticTexts[name].tap()\n return self\n }\n\n @discardableResult func tapCountryLocationCellExpandButton(withName name: String) -> Self {\n let cell = app.cells.containing(.any, identifier: name)\n let expandButton = cell.buttons[AccessibilityIdentifier.expandButton]\n expandButton.tap()\n return self\n }\n\n @discardableResult func tapCountryLocationCellExpandButton(withIndex: Int) -> Self {\n let cell = app.cells.containing(.any, identifier: AccessibilityIdentifier.countryLocationCell.asString)\n .element(boundBy: withIndex)\n let expandButton = cell.buttons[AccessibilityIdentifier.expandButton]\n expandButton.tap()\n return self\n }\n\n @discardableResult func tapCityLocationCellExpandButton(withIndex: Int) -> Self {\n let cell = app.cells.containing(.any, identifier: AccessibilityIdentifier.cityLocationCell.asString)\n .element(boundBy: withIndex)\n let expandButton = cell.buttons[AccessibilityIdentifier.expandButton]\n expandButton.tap()\n return self\n }\n\n @discardableResult func tapRelayLocationCell(withIndex: Int) -> Self {\n let cell = app.cells.containing(.any, identifier: AccessibilityIdentifier.relayLocationCell.asString)\n .element(boundBy: withIndex)\n cell.tap()\n return self\n }\n\n @discardableResult func tapLocationCellExpandButton(withName name: String) -> Self {\n let table = app.tables[AccessibilityIdentifier.selectLocationTableView]\n let matchingCells = table.cells.containing(.any, identifier: name)\n let buttons = matchingCells.buttons\n let expandButton = buttons[AccessibilityIdentifier.expandButton]\n\n expandButton.tap()\n\n return self\n }\n\n @discardableResult func tapLocationCellCollapseButton(withName name: String) -> Self {\n let table = app.tables[AccessibilityIdentifier.selectLocationTableView]\n let matchingCells = table.cells.containing(.any, identifier: name)\n let buttons = matchingCells.buttons\n let collapseButton = buttons[AccessibilityIdentifier.collapseButton]\n\n collapseButton.tap()\n\n return self\n }\n\n @discardableResult func tapCustomListEllipsisButton() -> Self {\n // This wait should not be needed, but is due to the issues we are having with the ellipsis button\n _ = app.buttons[.openCustomListsMenuButton].waitForExistence(timeout: BaseUITestCase.shortTimeout)\n\n let customListEllipsisButtons = app.buttons\n .matching(identifier: AccessibilityIdentifier.openCustomListsMenuButton.asString).allElementsBoundByIndex\n\n // This is a workaround for an issue we have with the ellipsis showing up multiple times in the accessibility hieararchy even though in the view hierarchy there is only one\n // Only the actually visual one is hittable, so only the visible button will be tapped\n for ellipsisButton in customListEllipsisButtons where ellipsisButton.isHittable {\n ellipsisButton.tap()\n return self\n }\n\n XCTFail("Found no hittable custom list ellipsis button")\n\n return self\n }\n\n @discardableResult func tapAddNewCustomList() -> Self {\n let addNewCustomListButton = app.buttons[AccessibilityIdentifier.addNewCustomListButton]\n addNewCustomListButton.tap()\n return self\n }\n\n @discardableResult func editExistingCustomLists() -> Self {\n let editCustomListsButton = app.buttons[AccessibilityIdentifier.editCustomListButton]\n editCustomListsButton.tap()\n return self\n }\n\n @discardableResult func cellWithIdentifier(identifier: String) -> XCUIElement {\n app.tables[AccessibilityIdentifier.selectLocationTableView].cells[identifier]\n }\n\n @discardableResult func tapFilterButton() -> Self {\n app.buttons[AccessibilityIdentifier.selectLocationFilterButton].tap()\n return self\n }\n\n @discardableResult func tapDoneButton() -> Self {\n app.buttons[AccessibilityIdentifier.closeSelectLocationButton].tap()\n return self\n }\n\n func locationCellIsExpanded(_ name: String) -> Bool {\n let matchingCells = app.cells.containing(.any, identifier: name)\n return matchingCells.buttons[AccessibilityIdentifier.expandButton].exists ? false : true\n }\n\n func verifyEditCustomListsButtonIs(enabled: Bool) {\n let editCustomListsButton = app.buttons[AccessibilityIdentifier.editCustomListButton]\n XCTAssertTrue(editCustomListsButton.isEnabled == enabled)\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Pages\SelectLocationPage.swift
SelectLocationPage.swift
Swift
5,152
0.95
0.022901
0.095238
python-kit
945
2025-05-14T20:45:55.144522
GPL-3.0
true
eb2bcf9b60e3fbd707b680a845d10da9
//\n// SettingsPage.swift\n// MullvadVPNUITests\n//\n// Created by Niklas Berglund on 2024-01-12.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport XCTest\n\nclass SettingsPage: Page {\n @discardableResult override init(_ app: XCUIApplication) {\n super.init(app)\n\n self.pageElement = app.otherElements[.settingsContainerView]\n waitForPageToBeShown()\n }\n\n @discardableResult func tapDoneButton() -> Self {\n app.buttons[AccessibilityIdentifier.settingsDoneButton]\n .tap()\n\n return self\n }\n\n @discardableResult func tapAPIAccessCell() -> Self {\n app\n .cells[AccessibilityIdentifier.apiAccessCell]\n .tap()\n\n return self\n }\n\n @discardableResult func tapDAITACell() -> Self {\n app.tables[AccessibilityIdentifier.settingsTableView]\n .cells[AccessibilityIdentifier.daitaCell]\n .tap()\n\n return self\n }\n\n @discardableResult func verifyDAITAOn() -> Self {\n let textElement = app.tables[AccessibilityIdentifier.settingsTableView]\n .cells[AccessibilityIdentifier.daitaCell]\n .staticTexts["On"]\n\n XCTAssertTrue(textElement.exists)\n\n return self\n }\n\n @discardableResult func verifyDAITAOff() -> Self {\n let textElement = app.tables[AccessibilityIdentifier.settingsTableView]\n .cells[AccessibilityIdentifier.daitaCell]\n .staticTexts["Off"]\n\n XCTAssertTrue(textElement.exists)\n\n return self\n }\n\n @discardableResult func tapMultihopCell() -> Self {\n app.tables[AccessibilityIdentifier.settingsTableView]\n .cells[AccessibilityIdentifier.multihopCell]\n .tap()\n\n return self\n }\n\n @discardableResult func verifyMultihopOn() -> Self {\n let textElement = app.tables[AccessibilityIdentifier.settingsTableView]\n .cells[AccessibilityIdentifier.multihopCell]\n .staticTexts["On"]\n\n XCTAssertTrue(textElement.exists)\n\n return self\n }\n\n @discardableResult func verifyMultihopOff() -> Self {\n let textElement = app.tables[AccessibilityIdentifier.settingsTableView]\n .cells[AccessibilityIdentifier.multihopCell]\n .staticTexts["Off"]\n\n XCTAssertTrue(textElement.exists)\n\n return self\n }\n\n @discardableResult func tapVPNSettingsCell() -> Self {\n app.tables[AccessibilityIdentifier.settingsTableView]\n .cells[AccessibilityIdentifier.vpnSettingsCell]\n .tap()\n\n return self\n }\n\n @discardableResult func tapReportAProblemCell() -> Self {\n app.tables[AccessibilityIdentifier.settingsTableView]\n .cells[AccessibilityIdentifier.problemReportCell]\n .tap()\n\n return self\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Pages\SettingsPage.swift
SettingsPage.swift
Swift
2,830
0.95
0.009434
0.088608
python-kit
699
2023-12-03T09:00:11.415139
BSD-3-Clause
true
206826eef4366ff9d55afa9fa926cf47
//\n// ShadowsocksObfuscationSettingsPage.swift\n// MullvadVPN\n//\n// Created by Andrew Bulhak on 2024-12-18.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport XCTest\n\nclass ShadowsocksObfuscationSettingsPage: Page {\n @discardableResult override init(_ app: XCUIApplication) {\n super.init(app)\n }\n\n private var table: XCUIElement {\n app.collectionViews[AccessibilityIdentifier.wireGuardObfuscationShadowsocksTable]\n }\n\n private func portCell(_ index: Int) -> XCUIElement {\n table.cells.element(boundBy: index)\n }\n\n private var customCell: XCUIElement {\n // assumption: the last cell is the legend\n table.cells.allElementsBoundByIndex.dropLast().last!\n }\n\n private var customTextField: XCUIElement {\n customCell.textFields.firstMatch\n }\n\n @discardableResult func tapAutomaticPortCell() -> Self {\n portCell(0).tap()\n return self\n }\n\n @discardableResult func tapCustomCell() -> Self {\n customCell.tap()\n return self\n }\n\n @discardableResult func typeTextIntoCustomField(_ text: String) -> Self {\n customTextField.typeText(text)\n return self\n }\n\n @discardableResult func tapBackButton() -> Self {\n // Workaround for setting accessibility identifier on navigation bar button being non-trivial\n app.navigationBars.buttons.element(boundBy: 0).tap()\n return self\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Pages\ShadowsocksObfuscationSettingsPage.swift
ShadowsocksObfuscationSettingsPage.swift
Swift
1,456
0.95
0.037037
0.204545
python-kit
162
2024-04-06T07:50:17.423127
MIT
true
0a4b33c866f26e9f950d7be6511c0a7c
//\n// TermsOfServicePage.swift\n// MullvadVPNUITests\n//\n// Created by Niklas Berglund on 2024-01-10.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport XCTest\n\nclass TermsOfServicePage: Page {\n @discardableResult override init(_ app: XCUIApplication) {\n super.init(app)\n\n self.pageElement = app.otherElements[.termsOfServiceView]\n waitForPageToBeShown()\n }\n\n @discardableResult func tapAgreeButton() -> Self {\n app.buttons[AccessibilityIdentifier.agreeButton].tap()\n return self\n }\n}\n
dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPNUITests\Pages\TermsOfServicePage.swift
TermsOfServicePage.swift
Swift
570
0.95
0.041667
0.35
node-utils
802
2024-08-24T16:09:30.264647
BSD-3-Clause
true
883172a91e9178fd8efb409f3afffcac