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// TunnelSettingsStrategy.swift\n// MullvadSettings\n//\n// Created by Mojgan on 2024-08-09.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\npublic protocol TunnelSettingsStrategyProtocol: Sendable {\n func shouldReconnectToNewRelay(oldSettings: LatestTunnelSettings, newSettings: LatestTunnelSettings) -> Bool\n func getReconnectionStrategy(\n oldSettings: LatestTunnelSettings,\n newSettings: LatestTunnelSettings\n ) -> TunnelSettingsReconnectionStrategy\n}\n\npublic struct TunnelSettingsStrategy: TunnelSettingsStrategyProtocol, Sendable {\n public init() {}\n\n public func shouldReconnectToNewRelay(\n oldSettings: LatestTunnelSettings,\n newSettings: LatestTunnelSettings\n ) -> Bool {\n getReconnectionStrategy(\n oldSettings: oldSettings,\n newSettings: newSettings\n ) != .currentRelayReconnect\n }\n\n public func getReconnectionStrategy(\n oldSettings: LatestTunnelSettings,\n newSettings: LatestTunnelSettings\n ) -> TunnelSettingsReconnectionStrategy {\n if oldSettings.localNetworkSharing != newSettings.localNetworkSharing ||\n oldSettings.includeAllNetworks != newSettings.includeAllNetworks {\n return .hardReconnect\n }\n switch (oldSettings, newSettings) {\n case let (old, new) where old != new:\n return .newRelayReconnect\n default:\n return .currentRelayReconnect\n }\n }\n}\n\n/// This enum representes reconnection strategies.\n/// > Warning: `hardReconnect` will disconnect and reconnect which\n/// > potentially leads to traffic leaking outside the tunnel.\npublic enum TunnelSettingsReconnectionStrategy {\n case currentRelayReconnect\n case newRelayReconnect\n case hardReconnect\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\TunnelSettingsStrategy.swift | TunnelSettingsStrategy.swift | Swift | 1,808 | 0.95 | 0.036364 | 0.2 | vue-tools | 644 | 2025-01-20T03:42:58.236770 | BSD-3-Clause | false | 9720f5b54795a0b619aa45740a82626a |
//\n// TunnelSettingsUpdate.swift\n// MullvadSettings\n//\n// Created by Andrew Bulhak on 2024-02-13.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\n\npublic enum TunnelSettingsUpdate: Sendable {\n case localNetworkSharing(Bool)\n case includeAllNetworks(Bool)\n case dnsSettings(DNSSettings)\n case obfuscation(WireGuardObfuscationSettings)\n case relayConstraints(RelayConstraints)\n case quantumResistance(TunnelQuantumResistance)\n case multihop(MultihopState)\n case daita(DAITASettings)\n}\n\nextension TunnelSettingsUpdate {\n public func apply(to settings: inout LatestTunnelSettings) {\n switch self {\n case let .localNetworkSharing(enabled):\n settings.localNetworkSharing = enabled\n case let .includeAllNetworks(enabled):\n settings.includeAllNetworks = enabled\n case let .dnsSettings(newDNSSettings):\n settings.dnsSettings = newDNSSettings\n case let .obfuscation(newObfuscationSettings):\n settings.wireGuardObfuscation = newObfuscationSettings\n case let .relayConstraints(newRelayConstraints):\n settings.relayConstraints = newRelayConstraints\n case let .quantumResistance(newQuantumResistance):\n settings.tunnelQuantumResistance = newQuantumResistance\n case let .multihop(newState):\n settings.tunnelMultihopState = newState\n case let .daita(newDAITASettings):\n settings.daita = newDAITASettings\n }\n }\n\n public var subjectName: String {\n switch self {\n case .localNetworkSharing: "Local network sharing"\n case .includeAllNetworks: "Include all networks"\n case .dnsSettings: "DNS settings"\n case .obfuscation: "obfuscation settings"\n case .relayConstraints: "relay constraints"\n case .quantumResistance: "quantum resistance"\n case .multihop: "multihop"\n case .daita: "daita"\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\TunnelSettingsUpdate.swift | TunnelSettingsUpdate.swift | Swift | 1,994 | 0.95 | 0.035088 | 0.132075 | awesome-app | 198 | 2023-08-24T11:24:46.630179 | BSD-3-Clause | false | 9281b79e5b4fd5d217bfa8b630015d16 |
//\n// TunnelSettingsV1.swift\n// MullvadVPN\n//\n// Created by pronebird on 19/06/2019.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\nimport Network\nimport WireGuardKitTypes\n\n/// A struct that holds the configuration passed via `NETunnelProviderProtocol`.\npublic struct TunnelSettingsV1: Codable, Equatable, TunnelSettings {\n public var relayConstraints = RelayConstraints()\n public var interface = InterfaceSettings()\n\n public func upgradeToNextVersion() -> any TunnelSettings {\n TunnelSettingsV2(relayConstraints: relayConstraints, dnsSettings: interface.dnsSettings)\n }\n}\n\n/// A struct that holds a tun interface configuration.\npublic struct InterfaceSettings: Codable, Equatable, @unchecked Sendable {\n public var privateKey: PrivateKeyWithMetadata\n public var nextPrivateKey: PrivateKeyWithMetadata?\n\n public var addresses: [IPAddressRange]\n public var dnsSettings: DNSSettings\n\n private enum CodingKeys: String, CodingKey {\n case privateKey, nextPrivateKey, addresses, dnsSettings\n }\n\n public init(\n privateKey: PrivateKeyWithMetadata = PrivateKeyWithMetadata(),\n nextPrivateKey: PrivateKeyWithMetadata? = nil,\n addresses: [IPAddressRange] = [],\n dnsSettings: DNSSettings = DNSSettings()\n ) {\n self.privateKey = privateKey\n self.nextPrivateKey = nextPrivateKey\n self.addresses = addresses\n self.dnsSettings = dnsSettings\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n\n privateKey = try container.decode(PrivateKeyWithMetadata.self, forKey: .privateKey)\n addresses = try container.decode([IPAddressRange].self, forKey: .addresses)\n\n // Added in 2022.1\n nextPrivateKey = try container.decodeIfPresent(\n PrivateKeyWithMetadata.self,\n forKey: .nextPrivateKey\n )\n\n // Provide default value, since `dnsSettings` key does not exist in <= 2021.2\n dnsSettings = try container.decodeIfPresent(DNSSettings.self, forKey: .dnsSettings)\n ?? DNSSettings()\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n\n try container.encode(privateKey, forKey: .privateKey)\n try container.encode(nextPrivateKey, forKey: .nextPrivateKey)\n try container.encode(addresses, forKey: .addresses)\n try container.encode(dnsSettings, forKey: .dnsSettings)\n }\n}\n\n/// A struct holding a private WireGuard key with associated metadata\npublic struct PrivateKeyWithMetadata: Equatable, Codable {\n private enum CodingKeys: String, CodingKey {\n case privateKey = "privateKeyData", creationDate\n }\n\n /// When the key was created\n public let creationDate: Date\n\n /// Private key\n public let privateKey: PrivateKey\n\n /// Public key\n public var publicKey: PublicKey {\n privateKey.publicKey\n }\n\n /// Initialize the new private key\n public init() {\n privateKey = PrivateKey()\n creationDate = Date()\n }\n\n /// Initialize with the existing private key\n public init(privateKey: PrivateKey, createdAt: Date) {\n self.privateKey = privateKey\n creationDate = createdAt\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\TunnelSettingsV1.swift | TunnelSettingsV1.swift | Swift | 3,343 | 0.95 | 0.087379 | 0.202381 | python-kit | 229 | 2025-06-08T04:30:57.746417 | BSD-3-Clause | false | 53dd2aff244f05fe124f162032ff2c98 |
//\n// TunnelSettingsV2.swift\n// MullvadVPN\n//\n// Created by pronebird on 27/04/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\n\npublic struct TunnelSettingsV2: Codable, Equatable, TunnelSettings {\n /// Relay constraints.\n public var relayConstraints: RelayConstraints\n\n /// DNS settings.\n public var dnsSettings: DNSSettings\n\n public init(\n relayConstraints: RelayConstraints = RelayConstraints(),\n dnsSettings: DNSSettings = DNSSettings()\n ) {\n self.relayConstraints = relayConstraints\n self.dnsSettings = dnsSettings\n }\n\n public func upgradeToNextVersion() -> any TunnelSettings {\n TunnelSettingsV3(\n relayConstraints: relayConstraints,\n dnsSettings: dnsSettings,\n wireGuardObfuscation: WireGuardObfuscationSettings()\n )\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\TunnelSettingsV2.swift | TunnelSettingsV2.swift | Swift | 892 | 0.95 | 0 | 0.310345 | react-lib | 909 | 2025-05-21T22:32:38.566418 | Apache-2.0 | false | 1545bef66287a9521d852551c2afba2c |
//\n// TunnelSettingsV3.swift\n// MullvadVPN\n//\n// Created by Marco Nikic on 2023-10-17.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\n\npublic struct TunnelSettingsV3: Codable, Equatable, TunnelSettings {\n /// Relay constraints.\n public var relayConstraints: RelayConstraints\n\n /// DNS settings.\n public var dnsSettings: DNSSettings\n\n /// WireGuard obfuscation settings\n public var wireGuardObfuscation: WireGuardObfuscationSettings\n\n public init(\n relayConstraints: RelayConstraints = RelayConstraints(),\n dnsSettings: DNSSettings = DNSSettings(),\n wireGuardObfuscation: WireGuardObfuscationSettings = WireGuardObfuscationSettings()\n ) {\n self.relayConstraints = relayConstraints\n self.dnsSettings = dnsSettings\n self.wireGuardObfuscation = wireGuardObfuscation\n }\n\n public func upgradeToNextVersion() -> any TunnelSettings {\n TunnelSettingsV4(\n relayConstraints: relayConstraints,\n dnsSettings: dnsSettings,\n wireGuardObfuscation: wireGuardObfuscation,\n tunnelQuantumResistance: .automatic\n )\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\TunnelSettingsV3.swift | TunnelSettingsV3.swift | Swift | 1,189 | 0.95 | 0 | 0.294118 | vue-tools | 477 | 2024-06-26T00:30:11.849341 | MIT | false | 1c33dc04242054f6a60aa5445c338251 |
//\n// TunnelSettingsV4.swift\n// MullvadSettings\n//\n// Created by Marco Nikic on 2024-02-06.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\n\npublic struct TunnelSettingsV4: Codable, Equatable, TunnelSettings {\n /// Relay constraints.\n public var relayConstraints: RelayConstraints\n\n /// DNS settings.\n public var dnsSettings: DNSSettings\n\n /// WireGuard obfuscation settings\n public var wireGuardObfuscation: WireGuardObfuscationSettings\n\n /// Whether Post Quantum exchanges are enabled.\n public var tunnelQuantumResistance: TunnelQuantumResistance\n\n public init(\n relayConstraints: RelayConstraints = RelayConstraints(),\n dnsSettings: DNSSettings = DNSSettings(),\n wireGuardObfuscation: WireGuardObfuscationSettings = WireGuardObfuscationSettings(),\n tunnelQuantumResistance: TunnelQuantumResistance = .automatic\n ) {\n self.relayConstraints = relayConstraints\n self.dnsSettings = dnsSettings\n self.wireGuardObfuscation = wireGuardObfuscation\n self.tunnelQuantumResistance = tunnelQuantumResistance\n }\n\n public func upgradeToNextVersion() -> any TunnelSettings {\n TunnelSettingsV5(\n relayConstraints: relayConstraints,\n dnsSettings: dnsSettings,\n wireGuardObfuscation: wireGuardObfuscation,\n tunnelQuantumResistance: tunnelQuantumResistance,\n tunnelMultihopState: .off\n )\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\TunnelSettingsV4.swift | TunnelSettingsV4.swift | Swift | 1,497 | 0.95 | 0 | 0.282051 | react-lib | 486 | 2024-09-08T15:49:30.913094 | GPL-3.0 | false | bade878dba773624ddb6eba4b2960818 |
//\n// TunnelSettingsV5.swift\n// MullvadSettings\n//\n// Created by Mojgan on 2024-05-13.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\n\npublic struct TunnelSettingsV5: Codable, Equatable, TunnelSettings {\n /// Relay constraints.\n public var relayConstraints: RelayConstraints\n\n /// DNS settings.\n public var dnsSettings: DNSSettings\n\n /// WireGuard obfuscation settings\n public var wireGuardObfuscation: WireGuardObfuscationSettings\n\n /// Whether Post Quantum exchanges are enabled.\n public var tunnelQuantumResistance: TunnelQuantumResistance\n\n /// Whether Multi-hop is enabled.\n public var tunnelMultihopState: MultihopState\n\n public init(\n relayConstraints: RelayConstraints = RelayConstraints(),\n dnsSettings: DNSSettings = DNSSettings(),\n wireGuardObfuscation: WireGuardObfuscationSettings = WireGuardObfuscationSettings(),\n tunnelQuantumResistance: TunnelQuantumResistance = .automatic,\n tunnelMultihopState: MultihopState = .off\n\n ) {\n self.relayConstraints = relayConstraints\n self.dnsSettings = dnsSettings\n self.wireGuardObfuscation = wireGuardObfuscation\n self.tunnelQuantumResistance = tunnelQuantumResistance\n self.tunnelMultihopState = tunnelMultihopState\n }\n\n public func upgradeToNextVersion() -> any TunnelSettings {\n TunnelSettingsV6(\n relayConstraints: relayConstraints,\n dnsSettings: dnsSettings,\n wireGuardObfuscation: wireGuardObfuscation,\n tunnelQuantumResistance: tunnelQuantumResistance,\n tunnelMultihopState: tunnelMultihopState,\n daita: DAITASettings()\n )\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\TunnelSettingsV5.swift | TunnelSettingsV5.swift | Swift | 1,739 | 0.95 | 0 | 0.272727 | python-kit | 772 | 2025-05-31T07:58:26.321530 | Apache-2.0 | false | 131ade5f04aef8d6ad906f6a93afa929 |
//\n// TunnelSettingsV6.swift\n// MullvadSettings\n//\n// Created by Mojgan on 2024-08-08.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\n\npublic struct TunnelSettingsV6: Codable, Equatable, TunnelSettings, Sendable {\n /// Relay constraints.\n public var relayConstraints: RelayConstraints\n\n /// DNS settings.\n public var dnsSettings: DNSSettings\n\n /// WireGuard obfuscation settings\n public var wireGuardObfuscation: WireGuardObfuscationSettings\n\n /// Whether Post Quantum exchanges are enabled.\n public var tunnelQuantumResistance: TunnelQuantumResistance\n\n /// Whether Multihop is enabled.\n public var tunnelMultihopState: MultihopState\n\n /// DAITA settings.\n public var daita: DAITASettings\n\n public init(\n relayConstraints: RelayConstraints = RelayConstraints(),\n dnsSettings: DNSSettings = DNSSettings(),\n wireGuardObfuscation: WireGuardObfuscationSettings = WireGuardObfuscationSettings(),\n tunnelQuantumResistance: TunnelQuantumResistance = .automatic,\n tunnelMultihopState: MultihopState = .off,\n daita: DAITASettings = DAITASettings()\n ) {\n self.relayConstraints = relayConstraints\n self.dnsSettings = dnsSettings\n self.wireGuardObfuscation = wireGuardObfuscation\n self.tunnelQuantumResistance = tunnelQuantumResistance\n self.tunnelMultihopState = tunnelMultihopState\n self.daita = daita\n }\n\n public func upgradeToNextVersion() -> any TunnelSettings {\n TunnelSettingsV7(\n relayConstraints: relayConstraints,\n dnsSettings: dnsSettings,\n wireGuardObfuscation: wireGuardObfuscation,\n tunnelQuantumResistance: tunnelQuantumResistance,\n tunnelMultihopState: tunnelMultihopState,\n daita: daita,\n localNetworkSharing: false,\n includeAllNetworks: false\n )\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\TunnelSettingsV6.swift | TunnelSettingsV6.swift | Swift | 1,952 | 0.95 | 0 | 0.26 | react-lib | 917 | 2025-03-31T17:20:06.469114 | Apache-2.0 | false | 23b03a4664ea8dfe96857933e9792a59 |
//\n// TunnelSettingsV6 2.swift\n// MullvadVPN\n//\n// Created by Steffen Ernst on 2025-02-04.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\n\npublic struct TunnelSettingsV7: Codable, Equatable, TunnelSettings, Sendable {\n /// Relay constraints.\n public var relayConstraints: RelayConstraints\n\n /// DNS settings.\n public var dnsSettings: DNSSettings\n\n /// WireGuard obfuscation settings\n public var wireGuardObfuscation: WireGuardObfuscationSettings\n\n /// Whether Post Quantum exchanges are enabled.\n public var tunnelQuantumResistance: TunnelQuantumResistance\n\n /// Whether Multihop is enabled.\n public var tunnelMultihopState: MultihopState\n\n /// DAITA settings.\n public var daita: DAITASettings\n\n /// Local networks sharing.\n public var localNetworkSharing: Bool\n\n /// Forces the system to route most traffic through the tunnel\n public var includeAllNetworks: Bool\n\n public init(\n relayConstraints: RelayConstraints = RelayConstraints(),\n dnsSettings: DNSSettings = DNSSettings(),\n wireGuardObfuscation: WireGuardObfuscationSettings = WireGuardObfuscationSettings(),\n tunnelQuantumResistance: TunnelQuantumResistance = .automatic,\n tunnelMultihopState: MultihopState = .off,\n daita: DAITASettings = DAITASettings(),\n localNetworkSharing: Bool = false,\n includeAllNetworks: Bool = false\n ) {\n self.relayConstraints = relayConstraints\n self.dnsSettings = dnsSettings\n self.wireGuardObfuscation = wireGuardObfuscation\n self.tunnelQuantumResistance = tunnelQuantumResistance\n self.tunnelMultihopState = tunnelMultihopState\n self.daita = daita\n self.localNetworkSharing = localNetworkSharing\n self.includeAllNetworks = includeAllNetworks\n }\n\n public func upgradeToNextVersion() -> any TunnelSettings {\n self\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\TunnelSettingsV7.swift | TunnelSettingsV7.swift | Swift | 1,946 | 0.95 | 0 | 0.306122 | vue-tools | 582 | 2023-07-25T16:03:31.382745 | MIT | false | d800ac7d9064e4840e1f504a7d86a509 |
//\n// WireGuardObfuscationSettings.swift\n// MullvadVPN\n//\n// Created by Marco Nikic on 2023-10-17.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\n/// Whether obfuscation is enabled and which method is used.\n///\n/// `.automatic` means an algorithm will decide whether to use obfuscation or not.\npublic enum WireGuardObfuscationState: Codable, Sendable {\n @available(*, deprecated, renamed: "udpOverTcp")\n case on\n\n case automatic\n case udpOverTcp\n case shadowsocks\n case off\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n\n var allKeys = ArraySlice(container.allKeys)\n guard let key = allKeys.popFirst(), allKeys.isEmpty else {\n throw DecodingError.typeMismatch(\n WireGuardObfuscationState.self,\n DecodingError.Context(\n codingPath: container.codingPath,\n debugDescription: "Invalid number of keys found, expected one.",\n underlyingError: nil\n )\n )\n }\n\n switch key {\n case .automatic:\n self = .automatic\n case .on, .udpOverTcp:\n self = .udpOverTcp\n case .shadowsocks:\n self = .shadowsocks\n case .off:\n self = .off\n }\n }\n\n public var isEnabled: Bool {\n [.udpOverTcp, .shadowsocks].contains(self)\n }\n}\n\npublic enum WireGuardObfuscationUdpOverTcpPort: Codable, Equatable, CustomStringConvertible, Sendable {\n case automatic\n case port80\n case port5001\n\n public var portValue: UInt16? {\n switch self {\n case .automatic:\n nil\n case .port80:\n 80\n case .port5001:\n 5001\n }\n }\n\n public var description: String {\n switch self {\n case .automatic:\n NSLocalizedString(\n "WIREGUARD_OBFUSCATION_UDP_TCP_PORT_AUTOMATIC",\n tableName: "VPNSettings",\n value: "Automatic",\n comment: ""\n )\n case .port80:\n "80"\n case .port5001:\n "5001"\n }\n }\n}\n\npublic enum WireGuardObfuscationShadowsocksPort: Codable, Equatable, CustomStringConvertible, Sendable {\n case automatic\n case custom(UInt16)\n\n public var portValue: UInt16? {\n switch self {\n case .automatic:\n nil\n case let .custom(port):\n port\n }\n }\n\n public var description: String {\n switch self {\n case .automatic:\n NSLocalizedString(\n "WIREGUARD_OBFUSCATION_SHADOWSOCKS_PORT_AUTOMATIC",\n tableName: "VPNSettings",\n value: "Automatic",\n comment: ""\n )\n case let .custom(port):\n String(port)\n }\n }\n}\n\n// Can't deprecate the whole type since it'll yield a lint warning when decoding\n// port in `WireGuardObfuscationSettings`.\nprivate enum WireGuardObfuscationPort: UInt16, Codable, Sendable {\n @available(*, deprecated, message: "Use `udpOverTcpPort` instead")\n case automatic = 0\n @available(*, deprecated, message: "Use `udpOverTcpPort` instead")\n case port80 = 80\n @available(*, deprecated, message: "Use `udpOverTcpPort` instead")\n case port5001 = 5001\n}\n\npublic struct WireGuardObfuscationSettings: Codable, Equatable, Sendable {\n @available(*, deprecated, message: "Use `udpOverTcpPort` instead")\n private var port: WireGuardObfuscationPort = .automatic\n\n public var state: WireGuardObfuscationState\n public var udpOverTcpPort: WireGuardObfuscationUdpOverTcpPort\n public var shadowsocksPort: WireGuardObfuscationShadowsocksPort\n\n public init(\n state: WireGuardObfuscationState = .automatic,\n udpOverTcpPort: WireGuardObfuscationUdpOverTcpPort = .automatic,\n shadowsocksPort: WireGuardObfuscationShadowsocksPort = .automatic\n ) {\n self.state = state\n self.udpOverTcpPort = udpOverTcpPort\n self.shadowsocksPort = shadowsocksPort\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n\n state = try container.decode(WireGuardObfuscationState.self, forKey: .state)\n shadowsocksPort = try container.decodeIfPresent(\n WireGuardObfuscationShadowsocksPort.self,\n forKey: .shadowsocksPort\n ) ?? .automatic\n\n if let port = try? container.decodeIfPresent(WireGuardObfuscationUdpOverTcpPort.self, forKey: .udpOverTcpPort) {\n udpOverTcpPort = port\n } else if let port = try? container.decodeIfPresent(WireGuardObfuscationPort.self, forKey: .port) {\n switch port {\n case .automatic:\n udpOverTcpPort = .automatic\n case .port80:\n udpOverTcpPort = .port80\n case .port5001:\n udpOverTcpPort = .port5001\n }\n } else {\n udpOverTcpPort = .automatic\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadSettings\WireGuardObfuscationSettings.swift | WireGuardObfuscationSettings.swift | Swift | 5,109 | 0.95 | 0.08284 | 0.080537 | awesome-app | 98 | 2024-08-15T05:46:26.500357 | MIT | false | 7118a8cb627dbddd78b86c02175f817d |
//\n// AnyIPAddress.swift\n// MullvadTypes\n//\n// Created by pronebird on 05/10/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport Network\n\n/// Container type that holds either `IPv4Address` or `IPv6Address`.\npublic enum AnyIPAddress: IPAddress, Codable, Equatable, CustomDebugStringConvertible {\n case ipv4(IPv4Address)\n case ipv6(IPv6Address)\n\n private enum CodingKeys: String, CodingKey {\n case ipv4, ipv6\n }\n\n private var innerAddress: IPAddress {\n switch self {\n case let .ipv4(ipv4Address):\n return ipv4Address\n case let .ipv6(ipv6Address):\n return ipv6Address\n }\n }\n\n public var rawValue: Data {\n innerAddress.rawValue\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n\n if container.contains(.ipv4) {\n self = .ipv4(try container.decode(IPv4Address.self, forKey: .ipv4))\n } else if container.contains(.ipv6) {\n self = .ipv6(try container.decode(IPv6Address.self, forKey: .ipv6))\n } else {\n throw DecodingError.dataCorruptedError(\n forKey: .ipv4,\n in: container,\n debugDescription: "Invalid AnyIPAddress representation"\n )\n }\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: CodingKeys.self)\n\n switch self {\n case let .ipv4(ipv4Address):\n try container.encode(ipv4Address, forKey: .ipv4)\n case let .ipv6(ipv6Address):\n try container.encode(ipv6Address, forKey: .ipv6)\n }\n }\n\n public init?(_ rawValue: Data, _ interface: NWInterface?) {\n if let ipv4Address = IPv4Address(rawValue, interface) {\n self = .ipv4(ipv4Address)\n } else if let ipv6Address = IPv6Address(rawValue, interface) {\n self = .ipv6(ipv6Address)\n } else {\n return nil\n }\n }\n\n public init?(_ string: String) {\n // Arbitrary integers should not be allowed by us and need to be handled separately\n // since Apple allows them.\n guard Int(string) == nil else { return nil }\n\n if let ipv4Address = IPv4Address(string) {\n self = .ipv4(ipv4Address)\n } else if let ipv6Address = IPv6Address(string) {\n self = .ipv6(ipv6Address)\n } else {\n return nil\n }\n }\n\n public var interface: NWInterface? {\n innerAddress.interface\n }\n\n public var isLoopback: Bool {\n innerAddress.isLoopback\n }\n\n public var isLinkLocal: Bool {\n innerAddress.isLinkLocal\n }\n\n public var isMulticast: Bool {\n innerAddress.isMulticast\n }\n\n public var debugDescription: String {\n switch self {\n case let .ipv4(ipv4Address):\n return "\(ipv4Address)"\n case let .ipv6(ipv6Address):\n return "\(ipv6Address)"\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\AnyIPAddress.swift | AnyIPAddress.swift | Swift | 3,041 | 0.95 | 0.12844 | 0.108696 | node-utils | 604 | 2024-01-15T18:55:18.198358 | Apache-2.0 | false | 9cb120e771fd49482cd2b3152a3641c4 |
//\n// AnyIPEndpoint.swift\n// MullvadTypes\n//\n// Created by pronebird on 20/10/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport protocol Network.IPAddress\n\npublic enum AnyIPEndpoint: Hashable, Equatable, Codable, CustomStringConvertible, @unchecked Sendable {\n case ipv4(IPv4Endpoint)\n case ipv6(IPv6Endpoint)\n\n public var ip: IPAddress {\n switch self {\n case let .ipv4(ipv4Endpoint):\n return ipv4Endpoint.ip\n case let .ipv6(ipv6Endpoint):\n return ipv6Endpoint.ip\n }\n }\n\n public var port: UInt16 {\n switch self {\n case let .ipv4(ipv4Endpoint):\n return ipv4Endpoint.port\n case let .ipv6(ipv6Endpoint):\n return ipv6Endpoint.port\n }\n }\n\n public init?(string: some StringProtocol) {\n if let ipv4Endpoint = IPv4Endpoint(string: string) {\n self = .ipv4(ipv4Endpoint)\n } else if let ipv6Endpoint = IPv6Endpoint(string: string) {\n self = .ipv6(ipv6Endpoint)\n } else {\n return nil\n }\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n let string = try container.decode(String.self)\n\n if let ipv4Endpoint = IPv4Endpoint(string: string) {\n self = .ipv4(ipv4Endpoint)\n } else if let ipv6Endpoint = IPv6Endpoint(string: string) {\n self = .ipv6(ipv6Endpoint)\n } else {\n throw DecodingError.dataCorruptedError(\n in: container,\n debugDescription: "Cannot parse the endpoint"\n )\n }\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n\n try container.encode("\(self)")\n }\n\n public var description: String {\n switch self {\n case let .ipv4(ipv4Endpoint):\n return "\(ipv4Endpoint)"\n case let .ipv6(ipv6Endpoint):\n return "\(ipv6Endpoint)"\n }\n }\n\n public static func == (lhs: AnyIPEndpoint, rhs: AnyIPEndpoint) -> Bool {\n switch (lhs, rhs) {\n case let (.ipv4(lhsEndpoint), .ipv4(rhsEndpoint)):\n return lhsEndpoint == rhsEndpoint\n\n case let (.ipv6(lhsEndpoint), .ipv6(rhsEndpoint)):\n return lhsEndpoint == rhsEndpoint\n\n default:\n return false\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\AnyIPEndpoint.swift | AnyIPEndpoint.swift | Swift | 2,433 | 0.95 | 0.126437 | 0.094595 | vue-tools | 994 | 2023-10-12T18:30:48.150574 | Apache-2.0 | false | 925e23f4a18278154312a5daf3b725b7 |
//\n// Cancellable.swift\n// MullvadTypes\n//\n// Created by pronebird on 15/03/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\npublic protocol Cancellable {\n func cancel()\n}\n\nextension Operation: Cancellable {}\n\n/// An object representing a cancellation token.\npublic final class AnyCancellable: Cancellable {\n private let block: (() -> Void)?\n\n /// Create cancellation token with block handler.\n public init(block: @escaping @Sendable () -> Void) {\n self.block = block\n }\n\n /// Create empty cancellation token.\n public init() {\n block = nil\n }\n\n public func cancel() {\n block?()\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\Cancellable.swift | Cancellable.swift | Swift | 676 | 0.95 | 0.029412 | 0.37037 | python-kit | 206 | 2024-07-11T00:00:21.508805 | BSD-3-Clause | false | cb437723dcf1436dc61111bf33dc6eda |
//\n// CustomErrorDescription.swift\n// MullvadTypes\n//\n// Created by pronebird on 23/09/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\n/// A protocol providing error a way to override error description when printing error chain.\npublic protocol CustomErrorDescriptionProtocol {\n /// A custom error description that overrides `localizedDescription` when printing error chain.\n var customErrorDescription: String? { get }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\CustomErrorDescriptionProtocol.swift | CustomErrorDescriptionProtocol.swift | Swift | 471 | 0.95 | 0 | 0.692308 | node-utils | 397 | 2024-02-21T19:16:14.697835 | Apache-2.0 | false | 1e6e17b6b02b8a9ccbbcf8403a9ce4be |
//\n// DisplayError.swift\n// MullvadTypes\n//\n// Created by pronebird on 17/01/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\n/// A protocol that adds a formal interface for all errors displayed in user interface.\n///\n/// This protocol is meant to be used in place of `LocalizedError` when producing a user friendly\n/// error message that requires a deeper look at the underlying cause.\n///\n/// Note that `Logger.error(error: Error)` picks up `errorDescription`s when unrolling\n/// the underlying error chain, hence it's better to keep error descriptions relatively concise,\n/// explaining what happened but without telling why that happened.\npublic protocol DisplayError {\n var displayErrorDescription: String? { get }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\DisplayError.swift | DisplayError.swift | Swift | 767 | 0.95 | 0.047619 | 0.789474 | node-utils | 647 | 2024-11-05T21:59:19.640020 | GPL-3.0 | false | a13b2015bf4a302606c447a6c5589013 |
//\n// Duration+Extensions.swift\n// MullvadTypes\n//\n// Created by Jon Petersson on 2023-08-18.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\n// Extends Duration with convenience accessors and functions.\nextension Duration {\n public var isFinite: Bool {\n return timeInterval.isFinite\n }\n\n public var seconds: Int64 {\n return components.seconds\n }\n\n public var timeInterval: TimeInterval {\n return TimeInterval(components.seconds) + (TimeInterval(components.attoseconds) * 1e-18)\n }\n\n public var milliseconds: Int {\n return Int(components.seconds.saturatingMultiplication(1000)) + Int(Double(components.attoseconds) * 1e-15)\n }\n\n public static func minutes(_ minutes: Int) -> Duration {\n return .seconds(minutes.saturatingMultiplication(60))\n }\n\n public static func hours(_ hours: Int) -> Duration {\n return .seconds(hours.saturatingMultiplication(3600))\n }\n\n public static func days(_ days: Int) -> Duration {\n return .seconds(days.saturatingMultiplication(86400))\n }\n}\n\n// Extends Duration with custom operators.\nextension Duration {\n public static func + (lhs: DispatchWallTime, rhs: Duration) -> DispatchWallTime {\n return lhs + rhs.timeInterval\n }\n\n public static func * (lhs: Duration, rhs: Double) -> Duration {\n let milliseconds = lhs.timeInterval * rhs * 1000\n\n let maxTruncated = min(milliseconds, Double(Int.max).nextDown)\n let bothTruncated = max(maxTruncated, Double(Int.min).nextUp)\n\n return .milliseconds(Int(bothTruncated))\n }\n\n public static func + (lhs: Duration, rhs: TimeInterval) -> Duration {\n return .milliseconds(lhs.milliseconds.saturatingAddition(Int(rhs * 1000)))\n }\n\n public static func - (lhs: Duration, rhs: TimeInterval) -> Duration {\n return .milliseconds(lhs.milliseconds.saturatingSubtraction(Int(rhs * 1000)))\n }\n\n public static func >= (lhs: TimeInterval, rhs: Duration) -> Bool {\n return lhs >= rhs.timeInterval\n }\n\n public static func <= (lhs: TimeInterval, rhs: Duration) -> Bool {\n return lhs <= rhs.timeInterval\n }\n\n public static func < (lhs: TimeInterval, rhs: Duration) -> Bool {\n return lhs < rhs.timeInterval\n }\n\n public static func > (lhs: TimeInterval, rhs: Duration) -> Bool {\n return lhs > rhs.timeInterval\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\Duration+Extensions.swift | Duration+Extensions.swift | Swift | 2,414 | 0.95 | 0 | 0.145161 | vue-tools | 234 | 2025-04-16T06:12:16.021210 | GPL-3.0 | false | 1c6c395af303a1684aa714888385d584 |
//\n// Duration.swift\n// MullvadTypes\n//\n// Created by Jon Petersson on 2023-08-16.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\n/// Custom implementation of iOS native `Duration` (available from iOS16). Meant as a\n/// drop-in replacement until the app supports iOS16. Ideally this whole file can\n/// then be deleted without affecting the rest of the code base.\n@available(iOS, introduced: 15.0, obsoleted: 16.0, message: "Replace with native Duration type.")\npublic struct Duration {\n private(set) var components: (seconds: Int64, attoseconds: Int64)\n\n public init(secondsComponent: Int64, attosecondsComponent: Int64 = 0) {\n components = (\n seconds: Int64(secondsComponent),\n attoseconds: Int64(attosecondsComponent)\n )\n }\n\n public static func milliseconds(_ milliseconds: Int) -> Duration {\n let subSeconds = milliseconds % 1000\n let seconds = (milliseconds - subSeconds) / 1000\n\n return Duration(\n secondsComponent: Int64(seconds),\n attosecondsComponent: Int64(subSeconds) * Int64(1e15)\n )\n }\n\n public static func seconds(_ seconds: Int) -> Duration {\n return Duration(secondsComponent: Int64(seconds))\n }\n\n public func logFormat() -> String {\n let timeInterval = timeInterval\n\n guard timeInterval >= 1 else {\n return "\(milliseconds)ms"\n }\n\n let trailingZeroesSuffix = ".00"\n var string = String(format: "%.2f", timeInterval)\n\n if string.hasSuffix(trailingZeroesSuffix) {\n string.removeLast(trailingZeroesSuffix.count)\n }\n\n return "\(string)s"\n }\n}\n\nextension Duration: DurationProtocol {\n public static var zero: Duration {\n return .seconds(0)\n }\n\n public static func / (lhs: Duration, rhs: Int) -> Duration {\n return .milliseconds(lhs.milliseconds / max(rhs, 1))\n }\n\n public static func * (lhs: Duration, rhs: Int) -> Duration {\n return .milliseconds(lhs.milliseconds.saturatingMultiplication(rhs))\n }\n\n public static func / (lhs: Duration, rhs: Duration) -> Double {\n guard rhs != .zero else {\n return lhs.timeInterval\n }\n\n return lhs.timeInterval / rhs.timeInterval\n }\n\n public static func + (lhs: Duration, rhs: Duration) -> Duration {\n return .milliseconds(lhs.milliseconds.saturatingAddition(rhs.milliseconds))\n }\n\n public static func - (lhs: Duration, rhs: Duration) -> Duration {\n return .milliseconds(lhs.milliseconds.saturatingSubtraction(rhs.milliseconds))\n }\n\n public static func < (lhs: Duration, rhs: Duration) -> Bool {\n return lhs.timeInterval < rhs.timeInterval\n }\n\n public static func == (lhs: Duration, rhs: Duration) -> Bool {\n return lhs.timeInterval == rhs.timeInterval\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\Duration.swift | Duration.swift | Swift | 2,869 | 0.95 | 0.010753 | 0.136986 | node-utils | 317 | 2025-06-05T14:46:31.357924 | MIT | false | b96aa94b7e0be67cca8255fe85142866 |
//\n// Error+Chain.swift\n// MullvadTypes\n//\n// Created by pronebird on 23/09/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nextension Error {\n /// Returns a flat list of errors by unrolling the underlying error chain.\n public var underlyingErrorChain: [Error] {\n var errors: [Error] = []\n var currentError: Error? = self as Error\n\n while let underlyingError = currentError?.getUnderlyingError() {\n currentError = underlyingError\n errors.append(underlyingError)\n }\n\n return errors\n }\n\n public func logFormatError() -> String {\n let nsError = self as NSError\n var message = ""\n\n let description = (self as? CustomErrorDescriptionProtocol)?\n .customErrorDescription ?? localizedDescription\n\n message += "\(description) (domain = \(nsError.domain), code = \(nsError.code))"\n\n return message\n }\n\n private func getUnderlyingError() -> Error? {\n if let wrappingError = self as? WrappingError {\n return wrappingError.underlyingError\n } else {\n return (self as NSError).userInfo[NSUnderlyingErrorKey] as? Error\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\Error+Chain.swift | Error+Chain.swift | Swift | 1,220 | 0.95 | 0.045455 | 0.228571 | node-utils | 397 | 2023-12-02T22:45:11.967191 | BSD-3-Clause | false | 8226811cbdba4274bc421b2706f57584 |
//\n// FileCache.swift\n// MullvadTypes\n//\n// Created by Marco Nikic on 2023-05-30.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\n/// File cache implementation that can read and write any `Codable` content and uses file coordinator to coordinate I/O.\npublic struct FileCache<Content: Codable>: FileCacheProtocol {\n public let fileURL: URL\n\n public init(fileURL: URL) {\n self.fileURL = fileURL\n }\n\n public func read() throws -> Content {\n let fileCoordinator = NSFileCoordinator(filePresenter: nil)\n\n return try fileCoordinator.coordinate(readingItemAt: fileURL, options: [.withoutChanges]) { fileURL in\n try JSONDecoder().decode(Content.self, from: Data(contentsOf: fileURL))\n }\n }\n\n public func write(_ content: Content) throws {\n let fileCoordinator = NSFileCoordinator(filePresenter: nil)\n\n try fileCoordinator.coordinate(writingItemAt: fileURL, options: [.forReplacing]) { fileURL in\n try JSONEncoder().encode(content).write(to: fileURL)\n }\n }\n\n public func clear() throws {\n let fileCoordinator = NSFileCoordinator(filePresenter: nil)\n try fileCoordinator.coordinate(writingItemAt: fileURL, options: [.forDeleting]) { fileURL in\n try FileManager.default.removeItem(at: fileURL)\n }\n }\n}\n\n/// Protocol describing file cache that's able to read and write serializable content.\npublic protocol FileCacheProtocol<Content> {\n associatedtype Content: Codable\n\n func read() throws -> Content\n func write(_ content: Content) throws\n func clear() throws\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\FileCache.swift | FileCache.swift | Swift | 1,630 | 0.95 | 0.12 | 0.225 | awesome-app | 84 | 2024-06-18T14:20:16.434813 | Apache-2.0 | false | d3b0f375601615ab36b1fa641147a356 |
//\n// FixedWidthInteger+Arithmetics.swift\n// PacketTunnel\n//\n// Created by pronebird on 28/08/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nextension FixedWidthInteger {\n /// Saturating integer multiplication. Computes `self * rhs`, saturating at the numeric bounds\n /// instead of overflowing.\n public func saturatingMultiplication(_ rhs: Self) -> Self {\n let (partialValue, isOverflow) = multipliedReportingOverflow(by: rhs)\n\n if isOverflow {\n return signum() == rhs.signum() ? .max : .min\n } else {\n return partialValue\n }\n }\n\n /// Saturating integer addition. Computes `self + rhs`, saturating at the numeric bounds\n /// instead of overflowing.\n public func saturatingAddition(_ rhs: Self) -> Self {\n let (partialValue, isOverflow) = addingReportingOverflow(rhs)\n\n if isOverflow {\n return partialValue.signum() >= 0 ? .min : .max\n } else {\n return partialValue\n }\n }\n\n /// Saturating integer subtraction. Computes `self - rhs`, saturating at the numeric bounds\n /// instead of overflowing.\n public func saturatingSubtraction(_ rhs: Self) -> Self {\n let (partialValue, isOverflow) = subtractingReportingOverflow(rhs)\n\n if isOverflow {\n return partialValue.signum() >= 0 ? .min : .max\n } else {\n return partialValue\n }\n }\n\n /// Saturating integer exponentiation. Computes `self ** exp`, saturating at the numeric\n /// bounds instead of overflowing.\n public func saturatingPow(_ exp: UInt32) -> Self {\n let result = pow(Double(self), Double(exp))\n\n if result.isFinite {\n if result <= Double(Self.min) {\n return .min\n } else if result >= Double(Self.max) {\n return .max\n } else {\n return Self(result)\n }\n } else {\n return result.sign == .minus ? Self.min : Self.max\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\FixedWidthInteger+Arithmetics.swift | FixedWidthInteger+Arithmetics.swift | Swift | 2,045 | 0.95 | 0.092308 | 0.267857 | vue-tools | 236 | 2023-07-16T10:47:37.699391 | Apache-2.0 | false | baa725026f1940d2e71f4879c0f02837 |
//\n// IPAddress+Codable.swift\n// MullvadTypes\n//\n// Created by pronebird on 12/06/2019.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Network\n\nextension IPv4Address: Codable {\n public init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n let ipString = try container.decode(String.self)\n\n if let decoded = IPv4Address(ipString) {\n self = decoded\n } else {\n throw DecodingError.dataCorruptedError(\n in: container,\n debugDescription: "Invalid IPv4 representation"\n )\n }\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n\n try container.encode(String(reflecting: self))\n }\n}\n\nextension IPv6Address: Codable {\n public init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n let ipString = try container.decode(String.self)\n\n if let decoded = IPv6Address(ipString) {\n self = decoded\n } else {\n throw DecodingError.dataCorruptedError(\n in: container,\n debugDescription: "Invalid IPv6 representation"\n )\n }\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n\n try container.encode(String(reflecting: self))\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\IPAddress+Codable.swift | IPAddress+Codable.swift | Swift | 1,453 | 0.95 | 0.150943 | 0.159091 | awesome-app | 822 | 2023-08-03T01:06:43.006827 | Apache-2.0 | false | 4e9513decc199a0f3a152822830b05a3 |
//\n// IPEndpoint.swift\n// MullvadTypes\n//\n// Created by pronebird on 06/12/2019.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport Network\n\npublic struct IPv4Endpoint: Hashable, Equatable, Codable, CustomStringConvertible, Sendable {\n public let ip: IPv4Address\n public let port: UInt16\n\n public init(ip: IPv4Address, port: UInt16) {\n self.ip = ip\n self.port = port\n }\n\n public init?(string: some StringProtocol) {\n let components = string.split(\n separator: ":",\n maxSplits: 2,\n omittingEmptySubsequences: false\n )\n\n if components.count == 2, let parsedIP = IPv4Address(String(components[0])),\n let parsedPort = UInt16(components[1]) {\n ip = parsedIP\n port = parsedPort\n } else {\n return nil\n }\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n let string = try container.decode(String.self)\n\n if let parsedAddress = IPv4Endpoint(string: string) {\n self = parsedAddress\n } else {\n throw DecodingError.dataCorruptedError(\n in: container,\n debugDescription: "Cannot parse the IPv4 endpoint"\n )\n }\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n\n try container.encode("\(self)")\n }\n\n public var description: String {\n "\(ip):\(port)"\n }\n\n public static func == (lhs: IPv4Endpoint, rhs: IPv4Endpoint) -> Bool {\n lhs.ip.rawValue == rhs.ip.rawValue && lhs.port == rhs.port\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\IPv4Endpoint.swift | IPv4Endpoint.swift | Swift | 1,714 | 0.95 | 0.078125 | 0.132075 | python-kit | 822 | 2024-12-06T09:19:37.766940 | BSD-3-Clause | false | 8d51b75435e9b89ab76b1f2e897e0c9a |
//\n// IPv6Endpoint.swift\n// MullvadTypes\n//\n// Created by pronebird on 20/10/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport Network\n\npublic struct IPv6Endpoint: Hashable, Equatable, Codable, CustomStringConvertible, Sendable {\n public let ip: IPv6Address\n public let port: UInt16\n\n public init(ip: IPv6Address, port: UInt16) {\n self.ip = ip\n self.port = port\n }\n\n public init?(string: some StringProtocol) {\n guard let lastColon = string.lastIndex(of: ":"), lastColon != string.endIndex else {\n return nil\n }\n\n let portIndex = string.index(after: lastColon)\n let addressString = string[..<lastColon]\n let portString = string[portIndex...]\n\n guard addressString.first == "[", addressString.last == "]" else {\n return nil\n }\n\n let ipv6AddressString = String(addressString.dropFirst().dropLast())\n\n if let parsedIP = IPv6Address(ipv6AddressString), let parsedPort = UInt16(portString) {\n ip = parsedIP\n port = parsedPort\n } else {\n return nil\n }\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n let string = try container.decode(String.self)\n\n if let parsedAddress = IPv6Endpoint(string: string) {\n self = parsedAddress\n } else {\n throw DecodingError.dataCorruptedError(\n in: container,\n debugDescription: "Cannot parse the IPv6 endpoint"\n )\n }\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n\n try container.encode("\(self)")\n }\n\n public var description: String {\n "[\(ip)]:\(port)"\n }\n\n public static func == (lhs: IPv6Endpoint, rhs: IPv6Endpoint) -> Bool {\n lhs.ip.rawValue == rhs.ip.rawValue && lhs.port == rhs.port\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\IPv6Endpoint.swift | IPv6Endpoint.swift | Swift | 1,993 | 0.95 | 0.070423 | 0.122807 | node-utils | 42 | 2024-11-24T12:59:44.608769 | MIT | false | 6a3b6c0af11878a2bcdc6fff0828ceb3 |
//\n// KeychainError.swift\n// MullvadVPN\n//\n// Created by pronebird on 02/10/2019.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport Security\n\npublic struct KeychainError: LocalizedError, Equatable {\n public let code: OSStatus\n public init(code: OSStatus) {\n self.code = code\n }\n\n public var errorDescription: String? {\n SecCopyErrorMessageString(code, nil) as String?\n }\n\n public static let duplicateItem = KeychainError(code: errSecDuplicateItem)\n public static let itemNotFound = KeychainError(code: errSecItemNotFound)\n public static let interactionNotAllowed = KeychainError(code: errSecInteractionNotAllowed)\n\n public static func == (lhs: KeychainError, rhs: KeychainError) -> Bool {\n lhs.code == rhs.code\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\KeychainError.swift | KeychainError.swift | Swift | 808 | 0.95 | 0 | 0.291667 | node-utils | 118 | 2024-09-01T15:20:00.745454 | Apache-2.0 | false | b5fa961d87e28f6c99c45853c13e7e41 |
//\n// LocalNetworkIPs.swift\n// MullvadTypes\n//\n// Created by Mojgan on 2024-07-26.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\npublic enum LocalNetworkIPs: String {\n case gatewayAddress = "10.64.0.1"\n case defaultRouteIpV4 = "0.0.0.0"\n case defaultRouteIpV6 = "::"\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\LocalNetworkIPs.swift | LocalNetworkIPs.swift | Swift | 317 | 0.95 | 0 | 0.538462 | awesome-app | 589 | 2024-05-22T00:10:41.005311 | MIT | false | 74e146b943509c843a22d67a2f80d857 |
//\n// Location.swift\n// MullvadTypes\n//\n// Created by pronebird on 12/02/2020.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport CoreLocation\nimport Foundation\n\npublic struct Location: Codable, Equatable, Sendable {\n public var country: String\n public var countryCode: String\n public var city: String\n public var cityCode: String\n public var latitude: Double\n public var longitude: Double\n\n public var geoCoordinate: CLLocationCoordinate2D {\n CLLocationCoordinate2D(latitude: latitude, longitude: longitude)\n }\n\n public init(\n country: String,\n countryCode: String,\n city: String,\n cityCode: String,\n latitude: Double,\n longitude: Double\n ) {\n self.country = country\n self.countryCode = countryCode\n self.city = city\n self.cityCode = cityCode\n self.latitude = latitude\n self.longitude = longitude\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\Location.swift | Location.swift | Swift | 949 | 0.95 | 0 | 0.2 | python-kit | 126 | 2024-01-17T16:54:56.294622 | BSD-3-Clause | false | 4ce5f48655f746144cbaebab8155d031 |
//\n// MullvadEndpoint.swift\n// MullvadTypes\n//\n// Created by pronebird on 12/06/2019.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport Network\n\n/// Contains server data needed to connect to a single mullvad endpoint.\npublic struct MullvadEndpoint: Equatable, Codable, Sendable {\n public let ipv4Relay: IPv4Endpoint\n public let ipv6Relay: IPv6Endpoint?\n public let ipv4Gateway: IPv4Address\n public let ipv6Gateway: IPv6Address\n public let publicKey: Data\n\n public init(\n ipv4Relay: IPv4Endpoint,\n ipv6Relay: IPv6Endpoint? = nil,\n ipv4Gateway: IPv4Address,\n ipv6Gateway: IPv6Address,\n publicKey: Data\n ) {\n self.ipv4Relay = ipv4Relay\n self.ipv6Relay = ipv6Relay\n self.ipv4Gateway = ipv4Gateway\n self.ipv6Gateway = ipv6Gateway\n self.publicKey = publicKey\n }\n\n public func override(ipv4Relay: IPv4Endpoint) -> Self {\n MullvadEndpoint(\n ipv4Relay: ipv4Relay,\n ipv6Relay: ipv6Relay,\n ipv4Gateway: ipv4Gateway,\n ipv6Gateway: ipv6Gateway,\n publicKey: publicKey\n )\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\MullvadEndpoint.swift | MullvadEndpoint.swift | Swift | 1,172 | 0.95 | 0 | 0.205128 | react-lib | 581 | 2024-06-03T04:00:50.332921 | Apache-2.0 | false | 404818c645582fd819ff2d9fad9762b7 |
//\n// NameInputFormatter.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-05-13.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\npublic struct NameInputFormatter {\n public static let maxLength = 30\n\n public static func format(_ string: String, maxLength: Int = Self.maxLength) -> String {\n String(string.trimmingCharacters(in: .whitespaces).prefix(maxLength))\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\NameInputFormatter.swift | NameInputFormatter.swift | Swift | 409 | 0.8 | 0 | 0.538462 | awesome-app | 191 | 2023-08-31T12:19:11.752892 | Apache-2.0 | false | 3d7add7aec938780127b12a2e507fece |
//\n// NewAccountData.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2025-04-08.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\npublic struct NewAccountData: Decodable, Sendable {\n public let id: String\n public let expiry: Date\n public let maxPorts: Int\n public let canAddPorts: Bool\n public let maxDevices: Int\n public let canAddDevices: Bool\n public let number: String\n\n public init(\n id: String,\n expiry: Date,\n maxPorts: Int,\n canAddPorts: Bool,\n maxDevices: Int,\n canAddDevices: Bool,\n number: String\n ) {\n self.id = id\n self.expiry = expiry\n self.maxPorts = maxPorts\n self.canAddPorts = canAddPorts\n self.maxDevices = maxDevices\n self.canAddDevices = canAddDevices\n self.number = number\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\NewAccountData.swift | NewAccountData.swift | Swift | 851 | 0.8 | 0 | 0.212121 | vue-tools | 322 | 2023-07-29T06:12:06.062957 | MIT | false | 6cd9a7a4745ca786df3f69c8b1c62908 |
//\n// NSFileCoordinator+Extensions.swift\n// MullvadTypes\n//\n// Created by Marco Nikic on 2023-05-11.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nextension NSFileCoordinator {\n public func coordinate<R>(\n readingItemAt itemURL: URL,\n options: ReadingOptions = [],\n accessor: (URL) throws -> R\n ) throws -> R {\n var error: NSError?\n var result: Result<R, Error> = .failure(CocoaError(.fileReadUnknown))\n\n coordinate(readingItemAt: itemURL, options: options, error: &error) { url in\n result = Result { try accessor(url) }\n }\n\n if let error {\n throw error\n }\n\n return try result.get()\n }\n\n public func coordinate(\n writingItemAt itemURL: URL,\n options: WritingOptions = [],\n accessor: (URL) throws -> Void\n ) throws {\n var error: NSError?\n var accessorError: Error?\n\n coordinate(writingItemAt: itemURL, options: options, error: &error) { url in\n do {\n try accessor(url)\n } catch {\n accessorError = error\n }\n }\n\n if let e = error ?? accessorError {\n throw e\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\NSFileCoordinator+Extensions.swift | NSFileCoordinator+Extensions.swift | Swift | 1,249 | 0.95 | 0.117647 | 0.162791 | node-utils | 893 | 2024-02-24T18:55:49.531763 | MIT | false | 7e03b7646c8520824153e717edb11252 |
//\n// ObserverList.swift\n// MullvadVPN\n//\n// Created by pronebird on 26/06/2020.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\npublic struct WeakBox<T>: Sendable {\n public var value: T? {\n valueProvider()\n }\n\n nonisolated(unsafe) private let valueProvider: () -> T?\n\n public init(_ value: T) {\n let reference = value as AnyObject\n\n valueProvider = { [weak reference] in\n reference as? T\n }\n }\n\n static func == (lhs: WeakBox<T>, rhs: WeakBox<T>) -> Bool {\n (lhs.value as AnyObject) === (rhs.value as AnyObject)\n }\n}\n\nfinal public class ObserverList<T>: Sendable {\n private let lock = NSLock()\n nonisolated(unsafe) private var observers = [WeakBox<T>]()\n\n public init() {}\n\n public func append(_ observer: T) {\n lock.lock()\n\n let hasObserver = observers.contains { box in\n box == WeakBox(observer)\n }\n\n if !hasObserver {\n observers.append(WeakBox(observer))\n }\n\n lock.unlock()\n }\n\n public func remove(_ observer: T) {\n lock.lock()\n\n let index = observers.firstIndex { box in\n box == WeakBox(observer)\n }\n\n if let index {\n observers.remove(at: index)\n }\n\n lock.unlock()\n }\n\n public func notify(_ body: (T) -> Void) {\n lock.lock()\n\n var indicesToRemove = [Int]()\n var observersToNotify = [T]()\n\n for (index, box) in observers.enumerated() {\n if let observer = box.value {\n observersToNotify.append(observer)\n } else {\n indicesToRemove.append(index)\n }\n }\n\n for index in indicesToRemove.reversed() {\n observers.remove(at: index)\n }\n\n lock.unlock()\n\n for observer in observersToNotify {\n body(observer)\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\ObserverList.swift | ObserverList.swift | Swift | 1,921 | 0.95 | 0.078652 | 0.104478 | awesome-app | 303 | 2025-02-13T04:40:11.924119 | Apache-2.0 | false | 71b85d176d54df6a96b74d9d3fe46c77 |
//\n// Promise.swift\n// MullvadVPN\n//\n// Created by pronebird on 28/01/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\npublic final class Promise<Success, Failure: Error>: @unchecked Sendable {\n public typealias Result = Swift.Result<Success, Failure>\n\n private let nslock = NSLock()\n private var observers: [(Result) -> Void] = []\n private var result: Result?\n\n public init(_ executor: (@escaping (Result) -> Void) -> Void) {\n executor(resolve)\n }\n\n public func observe(_ completion: @escaping (Result) -> Void) {\n nslock.lock()\n if let result {\n nslock.unlock()\n completion(result)\n } else {\n observers.append(completion)\n nslock.unlock()\n }\n }\n\n private func resolve(result: Result) {\n nslock.lock()\n if self.result == nil {\n self.result = result\n\n let observers = observers\n self.observers.removeAll()\n nslock.unlock()\n\n for observer in observers {\n observer(result)\n }\n } else {\n nslock.unlock()\n }\n }\n}\n\n// This object can be used like an async semaphore with exactly 1 writer. It\n// allows the waiter to wait to `receive()` from another operation\n// asynchronously. It is important not to forget to call `send`, otherwise this\n// operation will block indefinitely.\npublic struct OneshotChannel {\n private var continuation: AsyncStream<Void>.Continuation?\n private var stream: AsyncStream<Void>\n\n public init() {\n var ownedContinuation: AsyncStream<Void>.Continuation?\n stream = AsyncStream { continuation in\n ownedContinuation = continuation\n }\n self.continuation = ownedContinuation\n }\n\n public func send() {\n continuation?.yield()\n continuation?.finish()\n }\n\n public func receive() async {\n for await _ in stream {\n return\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\Promise.swift | Promise.swift | Swift | 2,013 | 0.95 | 0.064935 | 0.169231 | awesome-app | 40 | 2024-04-14T13:49:12.137155 | Apache-2.0 | false | 39c76617e42bd9c35d8987080bc1d6d1 |
//\n// RelayConstraint.swift\n// MullvadTypes\n//\n// Created by pronebird on 21/10/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nprivate let anyConstraint = "any"\n\npublic enum RelayConstraint<T>: Codable, Equatable, CustomDebugStringConvertible, Sendable\n where T: Codable & Equatable & Sendable {\n case any\n case only(T)\n\n public var value: T? {\n if case let .only(value) = self {\n return value\n } else {\n return nil\n }\n }\n\n public var debugDescription: String {\n var output = "RelayConstraint."\n switch self {\n case .any:\n output += "any"\n case let .only(value):\n output += "only(\(String(reflecting: value)))"\n }\n return output\n }\n\n private struct OnlyRepr: Codable, Sendable {\n var only: T\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n\n let decoded = try? container.decode(String.self)\n if decoded == anyConstraint {\n self = .any\n } else {\n let onlyVariant = try container.decode(OnlyRepr.self)\n self = .only(onlyVariant.only)\n }\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n\n switch self {\n case .any:\n try container.encode(anyConstraint)\n case let .only(inner):\n try container.encode(OnlyRepr(only: inner))\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\RelayConstraint.swift | RelayConstraint.swift | Swift | 1,554 | 0.95 | 0.142857 | 0.132075 | react-lib | 811 | 2023-08-22T17:41:53.298423 | GPL-3.0 | false | 829641352a0de236bc4c45ddd023b9c8 |
//\n// RelayConstraint.swift\n// MullvadTypes\n//\n// Created by pronebird on 10/06/2019.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\npublic struct RelayConstraints: Codable, Equatable, CustomDebugStringConvertible, @unchecked Sendable {\n @available(*, deprecated, renamed: "locations")\n private var location: RelayConstraint<RelayLocation> = .only(.country("se"))\n\n // Added in 2024.1\n // Changed from RelayLocations to UserSelectedRelays in 2024.3\n @available(*, deprecated, renamed: "exitLocations")\n private var locations: RelayConstraint<UserSelectedRelays> = .only(UserSelectedRelays(locations: [.country("se")]))\n\n // Added in 2024.5 to support multi-hop\n public var entryLocations: RelayConstraint<UserSelectedRelays>\n public var exitLocations: RelayConstraint<UserSelectedRelays>\n\n // Added in 2023.3\n public var port: RelayConstraint<UInt16>\n public var filter: RelayConstraint<RelayFilter>\n\n public var debugDescription: String {\n "RelayConstraints { entry locations: \(entryLocations), exit locations: \(exitLocations) , port: \(port), filter: \(filter) }"\n }\n\n public init(\n entryLocations: RelayConstraint<UserSelectedRelays> = .only(UserSelectedRelays(locations: [.country("se")])),\n exitLocations: RelayConstraint<UserSelectedRelays> = .only(UserSelectedRelays(locations: [.country("se")])),\n port: RelayConstraint<UInt16> = .any,\n filter: RelayConstraint<RelayFilter> = .any\n ) {\n self.entryLocations = entryLocations\n self.exitLocations = exitLocations\n self.port = port\n self.filter = filter\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n\n // Added in 2023.3\n port = try container.decodeIfPresent(RelayConstraint<UInt16>.self, forKey: .port) ?? .any\n filter = try container.decodeIfPresent(RelayConstraint<RelayFilter>.self, forKey: .filter) ?? .any\n\n // Added in 2024.5\n entryLocations = try container.decodeIfPresent(\n RelayConstraint<UserSelectedRelays>.self,\n forKey: .entryLocations\n ) ?? .only(UserSelectedRelays(locations: [.country("se")]))\n\n exitLocations = try container\n .decodeIfPresent(RelayConstraint<UserSelectedRelays>.self, forKey: .exitLocations) ??\n container.decodeIfPresent(\n RelayConstraint<UserSelectedRelays>.self,\n forKey: .locations\n ) ??\n Self.migrateRelayLocation(decoder: decoder)\n ?? .only(UserSelectedRelays(locations: [.country("se")]))\n }\n}\n\nextension RelayConstraints {\n private static func migrateRelayLocation(decoder: Decoder) -> RelayConstraint<UserSelectedRelays>? {\n let container = try? decoder.container(keyedBy: CodingKeys.self)\n\n guard\n let relay = try? container?.decodeIfPresent(RelayConstraint<RelayLocation>.self, forKey: .location)\n else {\n return nil\n }\n\n return switch relay {\n case .any:\n .any\n case let .only(relay):\n .only(UserSelectedRelays(locations: [relay]))\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\RelayConstraints.swift | RelayConstraints.swift | Swift | 3,238 | 0.95 | 0.094118 | 0.183099 | python-kit | 664 | 2024-10-08T13:01:58.530931 | MIT | false | 780d0f324521d119fa480db08ededfa6 |
//\n// RelayFilter.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-06-08.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\npublic struct RelayFilter: Codable, Equatable, Sendable {\n public enum Ownership: Codable, Sendable {\n case any\n case owned\n case rented\n }\n\n public var ownership: Ownership\n public var providers: RelayConstraint<[String]>\n\n public init(ownership: Ownership = .any, providers: RelayConstraint<[String]> = .any) {\n self.ownership = ownership\n self.providers = providers\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\RelayFilter.swift | RelayFilter.swift | Swift | 596 | 0.95 | 0 | 0.333333 | react-lib | 280 | 2024-02-08T14:05:01.636589 | MIT | false | 7ebbf8db7649f8cab6ebe0f4d0c11084 |
//\n// RelayLocation.swift\n// MullvadTypes\n//\n// Created by pronebird on 21/10/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\npublic enum RelayLocation: Codable, Hashable, CustomDebugStringConvertible, Sendable {\n case country(String)\n case city(String, String)\n case hostname(String, String, String)\n\n public init?(dashSeparatedString: String) {\n let components = dashSeparatedString.split(separator: "-", maxSplits: 2).map(String.init)\n\n switch components.count {\n case 1:\n self = .country(components[0])\n case 2:\n self = .city(components[0], components[1])\n case 3:\n self = .hostname(components[0], components[1], components[2])\n default:\n return nil\n }\n }\n\n public init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n let components = try container.decode([String].self)\n\n switch components.count {\n case 1:\n self = .country(components[0])\n case 2:\n self = .city(components[0], components[1])\n case 3:\n self = .hostname(components[0], components[1], components[2])\n default:\n throw DecodingError.dataCorruptedError(\n in: container,\n debugDescription: "Invalid enum representation"\n )\n }\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.singleValueContainer()\n\n switch self {\n case let .country(code):\n try container.encode([code])\n\n case let .city(countryCode, cityCode):\n try container.encode([countryCode, cityCode])\n\n case let .hostname(countryCode, cityCode, hostname):\n try container.encode([countryCode, cityCode, hostname])\n }\n }\n\n /// A list of `RelayLocation` items preceding the given one in the relay tree\n public var ancestors: [RelayLocation] {\n switch self {\n case let .hostname(country, city, _):\n return [.country(country), .city(country, city)]\n\n case let .city(country, _):\n return [.country(country)]\n\n case .country:\n return []\n }\n }\n\n public var debugDescription: String {\n var output = "RelayLocation."\n\n switch self {\n case let .country(country):\n output += "country(\(String(reflecting: country)))"\n\n case let .city(country, city):\n output += "city(\(String(reflecting: country)), \(String(reflecting: city)))"\n\n case let .hostname(country, city, host):\n output += "hostname(\(String(reflecting: country)), " +\n "\(String(reflecting: city)), " +\n "\(String(reflecting: host)))"\n }\n\n return output\n }\n\n public var stringRepresentation: String {\n switch self {\n case let .country(country):\n return country\n case let .city(country, city):\n return "\(country)-\(city)"\n case let .hostname(country, city, host):\n return "\(country)-\(city)-\(host)"\n }\n }\n}\n\npublic struct UserSelectedRelays: Codable, Equatable, Sendable {\n public let locations: [RelayLocation]\n public let customListSelection: CustomListSelection?\n\n public init(locations: [RelayLocation], customListSelection: CustomListSelection? = nil) {\n self.locations = locations\n self.customListSelection = customListSelection\n }\n}\n\nextension UserSelectedRelays {\n public struct CustomListSelection: Codable, Equatable, Sendable {\n /// The ID of the custom list that the selected relays belong to.\n public let listId: UUID\n /// Whether the selected relays are subnodes or the custom list itself.\n public let isList: Bool\n\n public init(listId: UUID, isList: Bool) {\n self.listId = listId\n self.isList = isList\n }\n }\n}\n\n@available(*, deprecated, message: "Use UserSelectedRelays instead.")\npublic struct RelayLocations: Codable, Equatable {\n public let locations: [RelayLocation]\n public let customListId: UUID?\n\n public init(locations: [RelayLocation], customListId: UUID? = nil) {\n self.locations = locations\n self.customListId = customListId\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\RelayLocation.swift | RelayLocation.swift | Swift | 4,366 | 0.95 | 0.076923 | 0.084746 | node-utils | 406 | 2025-05-06T07:30:19.287096 | Apache-2.0 | false | b45b6d40769945505d6030389d75a044 |
//\n// RESTTypes.swift\n// MullvadTypes\n//\n// Created by pronebird on 24/05/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n@preconcurrency import WireGuardKitTypes\n\npublic struct Account: Codable, Equatable, Sendable {\n public let id: String\n public let expiry: Date\n public let maxDevices: Int\n public let canAddDevices: Bool\n\n public init(id: String, expiry: Date, maxDevices: Int, canAddDevices: Bool) {\n self.id = id\n self.expiry = expiry\n self.maxDevices = maxDevices\n self.canAddDevices = canAddDevices\n }\n}\n\npublic struct Device: Codable, Equatable, Sendable {\n public let id: String\n public let name: String\n public let pubkey: PublicKey\n public let hijackDNS: Bool\n public let created: Date\n public let ipv4Address: IPAddressRange\n public let ipv6Address: IPAddressRange\n\n private enum CodingKeys: String, CodingKey {\n case hijackDNS = "hijackDns"\n case id, name, pubkey, created, ipv4Address, ipv6Address\n }\n\n public init(\n id: String,\n name: String,\n pubkey: PublicKey,\n hijackDNS: Bool,\n created: Date,\n ipv4Address: IPAddressRange,\n ipv6Address: IPAddressRange\n ) {\n self.id = id\n self.name = name\n self.pubkey = pubkey\n self.hijackDNS = hijackDNS\n self.created = created\n self.ipv4Address = ipv4Address\n self.ipv6Address = ipv6Address\n }\n}\n\npublic struct ProblemReportRequest: Codable, Sendable {\n public let address: String\n public let message: String\n public let log: String\n public let metadata: [String: String]\n\n public init(address: String, message: String, log: String, metadata: [String: String]) {\n self.address = address\n self.message = message\n self.log = log\n self.metadata = metadata\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\RESTTypes.swift | RESTTypes.swift | Swift | 1,897 | 0.95 | 0 | 0.111111 | awesome-app | 925 | 2025-06-11T01:15:46.417249 | GPL-3.0 | false | 2d679aad1c821bf7cf7c75ca06e353e0 |
//\n// Result+Extensions.swift\n// MullvadVPN\n//\n// Created by pronebird on 15/03/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nextension Result {\n public var value: Success? {\n switch self {\n case let .success(value):\n return value\n case .failure:\n return nil\n }\n }\n\n public var error: Failure? {\n switch self {\n case .success:\n return nil\n case let .failure(error):\n return error\n }\n }\n\n public var isSuccess: Bool {\n switch self {\n case .success:\n return true\n case .failure:\n return false\n }\n }\n\n public func tryMap<NewSuccess>(_ body: (Success) throws -> NewSuccess) -> Result<NewSuccess, Error> {\n Result<NewSuccess, Error> {\n let value = try self.get()\n\n return try body(value)\n }\n }\n\n @discardableResult public func inspectError(_ body: (Failure) -> Void) -> Self {\n if case let .failure(error) = self {\n body(error)\n }\n return self\n }\n}\n\nextension Result {\n public func flattenValue<T>() -> T? where Success == T? {\n switch self {\n case let .success(optional):\n return optional.flatMap { $0 }\n case .failure:\n return nil\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\Result+Extensions.swift | Result+Extensions.swift | Swift | 1,385 | 0.95 | 0.109375 | 0.125 | vue-tools | 400 | 2023-07-27T21:34:46.091924 | GPL-3.0 | false | e47a7855eb65ecb5409d5d1a05bddb80 |
//\n// StringDecodingError.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2024-12-02.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\npublic struct StringDecodingError: LocalizedError {\n public let data: Data\n\n public init(data: Data) {\n self.data = data\n }\n\n public var errorDescription: String? {\n "Failed to decode string from data."\n }\n}\n\npublic struct StringEncodingError: LocalizedError {\n public let string: String\n\n public init(string: String) {\n self.string = string\n }\n\n public var errorDescription: String? {\n "Failed to encode string into data."\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\StringConversionError.swift | StringConversionError.swift | Swift | 638 | 0.8 | 0 | 0.28 | vue-tools | 609 | 2024-05-15T20:26:23.704522 | BSD-3-Clause | false | 456cfb6a97887eff0a125c23189011f6 |
//\n// TransportLayer.swift\n// MullvadTypes\n//\n// Created by Marco Nikic on 2023-11-24.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\npublic enum TransportLayer: Codable, Sendable {\n case udp\n case tcp\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\TransportLayer.swift | TransportLayer.swift | Swift | 248 | 0.95 | 0 | 0.583333 | python-kit | 144 | 2023-10-08T00:53:21.600073 | GPL-3.0 | false | cf730781ef894440d65c64bad5da4ee0 |
//\n// WrappingError.swift\n// MullvadTypes\n//\n// Created by pronebird on 23/09/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\n/// Protocol describing errors that may contain underlying errors.\npublic protocol WrappingError: Error {\n var underlyingError: Error? { get }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\WrappingError.swift | WrappingError.swift | Swift | 317 | 0.95 | 0 | 0.666667 | vue-tools | 354 | 2025-02-23T14:50:58.290332 | MIT | false | 143450cd9069293727137d6fee993000 |
//\n// DaitaV2Parameters.swift\n// MullvadTypes\n//\n// Created by Marco Nikic on 2024-11-12.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\npublic struct DaitaV2Parameters: Equatable, Sendable {\n public let machines: String\n public let maximumEvents: UInt32\n public let maximumActions: UInt32\n public let maximumPadding: Double\n public let maximumBlocking: Double\n\n public init(\n machines: String,\n maximumEvents: UInt32,\n maximumActions: UInt32,\n maximumPadding: Double,\n maximumBlocking: Double\n ) {\n self.machines = machines\n self.maximumEvents = maximumEvents\n self.maximumActions = maximumActions\n self.maximumPadding = maximumPadding\n self.maximumBlocking = maximumBlocking\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\Protocols\DaitaV2Parameters.swift | DaitaV2Parameters.swift | Swift | 814 | 0.95 | 0 | 0.25 | python-kit | 506 | 2024-10-16T19:17:15.588431 | Apache-2.0 | false | bf047da35ac6e0f6843c18d4e6078b5f |
//\n// PostQuantumKeyReceiver.swift\n// MullvadTypes\n//\n// Created by Marco Nikic on 2024-07-04.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport NetworkExtension\nimport WireGuardKitTypes\n\npublic class EphemeralPeerReceiver: EphemeralPeerReceiving, TunnelProvider {\n public func tunnelHandle() throws -> Int32 {\n try tunnelProvider.tunnelHandle()\n }\n\n public func wgFunctions() -> WgFunctionPointers {\n tunnelProvider.wgFunctions()\n }\n\n unowned let tunnelProvider: any TunnelProvider\n let keyReceiver: any EphemeralPeerReceiving\n\n public init(tunnelProvider: TunnelProvider, keyReceiver: any EphemeralPeerReceiving) {\n self.tunnelProvider = tunnelProvider\n self.keyReceiver = keyReceiver\n }\n\n // MARK: - EphemeralPeerReceiving\n\n public func receivePostQuantumKey(\n _ key: PreSharedKey,\n ephemeralKey: PrivateKey,\n daitaParameters: DaitaV2Parameters?\n ) {\n let semaphore = DispatchSemaphore(value: 0)\n Task {\n await keyReceiver.receivePostQuantumKey(key, ephemeralKey: ephemeralKey, daitaParameters: daitaParameters)\n semaphore.signal()\n }\n semaphore.wait()\n }\n\n public func receiveEphemeralPeerPrivateKey(\n _ ephemeralPeerPrivateKey: PrivateKey,\n daitaParameters: DaitaV2Parameters?\n ) {\n let semaphore = DispatchSemaphore(value: 0)\n Task {\n await keyReceiver.receiveEphemeralPeerPrivateKey(ephemeralPeerPrivateKey, daitaParameters: daitaParameters)\n semaphore.signal()\n }\n semaphore.wait()\n }\n\n public func ephemeralPeerExchangeFailed() {\n keyReceiver.ephemeralPeerExchangeFailed()\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\Protocols\EphemeralPeerReceiver.swift | EphemeralPeerReceiver.swift | Swift | 1,749 | 0.95 | 0.033333 | 0.156863 | awesome-app | 653 | 2024-08-16T05:37:44.505384 | GPL-3.0 | false | d57975f095580d6f3fb98d876d973139 |
//\n// EphemeralPeerReceiving.swift\n// MullvadTypes\n//\n// Created by Andrew Bulhak on 2024-03-05.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport WireGuardKitTypes\n\npublic protocol EphemeralPeerReceiving {\n /// Called when successfully requesting an ephemeral peer with Post Quantum PSK enabled\n ///\n /// - Parameters:\n /// - key: The preshared key used by the Ephemeral Peer\n /// - ephemeralKey: The private key used by the Ephemeral Peer\n /// - daitaParameters: DAITA parameters\n func receivePostQuantumKey(_ key: PreSharedKey, ephemeralKey: PrivateKey, daitaParameters: DaitaV2Parameters?) async\n\n /// Called when successfully requesting an ephemeral peer with Daita enabled, and Post Quantum PSK disabled\n /// - Parameters:\n /// - _: The private key used by the Ephemeral Peer\n /// - daitaParameters: DAITA parameters\n func receiveEphemeralPeerPrivateKey(_: PrivateKey, daitaParameters: DaitaV2Parameters?) async\n\n /// Called when an ephemeral peer could not be successfully negotiated\n func ephemeralPeerExchangeFailed()\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\Protocols\EphemeralPeerReceiving.swift | EphemeralPeerReceiving.swift | Swift | 1,126 | 0.95 | 0 | 0.72 | react-lib | 580 | 2024-06-06T10:10:46.001962 | BSD-3-Clause | false | 3ee92e1a4bf3e274c26123d5e0fed749 |
//\n// NetworkExtension+HiddenSymbols.swift\n// MullvadTypes\n//\n// Created by Marco Nikic on 2024-12-04.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport NetworkExtension\n\n#if swift(>=6)\n#if compiler(>=6)\npublic typealias NWTCPConnection = __NWTCPConnection\npublic typealias NWHostEndpoint = __NWHostEndpoint\n#endif\n#endif\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\Protocols\NetworkExtension+HiddenSymbols.swift | NetworkExtension+HiddenSymbols.swift | Swift | 363 | 0.95 | 0.117647 | 0.733333 | vue-tools | 679 | 2025-03-10T18:49:07.200385 | GPL-3.0 | false | 0e371a047bc5b1960541ba6906928e51 |
//\n// TunnelProvider.swift\n// MullvadTypes\n//\n// Created by Marco Nikic on 2024-07-04.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport NetworkExtension\n\npublic protocol TunnelProvider: AnyObject {\n func tunnelHandle() throws -> Int32\n func wgFunctions() -> WgFunctionPointers\n}\n\npublic typealias TcpOpenFunction = @convention(c) (Int32, UnsafePointer<CChar>?, UInt64) -> Int32\npublic typealias TcpCloseFunction = @convention(c) (Int32, Int32) -> Int32\npublic typealias TcpSendFunction = @convention(c) (Int32, Int32, UnsafePointer<UInt8>?, Int32) -> Int32\npublic typealias TcpRecvFunction = @convention(c) (Int32, Int32, UnsafeMutablePointer<UInt8>?, Int32) -> Int32\n\npublic struct WgFunctionPointers {\n public let open: TcpOpenFunction\n public let close: TcpCloseFunction\n public let receive: TcpRecvFunction\n public let send: TcpSendFunction\n\n public init(open: TcpOpenFunction, close: TcpCloseFunction, receive: TcpRecvFunction, send: TcpSendFunction) {\n self.open = open\n self.close = close\n self.receive = receive\n self.send = send\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadTypes\Protocols\TunnelProvider.swift | TunnelProvider.swift | Swift | 1,137 | 0.95 | 0 | 0.241379 | react-lib | 929 | 2023-11-06T16:44:22.906659 | BSD-3-Clause | false | 9fa6034635a11fb6519164db3db7c0c2 |
//\n// AppDelegate.swift\n// MullvadVPN\n//\n// Created by pronebird on 19/03/2019.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport BackgroundTasks\nimport MullvadLogging\nimport MullvadMockData\nimport MullvadREST\nimport MullvadRustRuntime\nimport MullvadSettings\nimport MullvadTypes\nimport Operations\nimport StoreKit\nimport UIKit\nimport UserNotifications\n\n@main\nclass AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, StorePaymentManagerDelegate,\n @unchecked Sendable {\n nonisolated(unsafe) private var logger: Logger!\n\n #if targetEnvironment(simulator)\n private var simulatorTunnelProviderHost: SimulatorTunnelProviderHost?\n #endif\n\n private let operationQueue = AsyncOperationQueue.makeSerial()\n\n private(set) var tunnelStore: TunnelStore!\n nonisolated(unsafe) private(set) var tunnelManager: TunnelManager!\n private(set) var addressCache: REST.AddressCache!\n\n private var proxyFactory: ProxyFactoryProtocol!\n private(set) var apiProxy: APIQuerying!\n private(set) var accountsProxy: RESTAccountHandling!\n nonisolated(unsafe) private(set) var devicesProxy: DeviceHandling!\n\n private(set) var addressCacheTracker: AddressCacheTracker!\n nonisolated(unsafe) private(set) var relayCacheTracker: RelayCacheTracker!\n nonisolated(unsafe) private(set) var storePaymentManager: StorePaymentManager!\n nonisolated(unsafe) private var transportMonitor: TransportMonitor!\n nonisolated(unsafe) private var apiTransportMonitor: APITransportMonitor!\n private var settingsObserver: TunnelBlockObserver!\n private var migrationManager: MigrationManager!\n\n nonisolated(unsafe) private(set) var accessMethodRepository = AccessMethodRepository()\n private(set) var appPreferences = AppPreferences()\n private(set) var shadowsocksLoader: ShadowsocksLoaderProtocol!\n private(set) var configuredTransportProvider: ProxyConfigurationTransportProvider!\n private(set) var ipOverrideRepository = IPOverrideRepository()\n private(set) var relaySelector: RelaySelectorWrapper!\n private var launchArguments = LaunchArguments()\n private var encryptedDNSTransport: EncryptedDNSTransport!\n\n // MARK: - Application lifecycle\n\n // swiftlint:disable:next function_body_length\n func application(\n _ application: UIApplication,\n didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?\n ) -> Bool {\n if let overriddenLaunchArguments = try? ProcessInfo.processInfo.decode(LaunchArguments.self) {\n launchArguments = overriddenLaunchArguments\n }\n\n if launchArguments.areAnimationsDisabled {\n UIView.setAnimationsEnabled(false)\n }\n\n let containerURL = ApplicationConfiguration.containerURL\n migrationManager = MigrationManager(cacheDirectory: containerURL)\n configureLogging()\n\n addressCache = REST.AddressCache(canWriteToCache: true, cacheDirectory: containerURL)\n addressCache.loadFromFile()\n\n setUpProxies(containerURL: containerURL)\n\n let ipOverrideWrapper = IPOverrideWrapper(\n relayCache: RelayCache(cacheDirectory: containerURL),\n ipOverrideRepository: ipOverrideRepository\n )\n\n let tunnelSettingsListener = TunnelSettingsListener()\n let tunnelSettingsUpdater = SettingsUpdater(listener: tunnelSettingsListener)\n\n let backgroundTaskProvider = BackgroundTaskProvider(\n backgroundTimeRemaining: application.backgroundTimeRemaining,\n application: application\n )\n\n relayCacheTracker = RelayCacheTracker(\n relayCache: ipOverrideWrapper,\n backgroundTaskProvider: backgroundTaskProvider,\n apiProxy: apiProxy\n )\n\n addressCacheTracker = AddressCacheTracker(\n backgroundTaskProvider: backgroundTaskProvider,\n apiProxy: apiProxy,\n store: addressCache\n )\n\n tunnelStore = TunnelStore(application: backgroundTaskProvider)\n\n relaySelector = RelaySelectorWrapper(\n relayCache: ipOverrideWrapper\n )\n tunnelManager = createTunnelManager(\n backgroundTaskProvider: backgroundTaskProvider,\n relaySelector: relaySelector\n )\n\n settingsObserver = TunnelBlockObserver(didUpdateTunnelSettings: { _, settings in\n tunnelSettingsListener.onNewSettings?(settings)\n })\n tunnelManager.addObserver(settingsObserver)\n\n storePaymentManager = StorePaymentManager(\n backgroundTaskProvider: backgroundTaskProvider,\n queue: .default(),\n apiProxy: apiProxy,\n accountsProxy: accountsProxy,\n transactionLog: .default\n )\n let urlSessionTransport = URLSessionTransport(urlSession: REST.makeURLSession(addressCache: addressCache))\n let shadowsocksCache = ShadowsocksConfigurationCache(cacheDirectory: containerURL)\n let shadowsocksRelaySelector = ShadowsocksRelaySelector(\n relayCache: ipOverrideWrapper\n )\n\n shadowsocksLoader = ShadowsocksLoader(\n cache: shadowsocksCache,\n relaySelector: shadowsocksRelaySelector,\n settingsUpdater: tunnelSettingsUpdater\n )\n\n encryptedDNSTransport = EncryptedDNSTransport(urlSession: urlSessionTransport.urlSession)\n\n configuredTransportProvider = ProxyConfigurationTransportProvider(\n shadowsocksLoader: shadowsocksLoader,\n addressCache: addressCache,\n encryptedDNSTransport: encryptedDNSTransport\n )\n\n let transportStrategy = TransportStrategy(\n datasource: accessMethodRepository,\n shadowsocksLoader: shadowsocksLoader\n )\n\n let transportProvider = TransportProvider(\n urlSessionTransport: urlSessionTransport,\n addressCache: addressCache,\n transportStrategy: transportStrategy,\n encryptedDNSTransport: encryptedDNSTransport\n )\n\n let apiRequestFactory = MullvadApiRequestFactory(apiContext: REST.apiContext)\n let apiTransportProvider = APITransportProvider(requestFactory: apiRequestFactory)\n\n apiTransportMonitor = APITransportMonitor(\n tunnelManager: tunnelManager,\n tunnelStore: tunnelStore,\n requestFactory: apiRequestFactory\n )\n\n setUpTransportMonitor(transportProvider: transportProvider)\n setUpSimulatorHost(\n transportProvider: transportProvider,\n apiTransportProvider: apiTransportProvider,\n relaySelector: relaySelector\n )\n\n registerBackgroundTasks()\n setupPaymentHandler()\n setupNotifications()\n addApplicationNotifications(application: application)\n\n startInitialization(application: application)\n\n return true\n }\n\n private func createTunnelManager(\n backgroundTaskProvider: BackgroundTaskProviding,\n relaySelector: RelaySelectorProtocol\n ) -> TunnelManager {\n return TunnelManager(\n backgroundTaskProvider: backgroundTaskProvider,\n tunnelStore: tunnelStore,\n relayCacheTracker: relayCacheTracker,\n accountsProxy: accountsProxy,\n devicesProxy: devicesProxy,\n apiProxy: apiProxy,\n accessTokenManager: proxyFactory.configuration.accessTokenManager,\n relaySelector: relaySelector\n )\n }\n\n private func setUpProxies(containerURL: URL) {\n if launchArguments.target == .screenshots {\n proxyFactory = MockProxyFactory.makeProxyFactory(\n transportProvider: REST.AnyTransportProvider { [weak self] in\n self?.transportMonitor.makeTransport()\n },\n apiTransportProvider: REST.AnyAPITransportProvider { [weak self] in\n self?.apiTransportMonitor.makeTransport()\n },\n addressCache: addressCache\n )\n } else {\n proxyFactory = REST.ProxyFactory.makeProxyFactory(\n transportProvider: REST.AnyTransportProvider { [weak self] in\n self?.transportMonitor.makeTransport()\n },\n apiTransportProvider: REST.AnyAPITransportProvider { [weak self] in\n self?.apiTransportMonitor.makeTransport()\n },\n addressCache: addressCache\n )\n }\n apiProxy = proxyFactory.createAPIProxy()\n accountsProxy = proxyFactory.createAccountsProxy()\n devicesProxy = proxyFactory.createDevicesProxy()\n }\n\n private func setUpTransportMonitor(transportProvider: TransportProvider) {\n transportMonitor = TransportMonitor(\n tunnelManager: tunnelManager,\n tunnelStore: tunnelStore,\n transportProvider: transportProvider\n )\n }\n\n private func setUpSimulatorHost(\n transportProvider: TransportProvider,\n apiTransportProvider: APITransportProvider,\n relaySelector: RelaySelectorWrapper\n ) {\n #if targetEnvironment(simulator)\n // Configure mock tunnel provider on simulator\n simulatorTunnelProviderHost = SimulatorTunnelProviderHost(\n relaySelector: relaySelector,\n transportProvider: transportProvider,\n apiTransportProvider: apiTransportProvider\n )\n SimulatorTunnelProvider.shared.delegate = simulatorTunnelProviderHost\n #endif\n }\n\n // MARK: - UISceneSession lifecycle\n\n func application(\n _ application: UIApplication,\n configurationForConnecting connectingSceneSession: UISceneSession,\n options: UIScene.ConnectionOptions\n ) -> UISceneConfiguration {\n let sceneConfiguration = UISceneConfiguration(\n name: "Default Configuration",\n sessionRole: connectingSceneSession.role\n )\n sceneConfiguration.delegateClass = SceneDelegate.self\n\n return sceneConfiguration\n }\n\n func application(\n _ application: UIApplication,\n didDiscardSceneSessions sceneSessions: Set<UISceneSession>\n ) {}\n\n // MARK: - Notifications\n\n @objc private func didBecomeActive(_ notification: Notification) {\n tunnelManager.startPeriodicPrivateKeyRotation()\n relayCacheTracker.startPeriodicUpdates()\n addressCacheTracker.startPeriodicUpdates()\n }\n\n @objc private func willResignActive(_ notification: Notification) {\n tunnelManager.stopPeriodicPrivateKeyRotation()\n relayCacheTracker.stopPeriodicUpdates()\n addressCacheTracker.stopPeriodicUpdates()\n }\n\n @objc private func didEnterBackground(_ notification: Notification) {\n scheduleBackgroundTasks()\n }\n\n // MARK: - Background tasks\n\n private func registerBackgroundTasks() {\n registerAppRefreshTask()\n registerAddressCacheUpdateTask()\n registerKeyRotationTask()\n }\n\n private func registerAppRefreshTask() {\n let isRegistered = BGTaskScheduler.shared.register(\n forTaskWithIdentifier: BackgroundTask.appRefresh.identifier,\n using: .main\n ) { [self] task in\n\n nonisolated(unsafe) let handle = relayCacheTracker.updateRelays { result in\n task.setTaskCompleted(success: result.isSuccess)\n }\n\n task.expirationHandler = { @Sendable in\n handle.cancel()\n }\n\n scheduleAppRefreshTask()\n }\n\n if isRegistered {\n logger.debug("Registered app refresh task.")\n } else {\n logger.error("Failed to register app refresh task.")\n }\n }\n\n private func registerKeyRotationTask() {\n let isRegistered = BGTaskScheduler.shared.register(\n forTaskWithIdentifier: BackgroundTask.privateKeyRotation.identifier,\n using: .main\n ) { [self] task in\n nonisolated(unsafe) let handle = tunnelManager.rotatePrivateKey { [self] error in\n scheduleKeyRotationTask()\n task.setTaskCompleted(success: error == nil)\n }\n\n task.expirationHandler = { @Sendable in\n handle.cancel()\n }\n }\n\n if isRegistered {\n logger.debug("Registered private key rotation task.")\n } else {\n logger.error("Failed to register private key rotation task.")\n }\n }\n\n private func registerAddressCacheUpdateTask() {\n let isRegistered = BGTaskScheduler.shared.register(\n forTaskWithIdentifier: BackgroundTask.addressCacheUpdate.identifier,\n using: .main\n ) { [self] task in\n nonisolated(unsafe) let handle = addressCacheTracker.updateEndpoints { [self] result in\n scheduleAddressCacheUpdateTask()\n task.setTaskCompleted(success: result.isSuccess)\n }\n\n task.expirationHandler = { @Sendable in\n handle.cancel()\n }\n }\n\n if isRegistered {\n logger.debug("Registered address cache update task.")\n } else {\n logger.error("Failed to register address cache update task.")\n }\n }\n\n private func scheduleBackgroundTasks() {\n scheduleAppRefreshTask()\n scheduleKeyRotationTask()\n scheduleAddressCacheUpdateTask()\n }\n\n private func scheduleAppRefreshTask() {\n do {\n let date = relayCacheTracker.getNextUpdateDate()\n\n let request = BGAppRefreshTaskRequest(identifier: BackgroundTask.appRefresh.identifier)\n request.earliestBeginDate = date\n\n logger.debug("Schedule app refresh task at \(date.logFormatted).")\n\n try BGTaskScheduler.shared.submit(request)\n } catch {\n logger.error(error: error, message: "Could not schedule app refresh task.")\n }\n }\n\n private func scheduleKeyRotationTask() {\n do {\n guard let date = tunnelManager.getNextKeyRotationDate() else {\n return\n }\n\n let request = BGProcessingTaskRequest(identifier: BackgroundTask.privateKeyRotation.identifier)\n request.requiresNetworkConnectivity = true\n request.earliestBeginDate = date\n\n logger.debug("Schedule key rotation task at \(date.logFormatted).")\n\n try BGTaskScheduler.shared.submit(request)\n } catch {\n logger.error(error: error, message: "Could not schedule private key rotation task.")\n }\n }\n\n private func scheduleAddressCacheUpdateTask() {\n do {\n let date = addressCacheTracker.nextScheduleDate()\n\n let request = BGProcessingTaskRequest(identifier: BackgroundTask.addressCacheUpdate.identifier)\n request.requiresNetworkConnectivity = true\n request.earliestBeginDate = date\n\n logger.debug("Schedule address cache update task at \(date.logFormatted).")\n\n try BGTaskScheduler.shared.submit(request)\n } catch {\n logger.error(error: error, message: "Could not schedule address cache update task.")\n }\n }\n\n // MARK: - Private\n\n private func configureLogging() {\n var loggerBuilder = LoggerBuilder(header: "MullvadVPN version \(Bundle.main.productVersion)")\n loggerBuilder.addFileOutput(\n fileURL: ApplicationConfiguration.newLogFileURL(for: .mainApp, in: ApplicationConfiguration.containerURL)\n )\n #if DEBUG\n loggerBuilder.addOSLogOutput(subsystem: ApplicationTarget.mainApp.bundleIdentifier)\n #endif\n loggerBuilder.install()\n\n logger = Logger(label: "AppDelegate")\n }\n\n private func addApplicationNotifications(application: UIApplication) {\n let notificationCenter = NotificationCenter.default\n\n notificationCenter.addObserver(\n self,\n selector: #selector(didBecomeActive(_:)),\n name: UIApplication.didBecomeActiveNotification,\n object: application\n )\n notificationCenter.addObserver(\n self,\n selector: #selector(willResignActive(_:)),\n name: UIApplication.willResignActiveNotification,\n object: application\n )\n notificationCenter.addObserver(\n self,\n selector: #selector(didEnterBackground(_:)),\n name: UIApplication.didEnterBackgroundNotification,\n object: application\n )\n }\n\n private func setupPaymentHandler() {\n storePaymentManager.delegate = self\n storePaymentManager.addPaymentObserver(tunnelManager)\n }\n\n private func setupNotifications() {\n NotificationManager.shared.notificationProviders = [\n LatestChangesNotificationProvider(appPreferences: appPreferences),\n TunnelStatusNotificationProvider(tunnelManager: tunnelManager),\n AccountExpirySystemNotificationProvider(tunnelManager: tunnelManager),\n AccountExpiryInAppNotificationProvider(tunnelManager: tunnelManager),\n NewDeviceNotificationProvider(tunnelManager: tunnelManager),\n ]\n UNUserNotificationCenter.current().delegate = self\n }\n\n private func startInitialization(application: UIApplication) {\n let wipeSettingsOperation = getWipeSettingsOperation()\n let loadTunnelStoreOperation = getLoadTunnelStoreOperation()\n let migrateSettingsOperation = getMigrateSettingsOperation(application: application)\n let initTunnelManagerOperation = getInitTunnelManagerOperation()\n\n migrateSettingsOperation.addDependencies([wipeSettingsOperation, loadTunnelStoreOperation])\n initTunnelManagerOperation.addDependency(migrateSettingsOperation)\n\n operationQueue.addOperations(\n [\n wipeSettingsOperation,\n loadTunnelStoreOperation,\n migrateSettingsOperation,\n initTunnelManagerOperation,\n ],\n waitUntilFinished: false\n )\n }\n\n private func getLoadTunnelStoreOperation() -> AsyncBlockOperation {\n AsyncBlockOperation(dispatchQueue: .main) { [self] finish in\n MainActor.assumeIsolated {\n tunnelStore.loadPersistentTunnels { [self] error in\n if let error {\n logger.error(\n error: error,\n message: "Failed to load persistent tunnels."\n )\n }\n finish(nil)\n }\n }\n }\n }\n\n private func getMigrateSettingsOperation(application: UIApplication) -> AsyncBlockOperation {\n AsyncBlockOperation(dispatchQueue: .main, block: { [self] (finish: @escaping @Sendable (Error?) -> Void) in\n MainActor.assumeIsolated {\n migrationManager\n .migrateSettings(store: SettingsManager.store) { [self] migrationResult in\n switch migrationResult {\n case .success:\n // Tell the tunnel to re-read tunnel configuration after migration.\n logger.debug("Successful migration from UI Process")\n tunnelManager.reconnectTunnel(selectNewRelay: true)\n fallthrough\n\n case .nothing:\n logger.debug("Attempted migration from UI Process, but found nothing to do")\n finish(nil)\n\n case let .failure(error):\n logger.error("Failed migration from UI Process: \(error)")\n MainActor.assumeIsolated {\n let migrationUIHandler = application.connectedScenes\n .first { $0 is SettingsMigrationUIHandler } as? SettingsMigrationUIHandler\n\n if let migrationUIHandler {\n migrationUIHandler.showMigrationError(error) {\n MainActor.assumeIsolated {\n finish(error)\n }\n }\n } else {\n finish(error)\n }\n }\n }\n }\n }\n })\n }\n\n private func getInitTunnelManagerOperation() -> AsyncBlockOperation {\n // This operation is always treated as successful no matter what the configuration load yields.\n // If the tunnel settings or device state can't be read, we simply pretend they are not there\n // and leave user in logged out state. VPN config will be removed as well.\n AsyncBlockOperation(dispatchQueue: .main) { finish in\n self.tunnelManager.loadConfiguration {\n self.logger.debug("Finished initialization.")\n\n NotificationManager.shared.updateNotifications()\n self.storePaymentManager.start()\n\n finish(nil)\n }\n }\n }\n\n /// Returns an operation that acts on the following conditions:\n /// 1. If the app has never been launched, preload with default settings.\n /// - or -\n /// 1. Has the app been launched at least once after install? (`FirstTimeLaunch.hasFinished`)\n /// 2. Has the app - at some point in time - been updated from a version compatible with wiping settings?\n /// (`SettingsManager.getShouldWipeSettings()`)\n /// If (1) is `false` and (2) is `true`, we know that the app has been freshly installed/reinstalled and is\n /// compatible, thus triggering a settings wipe.\n private func getWipeSettingsOperation() -> AsyncBlockOperation {\n AsyncBlockOperation {\n let appHasNeverBeenLaunched = !FirstTimeLaunch.hasFinished && !SettingsManager.getShouldWipeSettings()\n let appWasLaunchedAfterReinstall = !FirstTimeLaunch.hasFinished && SettingsManager.getShouldWipeSettings()\n\n if appHasNeverBeenLaunched {\n try? SettingsManager.writeSettings(LatestTunnelSettings())\n } else if appWasLaunchedAfterReinstall {\n if let deviceState = try? SettingsManager.readDeviceState(),\n let accountData = deviceState.accountData,\n let deviceData = deviceState.deviceData {\n _ = self.devicesProxy.deleteDevice(\n accountNumber: accountData.number,\n identifier: deviceData.identifier,\n retryStrategy: .noRetry\n ) { _ in\n // Do nothing.\n }\n }\n\n SettingsManager.resetStore(completely: true)\n try? SettingsManager.writeSettings(LatestTunnelSettings())\n\n // Default access methods need to be repopulated again after settings wipe.\n self.accessMethodRepository.addDefaultsMethods()\n // At app startup, the relay cache tracker will get populated with a list of overriden IPs.\n // The overriden IPs will get wiped, therefore, the cache needs to be pruned as well.\n try? self.relayCacheTracker.refreshCachedRelays()\n }\n\n FirstTimeLaunch.setHasFinished()\n SettingsManager.setShouldWipeSettings()\n }\n }\n\n // MARK: - StorePaymentManagerDelegate\n\n nonisolated func storePaymentManager(\n _ manager: StorePaymentManager,\n didRequestAccountTokenFor payment: SKPayment\n ) -> String? {\n // Since we do not persist the relation between payment and account number between the\n // app launches, we assume that all successful purchases belong to the active account\n // number.\n tunnelManager.deviceState.accountData?.number\n }\n\n // MARK: - UNUserNotificationCenterDelegate\n\n nonisolated func userNotificationCenter(\n _ center: UNUserNotificationCenter,\n didReceive response: UNNotificationResponse,\n withCompletionHandler completionHandler: @escaping () -> Void\n ) {\n nonisolated(unsafe) let nonisolatedResponse = response\n nonisolated(unsafe) let nonisolatedCompletionHandler = completionHandler\n\n let blockOperation = AsyncBlockOperation(dispatchQueue: .main) {\n NotificationManager.shared.handleSystemNotificationResponse(nonisolatedResponse)\n\n nonisolatedCompletionHandler()\n }\n\n operationQueue.addOperation(blockOperation)\n }\n\n nonisolated func userNotificationCenter(\n _ center: UNUserNotificationCenter,\n willPresent notification: UNNotification,\n withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void\n ) {\n completionHandler([.list, .banner, .sound])\n }\n\n // swiftlint:disable:next file_length\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\AppDelegate.swift | AppDelegate.swift | Swift | 25,154 | 0.95 | 0.043011 | 0.076782 | node-utils | 494 | 2024-08-02T03:41:01.953955 | MIT | false | 1ee837c6b990fbefc1bebde5ec0d2d98 |
//\n// BackgroundTask.swift\n// MullvadVPN\n//\n// Created by pronebird on 09/06/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\n/**\n Background tasks defined by the app.\n\n When adding new background tasks, don't forget to update `BGTaskSchedulerPermittedIdentifiers` key in `Info.plist` by adding a task identifier\n using the following pattern:\n\n ```\n $(APPLICATION_IDENTIFIER).<TaskName>\n ```\n\n Note that `<TaskName>` is capitalized in plist, but the label for enum case should start with a lowercase letter.\n */\nenum BackgroundTask: String {\n case appRefresh, privateKeyRotation, addressCacheUpdate\n\n /// Returns background task identifier.\n /// Use it when registering or scheduling tasks with `BGTaskScheduler`.\n var identifier: String {\n "\(ApplicationTarget.mainApp.bundleIdentifier).\(capitalizedRawValue)"\n }\n\n private var capitalizedRawValue: String {\n rawValue.prefix(1).uppercased() + rawValue.dropFirst()\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\BackgroundTask.swift | BackgroundTask.swift | Swift | 997 | 0.95 | 0.028571 | 0.392857 | python-kit | 777 | 2024-10-18T13:27:25.791285 | Apache-2.0 | false | 30ff349e4c51aa39d552eaa4512a0857 |
//\n// SceneDelegate.swift\n// MullvadVPN\n//\n// Created by pronebird on 20/05/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadLogging\nimport MullvadREST\nimport MullvadSettings\nimport MullvadTypes\nimport Operations\nimport UIKit\n\nclass SceneDelegate: UIResponder, UIWindowSceneDelegate, @preconcurrency SettingsMigrationUIHandler {\n private let logger = Logger(label: "SceneDelegate")\n\n var window: UIWindow?\n private var privacyOverlayWindow: UIWindow?\n private var isSceneConfigured = false\n\n private var appCoordinator: ApplicationCoordinator?\n private var accountDataThrottling: AccountDataThrottling?\n private var deviceDataThrottling: DeviceDataThrottling?\n\n private var tunnelObserver: TunnelObserver?\n\n private var appDelegate: AppDelegate {\n // swiftlint:disable:next force_cast\n UIApplication.shared.delegate as! AppDelegate\n }\n\n private var accessMethodRepository: AccessMethodRepositoryProtocol {\n appDelegate.accessMethodRepository\n }\n\n private var tunnelManager: TunnelManager {\n appDelegate.tunnelManager\n }\n\n // MARK: - Private\n\n private func addTunnelObserver() {\n let tunnelObserver = TunnelBlockObserver(\n didLoadConfiguration: { [weak self] _ in\n self?.configureScene()\n },\n didUpdateDeviceState: { [weak self] _, deviceState, _ in\n self?.deviceStateDidChange(deviceState)\n }\n )\n\n self.tunnelObserver = tunnelObserver\n\n tunnelManager.addObserver(tunnelObserver)\n }\n\n private func configureScene() {\n guard !isSceneConfigured else { return }\n\n isSceneConfigured = true\n\n accountDataThrottling = AccountDataThrottling(tunnelManager: tunnelManager)\n deviceDataThrottling = DeviceDataThrottling(tunnelManager: tunnelManager)\n refreshLoginMetadata(forceUpdate: true)\n\n appCoordinator = ApplicationCoordinator(\n tunnelManager: tunnelManager,\n storePaymentManager: appDelegate.storePaymentManager,\n relayCacheTracker: appDelegate.relayCacheTracker,\n apiProxy: appDelegate.apiProxy,\n devicesProxy: appDelegate.devicesProxy,\n accountsProxy: appDelegate.accountsProxy,\n outgoingConnectionService: OutgoingConnectionService(\n outgoingConnectionProxy: OutgoingConnectionProxy(\n urlSession: REST.makeURLSession(addressCache: appDelegate.addressCache),\n hostname: ApplicationConfiguration.hostName\n )\n ),\n appPreferences: appDelegate.appPreferences,\n accessMethodRepository: accessMethodRepository,\n transportProvider: appDelegate.configuredTransportProvider,\n ipOverrideRepository: appDelegate.ipOverrideRepository,\n relaySelectorWrapper: appDelegate.relaySelector\n )\n\n appCoordinator?.onShowSettings = { [weak self] in\n // Refresh account data and device each time user opens settings\n self?.refreshLoginMetadata(forceUpdate: true)\n }\n\n appCoordinator?.onShowAccount = { [weak self] in\n // Refresh account data and device each time user opens account controller\n self?.refreshLoginMetadata(forceUpdate: true)\n }\n\n window?.rootViewController = appCoordinator?.rootViewController\n appCoordinator?.start()\n }\n\n private func setShowsPrivacyOverlay(_ showOverlay: Bool) {\n if showOverlay {\n privacyOverlayWindow?.isHidden = false\n privacyOverlayWindow?.makeKeyAndVisible()\n } else {\n privacyOverlayWindow?.isHidden = true\n window?.makeKeyAndVisible()\n }\n }\n\n private func deviceStateDidChange(_ deviceState: DeviceState) {\n switch deviceState {\n case .loggedOut, .revoked:\n resetLoginMetadataThrottling()\n\n case .loggedIn:\n break\n }\n }\n\n /**\n Refresh login metadata (account and device data) potentially throttling refresh requests based on recency of\n the last issued request.\n\n Account data is always refreshed when either settings or account are presented on screen, otherwise only when close\n to or past expiry.\n\n Both account and device data are refreshed regardless of other conditions when `forceUpdate` is `true`.\n\n For more information on exact timings used for throttling refresh requests refer to `AccountDataThrottling` and\n `DeviceDataThrottling` types.\n */\n private func refreshLoginMetadata(forceUpdate: Bool) {\n let condition: AccountDataThrottling.Condition\n\n if forceUpdate {\n condition = .always\n } else {\n let isPresentingSettings = appCoordinator?.isPresentingSettings ?? false\n let isPresentingAccount = appCoordinator?.isPresentingAccount ?? false\n\n condition = isPresentingSettings || isPresentingAccount ? .always : .whenCloseToExpiryAndBeyond\n }\n\n accountDataThrottling?.requestUpdate(condition: condition)\n deviceDataThrottling?.requestUpdate(forceUpdate: forceUpdate)\n }\n\n /**\n Reset throttling for login metadata making a subsequent refresh request execute unthrottled.\n */\n private func resetLoginMetadataThrottling() {\n accountDataThrottling?.reset()\n deviceDataThrottling?.reset()\n }\n\n // MARK: - UIWindowSceneDelegate\n\n func scene(\n _ scene: UIScene,\n willConnectTo session: UISceneSession,\n options connectionOptions: UIScene.ConnectionOptions\n ) {\n guard let windowScene = scene as? UIWindowScene else { return }\n\n window = UIWindow(windowScene: windowScene)\n window?.rootViewController = LaunchViewController()\n\n privacyOverlayWindow = UIWindow(windowScene: windowScene)\n privacyOverlayWindow?.rootViewController = LaunchViewController()\n privacyOverlayWindow?.windowLevel = .alert + 1\n\n window?.makeKeyAndVisible()\n\n addTunnelObserver()\n\n if tunnelManager.isConfigurationLoaded {\n configureScene()\n }\n }\n\n func sceneDidDisconnect(_ scene: UIScene) {}\n\n func sceneDidBecomeActive(_ scene: UIScene) {\n if isSceneConfigured {\n refreshLoginMetadata(forceUpdate: false)\n }\n\n setShowsPrivacyOverlay(false)\n }\n\n func sceneWillResignActive(_ scene: UIScene) {\n setShowsPrivacyOverlay(true)\n }\n\n func sceneWillEnterForeground(_ scene: UIScene) {}\n\n func sceneDidEnterBackground(_ scene: UIScene) {}\n\n // MARK: - SettingsMigrationUIHandler\n\n func showMigrationError(_ error: Error, completionHandler: @escaping () -> Void) {\n guard let appCoordinator else {\n completionHandler()\n return\n }\n\n let presentation = AlertPresentation(\n id: "settings-migration-error-alert",\n title: NSLocalizedString(\n "ALERT_TITLE",\n tableName: "SettingsMigrationUI",\n value: "Settings migration error",\n comment: ""\n ),\n message: Self.migrationErrorReason(error),\n buttons: [\n AlertAction(\n title: NSLocalizedString("Got it!", tableName: "SettingsMigrationUI", comment: ""),\n style: .default,\n handler: {\n completionHandler()\n }\n ),\n ]\n )\n\n let presenter = AlertPresenter(context: appCoordinator)\n presenter.showAlert(presentation: presentation, animated: true)\n }\n\n private static func migrationErrorReason(_ error: Error) -> String {\n if error is UnsupportedSettingsVersionError {\n return NSLocalizedString(\n "NEWER_STORED_SETTINGS_ERROR",\n tableName: "SettingsMigrationUI",\n value: """\n The version of settings stored on device is unrecognized.\\n Settings will be reset to defaults and the device will be logged out.\n """,\n comment: ""\n )\n } else {\n return NSLocalizedString(\n "INTERNAL_ERROR",\n tableName: "SettingsMigrationUI",\n value: """\n Internal error occurred. Settings will be reset to defaults and device logged out.\n """,\n comment: ""\n )\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\SceneDelegate.swift | SceneDelegate.swift | Swift | 8,589 | 0.95 | 0.035294 | 0.082126 | vue-tools | 479 | 2024-12-14T16:13:58.511162 | MIT | false | 234a9a2cfc4e48110b7b1d49288bc48d |
//\n// LocalNetworkProbe.swift\n// MullvadVPN\n//\n// Created by Marco Nikic on 2024-01-25.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport Network\n\nstruct LocalNetworkProbe {\n /// Does a best effort attempt to trigger the local network privacy alert.\n func triggerLocalNetworkPrivacyAlert() {\n let dispatchQueue = DispatchQueue(label: "com.mullvad.localNetworkAlert")\n let localIpv4Connection = NWConnection(\n to: NWEndpoint.hostPort(host: .ipv4(.broadcast), port: .any),\n using: .udp\n )\n localIpv4Connection.start(queue: dispatchQueue)\n\n let localIpv6Connection = NWConnection(\n to: NWEndpoint.hostPort(host: .ipv6(.broadcast), port: .any),\n using: .udp\n )\n localIpv6Connection.start(queue: dispatchQueue)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\AccessMethodRepository\LocalNetworkProbe.swift | LocalNetworkProbe.swift | Swift | 854 | 0.95 | 0 | 0.32 | python-kit | 778 | 2024-02-08T20:24:42.196755 | MIT | false | 18b9f3b0e50edd7432d9adab791dec8e |
//\n// AddressCacheTracker.swift\n// MullvadVPN\n//\n// Created by pronebird on 08/12/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadLogging\nimport MullvadREST\nimport MullvadTypes\nimport Operations\nimport UIKit\n\nfinal class AddressCacheTracker: @unchecked Sendable {\n /// Update interval.\n private static let updateInterval: Duration = .days(1)\n\n /// Retry interval.\n private static let retryInterval: Duration = .minutes(15)\n\n /// Logger.\n private let logger = Logger(label: "AddressCache.Tracker")\n private let backgroundTaskProvider: BackgroundTaskProviding\n\n /// REST API proxy.\n private let apiProxy: APIQuerying\n\n /// Address cache.\n private let store: REST.AddressCache\n\n /// A flag that indicates whether periodic updates are running\n private var isPeriodicUpdatesEnabled = false\n\n /// The date of last failed attempt.\n private var lastFailureAttemptDate: Date?\n\n /// Timer used for scheduling periodic updates.\n private var timer: DispatchSourceTimer?\n\n /// Operation queue.\n private let operationQueue = AsyncOperationQueue.makeSerial()\n\n /// Lock used for synchronizing member access.\n private let nslock = NSLock()\n\n /// Designated initializer\n init(backgroundTaskProvider: BackgroundTaskProviding, apiProxy: APIQuerying, store: REST.AddressCache) {\n self.backgroundTaskProvider = backgroundTaskProvider\n self.apiProxy = apiProxy\n self.store = store\n }\n\n func startPeriodicUpdates() {\n nslock.lock()\n defer { nslock.unlock() }\n\n guard !isPeriodicUpdatesEnabled else {\n return\n }\n\n logger.debug("Start periodic address cache updates.")\n\n isPeriodicUpdatesEnabled = true\n\n let scheduleDate = _nextScheduleDate()\n\n logger.debug("Schedule address cache update at \(scheduleDate.logFormatted).")\n\n scheduleEndpointsUpdate(startTime: .now() + scheduleDate.timeIntervalSinceNow)\n }\n\n func stopPeriodicUpdates() {\n nslock.lock()\n defer { nslock.unlock() }\n\n guard isPeriodicUpdatesEnabled else { return }\n\n logger.debug("Stop periodic address cache updates.")\n\n isPeriodicUpdatesEnabled = false\n\n timer?.cancel()\n timer = nil\n }\n\n func updateEndpoints(completionHandler: ((sending Result<Bool, Error>) -> Void)? = nil) -> Cancellable {\n let operation = ResultBlockOperation<Bool> { finish -> Cancellable in\n guard self.nextScheduleDate() <= Date() else {\n finish(.success(false))\n return AnyCancellable()\n }\n\n return self.apiProxy.getAddressList(retryStrategy: .default) { result in\n self.setEndpoints(from: result)\n finish(result.map { _ in true })\n }\n }\n\n operation.completionQueue = .main\n operation.completionHandler = completionHandler\n\n operation.addObserver(\n BackgroundObserver(\n backgroundTaskProvider: backgroundTaskProvider,\n name: "Update endpoints",\n cancelUponExpiration: true\n )\n )\n\n operationQueue.addOperation(operation)\n\n return operation\n }\n\n func nextScheduleDate() -> Date {\n nslock.lock()\n defer { nslock.unlock() }\n\n return _nextScheduleDate()\n }\n\n private func setEndpoints(from result: Result<[AnyIPEndpoint], Error>) {\n nslock.lock()\n defer { nslock.unlock() }\n\n switch result {\n case let .success(endpoints):\n store.setEndpoints(endpoints)\n lastFailureAttemptDate = nil\n\n case let .failure(error as REST.Error):\n logger.error(\n error: error,\n message: "Failed to update address cache."\n )\n fallthrough\n\n default:\n lastFailureAttemptDate = Date()\n }\n }\n\n private func scheduleEndpointsUpdate(startTime: DispatchWallTime) {\n let newTimer = DispatchSource.makeTimerSource()\n newTimer.setEventHandler { [weak self] in\n self?.handleTimer()\n }\n\n newTimer.schedule(wallDeadline: startTime)\n newTimer.activate()\n\n timer?.cancel()\n timer = newTimer\n }\n\n private func handleTimer() {\n _ = updateEndpoints { _ in\n self.nslock.lock()\n defer { self.nslock.unlock() }\n\n guard self.isPeriodicUpdatesEnabled else { return }\n\n let scheduleDate = self._nextScheduleDate()\n\n self.logger\n .debug("Schedule next address cache update at \(scheduleDate.logFormatted).")\n\n self.scheduleEndpointsUpdate(startTime: .now() + scheduleDate.timeIntervalSinceNow)\n }\n }\n\n private func _nextScheduleDate() -> Date {\n let nextDate = lastFailureAttemptDate.map { date in\n Date(\n timeInterval: Self.retryInterval.timeInterval,\n since: date\n )\n } ?? Date(\n timeInterval: Self.updateInterval.timeInterval,\n since: store.getLastUpdateDate()\n )\n\n return max(nextDate, Date())\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\AddressCacheTracker\AddressCacheTracker.swift | AddressCacheTracker.swift | Swift | 5,222 | 0.95 | 0.021505 | 0.128571 | node-utils | 733 | 2023-12-11T00:02:49.008344 | BSD-3-Clause | false | 758779a18fade0d8f383de922c427291 |
//\n// AccessibilityIdentifier.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\npublic enum AccessibilityIdentifier: Equatable {\n // Buttons\n case addAccessMethodButton\n case accessMethodAddButton\n case accessMethodTestButton\n case accountButton\n case accessMethodUnreachableBackButton\n case accessMethodUnreachableSaveButton\n case agreeButton\n case alertOkButton\n case appLogsDoneButton\n case appLogsShareButton\n case applyButton\n case cancelButton\n case continueWithLoginButton\n case collapseButton\n case expandButton\n case createAccountButton\n case deleteButton\n case deviceCellRemoveButton\n case disconnectButton\n case revokedDeviceLoginButton\n case dnsSettingsEditButton\n case infoButton\n case copyButton\n case learnAboutPrivacyButton\n case logOutDeviceConfirmButton\n case logOutDeviceCancelButton\n case loginBarButton\n case loginTextFieldButton\n case logoutButton\n case purchaseButton\n case redeemVoucherButton\n case restorePurchasesButton\n case connectButton\n case selectLocationButton\n case closeSelectLocationButton\n case settingsButton\n case startUsingTheAppButton\n case problemReportAppLogsButton\n case problemReportSendButton\n case relayStatusCollapseButton\n case settingsDoneButton\n case openCustomListsMenuButton\n case addNewCustomListButton\n case editCustomListButton\n case saveCreateCustomListButton\n case confirmDeleteCustomListButton\n case cancelDeleteCustomListButton\n case customListLocationCheckmarkButton\n case listCustomListDoneButton\n case selectLocationFilterButton\n case relayFilterChipCloseButton\n case openPortSelectorMenuButton\n case cancelPurchaseListButton\n case acceptLocalNetworkSharingButton\n\n // Cells\n case deviceCell\n case accessMethodDirectCell\n case accessMethodBridgesCell\n case accessMethodEncryptedDNSCell\n case accessMethodProtocolSelectionCell\n case vpnSettingsCell\n case dnsSettingsAddServerCell\n case dnsSettingsUseCustomDNSCell\n case preferencesCell\n case versionCell\n case problemReportCell\n case faqCell\n case apiAccessCell\n case relayFilterProviderCell\n case wireGuardPortsCell\n case wireGuardObfuscationCell\n case udpOverTCPPortCell\n case quantumResistantTunnelCell\n case customListEditNameFieldCell\n case customListEditAddOrEditLocationCell\n case customListEditDeleteListCell\n case locationFilterOwnershipHeaderCell\n case locationFilterProvidersHeaderCell\n case ownershipMullvadOwnedCell\n case ownershipRentedCell\n case ownershipAnyCell\n case countryLocationCell\n case cityLocationCell\n case relayLocationCell\n case customListLocationCell\n case daitaConfirmAlertBackButton\n case daitaConfirmAlertEnableButton\n case multihopCell\n case daitaCell\n case daitaFilterPill\n case obfuscationFilterPill\n\n // Labels\n case accountPageDeviceNameLabel\n case socks5ServerCell\n case socks5PortCell\n case accountPagePaidUntilLabel\n case addAccessMethodTestStatusReachableLabel\n case addAccessMethodTestStatusTestingLabel\n case addAccessMethodTestStatusUnreachableLabel\n case headerDeviceNameLabel\n case connectionStatusConnectedLabel\n case connectionStatusConnectingLabel\n case connectionStatusNotConnectedLabel\n case welcomeAccountNumberLabel\n case connectionPanelDetailLabel\n case relayFilterChipLabel\n\n // Views\n case accessMethodProtocolPickerView\n case accessMethodUnreachableAlert\n case accountView\n case addLocationsView\n case addAccessMethodTableView\n case apiAccessView\n case alertContainerView\n case alertTitle\n case appLogsView\n case changeLogAlert\n case deviceManagementView\n case editAccessMethodView\n case headerBarView\n case loginView\n case outOfTimeView\n case termsOfServiceView\n case selectLocationView\n case selectLocationViewWrapper\n case selectLocationTableView\n case settingsTableView\n case vpnSettingsTableView\n case connectionView\n case problemReportView\n case problemReportSubmittedView\n case revokedDeviceView\n case welcomeView\n case deleteAccountView\n case settingsContainerView\n case newCustomListView\n case customListEditTableView\n case listCustomListsView\n case listCustomListsTableView\n case editCustomListEditLocationsView\n case editCustomListEditLocationsTableView\n case relayFilterChipView\n case dnsSettingsTableView\n case multihopView\n case daitaView\n\n // Other UI elements\n case accessMethodEnableSwitch\n case accessMethodNameTextField\n case logOutSpinnerAlertView\n case connectionPanelInAddressRow\n case connectionPanelOutAddressRow\n case connectionPanelOutIpv6AddressRow\n case connectionPanelServerLabel\n case customSwitch\n case customWireGuardPortTextField\n case dnsContentBlockersHeaderView\n case dnsSettingsEnterIPAddressTextField\n case loginStatusIconAuthenticating\n case loginStatusIconFailure\n case loginStatusIconSuccess\n case loginTextField\n case selectLocationSearchTextField\n case problemReportAppLogsTextView\n case problemReportEmailTextField\n case problemReportMessageTextView\n case deleteAccountTextField\n case socks5AuthenticationSwitch\n case statusImageView\n\n // DNS settings\n case includeAllNetworks\n case localNetworkSharing\n case dnsSettings\n case ipOverrides\n case wireGuardCustomPort\n case wireGuardObfuscationAutomatic\n case wireGuardObfuscationPort\n case wireGuardObfuscationOff\n case wireGuardObfuscationUdpOverTcp\n case wireGuardObfuscationShadowsocks\n case wireGuardObfuscationUdpOverTcpPort\n case wireGuardObfuscationShadowsocksPort\n case wireGuardPort(UInt16?)\n case udpOverTcpObfuscationSettings\n\n // Custom DNS\n case blockAll\n case blockAdvertising\n case blockTracking\n case blockMalware\n case blockGambling\n case blockAdultContent\n case blockSocialMedia\n case useCustomDNS\n case addDNSServer\n case dnsServer\n case dnsServerInfo\n\n // DAITA\n case daitaSwitch\n case daitaPromptAlert\n case daitaDirectOnlySwitch\n\n // Quantum resistance\n case quantumResistanceAutomatic\n case quantumResistanceOff\n case quantumResistanceOn\n\n // Multihop\n case multihopSwitch\n\n // WireGuard obfuscation settings\n case wireGuardObfuscationUdpOverTcpTable\n case wireGuardObfuscationShadowsocksTable\n\n // Error\n case unknown\n}\n\nextension AccessibilityIdentifier {\n public var asString: String {\n "\(self)"\n }\n}\n\nextension UIAccessibilityIdentification {\n @MainActor\n func setAccessibilityIdentifier(_ value: AccessibilityIdentifier?) {\n accessibilityIdentifier = value.map(\.asString)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Classes\AccessbilityIdentifier.swift | AccessbilityIdentifier.swift | Swift | 6,925 | 0.95 | 0 | 0.081897 | node-utils | 50 | 2024-07-28T16:06:51.800012 | Apache-2.0 | false | b1b6f90923dfa5a431d6454860d108cd |
//\n// AccountDataThrottling.swift\n// MullvadVPN\n//\n// Created by pronebird on 09/08/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\n\n/// Struct used for throttling UI calls to update account data via tunnel manager.\nstruct AccountDataThrottling {\n /// Default cooldown interval between requests.\n private static let defaultWaitInterval: Duration = .minutes(1)\n\n /// Cooldown interval used when account has already expired.\n private static let waitIntervalForExpiredAccount: Duration = .seconds(10)\n\n /// Interval in days when account is considered to be close to expiry.\n private static let closeToExpiryDays = 4\n\n enum Condition {\n /// Always update account data.\n case always\n\n /// Only update account data when account is close to expiry or already expired.\n case whenCloseToExpiryAndBeyond\n }\n\n let tunnelManager: TunnelManager\n private(set) var lastUpdate: Date?\n\n init(tunnelManager: TunnelManager) {\n self.tunnelManager = tunnelManager\n }\n\n mutating func requestUpdate(condition: Condition) {\n guard let accountData = tunnelManager.deviceState.accountData else {\n return\n }\n\n let now = Date()\n\n switch condition {\n case .always:\n break\n\n case .whenCloseToExpiryAndBeyond:\n guard let closeToExpiry = Calendar.current.date(\n byAdding: .day,\n value: Self.closeToExpiryDays * -1,\n to: accountData.expiry\n ) else { return }\n\n if closeToExpiry > now {\n return\n }\n }\n\n let waitInterval = accountData.expiry > now\n ? Self.defaultWaitInterval\n : Self.waitIntervalForExpiredAccount\n\n let nextUpdateAfter = lastUpdate?.addingTimeInterval(waitInterval.timeInterval)\n let comparisonResult = nextUpdateAfter?.compare(now) ?? .orderedAscending\n\n switch comparisonResult {\n case .orderedAscending, .orderedSame:\n lastUpdate = now\n tunnelManager.updateAccountData()\n\n case .orderedDescending:\n break\n }\n }\n\n mutating func reset() {\n lastUpdate = nil\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Classes\AccountDataThrottling.swift | AccountDataThrottling.swift | Swift | 2,276 | 0.95 | 0.049383 | 0.206349 | awesome-app | 28 | 2024-12-15T23:19:11.571549 | MIT | false | 1f5859fb10feda77f70e8e984af5fc76 |
//\n// AppPreferences.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2023-08-09.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadSettings\n\nprotocol AppPreferencesDataSource {\n var isShownOnboarding: Bool { get set }\n var isAgreedToTermsOfService: Bool { get set }\n var lastSeenChangeLogVersion: String { get set }\n}\n\nenum AppStorageKey: String {\n case isShownOnboarding, isAgreedToTermsOfService, lastSeenChangeLogVersion\n}\n\nfinal class AppPreferences: AppPreferencesDataSource {\n @AppStorage(key: AppStorageKey.isShownOnboarding.rawValue, container: .standard)\n var isShownOnboarding = true\n\n @AppStorage(key: AppStorageKey.isAgreedToTermsOfService.rawValue, container: .standard)\n var isAgreedToTermsOfService = false\n\n @AppStorage(key: AppStorageKey.lastSeenChangeLogVersion.rawValue, container: .standard)\n var lastSeenChangeLogVersion = ""\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Classes\AppPreferences.swift | AppPreferences.swift | Swift | 926 | 0.95 | 0.032258 | 0.28 | vue-tools | 129 | 2023-07-16T22:32:46.361754 | BSD-3-Clause | false | 3bfe28fc1f819454b4c061e79e661d49 |
//\n// AppRoutes.swift\n// MullvadVPN\n//\n// Created by pronebird on 17/08/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Routing\nimport UIKit\n\n/**\n Enum type describing groups of routes.\n */\nenum AppRouteGroup: AppRouteGroupProtocol {\n /**\n Primary horizontal navigation group.\n */\n case primary\n\n /**\n Select location group.\n */\n case selectLocation\n\n /**\n Account group.\n */\n case account\n\n /**\n Settings group.\n */\n case settings\n\n /**\n Changelog group.\n */\n case changelog\n\n /**\n Alert group. Alert id should match the id of the alert being contained.\n */\n case alert(_ alertId: String)\n\n var isModal: Bool {\n switch self {\n case .primary:\n return false\n\n case .selectLocation, .account, .settings, .changelog, .alert:\n return true\n }\n }\n\n var modalLevel: Int {\n switch self {\n case .primary:\n return 0\n case .account, .selectLocation, .changelog:\n return 1\n case .settings:\n return 2\n case .alert:\n // Alerts should always be topmost.\n return .max\n }\n }\n}\n\n/**\n Enum type describing primary application routes.\n */\nenum AppRoute: AppRouteProtocol {\n /**\n Account route.\n */\n case account\n\n /**\n Settings route. Contains sub-route to display.\n */\n case settings(SettingsNavigationRoute?)\n\n /**\n DAITA standalone route (not subsetting).\n */\n case daita\n\n /**\n Select location route.\n */\n case selectLocation\n\n /**\n Changelog standalone route (not subsetting).\n */\n case changelog\n\n /**\n Alert route. Alert id must be a unique string in order to produce a unique route\n that distinguishes between different kinds of alerts.\n */\n case alert(_ alertId: String)\n\n /**\n Routes that are part of primary horizontal navigation group.\n */\n case tos, login, main, revoked, outOfTime, welcome\n\n var isExclusive: Bool {\n switch self {\n case .account, .settings, .alert:\n return true\n default:\n return false\n }\n }\n\n var supportsSubNavigation: Bool {\n if case .settings = self {\n return true\n } else {\n return false\n }\n }\n\n var routeGroup: AppRouteGroup {\n switch self {\n case .tos, .login, .main, .revoked, .outOfTime, .welcome:\n return .primary\n case .selectLocation:\n return .selectLocation\n case .account:\n return .account\n case .settings, .daita, .changelog:\n return .settings\n case let .alert(id):\n return .alert(id)\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Classes\AppRoutes.swift | AppRoutes.swift | Swift | 2,810 | 0.95 | 0.035211 | 0.311475 | python-kit | 416 | 2025-03-03T15:36:47.716672 | Apache-2.0 | false | e0510e6c7823f14d0c7d4ee86d01bcab |
//\n// AutomaticKeyboardResponder.swift\n// MullvadVPN\n//\n// Created by pronebird on 24/03/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadLogging\nimport UIKit\n\n@MainActor\nclass AutomaticKeyboardResponder {\n weak var targetView: UIView?\n private let handler: (UIView, CGFloat) -> Void\n\n private var lastKeyboardRect: CGRect?\n\n init<T: UIView>(targetView: T, handler: @escaping (T, CGFloat) -> Void) {\n self.targetView = targetView\n self.handler = { view, adjustment in\n if let view = view as? T {\n handler(view, adjustment)\n }\n }\n\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(keyboardWillChangeFrame(_:)),\n name: UIResponder.keyboardWillChangeFrameNotification,\n object: nil\n )\n }\n\n func updateContentInsets() {\n guard let keyboardRect = lastKeyboardRect else { return }\n adjustContentInsets(convertedKeyboardFrameEnd: keyboardRect)\n }\n\n // MARK: - Keyboard notifications\n\n @objc private func keyboardWillChangeFrame(_ notification: Notification) {\n handleKeyboardNotification(notification)\n }\n\n // MARK: - Private\n\n private func handleKeyboardNotification(_ notification: Notification) {\n guard let userInfo = notification.userInfo,\n let targetView else { return }\n // In iOS 16.1 and later, the keyboard notification object is the screen the keyboard appears on.\n if #available(iOS 16.1, *) {\n guard let screen = notification.object as? UIScreen,\n // Get the keyboard’s frame at the end of its animation.\n let keyboardFrameEnd = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return }\n\n // Use that screen to get the coordinate space to convert from.\n let fromCoordinateSpace = screen.coordinateSpace\n\n // Get your view's coordinate space.\n let toCoordinateSpace: UICoordinateSpace = targetView\n\n // Convert the keyboard's frame from the screen's coordinate space to your view's coordinate space.\n let convertedKeyboardFrameEnd = fromCoordinateSpace.convert(keyboardFrameEnd, to: toCoordinateSpace)\n\n lastKeyboardRect = convertedKeyboardFrameEnd\n\n adjustContentInsets(convertedKeyboardFrameEnd: convertedKeyboardFrameEnd)\n } else {\n guard let keyboardValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue\n else { return }\n let keyboardFrameEnd = keyboardValue.cgRectValue\n let convertedKeyboardFrameEnd = targetView.convert(keyboardFrameEnd, from: targetView.window)\n lastKeyboardRect = convertedKeyboardFrameEnd\n\n adjustContentInsets(convertedKeyboardFrameEnd: convertedKeyboardFrameEnd)\n }\n }\n\n private func adjustContentInsets(convertedKeyboardFrameEnd: CGRect) {\n guard let targetView else { return }\n\n // Get the safe area insets when the keyboard is offscreen.\n var bottomOffset = targetView.safeAreaInsets.bottom\n\n // Get the intersection between the keyboard's frame and the view's bounds to work with the\n // part of the keyboard that overlaps your view.\n let viewIntersection = targetView.bounds.intersection(convertedKeyboardFrameEnd)\n\n // Check whether the keyboard intersects your view before adjusting your offset.\n if !viewIntersection.isEmpty {\n // Adjust the offset by the difference between the view's height and the height of the\n // intersection rectangle.\n bottomOffset = targetView.bounds.maxY - viewIntersection.minY\n }\n\n handler(targetView, bottomOffset)\n }\n}\n\nextension AutomaticKeyboardResponder {\n /// A convenience initializer that automatically assigns the offset to the scroll view\n /// subclasses\n convenience init(targetView: some UIScrollView) {\n self.init(targetView: targetView) { scrollView, offset in\n if scrollView.canBecomeFirstResponder {\n scrollView.contentInset.bottom = targetView.isFirstResponder ? offset : 0\n scrollView.verticalScrollIndicatorInsets.bottom = targetView.isFirstResponder\n ? offset\n : 0\n } else {\n scrollView.contentInset.bottom = offset\n scrollView.verticalScrollIndicatorInsets.bottom = offset\n }\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Classes\AutomaticKeyboardResponder.swift | AutomaticKeyboardResponder.swift | Swift | 4,572 | 0.95 | 0.042735 | 0.231579 | react-lib | 432 | 2024-07-09T19:05:52.787419 | MIT | false | f616ad30c669f49bdaa749966a4439e9 |
//\n// ConsolidatedApplicationLog.swift\n// MullvadVPN\n//\n// Created by pronebird on 29/10/2020.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nprivate let kLogDelimiter = "===================="\nprivate let kRedactedPlaceholder = "[REDACTED]"\nprivate let kRedactedAccountPlaceholder = "[REDACTED ACCOUNT NUMBER]"\nprivate let kRedactedContainerPlaceholder = "[REDACTED CONTAINER PATH]"\n\nclass ConsolidatedApplicationLog: TextOutputStreamable, @unchecked Sendable {\n typealias Metadata = KeyValuePairs<MetadataKey, String>\n private let bufferSize: UInt64\n\n enum MetadataKey: String {\n case id, os\n case productVersion = "mullvad-product-version"\n }\n\n struct LogAttachment {\n let label: String\n let content: String\n }\n\n let redactCustomStrings: [String]?\n let applicationGroupContainers: [URL]\n let metadata: Metadata\n\n private let logQueue = DispatchQueue(label: "com.mullvad.consolidation.logs.queue")\n private var logs: [LogAttachment] = []\n\n init(\n redactCustomStrings: [String]? = nil,\n redactContainerPathsForSecurityGroupIdentifiers securityGroupIdentifiers: [String],\n bufferSize: UInt64\n ) {\n metadata = Self.makeMetadata()\n self.redactCustomStrings = redactCustomStrings\n self.bufferSize = bufferSize\n\n applicationGroupContainers = securityGroupIdentifiers\n .compactMap { securityGroupIdentifier -> URL? in\n FileManager.default\n .containerURL(forSecurityApplicationGroupIdentifier: securityGroupIdentifier)\n }\n }\n\n func addLogFiles(fileURLs: [URL], completion: (@Sendable () -> Void)? = nil) {\n logQueue.async(flags: .barrier) {\n for fileURL in fileURLs {\n self.addSingleLogFile(fileURL)\n }\n DispatchQueue.main.async {\n completion?()\n }\n }\n }\n\n func addError(message: String, error: String, completion: (@Sendable () -> Void)? = nil) {\n let redactedError = redact(string: error)\n logQueue.async(flags: .barrier) {\n self.logs.append(LogAttachment(label: message, content: redactedError))\n DispatchQueue.main.async {\n completion?()\n }\n }\n }\n\n var string: String {\n var logsCopy: [LogAttachment] = []\n var metadataCopy: Metadata = [:]\n logQueue.sync {\n logsCopy = logs\n metadataCopy = metadata\n }\n guard !logsCopy.isEmpty else { return "" }\n return formatLog(logs: logsCopy, metadata: metadataCopy)\n }\n\n func write(to stream: inout some TextOutputStream) {\n var logsCopy: [LogAttachment] = []\n var metadataCopy: Metadata = [:]\n logQueue.sync {\n logsCopy = logs\n metadataCopy = metadata\n }\n let localOutput = formatLog(logs: logsCopy, metadata: metadataCopy)\n stream.write(localOutput)\n }\n\n private func formatLog(logs: [LogAttachment], metadata: Metadata) -> String {\n var result = "System information:\n"\n for (key, value) in metadata {\n result += "\(key.rawValue): \(value)\n"\n }\n result += "\n"\n for attachment in logs {\n result += "\(kLogDelimiter)\n"\n result += "\(attachment.label)\n"\n result += "\(kLogDelimiter)\n"\n result += "\(attachment.content)\n\n"\n }\n return result\n }\n\n private func addSingleLogFile(_ fileURL: URL) {\n guard fileURL.isFileURL else {\n addError(\n message: fileURL.absoluteString,\n error: "Invalid log file URL: \(fileURL.absoluteString)."\n )\n return\n }\n\n let path = fileURL.path\n let redactedPath = redact(string: path)\n\n if let lossyString = readFileLossy(path: path, maxBytes: bufferSize) {\n let redactedString = redact(string: lossyString)\n logQueue.async(flags: .barrier) {\n self.logs.append(LogAttachment(label: redactedPath, content: redactedString))\n }\n } else {\n addError(message: redactedPath, error: "Log file does not exist: \(path).")\n }\n }\n\n private static func makeMetadata() -> Metadata {\n let osVersion = ProcessInfo.processInfo.operatingSystemVersion\n let osVersionString =\n "iOS \(osVersion.majorVersion).\(osVersion.minorVersion).\(osVersion.patchVersion)"\n\n return [\n .id: UUID().uuidString,\n .productVersion: Bundle.main.productVersion,\n .os: osVersionString,\n ]\n }\n\n private func readFileLossy(path: String, maxBytes: UInt64) -> String? {\n guard let fileHandle = FileHandle(forReadingAtPath: path) else {\n return nil\n }\n\n let endOfFileOffset = fileHandle.seekToEndOfFile()\n if endOfFileOffset > maxBytes {\n fileHandle.seek(toFileOffset: endOfFileOffset - maxBytes)\n } else {\n fileHandle.seek(toFileOffset: 0)\n }\n\n let replacementCharacter = Character(UTF8.decode(UTF8.encodedReplacementCharacter))\n if let data = try? fileHandle.read(upToCount: Int(bufferSize)),\n let lossyString = String(bytes: data, encoding: .utf8) {\n let resultString = lossyString.drop { ch in\n // Drop leading replacement characters produced when decoding data\n ch == replacementCharacter\n }\n return String(resultString)\n } else {\n return nil\n }\n }\n\n private func redactCustomStrings(in string: String) -> String {\n guard let customStrings = redactCustomStrings,\n !customStrings.isEmpty else {\n return string\n }\n return customStrings.reduce(string) { resultString, redact in\n resultString.replacingOccurrences(of: redact, with: kRedactedPlaceholder)\n }\n }\n\n private func redact(string: String) -> String {\n var result = string\n result = redactContainerPaths(string: result)\n result = redactAccountNumber(string: result)\n result = redactIPv4Address(string: result)\n result = redactIPv6Address(string: result)\n result = redactCustomStrings(in: result)\n return result\n }\n\n private func redactContainerPaths(string: String) -> String {\n applicationGroupContainers.reduce(string) { resultString, containerURL -> String in\n resultString.replacingOccurrences(\n of: containerURL.path,\n with: kRedactedContainerPlaceholder\n )\n }\n }\n\n private func redactAccountNumber(string: String) -> String {\n redact(\n // swiftlint:disable:next force_try\n regularExpression: try! NSRegularExpression(pattern: #"\d{16}"#),\n string: string,\n replacementString: kRedactedAccountPlaceholder\n )\n }\n\n private func redactIPv4Address(string: String) -> String {\n redact(\n regularExpression: NSRegularExpression.ipv4RegularExpression,\n string: string,\n replacementString: kRedactedPlaceholder\n )\n }\n\n private func redactIPv6Address(string: String) -> String {\n redact(\n regularExpression: NSRegularExpression.ipv6RegularExpression,\n string: string,\n replacementString: kRedactedPlaceholder\n )\n }\n\n private func redact(\n regularExpression: NSRegularExpression,\n string: String,\n replacementString: String\n ) -> String {\n let nsRange = NSRange(string.startIndex ..< string.endIndex, in: string)\n let template = NSRegularExpression.escapedTemplate(for: replacementString)\n\n return regularExpression.stringByReplacingMatches(\n in: string,\n options: [],\n range: nsRange,\n withTemplate: template\n )\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Classes\ConsolidatedApplicationLog.swift | ConsolidatedApplicationLog.swift | Swift | 8,041 | 0.95 | 0.041841 | 0.043062 | vue-tools | 213 | 2024-10-06T00:32:12.596995 | GPL-3.0 | false | 53aadcae58deaeb24e8e5b0b081a760b |
//\n// CustomDateComponentsFormatting.swift\n// MullvadVPN\n//\n// Created by pronebird on 14/05/2020.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nenum CustomDateComponentsFormatting {}\n\nextension CustomDateComponentsFormatting {\n /// Format a duration between the given dates returning a string that only contains one unit.\n ///\n /// The behaviour of that method differs from `DateComponentsFormatter`:\n ///\n /// 1. Intervals of less than a day return a custom string.\n /// 2. Intervals of two years or more are formatted in years quantity.\n /// 3. Otherwise intervals matching none of the above are formatted in days quantity.\n ///\n static func localizedString(\n from start: Date,\n to end: Date,\n calendar: Calendar = Calendar.current,\n unitsStyle: DateComponentsFormatter.UnitsStyle\n ) -> String? {\n let dateComponents = calendar.dateComponents([.year, .day], from: start, to: max(start, end))\n\n guard !isLessThanOneDay(dateComponents: dateComponents) else {\n return NSLocalizedString(\n "CUSTOM_DATE_COMPONENTS_FORMATTING_LESS_THAN_ONE_DAY",\n value: "Less than a day",\n comment: ""\n )\n }\n\n let formatter = DateComponentsFormatter()\n formatter.calendar = calendar\n formatter.unitsStyle = unitsStyle\n formatter.maximumUnitCount = 1\n formatter.allowedUnits = (dateComponents.year ?? 0) >= 2 ? .year : .day\n\n return formatter.string(from: start, to: max(start, end))\n }\n\n private static func isLessThanOneDay(dateComponents: DateComponents) -> Bool {\n let year = dateComponents.year ?? 0\n let day = dateComponents.day ?? 0\n\n return (year == 0) && (day == 0)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Classes\CustomDateComponentsFormatting.swift | CustomDateComponentsFormatting.swift | Swift | 1,817 | 0.95 | 0 | 0.333333 | react-lib | 419 | 2025-03-09T05:35:47.996896 | GPL-3.0 | false | fea255b8503c719cffd8b344d3534cfc |
//\n// DeviceDataThrottling.swift\n// MullvadVPN\n//\n// Created by pronebird on 13/12/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\n\n/// Struct used for throttling UI calls to update device data via tunnel manager.\nstruct DeviceDataThrottling {\n /// Default cooldown interval between requests.\n private static let defaultWaitInterval: Duration = .minutes(1)\n\n let tunnelManager: TunnelManager\n private(set) var lastUpdate: Date?\n\n init(tunnelManager: TunnelManager) {\n self.tunnelManager = tunnelManager\n }\n\n mutating func requestUpdate(forceUpdate: Bool) {\n guard tunnelManager.deviceState.isLoggedIn else {\n return\n }\n\n let now = Date()\n\n guard !forceUpdate else {\n startUpdate(now: now)\n return\n }\n\n let nextUpdateAfter = lastUpdate?.addingTimeInterval(Self.defaultWaitInterval.timeInterval)\n let comparisonResult = nextUpdateAfter?.compare(now) ?? .orderedAscending\n\n switch comparisonResult {\n case .orderedAscending, .orderedSame:\n startUpdate(now: now)\n\n case .orderedDescending:\n break\n }\n }\n\n mutating func reset() {\n lastUpdate = nil\n }\n\n private mutating func startUpdate(now: Date) {\n lastUpdate = now\n tunnelManager.updateDeviceData()\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Classes\DeviceDataThrottling.swift | DeviceDataThrottling.swift | Swift | 1,410 | 0.95 | 0.035714 | 0.204545 | python-kit | 978 | 2023-10-17T16:32:08.113520 | GPL-3.0 | false | ab442a76997a7a4d92fd9742d5a982f5 |
//\n// FirstTimeLaunch.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-04-04.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nenum FirstTimeLaunch {\n private static let userDefaultsKey = "hasFinishedFirstTimeLaunch"\n\n static var hasFinished: Bool {\n UserDefaults.standard.bool(forKey: userDefaultsKey)\n }\n\n static func setHasFinished() {\n UserDefaults.standard.set(true, forKey: userDefaultsKey)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Classes\FirstTimeLaunch.swift | FirstTimeLaunch.swift | Swift | 477 | 0.95 | 0 | 0.411765 | awesome-app | 100 | 2025-06-29T03:08:51.559411 | GPL-3.0 | false | a5058fc2a62406b7b9da5b578dab34b6 |
//\n// InputTextFormatter.swift\n// MullvadVPN\n//\n// Created by pronebird on 08/04/2020.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport UIKit\n\n/// A class describing the account token input and caret management.\n/// Suitable to be used with `UITextField`.\nclass InputTextFormatter: NSObject, UITextFieldDelegate, UITextPasteDelegate {\n enum AllowedInput {\n case numeric, alphanumeric(isUpperCase: Bool)\n }\n\n struct Configuration {\n /// Allowed characters.\n var allowedInput: AllowedInput\n\n /// Separator between groups of characters.\n var groupSeparator: Character\n\n /// The size of each group of characters .\n var groupSize: UInt8\n\n /// Maximum number of groups of characters allowed.\n var maxGroups: UInt8\n }\n\n var configuration: Configuration {\n didSet {\n replace(with: string)\n }\n }\n\n /// Parsed string\n private(set) var string = ""\n\n /// Formatted string\n private(set) var formattedString = ""\n\n // Computed caret position\n private(set) var caretPosition = 0\n\n init(string: String = "", configuration: Configuration) {\n self.configuration = configuration\n super.init()\n\n replace(with: string)\n }\n\n /// Replace the currently held value with the given string\n func replace(with replacementString: String) {\n let stringRange = formattedString.startIndex ..< formattedString.endIndex\n\n replaceCharacters(\n in: stringRange,\n replacementString: replacementString,\n emptySelection: false\n )\n }\n\n /// Replace characters in range maintaining the caret position\n /// Note: `emptySelection` hints that text field selection is empty. This is normally\n /// the default state unless a text range is selected.\n func replaceCharacters(\n in range: Range<String.Index>,\n replacementString: String,\n emptySelection: Bool\n ) {\n var stringRange = range\n\n // Since removing separator alone makes no sense, this computation extends the string range\n // to include the digit preceding a separator.\n if replacementString.isEmpty, emptySelection, !formattedString.isEmpty {\n let precedingDigitIndex = formattedString\n .prefix(through: stringRange.lowerBound)\n .lastIndex { isAllowed($0) } ?? formattedString.startIndex\n\n stringRange = precedingDigitIndex ..< stringRange.upperBound\n }\n\n // Replace the given range within a formatted string\n let newString = formattedString.replacingCharacters(in: stringRange, with: replacementString)\n\n // Number of digits within a string\n var numDigits = 0\n\n // Insertion location within the input string\n let insertionLocation = formattedString.distance(from: formattedString.startIndex, to: stringRange.lowerBound)\n\n // Original caret location based on insertion location + number of characters added\n let originalCaretPosition = insertionLocation + replacementString.count\n\n // Computed caret location that will be modified during the loop\n var newCaretPosition = originalCaretPosition\n\n // New re-parsed and re-formatted strings\n var reparsedString = ""\n var reformattedString = ""\n\n for (index, element) in newString.enumerated() {\n // Skip disallowed characters\n if !isAllowed(element) {\n // Adjust the caret position for characters removed before the insertion location\n if originalCaretPosition > index {\n newCaretPosition -= 1\n }\n continue\n }\n\n // Apply cap on number of groups of characters that can be entered.\n if configuration.maxGroups > 0, configuration.groupSize > 0 {\n let numGroups = reparsedString.count / Int(configuration.groupSize)\n\n if numGroups >= configuration.maxGroups {\n if originalCaretPosition > index {\n newCaretPosition = reformattedString.count\n }\n break\n }\n }\n\n // Add separator between the groups of digits\n if numDigits > 0,\n configuration.groupSize > 0,\n numDigits % Int(configuration.groupSize) == 0 {\n reformattedString.append(configuration.groupSeparator)\n\n if originalCaretPosition > index {\n // Adjust the caret position to account for separators added before the\n // insertion location\n newCaretPosition += 1\n }\n }\n\n reformattedString.append(element)\n reparsedString.append(element)\n numDigits += 1\n }\n\n if case AllowedInput.alphanumeric(true) = configuration.allowedInput {\n reformattedString = reformattedString.uppercased()\n }\n\n caretPosition = newCaretPosition\n formattedString = reformattedString\n string = reparsedString\n }\n\n /// Update the text and caret position in the given text field\n func updateTextField(_ textField: UITextField) {\n updateTextField(textField, notifyDelegate: false)\n }\n\n // MARK: - UITextFieldDelegate\n\n func textField(\n _ textField: UITextField,\n shouldChangeCharactersIn range: NSRange,\n replacementString string: String\n ) -> Bool {\n let emptySelection = textField.selectedTextRange?.isEmpty ?? false\n\n // Certain characters such as a backtick can pass through the textField, and appear as an empty string, with a\n // range outside of the boundaries of the `formattedString`. Such characters are ignored.\n guard let stringRange = Range(range, in: formattedString) else {\n updateTextField(textField, notifyDelegate: true)\n return false\n }\n\n replaceCharacters(\n in: stringRange,\n replacementString: string,\n emptySelection: emptySelection\n )\n\n updateTextField(textField, notifyDelegate: true)\n\n return false\n }\n\n // MARK: - UITextPasteDelegate\n\n func textPasteConfigurationSupporting(\n _ textPasteConfigurationSupporting: UITextPasteConfigurationSupporting,\n performPasteOf attributedString: NSAttributedString,\n to textRange: UITextRange\n ) -> UITextRange {\n guard let textField = textPasteConfigurationSupporting as? UITextField else {\n return textRange\n }\n\n let location = textField.offset(from: textField.beginningOfDocument, to: textRange.start)\n let length = textField.offset(from: textRange.start, to: textRange.end)\n let nsRange = NSRange(location: location, length: length)\n\n guard let stringRange = Range(nsRange, in: formattedString) else { return textRange }\n\n replaceCharacters(\n in: stringRange,\n replacementString: attributedString.string,\n emptySelection: textRange.isEmpty\n )\n updateTextField(textField, notifyDelegate: true)\n\n return caretTextRange(in: textField)!\n }\n\n // MARK: - Private\n\n /// A caret position as utf-16 offset compatible for use with `NSString` and `UITextField`.\n private var caretPositionUtf16: Int {\n let startIndex = formattedString.startIndex\n let endIndex = formattedString.index(startIndex, offsetBy: caretPosition)\n\n return formattedString.utf16.distance(from: startIndex, to: endIndex)\n }\n\n /// Convert the computed caret position to an empty `UITextRange` within the given text field.\n private func caretTextRange(in textField: UITextField) -> UITextRange? {\n guard let position = textField.position(\n from: textField.beginningOfDocument,\n offset: caretPositionUtf16\n ) else { return nil }\n\n return textField.textRange(from: position, to: position)\n }\n\n /// A helper to update the text and caret in the given text field, and optionally post\n /// `UITextField.textDidChange` notification.\n private func updateTextField(_ textField: UITextField, notifyDelegate: Bool) {\n textField.text = formattedString\n textField.selectedTextRange = caretTextRange(in: textField)\n\n if notifyDelegate {\n Self.notifyTextDidChange(in: textField)\n }\n }\n\n /// Posts `UITextField.textDidChange` notification.\n private class func notifyTextDidChange(in textField: UITextField) {\n NotificationCenter.default.post(\n name: UITextField.textDidChangeNotification,\n object: textField\n )\n }\n\n private func isAllowed(_ character: Character) -> Bool {\n guard character.isASCII else { return false }\n switch configuration.allowedInput {\n case .numeric:\n return character.isNumber\n case .alphanumeric:\n return character.isLetter || character.isNumber\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Classes\InputTextFormatter.swift | InputTextFormatter.swift | Swift | 9,116 | 0.95 | 0.068966 | 0.216346 | node-utils | 306 | 2023-09-08T22:54:28.000091 | GPL-3.0 | false | 3d38a46664512a1f9e3b0466f88e90f3 |
//\n// InterceptibleNavigationController.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-04-05.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass InterceptibleNavigationController: CustomNavigationController {\n var shouldPopViewController: ((UIViewController) -> Bool)?\n var shouldPopToViewController: ((UIViewController) -> Bool)?\n\n // Called when popping the topmost view controller in the stack, eg. by pressing a navigation\n // bar back button.\n @discardableResult\n override func popViewController(animated: Bool) -> UIViewController? {\n guard let viewController = viewControllers.last else { return nil }\n\n if shouldPopViewController?(viewController) ?? true {\n return super.popViewController(animated: animated)\n } else {\n return nil\n }\n }\n\n // Called when popping to a specific view controller, eg. by long pressing a navigation bar\n // back button (revealing a navigation menu) and selecting a destination view controller.\n @discardableResult\n override func popToViewController(_ viewController: UIViewController, animated: Bool) -> [UIViewController]? {\n if shouldPopToViewController?(viewController) ?? true {\n return super.popToViewController(viewController, animated: animated)\n } else {\n return nil\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Classes\InterceptibleNavigationController.swift | InterceptibleNavigationController.swift | Swift | 1,395 | 0.95 | 0.078947 | 0.333333 | react-lib | 458 | 2024-08-21T18:36:59.458899 | Apache-2.0 | false | 87eb22cb70a73333b88a730c186084de |
//\n// MarkdownStylingOptions.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-06-29.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nstruct MarkdownStylingOptions {\n var font: UIFont\n var paragraphStyle: NSParagraphStyle = .default\n\n var boldFont: UIFont {\n let fontDescriptor = font.fontDescriptor.withSymbolicTraits(.traitBold) ?? font.fontDescriptor\n return UIFont(descriptor: fontDescriptor, size: font.pointSize)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Classes\MarkdownStylingOptions.swift | MarkdownStylingOptions.swift | Swift | 491 | 0.95 | 0 | 0.4375 | python-kit | 642 | 2025-03-23T07:48:30.205082 | BSD-3-Clause | false | a964ff118cfb75131a467f5ffa0e6c2d |
//\n// CustomNavigationController.swift\n// MullvadVPN\n//\n// Created by pronebird on 23/02/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\n/// Custom navigation controller that applies the custom appearance to itself.\nclass CustomNavigationController: UINavigationController {\n override var childForStatusBarHidden: UIViewController? {\n topViewController\n }\n\n override var childForStatusBarStyle: UIViewController? {\n topViewController\n }\n\n override func viewDidLoad() {\n super.viewDidLoad()\n\n navigationBar.configureCustomAppeareance()\n }\n\n override func viewDidLayoutSubviews() {\n super.viewDidLayoutSubviews()\n\n // Navigation bar updates the prompt color on layout so we have to force our own appearance on each layout pass.\n navigationBar.overridePromptColor()\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Containers\Navigation\CustomNavigationController.swift | CustomNavigationController.swift | Swift | 879 | 0.95 | 0.030303 | 0.346154 | node-utils | 168 | 2024-06-01T04:26:36.677227 | GPL-3.0 | false | 27f7cebdc059e0cfb7e186cb50e36576 |
//\n// CustomNavigationBar.swift\n// MullvadVPN\n//\n// Created by pronebird on 22/05/2019.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nextension UINavigationBar {\n /// Locates the navigation bar prompt label within the view hirarchy and overrides the text color.\n /// - Note: Navigation bar does not provide the appearance configuration for the prompt.\n func overridePromptColor() {\n let promptView = subviews.first { $0.description.contains("Prompt") }\n let promptLabel = promptView?.subviews.first { $0 is UILabel } as? UILabel\n\n promptLabel?.textColor = UIColor.NavigationBar.promptColor\n }\n\n func configureCustomAppeareance() {\n var directionalMargins = directionalLayoutMargins\n directionalMargins.leading = UIMetrics.contentLayoutMargins.leading\n directionalMargins.trailing = UIMetrics.contentLayoutMargins.trailing\n\n directionalLayoutMargins = directionalMargins\n tintColor = UIColor.NavigationBar.titleColor\n\n standardAppearance = makeNavigationBarAppearance(isTransparent: false)\n scrollEdgeAppearance = makeNavigationBarAppearance(isTransparent: true)\n }\n\n private func makeNavigationBarAppearance(isTransparent: Bool) -> UINavigationBarAppearance {\n let backIndicatorImage = UIImage.Buttons.back.withTintColor(\n UIColor.NavigationBar.buttonColor,\n renderingMode: .alwaysOriginal\n )\n let backIndicatorTransitionMask = UIImage.backTransitionMask\n\n let titleTextAttributes: [NSAttributedString.Key: Any] = [\n .foregroundColor: UIColor.NavigationBar.titleColor,\n ]\n let backButtonTitlePositionOffset = UIOffset(horizontal: 4, vertical: 0)\n let backButtonTitleTextAttributes: [NSAttributedString.Key: Any] = [\n .foregroundColor: UIColor.NavigationBar.backButtonTitleColor,\n ]\n\n let navigationBarAppearance = UINavigationBarAppearance()\n\n if isTransparent {\n navigationBarAppearance.configureWithTransparentBackground()\n } else {\n navigationBarAppearance.configureWithDefaultBackground()\n navigationBarAppearance.backgroundEffect = UIBlurEffect(style: .dark)\n }\n\n navigationBarAppearance.titleTextAttributes = titleTextAttributes\n navigationBarAppearance.largeTitleTextAttributes = titleTextAttributes\n\n let plainBarButtonAppearance = UIBarButtonItemAppearance(style: .plain)\n plainBarButtonAppearance.normal.titleTextAttributes = titleTextAttributes\n\n let doneBarButtonAppearance = UIBarButtonItemAppearance(style: .done)\n doneBarButtonAppearance.normal.titleTextAttributes = titleTextAttributes\n\n let backButtonAppearance = UIBarButtonItemAppearance(style: .plain)\n backButtonAppearance.normal.titlePositionAdjustment = backButtonTitlePositionOffset\n backButtonAppearance.normal.titleTextAttributes = backButtonTitleTextAttributes\n\n navigationBarAppearance.buttonAppearance = plainBarButtonAppearance\n navigationBarAppearance.doneButtonAppearance = doneBarButtonAppearance\n navigationBarAppearance.backButtonAppearance = backButtonAppearance\n\n navigationBarAppearance.setBackIndicatorImage(\n backIndicatorImage,\n transitionMaskImage: backIndicatorTransitionMask\n )\n\n return navigationBarAppearance\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Containers\Navigation\UINavigationBar+Appearance.swift | UINavigationBar+Appearance.swift | Swift | 3,426 | 0.95 | 0.024691 | 0.140625 | react-lib | 389 | 2024-09-14T17:21:55.987856 | BSD-3-Clause | false | 74ad85fd9b4838bf7aa6ec982178a93a |
//\n// HeaderBarView.swift\n// MullvadVPN\n//\n// Created by pronebird on 19/06/2020.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass HeaderBarView: UIView {\n private let brandNameImage = UIImage(named: "LogoText")?\n .withTintColor(UIColor.HeaderBar.brandNameColor, renderingMode: .alwaysOriginal)\n\n private let logoImageView = UIImageView(image: UIImage(named: "LogoIcon"))\n\n private lazy var brandNameImageView: UIImageView = {\n let imageView = UIImageView(image: brandNameImage)\n imageView.contentMode = .scaleAspectFill\n return imageView\n }()\n\n private let deviceInfoHolder: UIStackView = {\n let stackView = UIStackView()\n stackView.axis = .horizontal\n stackView.distribution = .fill\n stackView.spacing = 16.0\n return stackView\n }()\n\n private lazy var deviceNameLabel: UILabel = {\n let label = UILabel()\n label.font = UIFont.systemFont(ofSize: 14)\n label.textColor = UIColor(white: 1.0, alpha: 0.8)\n label.setContentHuggingPriority(.defaultHigh, for: .horizontal)\n label.setAccessibilityIdentifier(.headerDeviceNameLabel)\n return label\n }()\n\n private lazy var timeLeftLabel: UILabel = {\n let label = UILabel()\n label.font = UIFont.systemFont(ofSize: 14)\n label.textColor = UIColor(white: 1.0, alpha: 0.8)\n label.setContentHuggingPriority(.defaultLow, for: .horizontal)\n return label\n }()\n\n private lazy var buttonContainer: UIStackView = {\n let stackView = UIStackView(arrangedSubviews: [accountButton, settingsButton])\n stackView.spacing = 12\n return stackView\n }()\n\n private let borderLayer: CALayer = {\n let layer = CALayer()\n layer.backgroundColor = UIColor.HeaderBar.dividerColor.cgColor\n return layer\n }()\n\n let accountButton: UIButton = {\n let button = makeHeaderBarButton(with: UIImage.Buttons.account)\n button.setAccessibilityIdentifier(.accountButton)\n button.accessibilityLabel = NSLocalizedString(\n "HEADER_BAR_ACCOUNT_BUTTON_ACCESSIBILITY_LABEL",\n tableName: "HeaderBar",\n value: "Account",\n comment: ""\n )\n button.heightAnchor.constraint(equalToConstant: UIMetrics.Button.barButtonSize).isActive = true\n button.widthAnchor.constraint(equalTo: button.heightAnchor, multiplier: 1).isActive = true\n return button\n }()\n\n let settingsButton: UIButton = {\n let button = makeHeaderBarButton(with: UIImage.Buttons.settings)\n button.setAccessibilityIdentifier(.settingsButton)\n button.accessibilityLabel = NSLocalizedString(\n "HEADER_BAR_SETTINGS_BUTTON_ACCESSIBILITY_LABEL",\n tableName: "HeaderBar",\n value: "Settings",\n comment: ""\n )\n button.heightAnchor.constraint(equalToConstant: UIMetrics.Button.barButtonSize).isActive = true\n button.widthAnchor.constraint(equalTo: button.heightAnchor, multiplier: 1).isActive = true\n return button\n }()\n\n class func makeHeaderBarButton(with image: UIImage?) -> IncreasedHitButton {\n let buttonImage = image?.withTintColor(UIColor.HeaderBar.buttonColor, renderingMode: .alwaysOriginal)\n let barButton = IncreasedHitButton(type: .system)\n barButton.setBackgroundImage(buttonImage, for: .normal)\n barButton.configureForAutoLayout()\n\n return barButton\n }\n\n var showsDivider = false {\n didSet {\n if showsDivider {\n layer.addSublayer(borderLayer)\n } else {\n borderLayer.removeFromSuperlayer()\n }\n }\n }\n\n var isDeviceInfoHidden = false {\n didSet {\n deviceInfoHolder.arrangedSubviews.forEach { $0.isHidden = isDeviceInfoHidden }\n }\n }\n\n private var isAccountButtonHidden = false {\n didSet {\n accountButton.isHidden = isAccountButtonHidden\n }\n }\n\n private var timeLeft: Date? {\n didSet {\n if let timeLeft {\n let formattedTimeLeft = NSLocalizedString(\n "TIME_LEFT_HEADER_VIEW",\n tableName: "Account",\n value: "Time left: %@",\n comment: ""\n )\n timeLeftLabel.text = String(\n format: formattedTimeLeft,\n CustomDateComponentsFormatting.localizedString(\n from: Date(),\n to: timeLeft,\n unitsStyle: .full\n ) ?? ""\n )\n } else {\n timeLeftLabel.text = ""\n }\n }\n }\n\n private var deviceName: String? {\n didSet {\n if let deviceName {\n let formattedDeviceName = NSLocalizedString(\n "DEVICE_NAME_HEADER_VIEW",\n tableName: "Account",\n value: "Device name: %@",\n comment: ""\n )\n deviceNameLabel.text = String(format: formattedDeviceName, deviceName)\n } else {\n deviceNameLabel.text = ""\n }\n }\n }\n\n override init(frame: CGRect) {\n super.init(frame: frame)\n directionalLayoutMargins = NSDirectionalEdgeInsets(\n top: 0,\n leading: UIMetrics.contentLayoutMargins.leading,\n bottom: 0,\n trailing: UIMetrics.contentLayoutMargins.trailing\n )\n\n accessibilityContainerType = .semanticGroup\n setAccessibilityIdentifier(.headerBarView)\n\n let brandImageSize = brandNameImage?.size ?? .zero\n let brandNameAspectRatio = brandImageSize.width / max(brandImageSize.height, 1)\n\n var buttonContainerTrailingAdjustment: CGFloat = 0\n if let buttonImageWidth = settingsButton.currentImage?.size.width {\n buttonContainerTrailingAdjustment = max((UIMetrics.Button.barButtonSize - buttonImageWidth) / 2, 0)\n }\n\n [deviceNameLabel, timeLeftLabel].forEach { deviceInfoHolder.addArrangedSubview($0) }\n\n addConstrainedSubviews([logoImageView, brandNameImageView, buttonContainer, deviceInfoHolder]) {\n logoImageView.leadingAnchor.constraint(equalTo: layoutMarginsGuide.leadingAnchor)\n logoImageView.centerYAnchor.constraint(equalTo: brandNameImageView.centerYAnchor)\n logoImageView.widthAnchor.constraint(equalToConstant: UIMetrics.headerBarLogoSize)\n logoImageView.heightAnchor.constraint(equalTo: logoImageView.widthAnchor, multiplier: 1)\n\n brandNameImageView.leadingAnchor.constraint(\n equalToSystemSpacingAfter: logoImageView.trailingAnchor,\n multiplier: 1\n )\n brandNameImageView.topAnchor.constraint(\n equalTo: layoutMarginsGuide.topAnchor,\n constant: UIMetrics.headerBarLogoSize * 0.5\n )\n brandNameImageView.widthAnchor.constraint(\n equalTo: brandNameImageView.heightAnchor,\n multiplier: brandNameAspectRatio\n )\n brandNameImageView.heightAnchor.constraint(equalToConstant: UIMetrics.headerBarBrandNameHeight)\n\n buttonContainer.centerYAnchor.constraint(equalTo: brandNameImageView.centerYAnchor)\n buttonContainer.trailingAnchor.constraint(\n equalTo: layoutMarginsGuide.trailingAnchor,\n constant: buttonContainerTrailingAdjustment\n )\n\n deviceInfoHolder.leadingAnchor.constraint(equalTo: layoutMarginsGuide.leadingAnchor)\n deviceInfoHolder.trailingAnchor.constraint(equalTo: layoutMarginsGuide.trailingAnchor)\n deviceInfoHolder.topAnchor.constraint(equalToSystemSpacingBelow: logoImageView.bottomAnchor, multiplier: 1)\n layoutMarginsGuide.bottomAnchor.constraint(\n equalToSystemSpacingBelow: deviceInfoHolder.bottomAnchor,\n multiplier: 1\n )\n }\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 borderLayer.frame = CGRect(x: 0, y: frame.maxY - 1, width: frame.width, height: 1)\n brandNameImageView.isHidden = shouldHideBrandName()\n }\n\n /// Returns `true` if container holding buttons intersects brand name.\n private func shouldHideBrandName() -> Bool {\n let buttonContainerRect = buttonContainer.convert(buttonContainer.bounds, to: nil)\n let brandNameRect = brandNameImageView.convert(brandNameImageView.bounds, to: nil)\n\n return brandNameRect.intersects(buttonContainerRect)\n }\n\n func update(configuration: RootConfiguration) {\n deviceName = configuration.deviceName\n timeLeft = configuration.expiry\n isAccountButtonHidden = !configuration.showsAccountButton\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Containers\Root\HeaderBarView.swift | HeaderBarView.swift | Swift | 9,034 | 0.95 | 0.041667 | 0.038647 | awesome-app | 443 | 2024-02-05T11:32:50.039920 | BSD-3-Clause | false | fdcd2cb1bfe74b1e0581462c99d54ca8 |
//\n// RootConfiguration.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-04-19.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadSettings\n\nstruct RootDeviceInfoViewModel {\n let configuration: RootConfiguration\n init(isPresentingAccountExpiryBanner: Bool, deviceState: DeviceState) {\n configuration = RootConfiguration(\n deviceName: deviceState.deviceData?.capitalizedName,\n expiry: (isPresentingAccountExpiryBanner || (deviceState.accountData?.isExpired ?? true))\n ? nil\n : deviceState.accountData?.expiry,\n showsAccountButton: deviceState.isLoggedIn\n )\n }\n}\n\nstruct RootConfiguration {\n var deviceName: String?\n var expiry: Date?\n var showsAccountButton: Bool\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Containers\Root\RootConfiguration.swift | RootConfiguration.swift | Swift | 817 | 0.95 | 0 | 0.269231 | python-kit | 934 | 2024-03-04T19:16:24.561087 | MIT | false | aa69c9cb3879cb6167053459c2f1f7e5 |
//\n// RootContainerViewController.swift\n// MullvadVPN\n//\n// Created by pronebird on 25/05/2019.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Routing\nimport UIKit\n\nenum HeaderBarStyle: Sendable {\n case transparent, `default`, unsecured, secured\n\n fileprivate func backgroundColor() -> UIColor {\n switch self {\n case .transparent:\n return UIColor.clear\n case .default:\n return UIColor.HeaderBar.defaultBackgroundColor\n case .secured:\n return UIColor.HeaderBar.securedBackgroundColor\n case .unsecured:\n return UIColor.HeaderBar.unsecuredBackgroundColor\n }\n }\n}\n\nstruct HeaderBarPresentation: Sendable {\n let style: HeaderBarStyle\n let showsDivider: Bool\n\n static var `default`: HeaderBarPresentation {\n HeaderBarPresentation(style: .default, showsDivider: false)\n }\n}\n\n/// A protocol that defines the relationship between the root container and its child controllers\n@MainActor\nprotocol RootContainment: Sendable {\n /// Return the preferred header bar style\n var preferredHeaderBarPresentation: HeaderBarPresentation { get }\n\n /// Return true if the view controller prefers header bar hidden\n var prefersHeaderBarHidden: Bool { get }\n\n /// Return true if the view controller prefers notification bar hidden\n var prefersNotificationBarHidden: Bool { get }\n\n /// Return true if the view controller prefers device info bar hidden\n var prefersDeviceInfoBarHidden: Bool { get }\n}\n\nextension RootContainment {\n var prefersNotificationBarHidden: Bool {\n true\n }\n\n var prefersDeviceInfoBarHidden: Bool {\n false\n }\n}\n\nprotocol RootContainerViewControllerDelegate: AnyObject, Sendable {\n func rootContainerViewControllerShouldShowAccount(\n _ controller: RootContainerViewController,\n animated: Bool\n )\n\n func rootContainerViewControllerShouldShowSettings(\n _ controller: RootContainerViewController,\n navigateTo route: SettingsNavigationRoute?,\n animated: Bool\n )\n\n func rootContainerViewSupportedInterfaceOrientations(_ controller: RootContainerViewController)\n -> UIInterfaceOrientationMask\n\n func rootContainerViewAccessibilityPerformMagicTap(_ controller: RootContainerViewController)\n -> Bool\n}\n\n/// A root container view controller\nclass RootContainerViewController: UIViewController {\n typealias CompletionHandler = () -> Void\n\n private let headerBarView = HeaderBarView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))\n let transitionContainer = UIView(frame: UIScreen.main.bounds)\n private var presentationContainerAccountButton: UIButton?\n private var presentationContainerSettingsButton: UIButton?\n private var configuration = RootConfiguration(showsAccountButton: false)\n\n private(set) var headerBarPresentation = HeaderBarPresentation.default\n private(set) var headerBarHidden = false\n private(set) var overrideHeaderBarHidden: Bool?\n\n private(set) var viewControllers = [UIViewController]()\n\n private var appearingController: UIViewController?\n private var disappearingController: UIViewController?\n private var interfaceOrientationMask: UIInterfaceOrientationMask?\n private var isNavigationBarHidden = false {\n didSet {\n guard let notificationController else {\n return\n }\n if isNavigationBarHidden {\n removeNotificationController(notificationController)\n } else {\n addNotificationController(notificationController)\n }\n }\n }\n\n var topViewController: UIViewController? {\n viewControllers.last\n }\n\n weak var delegate: RootContainerViewControllerDelegate?\n\n override var childForStatusBarStyle: UIViewController? {\n topViewController\n }\n\n override var childForStatusBarHidden: UIViewController? {\n topViewController\n }\n\n override var shouldAutomaticallyForwardAppearanceMethods: Bool {\n false\n }\n\n override var disablesAutomaticKeyboardDismissal: Bool {\n topViewController?.disablesAutomaticKeyboardDismissal ?? super\n .disablesAutomaticKeyboardDismissal\n }\n\n // MARK: - View lifecycle\n\n override func viewDidLoad() {\n super.viewDidLoad()\n var margins = view.directionalLayoutMargins\n margins.leading = UIMetrics.contentLayoutMargins.leading\n margins.trailing = UIMetrics.contentLayoutMargins.trailing\n view.directionalLayoutMargins = margins\n\n definesPresentationContext = true\n\n addTransitionView()\n addHeaderBarView()\n updateHeaderBarBackground()\n }\n\n override func viewDidLayoutSubviews() {\n super.viewDidLayoutSubviews()\n\n updateAdditionalSafeAreaInsetsIfNeeded()\n }\n\n override func viewSafeAreaInsetsDidChange() {\n super.viewSafeAreaInsetsDidChange()\n\n updateHeaderBarLayoutMarginsIfNeeded()\n }\n\n override func viewWillAppear(_ animated: Bool) {\n super.viewWillAppear(animated)\n\n if let childController = topViewController {\n beginChildControllerTransition(childController, isAppearing: true, animated: animated)\n }\n }\n\n override func viewDidAppear(_ animated: Bool) {\n super.viewDidAppear(animated)\n\n if let childController = topViewController {\n endChildControllerTransition(childController)\n }\n }\n\n override func viewWillDisappear(_ animated: Bool) {\n super.viewWillDisappear(animated)\n\n if let childController = topViewController {\n beginChildControllerTransition(childController, isAppearing: false, animated: animated)\n }\n }\n\n override func viewDidDisappear(_ animated: Bool) {\n super.viewDidDisappear(animated)\n\n if let childController = topViewController {\n endChildControllerTransition(childController)\n }\n }\n\n // MARK: - Autorotation\n\n override var shouldAutorotate: Bool {\n true\n }\n\n override var supportedInterfaceOrientations: UIInterfaceOrientationMask {\n interfaceOrientationMask ?? super.supportedInterfaceOrientations\n }\n\n // MARK: - Public\n\n func setViewControllers(\n _ newViewControllers: [UIViewController],\n animated: Bool,\n completion: CompletionHandler? = nil\n ) {\n // Fetch the initial orientation mask\n if interfaceOrientationMask == nil {\n updateInterfaceOrientation(attemptRotateToDeviceOrientation: false)\n }\n\n setViewControllersInternal(\n newViewControllers,\n isUnwinding: false,\n animated: animated,\n completion: completion\n )\n }\n\n func pushViewController(\n _ viewController: UIViewController,\n animated: Bool,\n completion: CompletionHandler? = nil\n ) {\n var newViewControllers = viewControllers.filter { $0 != viewController }\n newViewControllers.append(viewController)\n\n setViewControllersInternal(\n newViewControllers,\n isUnwinding: false,\n animated: animated,\n completion: completion\n )\n }\n\n func popToViewController(\n _ controller: UIViewController,\n animated: Bool,\n completion: CompletionHandler? = nil\n ) {\n guard let index = viewControllers.firstIndex(of: controller) else { return }\n\n let newViewControllers = Array(viewControllers[...index])\n\n setViewControllersInternal(\n newViewControllers,\n isUnwinding: true,\n animated: animated,\n completion: completion\n )\n }\n\n func popViewController(animated: Bool, completion: CompletionHandler? = nil) {\n guard viewControllers.count > 1 else { return }\n\n var newViewControllers = viewControllers\n newViewControllers.removeLast()\n\n setViewControllersInternal(\n newViewControllers,\n isUnwinding: true,\n animated: animated,\n completion: completion\n )\n }\n\n func popToRootViewController(animated: Bool, completion: CompletionHandler? = nil) {\n if let rootController = viewControllers.first, viewControllers.count > 1 {\n setViewControllersInternal(\n [rootController],\n isUnwinding: true,\n animated: animated,\n completion: completion\n )\n }\n }\n\n /// Request the root container to query the top controller for the new header bar style\n func updateHeaderBarAppearance() {\n updateHeaderBarStyleFromChildPreferences(animated: UIView.areAnimationsEnabled)\n }\n\n func updateHeaderBarHiddenAppearance() {\n updateHeaderBarHiddenFromChildPreferences(animated: UIView.areAnimationsEnabled)\n }\n\n /// Request to display settings controller\n func showAccount(animated: Bool) {\n delegate?.rootContainerViewControllerShouldShowAccount(\n self,\n animated: animated\n )\n }\n\n /// Request to display settings controller\n func showSettings(navigateTo route: SettingsNavigationRoute? = nil, animated: Bool) {\n delegate?.rootContainerViewControllerShouldShowSettings(\n self,\n navigateTo: route,\n animated: animated\n )\n }\n\n func setOverrideHeaderBarHidden(_ isHidden: Bool?, animated: Bool) {\n overrideHeaderBarHidden = isHidden\n\n if let isHidden {\n setHeaderBarHidden(isHidden, animated: animated)\n } else {\n updateHeaderBarHiddenFromChildPreferences(animated: animated)\n }\n }\n\n func enableHeaderBarButtons(_ enabled: Bool) {\n headerBarView.accountButton.isEnabled = enabled\n headerBarView.settingsButton.isEnabled = enabled\n }\n\n // MARK: - Accessibility\n\n override func accessibilityPerformMagicTap() -> Bool {\n delegate?.rootContainerViewAccessibilityPerformMagicTap(self) ?? super\n .accessibilityPerformMagicTap()\n }\n\n // MARK: - Private\n\n private func addTransitionView() {\n let constraints = [\n transitionContainer.topAnchor.constraint(equalTo: view.topAnchor),\n transitionContainer.leadingAnchor.constraint(equalTo: view.leadingAnchor),\n transitionContainer.trailingAnchor.constraint(equalTo: view.trailingAnchor),\n transitionContainer.bottomAnchor.constraint(equalTo: view.bottomAnchor),\n ]\n\n transitionContainer.translatesAutoresizingMaskIntoConstraints = false\n view.addSubview(transitionContainer)\n\n NSLayoutConstraint.activate(constraints)\n }\n\n private func addHeaderBarView() {\n let constraints = [\n headerBarView.topAnchor.constraint(equalTo: view.topAnchor),\n headerBarView.leadingAnchor.constraint(equalTo: view.leadingAnchor),\n headerBarView.trailingAnchor.constraint(equalTo: view.trailingAnchor),\n ]\n\n headerBarView.translatesAutoresizingMaskIntoConstraints = false\n\n // Prevent automatic layout margins adjustment as we manually control them.\n headerBarView.insetsLayoutMarginsFromSafeArea = false\n\n headerBarView.accountButton.addTarget(\n self,\n action: #selector(handleAccountButtonTap),\n for: .touchUpInside\n )\n\n headerBarView.settingsButton.addTarget(\n self,\n action: #selector(handleSettingsButtonTap),\n for: .touchUpInside\n )\n\n view.addSubview(headerBarView)\n\n NSLayoutConstraint.activate(constraints)\n }\n\n private func getPresentationContainerAccountButton() -> UIButton {\n let button: UIButton\n\n if let transitionViewButton = presentationContainerAccountButton {\n transitionViewButton.removeFromSuperview()\n button = transitionViewButton\n } else {\n button = HeaderBarView.makeHeaderBarButton(with: UIImage.Buttons.account)\n button.addTarget(\n self,\n action: #selector(handleAccountButtonTap),\n for: .touchUpInside\n )\n }\n\n button.isEnabled = headerBarView.accountButton.isEnabled\n button.isHidden = !configuration.showsAccountButton\n\n return button\n }\n\n private func getPresentationContainerSettingsButton() -> UIButton {\n let button: UIButton\n\n if let transitionViewButton = presentationContainerSettingsButton {\n transitionViewButton.removeFromSuperview()\n button = transitionViewButton\n } else {\n button = HeaderBarView.makeHeaderBarButton(with: UIImage.Buttons.settings)\n button.isEnabled = headerBarView.settingsButton.isEnabled\n button.addTarget(\n self,\n action: #selector(handleSettingsButtonTap),\n for: .touchUpInside\n )\n }\n\n return button\n }\n\n @objc private func handleAccountButtonTap() {\n showAccount(animated: true)\n }\n\n @objc private func handleSettingsButtonTap() {\n showSettings(animated: true)\n }\n\n // swiftlint:disable:next function_body_length\n private func setViewControllersInternal(\n _ newViewControllers: [UIViewController],\n isUnwinding: Bool,\n animated: Bool,\n completion: CompletionHandler? = nil\n ) {\n assert(\n Set(newViewControllers).count == newViewControllers.count,\n "All view controllers in root container controller must be distinct"\n )\n\n guard viewControllers != newViewControllers else {\n completion?()\n return\n }\n\n // Dot not handle appearance events when the container itself is not visible\n let shouldHandleAppearanceEvents = view.window != nil\n\n // Animations won't run when the container is not visible, so prevent them\n let shouldAnimate = animated && shouldHandleAppearanceEvents\n\n let sourceViewController = topViewController\n let targetViewController = newViewControllers.last\n\n let viewControllersToAdd = newViewControllers.filter { !viewControllers.contains($0) }\n let viewControllersToRemove = viewControllers.filter { !newViewControllers.contains($0) }\n\n // hide in-App notificationBanner when the container decides to keep it invisible\n isNavigationBarHidden = (targetViewController as? RootContainment)?.prefersNotificationBarHidden ?? false\n\n configureViewControllers(\n viewControllersToAdd: viewControllersToAdd,\n newViewControllers: newViewControllers,\n targetViewController: targetViewController,\n viewControllersToRemove: viewControllersToRemove\n )\n\n beginTransition(\n shouldHandleAppearanceEvents: shouldHandleAppearanceEvents,\n targetViewController: targetViewController,\n shouldAnimate: shouldAnimate,\n sourceViewController: sourceViewController\n )\n\n let finishTransition = { [weak self] in\n self?.onTransitionEnd(\n shouldHandleAppearanceEvents: shouldHandleAppearanceEvents,\n sourceViewController: sourceViewController,\n targetViewController: targetViewController,\n viewControllersToAdd: viewControllersToAdd,\n viewControllersToRemove: viewControllersToRemove\n )\n\n completion?()\n }\n\n let alongSideAnimations = { [weak self] in\n guard let self else { return }\n\n updateHeaderBarStyleFromChildPreferences(animated: shouldAnimate)\n updateHeaderBarHiddenFromChildPreferences(animated: shouldAnimate)\n updateNotificationBarHiddenFromChildPreferences()\n updateDeviceInfoBarHiddenFromChildPreferences()\n }\n\n if shouldAnimate {\n CATransaction.begin()\n CATransaction.setCompletionBlock {\n finishTransition()\n }\n\n animateTransition(\n sourceViewController: sourceViewController,\n newViewControllers: newViewControllers,\n targetViewController: targetViewController,\n isUnwinding: isUnwinding,\n alongSideAnimations: alongSideAnimations\n )\n\n CATransaction.commit()\n } else {\n alongSideAnimations()\n finishTransition()\n }\n }\n\n private func animateTransition(\n sourceViewController: UIViewController?,\n newViewControllers: [UIViewController],\n targetViewController: UIViewController?,\n isUnwinding: Bool,\n alongSideAnimations: () -> Void\n ) {\n let transition = CATransition()\n transition.duration = 0.35\n transition.type = .push\n\n // Pick the animation movement direction\n let sourceIndex = sourceViewController.flatMap { newViewControllers.firstIndex(of: $0) }\n let targetIndex = targetViewController.flatMap { newViewControllers.firstIndex(of: $0) }\n\n switch (sourceIndex, targetIndex) {\n case let (.some(lhs), .some(rhs)):\n transition.subtype = lhs > rhs ? .fromLeft : .fromRight\n case (.none, .some):\n transition.subtype = isUnwinding ? .fromLeft : .fromRight\n default:\n transition.subtype = .fromRight\n }\n\n transitionContainer.layer.add(transition, forKey: "transition")\n alongSideAnimations()\n }\n\n private func onTransitionEnd(\n shouldHandleAppearanceEvents: Bool,\n sourceViewController: UIViewController?,\n targetViewController: UIViewController?,\n viewControllersToAdd: [UIViewController],\n viewControllersToRemove: [UIViewController]\n ) {\n /*\n Finish transition appearance.\n Note this has to be done before the call to `didMove(to:)` or `removeFromParent()`\n otherwise `endAppearanceTransition()` will fire `didMove(to:)` twice.\n */\n if shouldHandleAppearanceEvents {\n if let targetViewController,\n sourceViewController != targetViewController {\n self.endChildControllerTransition(targetViewController)\n }\n\n if let sourceViewController,\n sourceViewController != targetViewController {\n self.endChildControllerTransition(sourceViewController)\n }\n }\n\n // Notify the added controllers that they finished a transition into the container\n for child in viewControllersToAdd {\n child.didMove(toParent: self)\n }\n\n // Remove the controllers that transitioned out of the container\n // The call to removeFromParent() automatically calls child.didMove()\n for child in viewControllersToRemove {\n child.view.removeFromSuperview()\n child.removeFromParent()\n }\n\n // Remove the source controller from view hierarchy\n if sourceViewController != targetViewController {\n sourceViewController?.view.removeFromSuperview()\n }\n\n self.updateInterfaceOrientation(attemptRotateToDeviceOrientation: true)\n self.updateAccessibilityElementsAndNotifyScreenChange()\n }\n\n private func configureViewControllers(\n viewControllersToAdd: [UIViewController],\n newViewControllers: [UIViewController],\n targetViewController: UIViewController?,\n viewControllersToRemove: [UIViewController]\n ) {\n // Add new child controllers. The call to addChild() automatically calls child.willMove()\n // Children have to be registered in the container for Storyboard unwind segues to function\n // properly, however the child controller views don't have to be added immediately, and\n // appearance methods have to be handled manually.\n for child in viewControllersToAdd {\n addChild(child)\n }\n\n // Make sure that all new view controllers have loaded their views\n // This is important because the unwind segue calls the unwind action which may rely on\n // IB outlets to be set at that time.\n for newViewController in newViewControllers {\n newViewController.loadViewIfNeeded()\n }\n\n // Add the destination view into the view hierarchy\n if let targetView = targetViewController?.view {\n addChildView(targetView)\n }\n\n // Notify the controllers that they will transition out of the container\n for child in viewControllersToRemove {\n child.willMove(toParent: nil)\n }\n\n viewControllers = newViewControllers\n }\n\n private func beginTransition(\n shouldHandleAppearanceEvents: Bool,\n targetViewController: UIViewController?,\n shouldAnimate: Bool,\n sourceViewController: UIViewController?\n ) {\n if shouldHandleAppearanceEvents {\n if let sourceViewController,\n sourceViewController != targetViewController {\n beginChildControllerTransition(\n sourceViewController,\n isAppearing: false,\n animated: shouldAnimate\n )\n }\n if let targetViewController,\n sourceViewController != targetViewController {\n beginChildControllerTransition(\n targetViewController,\n isAppearing: true,\n animated: shouldAnimate\n )\n }\n setNeedsStatusBarAppearanceUpdate()\n }\n }\n\n private func addChildView(_ childView: UIView) {\n childView.translatesAutoresizingMaskIntoConstraints = true\n childView.autoresizingMask = [.flexibleWidth, .flexibleHeight]\n childView.frame = transitionContainer.bounds\n\n transitionContainer.addSubview(childView)\n }\n\n /// Updates the header bar's layout margins to make sure it doesn't go below the system status\n /// bar.\n private func updateHeaderBarLayoutMarginsIfNeeded() {\n let offsetTop = view.safeAreaInsets.top - additionalSafeAreaInsets.top\n\n if headerBarView.layoutMargins.top != offsetTop {\n headerBarView.layoutMargins.top = offsetTop\n }\n }\n\n /// Updates additional safe area insets to push the child views below the header bar\n private func updateAdditionalSafeAreaInsetsIfNeeded() {\n let offsetTop = view.safeAreaInsets.top - additionalSafeAreaInsets.top\n let insetTop = headerBarHidden ? 0 : headerBarView.frame.height - offsetTop\n\n if additionalSafeAreaInsets.top != insetTop {\n additionalSafeAreaInsets.top = insetTop\n }\n }\n\n private func setHeaderBarPresentation(_ presentation: HeaderBarPresentation, animated: Bool) {\n headerBarPresentation = presentation\n\n let action = {\n self.updateHeaderBarBackground()\n }\n\n if animated {\n UIView.animate(withDuration: 0.25, animations: action)\n } else {\n action()\n }\n }\n\n private func setHeaderBarHidden(_ hidden: Bool, animated: Bool) {\n headerBarHidden = hidden\n\n let action = {\n self.headerBarView.alpha = hidden ? 0 : 1\n }\n\n if animated {\n UIView.animate(withDuration: 0.25, animations: action)\n } else {\n action()\n }\n }\n\n private func updateHeaderBarBackground() {\n headerBarView.backgroundColor = headerBarPresentation.style.backgroundColor()\n headerBarView.showsDivider = headerBarPresentation.showsDivider\n }\n\n private func updateHeaderBarStyleFromChildPreferences(animated: Bool) {\n if let conforming = topViewController as? RootContainment {\n setHeaderBarPresentation(conforming.preferredHeaderBarPresentation, animated: animated)\n }\n }\n\n private func updateDeviceInfoBarHiddenFromChildPreferences() {\n if let conforming = topViewController as? RootContainment {\n headerBarView.isDeviceInfoHidden = conforming.prefersDeviceInfoBarHidden\n }\n }\n\n private func updateNotificationBarHiddenFromChildPreferences() {\n if let notificationController,\n let conforming = topViewController as? RootContainment {\n if conforming.prefersNotificationBarHidden {\n removeNotificationController(notificationController)\n } else {\n addNotificationController(notificationController)\n }\n }\n }\n\n private func updateHeaderBarHiddenFromChildPreferences(animated: Bool) {\n guard overrideHeaderBarHidden == nil else { return }\n\n if let conforming = topViewController as? RootContainment {\n setHeaderBarHidden(conforming.prefersHeaderBarHidden, animated: animated)\n }\n }\n\n private func updateInterfaceOrientation(attemptRotateToDeviceOrientation: Bool) {\n let newSupportedOrientations = delegate?\n .rootContainerViewSupportedInterfaceOrientations(self)\n\n if interfaceOrientationMask != newSupportedOrientations {\n interfaceOrientationMask = newSupportedOrientations\n\n // Tell UIKit to update the interface orientation\n if attemptRotateToDeviceOrientation {\n Self.attemptRotationToDeviceOrientation()\n }\n }\n }\n\n private func beginChildControllerTransition(\n _ controller: UIViewController,\n isAppearing: Bool,\n animated: Bool\n ) {\n if appearingController != controller, isAppearing {\n appearingController = controller\n controller.beginAppearanceTransition(isAppearing, animated: animated)\n }\n\n if disappearingController != controller, !isAppearing {\n disappearingController = controller\n controller.beginAppearanceTransition(isAppearing, animated: animated)\n }\n }\n\n private func endChildControllerTransition(_ controller: UIViewController) {\n if controller == appearingController {\n appearingController = nil\n controller.endAppearanceTransition()\n }\n\n if controller == disappearingController {\n disappearingController = nil\n controller.endAppearanceTransition()\n }\n }\n\n private func updateAccessibilityElementsAndNotifyScreenChange() {\n // Update accessibility elements to define the correct navigation order: header bar, content\n // view.\n view.accessibilityElements = [headerBarView, topViewController?.view].compactMap { $0 }\n\n // Tell accessibility that the significant part of screen was changed.\n UIAccessibility.post(notification: .screenChanged, argument: nil)\n }\n\n // MARK: - Notification controller support\n\n /**\n An instance of notification controller presented within container.\n */\n var notificationController: NotificationController? {\n didSet {\n guard oldValue != notificationController else { return }\n\n oldValue.flatMap { removeNotificationController($0) }\n notificationController.flatMap { addNotificationController($0) }\n }\n }\n\n /**\n Layout guide for notification view.\n\n When set, notification view follows the layout guide that defines its dimensions and position, otherwise it's\n laid out within container's safe area.\n */\n var notificationViewLayoutGuide: UILayoutGuide? {\n didSet {\n notificationController.flatMap { updateNotificationViewConstraints($0) }\n }\n }\n\n private var notificationViewConstraints: [NSLayoutConstraint] = []\n\n private func updateNotificationViewConstraints(_ notificationController: NotificationController) {\n let newConstraints = notificationController.view\n .pinEdgesTo(notificationViewLayoutGuide ?? view.safeAreaLayoutGuide)\n\n NSLayoutConstraint.deactivate(notificationViewConstraints)\n NSLayoutConstraint.activate(newConstraints)\n\n notificationViewConstraints = newConstraints\n }\n\n private func addNotificationController(_ notificationController: NotificationController) {\n guard let notificationView = notificationController.view else { return }\n\n notificationView.configureForAutoLayout()\n\n addChild(notificationController)\n view.addSubview(notificationView)\n notificationController.didMove(toParent: self)\n\n updateNotificationViewConstraints(notificationController)\n }\n\n private func removeNotificationController(_ notificationController: NotificationController) {\n notificationController.willMove(toParent: nil)\n notificationController.view.removeFromSuperview()\n notificationController.removeFromParent()\n }\n}\n\n/// A UIViewController extension that gives view controllers an access to root container\nextension UIViewController {\n var rootContainerController: RootContainerViewController? {\n var current: UIViewController? = self\n let iterator = AnyIterator { () -> UIViewController? in\n current = current?.parent\n return current\n }\n\n return iterator.first { $0 is RootContainerViewController } as? RootContainerViewController\n }\n\n func setNeedsHeaderBarStyleAppearanceUpdate() {\n rootContainerController?.updateHeaderBarAppearance()\n }\n\n func setNeedsHeaderBarHiddenAppearanceUpdate() {\n rootContainerController?.updateHeaderBarHiddenAppearance()\n }\n}\n\nextension RootContainerViewController {\n func update(configuration: RootConfiguration) {\n self.configuration = configuration\n presentationContainerAccountButton?.isHidden = !configuration.showsAccountButton\n headerBarView.update(configuration: configuration)\n }\n\n // swiftlint:disable:next file_length\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Containers\Root\RootContainerViewController.swift | RootContainerViewController.swift | Swift | 30,018 | 0.95 | 0.060364 | 0.079944 | vue-tools | 907 | 2023-12-24T14:13:07.712118 | GPL-3.0 | false | 021811f409cc55626bc6270bf5a7d512 |
//\n// AccountCoordinator.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-04-14.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Routing\nimport StoreKit\nimport UIKit\n\nenum AccountDismissReason: Equatable, Sendable {\n case none\n case userLoggedOut\n case accountDeletion\n}\n\nfinal class AccountCoordinator: Coordinator, Presentable, Presenting, @unchecked Sendable {\n private let interactor: AccountInteractor\n private let storePaymentManager: StorePaymentManager\n private var accountController: AccountViewController?\n\n let navigationController: UINavigationController\n var presentedViewController: UIViewController {\n navigationController\n }\n\n var didFinish: (@MainActor (AccountCoordinator, AccountDismissReason) -> Void)?\n\n init(\n navigationController: UINavigationController,\n interactor: AccountInteractor,\n storePaymentManager: StorePaymentManager\n ) {\n self.navigationController = navigationController\n self.interactor = interactor\n self.storePaymentManager = storePaymentManager\n }\n\n func start(animated: Bool) {\n navigationController.navigationBar.prefersLargeTitles = true\n\n let accountController = AccountViewController(\n interactor: interactor,\n errorPresenter: PaymentAlertPresenter(alertContext: self)\n )\n\n accountController.actionHandler = handleViewControllerAction\n\n navigationController.pushViewController(accountController, animated: animated)\n self.accountController = accountController\n }\n\n private func handleViewControllerAction(_ action: AccountViewControllerAction) {\n switch action {\n case .deviceInfo:\n showAccountDeviceInfo()\n case .finish:\n didFinish?(self, .none)\n case .logOut:\n logOut()\n case .navigateToVoucher:\n navigateToRedeemVoucher()\n case .navigateToDeleteAccount:\n navigateToDeleteAccount()\n case .restorePurchasesInfo:\n showRestorePurchasesInfo()\n case .showFailedToLoadProducts:\n showFailToFetchProducts()\n case .showRestorePurchases:\n didRequestShowInAppPurchase(paymentAction: .restorePurchase)\n case .showPurchaseOptions:\n didRequestShowInAppPurchase(paymentAction: .purchase)\n }\n }\n\n private func didRequestShowInAppPurchase(\n paymentAction: PaymentAction\n ) {\n guard let accountNumber = interactor.deviceState.accountData?.number else { return }\n let coordinator = InAppPurchaseCoordinator(\n storePaymentManager: storePaymentManager,\n accountNumber: accountNumber,\n paymentAction: paymentAction\n )\n coordinator.didFinish = { coordinator in\n coordinator.dismiss(animated: true)\n }\n coordinator.start()\n presentChild(coordinator, animated: true)\n }\n\n private func navigateToRedeemVoucher() {\n let coordinator = ProfileVoucherCoordinator(\n navigationController: CustomNavigationController(),\n interactor: RedeemVoucherInteractor(\n tunnelManager: interactor.tunnelManager,\n accountsProxy: interactor.accountsProxy,\n verifyVoucherAsAccount: false\n )\n )\n coordinator.didFinish = { coordinator in\n coordinator.dismiss(animated: true)\n }\n coordinator.didCancel = { coordinator in\n coordinator.dismiss(animated: true)\n }\n\n coordinator.start()\n presentChild(\n coordinator,\n animated: true,\n configuration: ModalPresentationConfiguration(\n preferredContentSize: UIMetrics.SettingsRedeemVoucher.preferredContentSize,\n modalPresentationStyle: .custom,\n transitioningDelegate: FormSheetTransitioningDelegate(options: FormSheetPresentationOptions(\n useFullScreenPresentationInCompactWidth: false,\n adjustViewWhenKeyboardAppears: true\n ))\n )\n )\n }\n\n @MainActor\n private func navigateToDeleteAccount() {\n let coordinator = AccountDeletionCoordinator(\n navigationController: CustomNavigationController(),\n interactor: AccountDeletionInteractor(tunnelManager: interactor.tunnelManager)\n )\n\n coordinator.start()\n coordinator.didCancel = { accountDeletionCoordinator in\n Task { @MainActor in\n accountDeletionCoordinator.dismiss(animated: true)\n }\n }\n\n coordinator.didFinish = { @MainActor accountDeletionCoordinator in\n accountDeletionCoordinator.dismiss(animated: true) {\n self.didFinish?(self, .userLoggedOut)\n }\n }\n\n presentChild(\n coordinator,\n animated: true,\n configuration: ModalPresentationConfiguration(\n preferredContentSize: UIMetrics.AccountDeletion.preferredContentSize,\n modalPresentationStyle: .custom,\n transitioningDelegate: FormSheetTransitioningDelegate(options: FormSheetPresentationOptions(\n useFullScreenPresentationInCompactWidth: true,\n adjustViewWhenKeyboardAppears: false\n ))\n )\n )\n }\n\n // MARK: - Alerts\n\n private func logOut() {\n let presentation = AlertPresentation(\n id: "account-logout-alert",\n accessibilityIdentifier: .logOutSpinnerAlertView,\n icon: .spinner,\n message: nil,\n buttons: []\n )\n\n let alertPresenter = AlertPresenter(context: self)\n\n Task {\n await interactor.logout()\n DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) { [weak self] in\n guard let self else { return }\n\n alertPresenter.dismissAlert(presentation: presentation, animated: true)\n self.didFinish?(self, .userLoggedOut)\n }\n }\n\n alertPresenter.showAlert(presentation: presentation, animated: true)\n }\n\n private func showAccountDeviceInfo() {\n let message = NSLocalizedString(\n "DEVICE_INFO_DIALOG_MESSAGE_PART_1",\n tableName: "Account",\n value: """\n This is the name assigned to the device. Each device logged in on a Mullvad account gets a unique name \\n that helps you identify it when you manage your devices in the app or on the website.\n You can have up to 5 devices logged in on one Mullvad account.\n If you log out, the device and the device name is removed. When \\n you log back in again, the device will get a new name.\n """,\n comment: ""\n )\n\n let presentation = AlertPresentation(\n id: "account-device-info-alert",\n icon: .info,\n message: message,\n buttons: [AlertAction(\n title: NSLocalizedString(\n "DEVICE_INFO_DIALOG_OK_ACTION",\n tableName: "Account",\n value: "Got it!",\n comment: ""\n ),\n style: .default\n )]\n )\n\n let presenter = AlertPresenter(context: self)\n presenter.showAlert(presentation: presentation, animated: true)\n }\n\n private func showRestorePurchasesInfo() {\n let message = NSLocalizedString(\n "RESTORE_PURCHASES_DIALOG_MESSAGE",\n tableName: "Account",\n value: """\n You can use the "restore purchases" function to check for any in-app payments \\n made via Apple services. If there is a payment that has not been credited, it will \\n add the time to the currently logged in Mullvad account.\n """,\n comment: ""\n )\n\n let presentation = AlertPresentation(\n id: "account-device-info-alert",\n icon: .info,\n title: NSLocalizedString(\n "RESTORE_PURCHASES_DIALOG_TITLE",\n tableName: "Account",\n value: "If you haven’t received additional VPN time after purchasing",\n comment: ""\n ),\n message: message,\n buttons: [AlertAction(\n title: NSLocalizedString(\n "RESTORE_PURCHASES_DIALOG_OK_ACTION",\n tableName: "Account",\n value: "Got it!",\n comment: ""\n ),\n style: .default\n )]\n )\n\n let presenter = AlertPresenter(context: self)\n presenter.showAlert(presentation: presentation, animated: true)\n }\n\n func showFailToFetchProducts() {\n let message = NSLocalizedString(\n "WELCOME_FAILED_TO_FETCH_PRODUCTS_DIALOG",\n tableName: "Welcome",\n value:\n """\n Failed to connect to App store, please try again later.\n """,\n comment: ""\n )\n\n let presentation = AlertPresentation(\n id: "welcome-failed-to-fetch-products-alert",\n icon: .info,\n message: message,\n buttons: [\n AlertAction(\n title: NSLocalizedString(\n "WELCOME_FAILED_TO_FETCH_PRODUCTS_OK_ACTION",\n tableName: "Welcome",\n value: "Got it!",\n comment: ""\n ),\n style: .default\n ),\n ]\n )\n\n let presenter = AlertPresenter(context: self)\n presenter.showAlert(presentation: presentation, animated: true)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\AccountCoordinator.swift | AccountCoordinator.swift | Swift | 9,879 | 0.95 | 0.017483 | 0.031621 | python-kit | 471 | 2024-10-12T08:06:09.019094 | BSD-3-Clause | false | eeee04c68d1473ea1b3938785df4dcdb |
//\n// AccountDeletionCoordinator.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2023-07-13.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport Routing\nimport UIKit\n\nfinal class AccountDeletionCoordinator: Coordinator, Presentable {\n private let navigationController: UINavigationController\n private let interactor: AccountDeletionInteractor\n\n var didCancel: (@MainActor (AccountDeletionCoordinator) -> Void)?\n var didFinish: (@MainActor (AccountDeletionCoordinator) -> Void)?\n\n var presentedViewController: UIViewController {\n navigationController\n }\n\n init(\n navigationController: UINavigationController,\n interactor: AccountDeletionInteractor\n ) {\n self.navigationController = navigationController\n self.interactor = interactor\n }\n\n func start() {\n navigationController.navigationBar.isHidden = true\n let viewController = AccountDeletionViewController(interactor: interactor)\n viewController.delegate = self\n navigationController.pushViewController(viewController, animated: true)\n }\n}\n\nextension AccountDeletionCoordinator: @preconcurrency AccountDeletionViewControllerDelegate {\n func deleteAccountDidSucceed(controller: AccountDeletionViewController) {\n didFinish?(self)\n }\n\n func deleteAccountDidCancel(controller: AccountDeletionViewController) {\n didCancel?(self)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\AccountDeletionCoordinator.swift | AccountDeletionCoordinator.swift | Swift | 1,439 | 0.95 | 0.020833 | 0.175 | react-lib | 402 | 2024-01-16T16:17:26.351468 | BSD-3-Clause | false | ab0489e720d840ae9462df233b8824b3 |
//\n// AlertCoordinator.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-08-23.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadLogging\nimport Routing\nimport UIKit\n\nfinal class AlertCoordinator: Coordinator, Presentable {\n private var alertController: AlertViewController?\n private let presentation: AlertPresentation\n\n var didFinish: (() -> Void)?\n\n var presentedViewController: UIViewController {\n return alertController!\n }\n\n init(presentation: AlertPresentation) {\n self.presentation = presentation\n }\n\n func start() {\n alertController = AlertViewController(presentation: presentation)\n\n alertController?.onDismiss = { [weak self] in\n self?.didFinish?()\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\AlertCoordinator.swift | AlertCoordinator.swift | Swift | 780 | 0.95 | 0.029412 | 0.259259 | react-lib | 741 | 2024-05-03T02:04:09.130757 | MIT | false | 2c45fa7d7a151b8bc7e8b00b35dc6e4d |
//\n// ApplicationCoordinator.swift\n// MullvadVPN\n//\n// Created by pronebird on 13/01/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport MullvadREST\nimport MullvadSettings\nimport MullvadTypes\nimport Routing\nimport UIKit\n\n/**\n Application coordinator managing split view and two navigation contexts.\n */\nfinal class ApplicationCoordinator: Coordinator, Presenting, @preconcurrency RootContainerViewControllerDelegate,\n UISplitViewControllerDelegate, @preconcurrency ApplicationRouterDelegate,\n @preconcurrency NotificationManagerDelegate {\n typealias RouteType = AppRoute\n\n /**\n Application router.\n */\n nonisolated(unsafe) private(set) var router: ApplicationRouter<AppRoute>!\n\n /**\n Navigation container.\n\n Used as a container for horizontal flows (TOS, Login, Revoked, Out-of-time).\n */\n private let navigationContainer = RootContainerViewController()\n\n /// Posts `preferredAccountNumber` notification when user inputs the account number instead of voucher code\n private let preferredAccountNumberSubject = PassthroughSubject<String, Never>()\n\n private let notificationController = NotificationController()\n\n private var splitTunnelCoordinator: TunnelCoordinator?\n private var splitLocationCoordinator: LocationCoordinator?\n\n private let tunnelManager: TunnelManager\n private let storePaymentManager: StorePaymentManager\n private let relayCacheTracker: RelayCacheTracker\n\n private let apiProxy: APIQuerying\n private let devicesProxy: DeviceHandling\n private let accountsProxy: RESTAccountHandling\n private var tunnelObserver: TunnelObserver?\n private var appPreferences: AppPreferencesDataSource\n private var outgoingConnectionService: OutgoingConnectionServiceHandling\n private var accessMethodRepository: AccessMethodRepositoryProtocol\n private let configuredTransportProvider: ProxyConfigurationTransportProvider\n private let ipOverrideRepository: IPOverrideRepository\n private let relaySelectorWrapper: RelaySelectorWrapper\n\n private var outOfTimeTimer: Timer?\n\n var rootViewController: UIViewController {\n navigationContainer\n }\n\n init(\n tunnelManager: TunnelManager,\n storePaymentManager: StorePaymentManager,\n relayCacheTracker: RelayCacheTracker,\n apiProxy: APIQuerying,\n devicesProxy: DeviceHandling,\n accountsProxy: RESTAccountHandling,\n outgoingConnectionService: OutgoingConnectionServiceHandling,\n appPreferences: AppPreferencesDataSource,\n accessMethodRepository: AccessMethodRepositoryProtocol,\n transportProvider: ProxyConfigurationTransportProvider,\n ipOverrideRepository: IPOverrideRepository,\n relaySelectorWrapper: RelaySelectorWrapper\n\n ) {\n self.tunnelManager = tunnelManager\n self.storePaymentManager = storePaymentManager\n self.relayCacheTracker = relayCacheTracker\n self.apiProxy = apiProxy\n self.devicesProxy = devicesProxy\n self.accountsProxy = accountsProxy\n self.appPreferences = appPreferences\n self.outgoingConnectionService = outgoingConnectionService\n self.accessMethodRepository = accessMethodRepository\n self.configuredTransportProvider = transportProvider\n self.ipOverrideRepository = ipOverrideRepository\n self.relaySelectorWrapper = relaySelectorWrapper\n\n super.init()\n\n navigationContainer.delegate = self\n\n router = ApplicationRouter(self)\n\n addTunnelObserver()\n\n NotificationManager.shared.delegate = self\n }\n\n func start() {\n navigationContainer.notificationController = notificationController\n\n continueFlow(animated: false)\n }\n\n // MARK: - ApplicationRouterDelegate\n\n func applicationRouter(\n _ router: ApplicationRouter<RouteType>,\n presentWithContext context: RoutePresentationContext<RouteType>,\n animated: Bool,\n completion: @escaping @Sendable (Coordinator) -> Void\n ) {\n switch context.route {\n case .account:\n presentAccount(animated: animated, completion: completion)\n\n case let .settings(subRoute):\n presentSettings(route: subRoute, animated: animated, completion: completion)\n\n case .daita:\n presentDAITA(animated: animated, completion: completion)\n\n case .selectLocation:\n presentSelectLocation(animated: animated, completion: completion)\n\n case .outOfTime:\n presentOutOfTime(animated: animated, completion: completion)\n\n case .revoked:\n presentRevoked(animated: animated, completion: completion)\n\n case .login:\n presentLogin(animated: animated, completion: completion)\n\n case .changelog:\n presentChangeLog(animated: animated, completion: completion)\n\n case .tos:\n presentTOS(animated: animated, completion: completion)\n\n case .main:\n presentMain(animated: animated, completion: completion)\n\n case .welcome:\n presentWelcome(animated: animated, completion: completion)\n\n case .alert:\n presentAlert(animated: animated, context: context, completion: completion)\n }\n }\n\n func applicationRouter(\n _ router: ApplicationRouter<RouteType>,\n dismissWithContext context: RouteDismissalContext<RouteType>,\n completion: @escaping @Sendable () -> Void\n ) {\n let dismissedRoute = context.dismissedRoutes.first!\n\n if context.isClosing {\n switch dismissedRoute.route.routeGroup {\n case .primary:\n completion()\n context.dismissedRoutes.forEach { $0.coordinator.removeFromParent() }\n\n case .selectLocation, .account, .settings, .changelog, .alert:\n guard let coordinator = dismissedRoute.coordinator as? Presentable else {\n completion()\n return assertionFailure("Expected presentable coordinator for \(dismissedRoute.route)")\n }\n\n coordinator.dismiss(animated: context.isAnimated, completion: completion)\n }\n } else {\n assert(context.dismissedRoutes.count == 1)\n\n switch dismissedRoute.route {\n case .outOfTime, .welcome:\n guard let coordinator = dismissedRoute.coordinator as? Poppable else {\n completion()\n return assertionFailure("Expected presentable coordinator for \(dismissedRoute.route)")\n }\n\n coordinator.popFromNavigationStack(\n animated: context.isAnimated,\n completion: completion\n )\n\n coordinator.removeFromParent()\n\n default:\n assertionFailure("Unhandled dismissal for \(dismissedRoute.route)")\n completion()\n }\n }\n }\n\n func applicationRouter(_ router: ApplicationRouter<RouteType>, shouldPresent route: RouteType) -> Bool {\n switch route {\n case .revoked:\n // Check if device is still revoked.\n return tunnelManager.deviceState == .revoked\n\n case .outOfTime:\n // Check if device is still out of time.\n return tunnelManager.deviceState.accountData?.isExpired ?? false\n\n default:\n return true\n }\n }\n\n func applicationRouter(\n _ router: ApplicationRouter<RouteType>,\n shouldDismissWithContext context: RouteDismissalContext<RouteType>\n ) -> Bool {\n context.dismissedRoutes.allSatisfy { dismissedRoute in\n /*\n Prevent dismissal of "out of time" route in response to device state change when\n making payment. It will dismiss itself once done.\n */\n if dismissedRoute.route == .outOfTime {\n guard let coordinator = dismissedRoute.coordinator as? OutOfTimeCoordinator else {\n return false\n }\n return !coordinator.isMakingPayment\n }\n\n return true\n }\n }\n\n func applicationRouter(\n _ router: ApplicationRouter<RouteType>,\n handleSubNavigationWithContext context: RouteSubnavigationContext<RouteType>,\n completion: @escaping @Sendable @MainActor () -> Void\n ) {\n switch context.route {\n case let .settings(subRoute):\n guard let coordinator = context.presentedRoute.coordinator as? SettingsCoordinator else { return }\n if let subRoute {\n coordinator.navigate(\n to: subRoute,\n animated: context.isAnimated,\n completion: completion\n )\n } else {\n completion()\n }\n\n default:\n completion()\n }\n }\n\n // MARK: - Private\n\n private var isPresentingAccountExpiryBanner = false\n\n /**\n Continues application flow by evaluating what route to present next.\n */\n private func continueFlow(animated: Bool) {\n let nextRoutes = evaluateNextRoutes()\n\n for nextRoute in nextRoutes {\n router.present(nextRoute, animated: animated)\n }\n }\n\n /**\n Evaluates conditions and returns the routes that need to be presented next.\n */\n private func evaluateNextRoutes() -> [AppRoute] {\n // Show TOS alone blocking all other routes.\n guard appPreferences.isAgreedToTermsOfService else {\n return [.tos]\n }\n\n var routes = [AppRoute]()\n\n // Pick the primary route to present\n switch tunnelManager.deviceState {\n case .revoked:\n routes.append(.revoked)\n\n case .loggedOut:\n routes.append(.login)\n\n case let .loggedIn(accountData, _):\n if !appPreferences.isShownOnboarding {\n routes.append(.welcome)\n } else {\n routes.append(accountData.isExpired ? .outOfTime : .main)\n }\n }\n\n return routes\n }\n\n private func logoutRevokedDevice() {\n Task { [weak self] in\n guard let self else { return }\n await tunnelManager.unsetAccount()\n continueFlow(animated: true)\n }\n }\n\n private func didDismissAccount(_ reason: AccountDismissReason) {\n if reason == .userLoggedOut {\n router.dismissAll(.primary, animated: false)\n continueFlow(animated: false)\n }\n router.dismiss(.account, animated: true)\n }\n\n private func presentTOS(animated: Bool, completion: @escaping (Coordinator) -> Void) {\n let coordinator = TermsOfServiceCoordinator(navigationController: navigationContainer)\n\n coordinator.didFinish = { [weak self] _ in\n self?.appPreferences.isAgreedToTermsOfService = true\n self?.continueFlow(animated: true)\n }\n\n addChild(coordinator)\n coordinator.start()\n\n completion(coordinator)\n }\n\n private func presentChangeLog(animated: Bool, completion: @escaping (Coordinator) -> Void) {\n let coordinator = ChangeLogCoordinator(\n route: .changelog,\n navigationController: CustomNavigationController(),\n viewModel: ChangeLogViewModel(changeLogReader: ChangeLogReader())\n )\n\n coordinator.didFinish = { [weak self] _ in\n self?.router.dismiss(.changelog, animated: animated)\n }\n\n coordinator.start(animated: false)\n\n presentChild(coordinator, animated: animated) {\n completion(coordinator)\n }\n }\n\n private func presentMain(animated: Bool, completion: @escaping (Coordinator) -> Void) {\n let tunnelCoordinator = makeTunnelCoordinator()\n\n navigationContainer.pushViewController(\n tunnelCoordinator.rootViewController,\n animated: animated\n )\n\n addChild(tunnelCoordinator)\n tunnelCoordinator.start()\n\n completion(tunnelCoordinator)\n }\n\n private func presentRevoked(animated: Bool, completion: @escaping (Coordinator) -> Void) {\n let coordinator = RevokedCoordinator(\n navigationController: navigationContainer,\n tunnelManager: tunnelManager\n )\n\n coordinator.didFinish = { [weak self] _ in\n self?.logoutRevokedDevice()\n }\n\n addChild(coordinator)\n coordinator.start(animated: animated)\n\n completion(coordinator)\n }\n\n private func presentOutOfTime(animated: Bool, completion: @escaping (Coordinator) -> Void) {\n let coordinator = OutOfTimeCoordinator(\n navigationController: navigationContainer,\n storePaymentManager: storePaymentManager,\n tunnelManager: tunnelManager\n )\n\n coordinator.didFinishPayment = { [weak self] _ in\n guard let self = self else { return }\n\n Task { @MainActor in\n if shouldDismissOutOfTime() {\n router.dismiss(.outOfTime, animated: true)\n continueFlow(animated: true)\n }\n }\n }\n\n addChild(coordinator)\n coordinator.start(animated: animated)\n\n completion(coordinator)\n }\n\n private func presentWelcome(animated: Bool, completion: @escaping (Coordinator) -> Void) {\n appPreferences.isShownOnboarding = true\n\n let coordinator = WelcomeCoordinator(\n navigationController: navigationContainer,\n storePaymentManager: storePaymentManager,\n tunnelManager: tunnelManager,\n accountsProxy: accountsProxy\n )\n coordinator.didFinish = { [weak self] in\n guard let self else { return }\n router.dismiss(.welcome, animated: false)\n continueFlow(animated: false)\n }\n coordinator.didLogout = { [weak self] preferredAccountNumber in\n guard let self else { return }\n router.dismissAll(.primary, animated: true)\n DispatchQueue.main.async {\n self.continueFlow(animated: true)\n }\n preferredAccountNumberSubject.send(preferredAccountNumber)\n }\n\n addChild(coordinator)\n coordinator.start(animated: animated)\n\n completion(coordinator)\n }\n\n private func shouldDismissOutOfTime() -> Bool {\n !(tunnelManager.deviceState.accountData?.isExpired ?? false)\n }\n\n private func presentSelectLocation(animated: Bool, completion: @escaping (Coordinator) -> Void) {\n let coordinator = makeLocationCoordinator(forModalPresentation: true)\n coordinator.start()\n\n presentChild(coordinator, animated: animated) {\n completion(coordinator)\n }\n }\n\n private func presentLogin(animated: Bool, completion: @escaping (Coordinator) -> Void) {\n let coordinator = LoginCoordinator(\n navigationController: navigationContainer,\n tunnelManager: tunnelManager,\n devicesProxy: devicesProxy\n )\n\n coordinator.preferredAccountNumberPublisher = preferredAccountNumberSubject.eraseToAnyPublisher()\n\n coordinator.didFinish = { [weak self] _ in\n self?.continueFlow(animated: true)\n }\n coordinator.didCreateAccount = { [weak self] in\n self?.appPreferences.isShownOnboarding = false\n }\n\n addChild(coordinator)\n coordinator.start(animated: animated)\n\n completion(coordinator)\n }\n\n private func presentAlert(\n animated: Bool,\n context: RoutePresentationContext<RouteType>,\n completion: @escaping (Coordinator) -> Void\n ) {\n guard let metadata = context.metadata as? AlertMetadata else {\n assertionFailure("Could not get AlertMetadata from RoutePresentationContext.")\n return\n }\n\n let coordinator = AlertCoordinator(presentation: metadata.presentation)\n\n coordinator.didFinish = { [weak self] in\n self?.router.dismiss(context.route)\n }\n\n coordinator.start()\n\n metadata.context.presentChild(coordinator, animated: animated) {\n completion(coordinator)\n }\n }\n\n private func makeTunnelCoordinator() -> TunnelCoordinator {\n let tunnelCoordinator = TunnelCoordinator(\n tunnelManager: tunnelManager,\n outgoingConnectionService: outgoingConnectionService,\n ipOverrideRepository: ipOverrideRepository\n )\n\n tunnelCoordinator.showSelectLocationPicker = { [weak self] in\n self?.router.present(.selectLocation, animated: true)\n }\n\n return tunnelCoordinator\n }\n\n private func makeLocationCoordinator(forModalPresentation isModalPresentation: Bool)\n -> LocationCoordinator {\n let navigationController = CustomNavigationController()\n navigationController.isNavigationBarHidden = !isModalPresentation\n\n let locationCoordinator = LocationCoordinator(\n navigationController: navigationController,\n tunnelManager: tunnelManager,\n relaySelectorWrapper: relaySelectorWrapper,\n customListRepository: CustomListRepository()\n )\n\n locationCoordinator.didFinish = { [weak self] _ in\n if isModalPresentation {\n self?.router.dismiss(.selectLocation, animated: true)\n }\n }\n\n return locationCoordinator\n }\n\n private func presentAccount(animated: Bool, completion: @escaping (Coordinator) -> Void) {\n let accountInteractor = AccountInteractor(\n tunnelManager: tunnelManager,\n accountsProxy: accountsProxy,\n apiProxy: apiProxy\n )\n\n let coordinator = AccountCoordinator(\n navigationController: CustomNavigationController(),\n interactor: accountInteractor,\n storePaymentManager: storePaymentManager\n )\n\n coordinator.didFinish = { [weak self] _, reason in\n self?.didDismissAccount(reason)\n }\n\n coordinator.start(animated: animated)\n\n presentChild(\n coordinator,\n animated: animated\n ) { [weak self] in\n completion(coordinator)\n\n self?.onShowAccount?()\n }\n }\n\n private func presentSettings(\n route: SettingsNavigationRoute?,\n animated: Bool,\n completion: @escaping @Sendable (Coordinator) -> Void\n ) {\n let interactorFactory = SettingsInteractorFactory(\n tunnelManager: tunnelManager,\n apiProxy: apiProxy,\n relayCacheTracker: relayCacheTracker,\n ipOverrideRepository: ipOverrideRepository\n )\n\n let navigationController = CustomNavigationController()\n navigationController.view.setAccessibilityIdentifier(.settingsContainerView)\n\n let configurationTester = ProxyConfigurationTester(transportProvider: configuredTransportProvider)\n\n let coordinator = SettingsCoordinator(\n navigationController: navigationController,\n interactorFactory: interactorFactory,\n accessMethodRepository: accessMethodRepository,\n proxyConfigurationTester: configurationTester,\n ipOverrideRepository: ipOverrideRepository\n )\n\n coordinator.didFinish = { [weak self] _ in\n Task { @MainActor in\n self?.router.dismissAll(.settings, animated: true)\n }\n }\n\n coordinator.willNavigate = { [weak self] _, _, to in\n if to == .root {\n self?.onShowSettings?()\n }\n }\n\n coordinator.start(initialRoute: route)\n\n presentChild(\n coordinator,\n animated: animated\n ) {\n completion(coordinator)\n }\n }\n\n private func presentDAITA(animated: Bool, completion: @escaping @Sendable (Coordinator) -> Void) {\n let viewModel = DAITATunnelSettingsViewModel(tunnelManager: tunnelManager)\n let coordinator = DAITASettingsCoordinator(\n navigationController: CustomNavigationController(),\n route: .daita,\n viewModel: viewModel\n )\n\n coordinator.didFinish = { [weak self] _ in\n self?.router.dismiss(.daita, animated: true)\n }\n\n coordinator.start(animated: animated)\n\n presentChild(coordinator, animated: animated) {\n completion(coordinator)\n }\n }\n\n private func addTunnelObserver() {\n let tunnelObserver =\n TunnelBlockObserver(\n didUpdateTunnelStatus: { [weak self] _, tunnelStatus in\n if case let .error(observedState) = tunnelStatus.observedState,\n observedState.reason == .accountExpired {\n self?.router.present(.outOfTime)\n }\n },\n didUpdateDeviceState: { [weak self] _, deviceState, previousDeviceState in\n self?.deviceStateDidChange(deviceState, previousDeviceState: previousDeviceState)\n }\n )\n\n tunnelManager.addObserver(tunnelObserver)\n\n self.tunnelObserver = tunnelObserver\n\n updateDeviceInfo(deviceState: tunnelManager.deviceState)\n }\n\n private func deviceStateDidChange(_ deviceState: DeviceState, previousDeviceState: DeviceState) {\n updateDeviceInfo(deviceState: deviceState)\n\n switch deviceState {\n case let .loggedIn(accountData, _):\n\n // Account creation is being shown\n guard !isPresentingWelcome && !appPreferences.isShownOnboarding else { return }\n\n // Handle transition to and from expired state.\n switch (previousDeviceState.accountData?.isExpired ?? false, accountData.isExpired) {\n // add more credit\n case (true, false):\n updateOutOfTimeTimer(accountData: accountData)\n continueFlow(animated: true)\n router.dismiss(.outOfTime, animated: true)\n // account was expired\n case (false, true):\n router.present(.outOfTime, animated: true)\n\n default:\n break\n }\n case .revoked:\n appPreferences.isShownOnboarding = true\n cancelOutOfTimeTimer()\n router.present(.revoked, animated: true)\n case .loggedOut:\n appPreferences.isShownOnboarding = true\n cancelOutOfTimeTimer()\n }\n }\n\n private func updateDeviceInfo(deviceState: DeviceState) {\n let rootDeviceInfoViewModel = RootDeviceInfoViewModel(\n isPresentingAccountExpiryBanner: isPresentingAccountExpiryBanner,\n deviceState: deviceState\n )\n self.navigationContainer.update(configuration: rootDeviceInfoViewModel.configuration)\n }\n\n // MARK: - Out of time\n\n private func updateOutOfTimeTimer(accountData: StoredAccountData) {\n cancelOutOfTimeTimer()\n\n guard !accountData.isExpired else { return }\n\n let timer = Timer(fire: accountData.expiry, interval: 0, repeats: false, block: { [weak self] _ in\n Task { @MainActor in\n self?.router.present(.outOfTime, animated: true)\n }\n })\n\n RunLoop.main.add(timer, forMode: .common)\n\n outOfTimeTimer = timer\n }\n\n private func cancelOutOfTimeTimer() {\n outOfTimeTimer?.invalidate()\n outOfTimeTimer = nil\n }\n\n // MARK: - Settings\n\n /**\n This closure is called each time when settings are presented or when navigating from any of sub-routes within\n settings back to root.\n */\n var onShowSettings: (() -> Void)?\n\n /// This closure is called each time when account controller is being presented.\n var onShowAccount: (() -> Void)?\n\n /// Returns `true` if settings are being presented.\n var isPresentingSettings: Bool {\n router.isPresenting(group: .settings)\n }\n\n /// Returns `true` if account controller is being presented.\n var isPresentingAccount: Bool {\n router.isPresenting(group: .account)\n }\n\n /// Returns `true` if welcome controller is being presented.\n private var isPresentingWelcome: Bool {\n router.isPresenting(route: .welcome)\n }\n\n // MARK: - UISplitViewControllerDelegate\n\n func primaryViewController(forExpanding splitViewController: UISplitViewController)\n -> UIViewController? {\n splitLocationCoordinator?.navigationController\n }\n\n func primaryViewController(forCollapsing splitViewController: UISplitViewController)\n -> UIViewController? {\n splitTunnelCoordinator?.rootViewController\n }\n\n func splitViewController(\n _ splitViewController: UISplitViewController,\n collapseSecondary secondaryViewController: UIViewController,\n onto primaryViewController: UIViewController\n ) -> Bool {\n true\n }\n\n func splitViewController(\n _ splitViewController: UISplitViewController,\n separateSecondaryFrom primaryViewController: UIViewController\n ) -> UIViewController? {\n nil\n }\n\n func splitViewControllerDidExpand(_ svc: UISplitViewController) {\n router.dismissAll(.selectLocation, animated: false)\n }\n\n // MARK: - RootContainerViewControllerDelegate\n\n func rootContainerViewControllerShouldShowAccount(\n _ controller: RootContainerViewController,\n animated: Bool\n ) {\n router.present(.account, animated: animated)\n }\n\n func rootContainerViewControllerShouldShowSettings(\n _ controller: RootContainerViewController,\n navigateTo route: SettingsNavigationRoute?,\n animated: Bool\n ) {\n router.present(.settings(route), animated: animated)\n }\n\n func rootContainerViewSupportedInterfaceOrientations(_ controller: RootContainerViewController)\n -> UIInterfaceOrientationMask {\n return [.portrait]\n }\n\n func rootContainerViewAccessibilityPerformMagicTap(_ controller: RootContainerViewController)\n -> Bool {\n guard tunnelManager.deviceState.isLoggedIn else { return false }\n\n switch tunnelManager.tunnelStatus.state {\n case .connected, .connecting, .reconnecting, .waitingForConnectivity(.noConnection), .error,\n .negotiatingEphemeralPeer:\n tunnelManager.reconnectTunnel(selectNewRelay: true)\n\n case .disconnecting, .disconnected:\n tunnelManager.startTunnel()\n\n case .pendingReconnect, .waitingForConnectivity(.noNetwork):\n break\n }\n return true\n }\n\n // MARK: - NotificationManagerDelegate\n\n func notificationManagerDidUpdateInAppNotifications(\n _ manager: NotificationManager,\n notifications: [InAppNotificationDescriptor]\n ) {\n isPresentingAccountExpiryBanner = notifications\n .contains(where: { $0.identifier == .accountExpiryInAppNotification })\n updateDeviceInfo(deviceState: tunnelManager.deviceState)\n notificationController.setNotifications(notifications, animated: true)\n }\n\n func notificationManager(_ manager: NotificationManager, didReceiveResponse response: NotificationResponse) {\n switch response.providerIdentifier {\n case .accountExpirySystemNotification:\n router.present(.account)\n case .accountExpiryInAppNotification:\n isPresentingAccountExpiryBanner = false\n updateDeviceInfo(deviceState: tunnelManager.deviceState)\n case .latestChangesInAppNotificationProvider:\n router.present(.changelog)\n default: return\n }\n }\n\n // MARK: - Presenting\n\n var presentationContext: UIViewController {\n navigationContainer.presentedViewController ?? navigationContainer\n }\n}\n\nextension DeviceState {\n var splitViewMode: UISplitViewController.DisplayMode {\n isLoggedIn ? UISplitViewController.DisplayMode.oneBesideSecondary : .secondaryOnly\n }\n} // swiftlint:disable:this file_length\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\ApplicationCoordinator.swift | ApplicationCoordinator.swift | Swift | 28,125 | 0.95 | 0.035629 | 0.062222 | python-kit | 225 | 2023-11-09T07:13:37.932681 | BSD-3-Clause | false | 7f57b09be5bf4dea4389c0df15019eae |
//\n// ChangeLogCoordinator.swift\n// MullvadVPN\n//\n// Created by pronebird on 24/03/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadLogging\nimport Routing\nimport SwiftUI\nimport UIKit\n\nfinal class ChangeLogCoordinator: Coordinator, Presentable, SettingsChildCoordinator {\n private let route: AppRoute\n private let viewModel: ChangeLogViewModel\n private var navigationController: UINavigationController?\n var didFinish: ((ChangeLogCoordinator) -> Void)?\n\n var presentedViewController: UIViewController {\n navigationController!\n }\n\n init(\n route: AppRoute,\n navigationController: UINavigationController,\n viewModel: ChangeLogViewModel\n ) {\n self.route = route\n self.viewModel = viewModel\n self.navigationController = navigationController\n }\n\n func start(animated: Bool) {\n let changeLogViewController = UIHostingController(rootView: ChangeLogView(viewModel: viewModel))\n changeLogViewController.view.setAccessibilityIdentifier(.changeLogAlert)\n changeLogViewController.navigationItem.title = NSLocalizedString(\n "whats_new_title",\n tableName: "Changelog",\n value: "What's new",\n comment: ""\n )\n\n switch route {\n case .changelog:\n let barButtonItem = UIBarButtonItem(\n title: NSLocalizedString(\n "CHANGELOG_NAVIGATION_DONE_BUTTON",\n tableName: "Changelog",\n value: "Done",\n comment: ""\n ),\n primaryAction: UIAction { [weak self] _ in\n guard let self else { return }\n didFinish?(self)\n }\n )\n barButtonItem.style = .done\n changeLogViewController.navigationItem.rightBarButtonItem = barButtonItem\n fallthrough\n case .settings:\n changeLogViewController.navigationItem.largeTitleDisplayMode = .always\n navigationController?.navigationBar.prefersLargeTitles = true\n default: break\n }\n\n navigationController?.pushViewController(changeLogViewController, animated: animated)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\ChangeLogCoordinator.swift | ChangeLogCoordinator.swift | Swift | 2,251 | 0.95 | 0.028986 | 0.112903 | react-lib | 873 | 2024-12-23T02:54:25.483105 | Apache-2.0 | false | fa186b2ae3b497cfeeba63b88ba055d0 |
//\n// InAppPurchaseCoordinator.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2023-07-21.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Routing\nimport StoreKit\nimport UIKit\n\nenum PaymentAction {\n case purchase\n case restorePurchase\n}\n\nfinal class InAppPurchaseCoordinator: Coordinator, Presentable, Presenting {\n private var controller: InAppPurchaseViewController?\n private let storePaymentManager: StorePaymentManager\n private let accountNumber: String\n private let paymentAction: PaymentAction\n\n var didFinish: ((InAppPurchaseCoordinator) -> Void)?\n\n var presentedViewController: UIViewController {\n return controller!\n }\n\n init(storePaymentManager: StorePaymentManager, accountNumber: String, paymentAction: PaymentAction) {\n self.storePaymentManager = storePaymentManager\n self.accountNumber = accountNumber\n self.paymentAction = paymentAction\n }\n\n func dismiss() {\n didFinish?(self)\n }\n\n func start() {\n controller = InAppPurchaseViewController(\n storePaymentManager: storePaymentManager,\n accountNumber: accountNumber,\n errorPresenter: PaymentAlertPresenter(alertContext: self),\n paymentAction: paymentAction\n )\n controller?.didFinish = dismiss\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\InAppPurchaseCoordinator.swift | InAppPurchaseCoordinator.swift | Swift | 1,329 | 0.95 | 0.020408 | 0.170732 | awesome-app | 785 | 2023-08-09T00:28:03.148092 | Apache-2.0 | false | 23c8fd670e2bcc95da0f0824bd1698fb |
//\n// LocationCoordinator.swift\n// MullvadVPN\n//\n// Created by pronebird on 29/01/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadREST\nimport MullvadSettings\nimport MullvadTypes\nimport Routing\nimport UIKit\n\nclass LocationCoordinator: Coordinator, Presentable, Presenting {\n private let tunnelManager: TunnelManager\n private var tunnelObserver: TunnelObserver?\n private let relaySelectorWrapper: RelaySelectorWrapper\n private let customListRepository: CustomListRepositoryProtocol\n\n let navigationController: UINavigationController\n\n var presentedViewController: UIViewController {\n navigationController\n }\n\n var locationViewControllerWrapper: LocationViewControllerWrapper? {\n return navigationController.viewControllers.first {\n $0 is LocationViewControllerWrapper\n } as? LocationViewControllerWrapper\n }\n\n var didFinish: ((LocationCoordinator) -> Void)?\n\n init(\n navigationController: UINavigationController,\n tunnelManager: TunnelManager,\n relaySelectorWrapper: RelaySelectorWrapper,\n customListRepository: CustomListRepositoryProtocol\n ) {\n self.navigationController = navigationController\n self.tunnelManager = tunnelManager\n self.relaySelectorWrapper = relaySelectorWrapper\n self.customListRepository = customListRepository\n }\n\n func start() {\n // If multihop is enabled, we should check if there's a DAITA related error when opening the location\n // view. If there is, help the user by showing the entry instead of the exit view.\n var startContext: LocationViewControllerWrapper.MultihopContext = .exit\n if tunnelManager.settings.tunnelMultihopState.isEnabled {\n startContext = if case .noRelaysSatisfyingDaitaConstraints = tunnelManager.tunnelStatus.observedState\n .blockedState?.reason { .entry } else { .exit }\n }\n\n let locationViewControllerWrapper = LocationViewControllerWrapper(\n settings: tunnelManager.settings,\n relaySelectorWrapper: relaySelectorWrapper,\n customListRepository: customListRepository,\n startContext: startContext\n )\n\n locationViewControllerWrapper.delegate = self\n\n locationViewControllerWrapper.didFinish = { [weak self] in\n guard let self else { return }\n\n if let tunnelObserver {\n tunnelManager.removeObserver(tunnelObserver)\n }\n didFinish?(self)\n }\n\n addTunnelObserver()\n\n navigationController.pushViewController(locationViewControllerWrapper, animated: false)\n }\n\n private func addTunnelObserver() {\n let tunnelObserver =\n TunnelBlockObserver(\n didUpdateTunnelSettings: { [weak self] _, settings in\n guard let self else { return }\n locationViewControllerWrapper?.onNewSettings?(settings)\n }\n )\n\n tunnelManager.addObserver(tunnelObserver)\n self.tunnelObserver = tunnelObserver\n }\n\n private func showAddCustomList(nodes: [LocationNode]) {\n let coordinator = AddCustomListCoordinator(\n navigationController: CustomNavigationController(),\n interactor: CustomListInteractor(\n repository: customListRepository\n ),\n nodes: nodes\n )\n\n coordinator.didFinish = { [weak self] addCustomListCoordinator in\n addCustomListCoordinator.dismiss(animated: true)\n self?.locationViewControllerWrapper?.refreshCustomLists()\n }\n\n coordinator.start()\n presentChild(coordinator, animated: true)\n }\n\n private func showEditCustomLists(nodes: [LocationNode]) {\n let coordinator = ListCustomListCoordinator(\n navigationController: InterceptibleNavigationController(),\n interactor: CustomListInteractor(repository: customListRepository),\n tunnelManager: tunnelManager,\n nodes: nodes\n )\n\n coordinator.didFinish = { [weak self] listCustomListCoordinator in\n listCustomListCoordinator.dismiss(animated: true)\n self?.locationViewControllerWrapper?.refreshCustomLists()\n }\n\n coordinator.start()\n presentChild(coordinator, animated: true)\n\n coordinator.presentedViewController.presentationController?.delegate = self\n }\n}\n\n// Intercept dismissal (by down swipe) of ListCustomListCoordinator and apply custom actions.\n// See showEditCustomLists() above.\nextension LocationCoordinator: UIAdaptivePresentationControllerDelegate {\n func presentationControllerDidDismiss(_ presentationController: UIPresentationController) {\n locationViewControllerWrapper?.refreshCustomLists()\n }\n}\n\nextension LocationCoordinator: @preconcurrency LocationViewControllerWrapperDelegate {\n func navigateToFilter() {\n let relayFilterCoordinator = RelayFilterCoordinator(\n navigationController: CustomNavigationController(),\n tunnelManager: tunnelManager,\n relaySelectorWrapper: relaySelectorWrapper\n )\n\n relayFilterCoordinator.didFinish = { coordinator, _ in\n coordinator.dismiss(animated: true)\n }\n relayFilterCoordinator.start()\n\n presentChild(relayFilterCoordinator, animated: true)\n }\n\n func didSelectEntryRelays(_ relays: UserSelectedRelays) {\n var relayConstraints = tunnelManager.settings.relayConstraints\n relayConstraints.entryLocations = .only(relays)\n\n tunnelManager.updateSettings([.relayConstraints(relayConstraints)]) {\n self.tunnelManager.startTunnel()\n }\n }\n\n func navigateToDaitaSettings() {\n applicationRouter?.present(.daita)\n }\n\n func didSelectExitRelays(_ relays: UserSelectedRelays) {\n var relayConstraints = tunnelManager.settings.relayConstraints\n relayConstraints.exitLocations = .only(relays)\n\n tunnelManager.updateSettings([.relayConstraints(relayConstraints)]) {\n self.tunnelManager.startTunnel()\n }\n }\n\n func didUpdateFilter(_ filter: RelayFilter) {\n var relayConstraints = tunnelManager.settings.relayConstraints\n relayConstraints.filter = .only(filter)\n tunnelManager.updateSettings([.relayConstraints(relayConstraints)])\n }\n\n func navigateToCustomLists(nodes: [LocationNode]) {\n let actionSheet = UIAlertController(\n title: NSLocalizedString(\n "ACTION_SHEET_TITLE", tableName: "CustomLists", value: "Custom lists", comment: ""\n ),\n message: nil,\n preferredStyle: UIDevice.current.userInterfaceIdiom == .pad ? .alert : .actionSheet\n )\n actionSheet.overrideUserInterfaceStyle = .dark\n actionSheet.view.tintColor = .AlertController.tintColor\n\n let addCustomListAction = UIAlertAction(\n title: NSLocalizedString(\n "ACTION_SHEET_ADD_LIST_BUTTON", tableName: "CustomLists", value: "Add new list", comment: ""\n ),\n style: .default,\n handler: { [weak self] _ in\n self?.showAddCustomList(nodes: nodes)\n }\n )\n addCustomListAction.setAccessibilityIdentifier(.addNewCustomListButton)\n actionSheet.addAction(addCustomListAction)\n\n let editAction = UIAlertAction(\n title: NSLocalizedString(\n "ACTION_SHEET_EDIT_LISTS_BUTTON", tableName: "CustomLists", value: "Edit lists", comment: ""\n ),\n style: .default,\n handler: { [weak self] _ in\n self?.showEditCustomLists(nodes: nodes)\n }\n )\n editAction.isEnabled = !customListRepository.fetchAll().isEmpty\n editAction.setAccessibilityIdentifier(.editCustomListButton)\n actionSheet.addAction(editAction)\n\n actionSheet.addAction(UIAlertAction(\n title: NSLocalizedString(\n "CUSTOM_LIST_ACTION_SHEET_CANCEL_BUTTON",\n tableName: "CustomLists",\n value: "Cancel",\n comment: ""\n ),\n style: .cancel\n ))\n\n presentationContext.present(actionSheet, animated: true)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\LocationCoordinator.swift | LocationCoordinator.swift | Swift | 8,322 | 0.95 | 0.021739 | 0.057292 | react-lib | 248 | 2023-08-26T15:13:03.921512 | MIT | false | 61181a009f547dee29365921ab9e15c0 |
//\n// LoginCoordinator.swift\n// MullvadVPN\n//\n// Created by pronebird on 27/01/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport MullvadREST\nimport MullvadTypes\nimport Operations\nimport Routing\nimport UIKit\n\nfinal class LoginCoordinator: Coordinator, Presenting, @preconcurrency DeviceManagementViewControllerDelegate {\n private let tunnelManager: TunnelManager\n private let devicesProxy: DeviceHandling\n\n private var loginController: LoginViewController?\n nonisolated(unsafe) private var lastLoginAction: LoginAction?\n private var subscriptions = Set<Combine.AnyCancellable>()\n\n var didFinish: (@MainActor @Sendable (LoginCoordinator) -> Void)?\n var didCreateAccount: (@MainActor @Sendable () -> Void)?\n\n var preferredAccountNumberPublisher: AnyPublisher<String, Never>?\n var presentationContext: UIViewController {\n navigationController\n }\n\n let navigationController: RootContainerViewController\n\n init(\n navigationController: RootContainerViewController,\n tunnelManager: TunnelManager,\n devicesProxy: DeviceHandling\n ) {\n self.navigationController = navigationController\n self.tunnelManager = tunnelManager\n self.devicesProxy = devicesProxy\n }\n\n func start(animated: Bool) {\n let interactor = LoginInteractor(tunnelManager: tunnelManager)\n let loginController = LoginViewController(interactor: interactor)\n\n loginController.didFinishLogin = { [weak self] action, error in\n self?.didFinishLogin(action: action, error: error) ?? .nothing\n }\n\n preferredAccountNumberPublisher?\n .compactMap { $0 }\n .sink(receiveValue: { preferredAccountNumber in\n interactor.suggestPreferredAccountNumber?(preferredAccountNumber)\n })\n .store(in: &subscriptions)\n\n interactor.didCreateAccount = didCreateAccount\n\n navigationController.pushViewController(loginController, animated: animated)\n\n self.loginController = loginController\n }\n\n // MARK: - DeviceManagementViewControllerDelegate\n\n func deviceManagementViewControllerDidCancel(_ controller: DeviceManagementViewController) {\n returnToLogin(repeatLogin: false)\n }\n\n func deviceManagementViewControllerDidFinish(_ controller: DeviceManagementViewController) {\n returnToLogin(repeatLogin: true)\n }\n\n // MARK: - Private\n\n private func didFinishLogin(action: LoginAction, error: Error?) -> EndLoginAction {\n guard let error else {\n callDidFinishAfterDelay()\n return .nothing\n }\n\n if case let .useExistingAccount(accountNumber) = action {\n if let error = error as? REST.Error, error.compareErrorCode(.maxDevicesReached) {\n return .wait(Promise { resolve in\n nonisolated(unsafe) let sendableResolve = resolve\n self.showDeviceList(for: accountNumber) { error in\n self.lastLoginAction = action\n\n sendableResolve(error.map { .failure($0) } ?? .success(()))\n }\n })\n } else {\n return .activateTextField\n }\n }\n\n return .nothing\n }\n\n private func callDidFinishAfterDelay() {\n DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) { [weak self] in\n guard let self else { return }\n didFinish?(self)\n }\n }\n\n private func returnToLogin(repeatLogin: Bool) {\n guard let loginController else { return }\n\n navigationController.popToViewController(loginController, animated: true) {\n if let lastLoginAction = self.lastLoginAction, repeatLogin {\n self.loginController?.start(action: lastLoginAction)\n }\n }\n }\n\n private func showDeviceList(for accountNumber: String, completion: @escaping @Sendable (Error?) -> Void) {\n let interactor = DeviceManagementInteractor(\n accountNumber: accountNumber,\n devicesProxy: devicesProxy\n )\n let controller = DeviceManagementViewController(\n interactor: interactor,\n alertPresenter: AlertPresenter(context: self)\n )\n controller.delegate = self\n\n controller.fetchDevices(animateUpdates: false) { [weak self] result in\n guard let self = self else { return }\n\n switch result {\n case .success:\n Task { @MainActor in\n navigationController.pushViewController(controller, animated: true) {\n completion(nil)\n }\n }\n\n case let .failure(error):\n completion(error)\n }\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\LoginCoordinator.swift | LoginCoordinator.swift | Swift | 4,831 | 0.95 | 0.047945 | 0.076271 | node-utils | 618 | 2024-02-18T23:32:32.172608 | BSD-3-Clause | false | b09042c44d599f6b43d4cf7a84e46332 |
//\n// OutOfTimeCoordinator.swift\n// MullvadVPN\n//\n// Created by pronebird on 10/03/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Routing\nimport StoreKit\nimport UIKit\n\nclass OutOfTimeCoordinator: Coordinator, Presenting, @preconcurrency OutOfTimeViewControllerDelegate, Poppable {\n let navigationController: RootContainerViewController\n let storePaymentManager: StorePaymentManager\n let tunnelManager: TunnelManager\n\n nonisolated(unsafe) var didFinishPayment: (@Sendable (OutOfTimeCoordinator) -> Void)?\n\n var presentedViewController: UIViewController {\n navigationController\n }\n\n private(set) var isMakingPayment = false\n private var viewController: OutOfTimeViewController?\n\n init(\n navigationController: RootContainerViewController,\n storePaymentManager: StorePaymentManager,\n tunnelManager: TunnelManager\n ) {\n self.navigationController = navigationController\n self.storePaymentManager = storePaymentManager\n self.tunnelManager = tunnelManager\n }\n\n func start(animated: Bool) {\n let interactor = OutOfTimeInteractor(\n tunnelManager: tunnelManager\n )\n\n interactor.didAddMoreCredit = { [weak self] in\n guard let self else { return }\n didFinishPayment?(self)\n }\n\n let controller = OutOfTimeViewController(\n interactor: interactor,\n errorPresenter: PaymentAlertPresenter(alertContext: self)\n )\n\n controller.delegate = self\n\n viewController = controller\n\n navigationController.pushViewController(controller, animated: animated)\n }\n\n func popFromNavigationStack(animated: Bool, completion: (() -> Void)?) {\n guard let viewController else {\n completion?()\n return\n }\n\n let viewControllers = navigationController.viewControllers.filter { $0 != viewController }\n\n navigationController.setViewControllers(\n viewControllers,\n animated: animated,\n completion: completion\n )\n }\n\n // MARK: - OutOfTimeViewControllerDelegate\n\n func didRequestShowInAppPurchase(\n accountNumber: String,\n paymentAction: PaymentAction\n ) {\n let coordinator = InAppPurchaseCoordinator(\n storePaymentManager: storePaymentManager,\n accountNumber: accountNumber,\n paymentAction: paymentAction\n )\n coordinator.didFinish = { coordinator in\n coordinator.dismiss(animated: true)\n }\n coordinator.start()\n presentChild(coordinator, animated: true)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\OutOfTimeCoordinator.swift | OutOfTimeCoordinator.swift | Swift | 2,658 | 0.95 | 0.010989 | 0.108108 | node-utils | 942 | 2025-03-27T19:51:26.699440 | GPL-3.0 | false | ea720426435fe016ab3ec6798edc5845 |
//\n// ProfileVoucherCoordinator.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2023-06-13.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\nimport Routing\nimport UIKit\n\nfinal class ProfileVoucherCoordinator: Coordinator, Presentable {\n private let navigationController: UINavigationController\n private let viewController: RedeemVoucherViewController\n\n var didFinish: ((ProfileVoucherCoordinator) -> Void)?\n var didCancel: ((ProfileVoucherCoordinator) -> Void)?\n\n init(\n navigationController: UINavigationController,\n interactor: RedeemVoucherInteractor\n ) {\n self.navigationController = navigationController\n viewController = RedeemVoucherViewController(\n configuration: RedeemVoucherViewConfiguration(\n adjustViewWhenKeyboardAppears: false,\n shouldUseCompactStyle: true,\n layoutMargins: UIMetrics.SettingsRedeemVoucher.contentLayoutMargins\n ),\n interactor: interactor\n )\n }\n\n var presentedViewController: UIViewController {\n navigationController\n }\n\n func start() {\n navigationController.navigationBar.isHidden = true\n viewController.delegate = self\n navigationController.pushViewController(viewController, animated: true)\n }\n}\n\nextension ProfileVoucherCoordinator: @preconcurrency RedeemVoucherViewControllerDelegate {\n func redeemVoucherDidSucceed(\n _ controller: RedeemVoucherViewController,\n with response: REST.SubmitVoucherResponse\n ) {\n let viewController = AddCreditSucceededViewController(timeAddedComponents: response.dateComponents)\n viewController.delegate = self\n navigationController.pushViewController(viewController, animated: true)\n }\n\n func redeemVoucherDidCancel(_ controller: RedeemVoucherViewController) {\n didCancel?(self)\n }\n}\n\nextension ProfileVoucherCoordinator: @preconcurrency AddCreditSucceededViewControllerDelegate {\n func addCreditSucceededViewControllerDidFinish(in controller: AddCreditSucceededViewController) {\n didFinish?(self)\n }\n\n func header(in controller: AddCreditSucceededViewController) -> String {\n NSLocalizedString(\n "REDEEM_VOUCHER_SUCCESS_TITLE",\n tableName: "ProfileRedeemVoucher",\n value: "Voucher was successfully redeemed.",\n comment: ""\n )\n }\n\n func titleForAction(in controller: AddCreditSucceededViewController) -> String {\n NSLocalizedString(\n "REDEEM_VOUCHER_DISMISS_BUTTON",\n tableName: "ProfileRedeemVoucher",\n value: "Got it!",\n comment: ""\n )\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\ProfileVoucherCoordinator.swift | ProfileVoucherCoordinator.swift | Swift | 2,736 | 0.95 | 0.011905 | 0.09589 | react-lib | 135 | 2025-06-01T02:27:49.687661 | BSD-3-Clause | false | 20cf07b7edfafd947d445725e81b5bc4 |
//\n// RelayFilterCoordinator.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-06-14.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadREST\nimport MullvadTypes\nimport Routing\nimport UIKit\n\nclass RelayFilterCoordinator: Coordinator, Presentable {\n private let tunnelManager: TunnelManager\n private let relaySelectorWrapper: RelaySelectorWrapper\n private var tunnelObserver: TunnelObserver?\n\n let navigationController: UINavigationController\n\n var presentedViewController: UIViewController {\n return navigationController\n }\n\n var relayFilterViewController: RelayFilterViewController? {\n return navigationController.viewControllers.first {\n $0 is RelayFilterViewController\n } as? RelayFilterViewController\n }\n\n var didFinish: ((RelayFilterCoordinator, RelayFilter?) -> Void)?\n\n init(\n navigationController: UINavigationController,\n tunnelManager: TunnelManager,\n relaySelectorWrapper: RelaySelectorWrapper\n ) {\n self.navigationController = navigationController\n self.tunnelManager = tunnelManager\n self.relaySelectorWrapper = relaySelectorWrapper\n }\n\n func start() {\n let relayFilterViewController = RelayFilterViewController(\n settings: tunnelManager.settings,\n relaySelectorWrapper: relaySelectorWrapper\n )\n\n relayFilterViewController.onApplyFilter = { [weak self] filter in\n guard let self else { return }\n\n var relayConstraints = tunnelManager.settings.relayConstraints\n relayConstraints.filter = .only(filter)\n\n tunnelManager.updateSettings([.relayConstraints(relayConstraints)])\n\n didFinish?(self, filter)\n }\n\n relayFilterViewController.didFinish = { [weak self] in\n guard let self else { return }\n didFinish?(self, nil)\n }\n navigationController.pushViewController(relayFilterViewController, animated: false)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\RelayFilterCoordinator.swift | RelayFilterCoordinator.swift | Swift | 2,021 | 0.95 | 0.015152 | 0.132075 | react-lib | 997 | 2025-01-03T19:49:39.629077 | BSD-3-Clause | false | 8a675421bd0d23269fffc58ed00a042d |
//\n// RevokedCoordinator.swift\n// MullvadVPN\n//\n// Created by pronebird on 07/03/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Routing\nimport UIKit\n\nfinal class RevokedCoordinator: Coordinator {\n let navigationController: RootContainerViewController\n private let tunnelManager: TunnelManager\n\n var didFinish: ((RevokedCoordinator) -> Void)?\n\n init(navigationController: RootContainerViewController, tunnelManager: TunnelManager) {\n self.navigationController = navigationController\n self.tunnelManager = tunnelManager\n }\n\n func start(animated: Bool) {\n let interactor = RevokedDeviceInteractor(tunnelManager: tunnelManager)\n let controller = RevokedDeviceViewController(interactor: interactor)\n\n controller.didFinish = { [weak self] in\n guard let self else { return }\n\n didFinish?(self)\n }\n\n navigationController.pushViewController(controller, animated: animated)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\RevokedCoordinator.swift | RevokedCoordinator.swift | Swift | 993 | 0.95 | 0.028571 | 0.259259 | python-kit | 645 | 2024-08-11T06:26:52.234956 | MIT | false | 482e4ff53edcc2d623608cb2c04bc9ea |
//\n// SafariCoordinator.swift\n// MullvadVPN\n//\n// Created by pronebird on 29/03/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport Routing\nimport SafariServices\n\n@MainActor\nclass SafariCoordinator: Coordinator, Presentable, @preconcurrency SFSafariViewControllerDelegate {\n nonisolated(unsafe) var didFinish: (@Sendable () -> Void)?\n\n var presentedViewController: UIViewController {\n safariController\n }\n\n private let safariController: SFSafariViewController\n\n init(url: URL) {\n safariController = SFSafariViewController(url: url)\n super.init()\n\n safariController.delegate = self\n }\n\n func safariViewControllerDidFinish(_ controller: SFSafariViewController) {\n dismiss(animated: true) {\n self.didFinish?()\n }\n }\n\n func safariViewControllerWillOpenInBrowser(_ controller: SFSafariViewController) {\n dismiss(animated: false) {\n self.didFinish?()\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\SafariCoordinator.swift | SafariCoordinator.swift | Swift | 1,006 | 0.95 | 0.02439 | 0.212121 | python-kit | 397 | 2025-05-05T13:53:14.662430 | GPL-3.0 | false | aeca0fa16f3c2bf43a058250620d2e5b |
//\n// SetupAccountCompletedCoordinator.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2023-07-03.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport Routing\nimport UIKit\n\nclass SetupAccountCompletedCoordinator: Coordinator, Presenting {\n private let navigationController: RootContainerViewController\n private var viewController: SetupAccountCompletedController?\n\n var didFinish: ((SetupAccountCompletedCoordinator) -> Void)?\n\n var presentationContext: UIViewController {\n viewController ?? navigationController\n }\n\n init(navigationController: RootContainerViewController) {\n self.navigationController = navigationController\n }\n\n func start(animated: Bool) {\n let controller = SetupAccountCompletedController()\n controller.delegate = self\n\n viewController = controller\n\n navigationController.pushViewController(controller, animated: animated)\n }\n}\n\nextension SetupAccountCompletedCoordinator: @preconcurrency SetupAccountCompletedControllerDelegate {\n func didRequestToSeePrivacy(controller: SetupAccountCompletedController) {\n presentChild(SafariCoordinator(url: ApplicationConfiguration.privacyGuidesURL), animated: true)\n }\n\n func didRequestToStartTheApp(controller: SetupAccountCompletedController) {\n didFinish?(self)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\SetupAccountCompletedCoordinator.swift | SetupAccountCompletedCoordinator.swift | Swift | 1,362 | 0.95 | 0.022222 | 0.2 | react-lib | 842 | 2024-03-07T19:19:06.075315 | BSD-3-Clause | false | 42c439dd7d91a9c1092c541b92b52a5c |
//\n// TermsOfServiceCoordinator.swift\n// MullvadVPN\n//\n// Created by pronebird on 29/01/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Routing\nimport UIKit\n\nclass TermsOfServiceCoordinator: Coordinator, Presenting {\n private let navigationController: RootContainerViewController\n\n var presentationContext: UIViewController {\n navigationController\n }\n\n var didFinish: ((TermsOfServiceCoordinator) -> Void)?\n\n init(navigationController: RootContainerViewController) {\n self.navigationController = navigationController\n }\n\n func start() {\n let controller = TermsOfServiceViewController()\n\n controller.showPrivacyPolicy = { [weak self] in\n self?.presentChild(SafariCoordinator(url: ApplicationConfiguration.privacyPolicyURL), animated: true)\n }\n\n controller.completionHandler = { [weak self] in\n guard let self else { return }\n didFinish?(self)\n }\n\n navigationController.pushViewController(controller, animated: false)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\TermsOfServiceCoordinator.swift | TermsOfServiceCoordinator.swift | Swift | 1,065 | 0.95 | 0.025641 | 0.233333 | node-utils | 854 | 2023-10-02T20:24:59.500741 | GPL-3.0 | false | ce69485a391152cc2dec18f8e5774e5b |
//\n// TunnelCoordinator.swift\n// MullvadVPN\n//\n// Created by pronebird on 01/02/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\nimport Routing\nimport UIKit\n\nclass TunnelCoordinator: Coordinator, Presenting {\n private let tunnelManager: TunnelManager\n private let controller: TunnelViewController\n private var tunnelObserver: TunnelObserver?\n\n var presentationContext: UIViewController {\n controller\n }\n\n var rootViewController: UIViewController {\n controller\n }\n\n var showSelectLocationPicker: (() -> Void)?\n\n init(\n tunnelManager: TunnelManager,\n outgoingConnectionService: OutgoingConnectionServiceHandling,\n ipOverrideRepository: IPOverrideRepositoryProtocol\n ) {\n self.tunnelManager = tunnelManager\n\n let interactor = TunnelViewControllerInteractor(\n tunnelManager: tunnelManager,\n outgoingConnectionService: outgoingConnectionService,\n ipOverrideRepository: ipOverrideRepository\n )\n\n controller = TunnelViewController(interactor: interactor)\n\n super.init()\n\n controller.shouldShowSelectLocationPicker = { [weak self] in\n self?.showSelectLocationPicker?()\n }\n\n controller.shouldShowCancelTunnelAlert = { [weak self] in\n self?.showCancelTunnelAlert()\n }\n }\n\n func start() {\n let tunnelObserver =\n TunnelBlockObserver(didUpdateDeviceState: { [weak self] _, _, _ in\n self?.updateVisibility(animated: true)\n })\n\n self.tunnelObserver = tunnelObserver\n\n tunnelManager.addObserver(tunnelObserver)\n\n updateVisibility(animated: false)\n }\n\n private func updateVisibility(animated: Bool) {\n let deviceState = tunnelManager.deviceState\n\n controller.setMainContentHidden(!deviceState.isLoggedIn, animated: animated)\n }\n\n private func showCancelTunnelAlert() {\n let presentation = AlertPresentation(\n id: "main-cancel-tunnel-alert",\n icon: .alert,\n message: NSLocalizedString(\n "CANCEL_TUNNEL_ALERT_MESSAGE",\n tableName: "Main",\n value: "If you disconnect now, you won’t be able to secure your connection until the device is online.",\n comment: ""\n ),\n buttons: [\n AlertAction(\n title: NSLocalizedString(\n "CANCEL_TUNNEL_ALERT_DISCONNECT_ACTION",\n tableName: "Main",\n value: "Disconnect",\n comment: ""\n ),\n style: .destructive,\n handler: { [weak self] in\n self?.tunnelManager.stopTunnel()\n }\n ),\n AlertAction(\n title: NSLocalizedString(\n "CANCEL_TUNNEL_ALERT_CANCEL_ACTION",\n tableName: "Main",\n value: "Cancel",\n comment: ""\n ),\n style: .default\n ),\n ]\n )\n\n let presenter = AlertPresenter(context: self)\n presenter.showAlert(presentation: presentation, animated: true)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\TunnelCoordinator.swift | TunnelCoordinator.swift | Swift | 3,370 | 0.95 | 0.009009 | 0.076087 | react-lib | 239 | 2023-08-04T10:57:30.076955 | BSD-3-Clause | false | 62ea246222c1a061f5ad63da0fd3afb5 |
//\n// VPNSettingsCoordinator.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-03-18.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\nimport MullvadTypes\nimport Routing\nimport UIKit\n\nclass VPNSettingsCoordinator: Coordinator, Presenting, SettingsChildCoordinator {\n private let navigationController: UINavigationController\n private let interactorFactory: SettingsInteractorFactory\n private let ipOverrideRepository: IPOverrideRepositoryProtocol\n\n var presentationContext: UIViewController {\n navigationController\n }\n\n init(\n navigationController: UINavigationController,\n interactorFactory: SettingsInteractorFactory,\n ipOverrideRepository: IPOverrideRepositoryProtocol\n ) {\n self.navigationController = navigationController\n self.interactorFactory = interactorFactory\n self.ipOverrideRepository = ipOverrideRepository\n }\n\n func start(animated: Bool) {\n let controller = VPNSettingsViewController(\n interactor: interactorFactory.makeVPNSettingsInteractor(),\n alertPresenter: AlertPresenter(context: self)\n )\n\n controller.delegate = self\n\n navigationController.pushViewController(controller, animated: animated)\n }\n}\n\nextension VPNSettingsCoordinator: @preconcurrency VPNSettingsViewControllerDelegate {\n func showIPOverrides() {\n let coordinator = IPOverrideCoordinator(\n navigationController: navigationController,\n repository: ipOverrideRepository,\n tunnelManager: interactorFactory.tunnelManager\n )\n\n addChild(coordinator)\n coordinator.start(animated: true)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\VPNSettingsCoordinator.swift | VPNSettingsCoordinator.swift | Swift | 1,712 | 0.95 | 0.017857 | 0.148936 | vue-tools | 124 | 2024-02-12T12:02:07.296508 | GPL-3.0 | false | 59eb1c80e5dc45fbbc0310ca74bc762a |
//\n// WelcomeCoordinator.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2023-06-28.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadREST\nimport Routing\nimport StoreKit\nimport UIKit\n\nfinal class WelcomeCoordinator: Coordinator, Poppable, Presenting {\n private let navigationController: RootContainerViewController\n private let storePaymentManager: StorePaymentManager\n private let tunnelManager: TunnelManager\n private let accountsProxy: RESTAccountHandling\n\n private var viewController: WelcomeViewController?\n\n var didFinish: (() -> Void)?\n var didLogout: ((String) -> Void)?\n\n var presentedViewController: UIViewController {\n navigationController\n }\n\n init(\n navigationController: RootContainerViewController,\n storePaymentManager: StorePaymentManager,\n tunnelManager: TunnelManager,\n accountsProxy: RESTAccountHandling\n ) {\n self.navigationController = navigationController\n self.storePaymentManager = storePaymentManager\n self.tunnelManager = tunnelManager\n self.accountsProxy = accountsProxy\n }\n\n func start(animated: Bool) {\n let interactor = WelcomeInteractor(\n tunnelManager: tunnelManager\n )\n\n interactor.didAddMoreCredit = { [weak self] in\n self?.showSetupAccountCompleted()\n }\n\n let controller = WelcomeViewController(interactor: interactor)\n controller.delegate = self\n\n viewController = controller\n\n navigationController.pushViewController(controller, animated: animated)\n }\n\n func showSetupAccountCompleted() {\n let coordinator = SetupAccountCompletedCoordinator(navigationController: navigationController)\n coordinator.didFinish = { [weak self] coordinator in\n coordinator.removeFromParent()\n self?.didFinish?()\n }\n addChild(coordinator)\n coordinator.start(animated: true)\n }\n\n func popFromNavigationStack(animated: Bool, completion: (() -> Void)?) {\n guard let viewController,\n let index = navigationController.viewControllers.firstIndex(of: viewController)\n else {\n completion?()\n return\n }\n navigationController.setViewControllers(\n Array(navigationController.viewControllers[0 ..< index]),\n animated: animated,\n completion: completion\n )\n }\n}\n\nextension WelcomeCoordinator: @preconcurrency WelcomeViewControllerDelegate {\n func didRequestToShowFailToFetchProducts(controller: WelcomeViewController) {\n let message = NSLocalizedString(\n "WELCOME_FAILED_TO_FETCH_PRODUCTS_DIALOG",\n tableName: "Welcome",\n value:\n """\n Failed to connect to App store, please try again later.\n """,\n comment: ""\n )\n\n let presentation = AlertPresentation(\n id: "welcome-failed-to-fetch-products-alert",\n icon: .info,\n message: message,\n buttons: [\n AlertAction(\n title: NSLocalizedString(\n "WELCOME_FAILED_TO_FETCH_PRODUCTS_OK_ACTION",\n tableName: "Welcome",\n value: "Got it!",\n comment: ""\n ),\n style: .default\n ),\n ]\n )\n\n let presenter = AlertPresenter(context: self)\n presenter.showAlert(presentation: presentation, animated: true)\n }\n\n func didRequestToShowInfo(controller: WelcomeViewController) {\n let message = NSLocalizedString(\n "WELCOME_DEVICE_CONCEPT_TEXT_DIALOG",\n tableName: "Welcome",\n value:\n """\n This is the name assigned to the device. Each device logged in on a \\n Mullvad account gets a unique name that helps \\n you identify it when you manage your devices in the app or on the website.\n You can have up to 5 devices logged in on one Mullvad account.\n If you log out, the device and the device name is removed. \\n When you log back in again, the device will get a new name.\n """,\n comment: ""\n )\n\n let presentation = AlertPresentation(\n id: "welcome-device-name-alert",\n icon: .info,\n message: message,\n buttons: [\n AlertAction(\n title: NSLocalizedString(\n "WELCOME_DEVICE_NAME_DIALOG_OK_ACTION",\n tableName: "Welcome",\n value: "Got it!",\n comment: ""\n ),\n style: .default\n ),\n ]\n )\n\n let presenter = AlertPresenter(context: self)\n presenter.showAlert(presentation: presentation, animated: true)\n }\n\n func didRequestToViewPurchaseOptions(\n accountNumber: String\n ) {\n let coordinator = InAppPurchaseCoordinator(\n storePaymentManager: storePaymentManager,\n accountNumber: accountNumber,\n paymentAction: .purchase\n )\n coordinator.didFinish = { coordinator in\n coordinator.dismiss(animated: true)\n }\n coordinator.start()\n presentChild(coordinator, animated: true)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\WelcomeCoordinator.swift | WelcomeCoordinator.swift | Swift | 5,446 | 0.95 | 0.011976 | 0.047619 | node-utils | 711 | 2023-08-30T17:13:05.855097 | GPL-3.0 | false | f22d787b9a60f38b7d0f95e8c21e964f |
//\n// AddCustomListCoordinator.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-02-14.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport MullvadSettings\nimport Routing\nimport UIKit\n\nclass AddCustomListCoordinator: Coordinator, Presentable, Presenting {\n let navigationController: UINavigationController\n let interactor: CustomListInteractorProtocol\n let nodes: [LocationNode]\n let subject = CurrentValueSubject<CustomListViewModel, Never>(\n CustomListViewModel(id: UUID(), name: "", locations: [], tableSections: [.name, .addLocations])\n )\n\n var presentedViewController: UIViewController {\n navigationController\n }\n\n var didFinish: ((AddCustomListCoordinator) -> Void)?\n\n init(\n navigationController: UINavigationController,\n interactor: CustomListInteractorProtocol,\n nodes: [LocationNode]\n ) {\n self.navigationController = navigationController\n self.interactor = interactor\n self.nodes = nodes\n }\n\n func start() {\n let controller = CustomListViewController(\n interactor: interactor,\n subject: subject,\n alertPresenter: AlertPresenter(context: self)\n )\n controller.delegate = self\n\n controller.navigationItem.title = NSLocalizedString(\n "CUSTOM_LISTS_NAVIGATION_EDIT_TITLE",\n tableName: "CustomLists",\n value: "New custom list",\n comment: ""\n )\n\n controller.saveBarButton.title = NSLocalizedString(\n "CUSTOM_LISTS_NAVIGATION_CREATE_BUTTON",\n tableName: "CustomLists",\n value: "Create",\n comment: ""\n )\n\n controller.navigationItem.leftBarButtonItem = UIBarButtonItem(\n systemItem: .cancel,\n primaryAction: UIAction(handler: { [weak self] _ in\n guard let self else {\n return\n }\n didFinish?(self)\n })\n )\n\n navigationController.pushViewController(controller, animated: false)\n }\n}\n\nextension AddCustomListCoordinator: @preconcurrency CustomListViewControllerDelegate {\n func customListDidSave(_ list: CustomList) {\n didFinish?(self)\n }\n\n func customListDidDelete(_ list: CustomList) {\n // No op.\n }\n\n func showLocations(_ list: CustomList) {\n let coordinator = AddLocationsCoordinator(\n navigationController: navigationController,\n nodes: nodes,\n subject: subject\n )\n\n coordinator.didFinish = { locationsCoordinator in\n locationsCoordinator.removeFromParent()\n }\n\n coordinator.start()\n\n addChild(coordinator)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\CustomLists\AddCustomListCoordinator.swift | AddCustomListCoordinator.swift | Swift | 2,760 | 0.95 | 0.010204 | 0.097561 | awesome-app | 453 | 2023-11-01T18:05:33.450372 | Apache-2.0 | false | 7e5a49e2ba3cfb3d1bbe536d6b218f64 |
//\n// AddLocationsCoordinator.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2024-03-04.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport MullvadSettings\nimport MullvadTypes\nimport Routing\nimport UIKit\n\nclass AddLocationsCoordinator: Coordinator, Presentable, Presenting {\n private let navigationController: UINavigationController\n private let nodes: [LocationNode]\n private var subject: CurrentValueSubject<CustomListViewModel, Never>\n\n var didFinish: ((AddLocationsCoordinator) -> Void)?\n\n var presentedViewController: UIViewController {\n navigationController\n }\n\n init(\n navigationController: UINavigationController,\n nodes: [LocationNode],\n subject: CurrentValueSubject<CustomListViewModel, Never>\n ) {\n self.navigationController = navigationController\n self.nodes = nodes\n self.subject = subject\n }\n\n func start() {\n let controller = AddLocationsViewController(\n allLocationsNodes: nodes,\n subject: subject\n )\n controller.delegate = self\n\n controller.navigationItem.title = NSLocalizedString(\n "ADD_LOCATIONS_NAVIGATION_TITLE",\n tableName: "AddLocations",\n value: "Add locations",\n comment: ""\n )\n\n navigationController.pushViewController(controller, animated: true)\n }\n}\n\nextension AddLocationsCoordinator: @preconcurrency AddLocationsViewControllerDelegate {\n func didBack() {\n didFinish?(self)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\CustomLists\AddLocationsCoordinator.swift | AddLocationsCoordinator.swift | Swift | 1,549 | 0.95 | 0.017241 | 0.142857 | python-kit | 618 | 2024-08-07T12:26:42.342635 | GPL-3.0 | false | f5be67bbfeef7c5f90b724642492bc42 |
//\n// AddLocationsDataSource.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2024-02-29.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport MullvadSettings\nimport MullvadTypes\nimport UIKit\n\nclass AddLocationsDataSource:\n UITableViewDiffableDataSource<LocationSection, LocationCellViewModel>,\n LocationDiffableDataSourceProtocol, @unchecked Sendable {\n private var customListLocationNode: CustomListLocationNode\n private let nodes: [LocationNode]\n private let subject: CurrentValueSubject<CustomListViewModel, Never>\n let tableView: UITableView\n let sections: [LocationSection]\n\n init(\n tableView: UITableView,\n allLocationNodes: [LocationNode],\n subject: CurrentValueSubject<CustomListViewModel, Never>\n ) {\n self.tableView = tableView\n self.nodes = allLocationNodes\n self.subject = subject\n\n self.customListLocationNode = CustomListLocationNodeBuilder(\n customList: subject.value.customList,\n allLocations: self.nodes\n ).customListLocationNode\n\n let sections: [LocationSection] = [.customLists]\n self.sections = sections\n\n super.init(tableView: tableView) { _, indexPath, itemIdentifier in\n let cell = tableView.dequeueReusableView(\n withIdentifier: sections[indexPath.section],\n for: indexPath\n ) as! LocationCell // swiftlint:disable:this force_cast\n cell.configure(item: itemIdentifier, behavior: .add)\n cell.selectionStyle = .none\n return cell\n }\n\n tableView.delegate = self\n tableView.registerReusableViews(from: LocationSection.self)\n defaultRowAnimation = .fade\n reloadWithSelectedLocations()\n }\n\n private func reloadWithSelectedLocations() {\n var locationsList: [LocationCellViewModel] = []\n nodes.forEach { node in\n let viewModel = LocationCellViewModel(\n section: .customLists,\n node: node,\n isSelected: customListLocationNode.children.contains(node)\n )\n locationsList.append(viewModel)\n\n // Determine if the node should be expanded.\n guard isLocationInCustomList(node: node) else {\n return\n }\n\n // Only parents with partially selected children should be expanded.\n node.forEachDescendant { descendantNode in\n if customListLocationNode.children.contains(descendantNode) {\n descendantNode.forEachAncestor { descendantParentNode in\n descendantParentNode.showsChildren = true\n }\n }\n }\n\n locationsList.append(contentsOf: recursivelyCreateCellViewModelTree(\n for: node,\n in: .customLists,\n indentationLevel: 1\n ))\n }\n reloadDataSnapshot(with: [locationsList])\n }\n\n private func isLocationInCustomList(node: LocationNode) -> Bool {\n customListLocationNode.children.contains(where: { containsChild(parent: node, child: $0) })\n }\n\n private func containsChild(parent: LocationNode, child: LocationNode) -> Bool {\n parent.flattened.contains(child)\n }\n\n override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {\n // swiftlint:disable:next force_cast\n let cell = super.tableView(tableView, cellForRowAt: indexPath) as! LocationCell\n cell.delegate = self\n return cell\n }\n}\n\nextension AddLocationsDataSource: UITableViewDelegate {\n func tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: IndexPath) -> Int {\n itemIdentifier(for: indexPath)?.indentationLevel ?? 0\n }\n}\n\nextension AddLocationsDataSource: @preconcurrency LocationCellDelegate {\n func toggleExpanding(cell: LocationCell) {\n toggleItems(for: cell) {\n if let indexPath = self.tableView.indexPath(for: cell),\n let item = self.itemIdentifier(for: indexPath) {\n self.scroll(to: item, animated: true)\n }\n }\n }\n\n func toggleSelecting(cell: LocationCell) {\n guard let index = tableView.indexPath(for: cell)?.row else { return }\n\n var locationList = snapshot().itemIdentifiers\n let item = locationList[index]\n let isSelected = !item.isSelected\n locationList[index].isSelected = isSelected\n\n locationList.deselectAncestors(from: item.node)\n locationList.toggleSelectionSubNodes(from: item.node, isSelected: isSelected)\n\n if isSelected {\n customListLocationNode.add(selectedLocation: item.node)\n } else {\n customListLocationNode.remove(selectedLocation: item.node, with: locationList)\n }\n reloadDataSnapshot(with: [locationList], completion: {\n let locations = self.customListLocationNode.children.reduce([]) { partialResult, locationNode in\n partialResult + locationNode.locations\n }\n self.subject.value.locations = locations\n })\n }\n}\n\n// MARK: - Called from LocationDiffableDataSourceProtocol\n\nextension AddLocationsDataSource {\n func nodeShowsChildren(_ node: LocationNode) -> Bool {\n isLocationInCustomList(node: node)\n }\n\n func nodeShouldBeSelected(_ node: LocationNode) -> Bool {\n customListLocationNode.children.contains(node)\n }\n}\n\n// MARK: - Toggle selection in table view\n\nfileprivate extension [LocationCellViewModel] {\n mutating func deselectAncestors(from node: LocationNode?) {\n node?.forEachAncestor { parent in\n guard let index = firstIndex(where: { $0.node == parent }) else {\n return\n }\n self[index].isSelected = false\n }\n }\n\n mutating func toggleSelectionSubNodes(from node: LocationNode, isSelected: Bool) {\n node.forEachDescendant { child in\n guard let index = firstIndex(where: { $0.node == child }) else {\n return\n }\n self[index].isSelected = isSelected\n }\n }\n}\n\n// MARK: - Update custom list\n\nfileprivate extension CustomListLocationNode {\n func remove(selectedLocation: LocationNode, with locationList: [LocationCellViewModel]) {\n if let index = children.firstIndex(of: selectedLocation) {\n children.remove(at: index)\n }\n removeAncestors(node: selectedLocation)\n addSiblings(from: locationList, for: selectedLocation)\n }\n\n func add(selectedLocation: LocationNode) {\n children.append(selectedLocation)\n removeSubNodes(node: selectedLocation)\n }\n\n private func removeSubNodes(node: LocationNode) {\n node.forEachDescendant { child in\n // removing children if they are already added to custom list\n if let index = children.firstIndex(of: child) {\n children.remove(at: index)\n }\n }\n }\n\n private func removeAncestors(node: LocationNode) {\n node.forEachAncestor { parent in\n if let index = children.firstIndex(of: parent) {\n children.remove(at: index)\n }\n }\n }\n\n private func addSiblings(from locationList: [LocationCellViewModel], for node: LocationNode) {\n guard let parent = node.parent else { return }\n parent.children.forEach { child in\n // adding siblings if they are already selected in snapshot\n if let item = locationList.first(where: { $0.node == child }),\n item.isSelected && !children.contains(child) {\n children.append(child)\n }\n }\n addSiblings(from: locationList, for: parent)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\CustomLists\AddLocationsDataSource.swift | AddLocationsDataSource.swift | Swift | 7,820 | 0.95 | 0.09375 | 0.078125 | python-kit | 669 | 2023-08-31T02:56:30.688991 | GPL-3.0 | false | a6782cf94cadf91e6d3e338afa062b71 |
//\n// AddLocationsViewController.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2024-02-29.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport MullvadSettings\nimport MullvadTypes\nimport UIKit\n\nprotocol AddLocationsViewControllerDelegate: AnyObject, Sendable {\n func didBack()\n}\n\nclass AddLocationsViewController: UIViewController {\n private var dataSource: AddLocationsDataSource?\n private let nodes: [LocationNode]\n private let subject: CurrentValueSubject<CustomListViewModel, Never>\n\n weak var delegate: AddLocationsViewControllerDelegate?\n private let tableView: UITableView = {\n let tableView = UITableView()\n tableView.separatorColor = .secondaryColor\n tableView.separatorInset = .zero\n tableView.rowHeight = 56\n tableView.indicatorStyle = .white\n tableView.setAccessibilityIdentifier(.editCustomListEditLocationsTableView)\n return tableView\n }()\n\n init(\n allLocationsNodes: [LocationNode],\n subject: CurrentValueSubject<CustomListViewModel, Never>\n ) {\n self.nodes = allLocationsNodes\n self.subject = subject\n super.init(nibName: nil, bundle: nil)\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n override func viewDidLoad() {\n super.viewDidLoad()\n view.setAccessibilityIdentifier(.editCustomListEditLocationsView)\n tableView.backgroundColor = view.backgroundColor\n view.backgroundColor = .secondaryColor\n addConstraints()\n setUpDataSource()\n }\n\n override func didMove(toParent parent: UIViewController?) {\n super.didMove(toParent: parent)\n\n if parent == nil {\n delegate?.didBack()\n }\n }\n\n private func addConstraints() {\n view.addConstrainedSubviews([tableView]) {\n tableView.pinEdgesToSuperview()\n }\n }\n\n private func setUpDataSource() {\n dataSource = AddLocationsDataSource(\n tableView: tableView,\n allLocationNodes: nodes.copy(),\n subject: subject\n )\n }\n}\n\nfileprivate extension [LocationNode] {\n func copy() -> Self {\n map {\n let copy = $0.copy()\n copy.showsChildren = false\n copy.flattened.forEach { $0.showsChildren = false }\n return copy\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\CustomLists\AddLocationsViewController.swift | AddLocationsViewController.swift | Swift | 2,406 | 0.95 | 0.022727 | 0.092105 | react-lib | 211 | 2025-03-25T00:09:33.620759 | BSD-3-Clause | false | 90209d39a15f426d5f5527107b62fab7 |
//\n// CustomListCellConfiguration.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-02-14.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport MullvadTypes\nimport UIKit\n\n@MainActor\nstruct CustomListCellConfiguration {\n let tableView: UITableView\n let subject: CurrentValueSubject<CustomListViewModel, Never>\n\n var onDelete: (() -> Void)?\n\n func dequeueCell(\n at indexPath: IndexPath,\n for itemIdentifier: CustomListItemIdentifier,\n validationErrors: Set<CustomListFieldValidationError>\n ) -> UITableViewCell {\n let cell = tableView.dequeueReusableView(withIdentifier: itemIdentifier.cellIdentifier, for: indexPath)\n\n configureBackground(cell: cell, itemIdentifier: itemIdentifier, validationErrors: validationErrors)\n\n switch itemIdentifier {\n case .name:\n configureName(cell, itemIdentifier: itemIdentifier)\n case .addLocations, .editLocations:\n configureLocations(cell, itemIdentifier: itemIdentifier)\n case .deleteList:\n configureDelete(cell, itemIdentifier: itemIdentifier)\n }\n\n return cell\n }\n\n private func configureBackground(\n cell: UITableViewCell,\n itemIdentifier: CustomListItemIdentifier,\n validationErrors: Set<CustomListFieldValidationError>\n ) {\n configureErrorState(\n cell: cell,\n itemIdentifier: itemIdentifier,\n contentValidationErrors: validationErrors\n )\n\n guard let cell = cell as? DynamicBackgroundConfiguration else { return }\n\n cell.setAutoAdaptingBackgroundConfiguration(.mullvadListGroupedCell(), selectionType: .dimmed)\n }\n\n private func configureErrorState(\n cell: UITableViewCell,\n itemIdentifier: CustomListItemIdentifier,\n contentValidationErrors: Set<CustomListFieldValidationError>\n ) {\n let itemsWithErrors = CustomListItemIdentifier.fromFieldValidationErrors(contentValidationErrors)\n\n if itemsWithErrors.contains(itemIdentifier) {\n cell.layer.cornerRadius = 10\n cell.layer.borderWidth = 1\n cell.layer.borderColor = UIColor.Cell.validationErrorBorderColor.cgColor\n } else {\n cell.layer.borderWidth = 0\n }\n }\n\n private func configureName(_ cell: UITableViewCell, itemIdentifier: CustomListItemIdentifier) {\n var contentConfiguration = TextCellContentConfiguration()\n\n contentConfiguration.text = itemIdentifier.text\n contentConfiguration.setPlaceholder(type: .required)\n contentConfiguration.textFieldProperties = .withSmartFeaturesDisabled()\n contentConfiguration.inputText = subject.value.name\n contentConfiguration.maxLength = NameInputFormatter.maxLength\n contentConfiguration.editingEvents.onChange = subject.bindTextAction(to: \.name)\n\n cell.setAccessibilityIdentifier(.customListEditNameFieldCell)\n cell.contentConfiguration = contentConfiguration\n }\n\n private func configureLocations(_ cell: UITableViewCell, itemIdentifier: CustomListItemIdentifier) {\n var contentConfiguration = UIListContentConfiguration.mullvadValueCell(tableStyle: tableView.style)\n\n contentConfiguration.text = itemIdentifier.text\n cell.contentConfiguration = contentConfiguration\n cell.setAccessibilityIdentifier(.customListEditAddOrEditLocationCell)\n\n if let cell = cell as? CustomCellDisclosureHandling {\n cell.disclosureType = .chevron\n }\n }\n\n private func configureDelete(_ cell: UITableViewCell, itemIdentifier: CustomListItemIdentifier) {\n var contentConfiguration = ButtonCellContentConfiguration()\n\n contentConfiguration.style = .tableInsetGroupedDanger\n contentConfiguration.text = itemIdentifier.text\n contentConfiguration.primaryAction = UIAction { _ in\n onDelete?()\n }\n\n cell.setAccessibilityIdentifier(.customListEditDeleteListCell)\n cell.contentConfiguration = contentConfiguration\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\CustomLists\CustomListCellConfiguration.swift | CustomListCellConfiguration.swift | Swift | 4,077 | 0.95 | 0.045045 | 0.077778 | vue-tools | 442 | 2024-02-29T00:04:22.332347 | MIT | false | 632757db6eaacf7c06679437164ece26 |
//\n// CustomListDataSourceConfigurationv.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-02-14.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\n@MainActor\nclass CustomListDataSourceConfiguration: NSObject {\n let dataSource: UITableViewDiffableDataSource<CustomListSectionIdentifier, CustomListItemIdentifier>\n var validationErrors: Set<CustomListFieldValidationError> = []\n\n var didSelectItem: ((CustomListItemIdentifier) -> Void)?\n\n init(dataSource: UITableViewDiffableDataSource<CustomListSectionIdentifier, CustomListItemIdentifier>) {\n self.dataSource = dataSource\n }\n\n func updateDataSource(\n sections: [CustomListSectionIdentifier],\n validationErrors: Set<CustomListFieldValidationError>,\n animated: Bool,\n completion: (() -> Void)? = nil\n ) {\n var snapshot = NSDiffableDataSourceSnapshot<CustomListSectionIdentifier, CustomListItemIdentifier>()\n\n sections.forEach { section in\n switch section {\n case .name:\n snapshot.appendSections([.name])\n snapshot.appendItems([.name], toSection: .name)\n case .addLocations:\n snapshot.appendSections([.addLocations])\n snapshot.appendItems([.addLocations], toSection: .addLocations)\n case .editLocations:\n snapshot.appendSections([.editLocations])\n snapshot.appendItems([.editLocations], toSection: .editLocations)\n case .deleteList:\n snapshot.appendSections([.deleteList])\n snapshot.appendItems([.deleteList], toSection: .deleteList)\n }\n }\n\n dataSource.apply(snapshot, animatingDifferences: animated)\n }\n\n func set(validationErrors: Set<CustomListFieldValidationError>) {\n self.validationErrors = validationErrors\n\n var snapshot = dataSource.snapshot()\n\n validationErrors.forEach { error in\n switch error {\n case .name:\n snapshot.reloadSections([.name])\n }\n }\n\n dataSource.apply(snapshot, animatingDifferences: false)\n }\n}\n\nextension CustomListDataSourceConfiguration: UITableViewDelegate {\n func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {\n return nil\n }\n\n func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {\n let sectionIdentifier = dataSource.snapshot().sectionIdentifiers[section]\n\n return switch sectionIdentifier {\n case .name:\n 16\n default:\n UITableView.automaticDimension\n }\n }\n\n func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {\n UIMetrics.SettingsCell.customListsCellHeight\n }\n\n func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {\n let snapshot = dataSource.snapshot()\n\n let sectionIdentifier = snapshot.sectionIdentifiers[section]\n let itemsInSection = snapshot.itemIdentifiers(inSection: sectionIdentifier)\n\n let itemsWithErrors = CustomListItemIdentifier.fromFieldValidationErrors(validationErrors)\n let errorsInSection = itemsWithErrors.filter { itemsInSection.contains($0) }.compactMap { item in\n switch item {\n case .name:\n Array(validationErrors).filter { error in\n if case .name = error {\n return true\n }\n return false\n }\n case .addLocations, .editLocations, .deleteList:\n nil\n }\n }\n\n switch sectionIdentifier {\n case .name:\n let view = SettingsFieldValidationErrorContentView(\n configuration: SettingsFieldValidationErrorConfiguration(\n errors: errorsInSection.flatMap { $0.settingsFieldValidationErrors }\n )\n )\n return view\n default:\n return nil\n }\n }\n\n func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {\n tableView.deselectRow(at: indexPath, animated: false)\n\n if let item = dataSource.itemIdentifier(for: indexPath) {\n didSelectItem?(item)\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\CustomLists\CustomListDataSourceConfiguration.swift | CustomListDataSourceConfiguration.swift | Swift | 4,376 | 0.95 | 0.070866 | 0.066038 | python-kit | 946 | 2025-04-25T18:09:12.847234 | GPL-3.0 | false | 24d7df020101adb6fc4fb42d9d470ec5 |
//\n// CustomListInteractor.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-02-15.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\n\nprotocol CustomListInteractorProtocol {\n func fetchAll() -> [CustomList]\n func save(viewModel: CustomListViewModel) throws\n func delete(id: UUID)\n}\n\nstruct CustomListInteractor: CustomListInteractorProtocol {\n let repository: CustomListRepositoryProtocol\n\n func fetchAll() -> [CustomList] {\n repository.fetchAll()\n }\n\n func save(viewModel: CustomListViewModel) throws {\n try repository.save(list: viewModel.customList)\n }\n\n func delete(id: UUID) {\n repository.delete(id: id)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\CustomLists\CustomListInteractor.swift | CustomListInteractor.swift | Swift | 714 | 0.95 | 0.032258 | 0.28 | vue-tools | 276 | 2024-02-16T04:18:53.574200 | MIT | false | 3f95528ae45ba4aaf04e642c5e51a8e1 |
//\n// CustomListItemIdentifier.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-02-14.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nenum CustomListItemIdentifier: Hashable, CaseIterable {\n case name\n case addLocations\n case editLocations\n case deleteList\n\n enum CellIdentifier: String, CellIdentifierProtocol {\n case name\n case locations\n case delete\n\n var cellClass: AnyClass {\n BasicCell.self\n }\n }\n\n var cellIdentifier: CellIdentifier {\n switch self {\n case .name:\n .name\n case .addLocations:\n .locations\n case .editLocations:\n .locations\n case .deleteList:\n .delete\n }\n }\n\n var text: String? {\n switch self {\n case .name:\n NSLocalizedString("NAME", tableName: "CustomLists", value: "Name", comment: "")\n case .addLocations:\n NSLocalizedString("ADD", tableName: "CustomLists", value: "Add locations", comment: "")\n case .editLocations:\n NSLocalizedString("EDIT", tableName: "CustomLists", value: "Edit locations", comment: "")\n case .deleteList:\n NSLocalizedString("Delete", tableName: "CustomLists", value: "Delete list", comment: "")\n }\n }\n\n static func fromFieldValidationErrors(_ errors: Set<CustomListFieldValidationError>) -> [CustomListItemIdentifier] {\n errors.compactMap { error in\n switch error {\n case .name:\n .name\n }\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\CustomLists\CustomListItemIdentifier.swift | CustomListItemIdentifier.swift | Swift | 1,607 | 0.95 | 0.04918 | 0.12963 | node-utils | 546 | 2024-01-12T07:21:39.152737 | GPL-3.0 | false | 3c670bb55b80a78373d6d43df08c0027 |
//\n// CustomListSectionIdentifier.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-02-14.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nenum CustomListSectionIdentifier: Hashable, CaseIterable {\n case name\n case addLocations\n case editLocations\n case deleteList\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\CustomLists\CustomListSectionIdentifier.swift | CustomListSectionIdentifier.swift | Swift | 325 | 0.95 | 0 | 0.5 | python-kit | 988 | 2025-05-31T01:02:18.832693 | Apache-2.0 | false | d59feb2639f615e33bb6a6f5713fc4ef |
//\n// CustomListValidationError.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-02-16.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadSettings\n\nenum CustomListFieldValidationError: LocalizedError, Hashable {\n case name(CustomRelayListError)\n\n var errorDescription: String? {\n switch self {\n case let .name(error):\n error.errorDescription\n }\n }\n}\n\nextension Collection<CustomListFieldValidationError> {\n var settingsFieldValidationErrors: [SettingsFieldValidationError] {\n map { SettingsFieldValidationError(errorDescription: $0.errorDescription) }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\CustomLists\CustomListValidationError.swift | CustomListValidationError.swift | Swift | 669 | 0.95 | 0.037037 | 0.304348 | python-kit | 815 | 2024-05-02T13:06:17.434678 | Apache-2.0 | false | d41a838742a739d61b18d8d8a41591d7 |
//\n// CustomListViewController.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-02-15.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport MullvadSettings\nimport UIKit\n\nprotocol CustomListViewControllerDelegate: AnyObject {\n func customListDidSave(_ list: CustomList)\n func customListDidDelete(_ list: CustomList)\n func showLocations(_ list: CustomList)\n}\n\nclass CustomListViewController: UIViewController {\n typealias DataSource = UITableViewDiffableDataSource<CustomListSectionIdentifier, CustomListItemIdentifier>\n\n private let interactor: CustomListInteractorProtocol\n private let tableView = UITableView(frame: .zero, style: .insetGrouped)\n private let subject: CurrentValueSubject<CustomListViewModel, Never>\n private var cancellables = Set<AnyCancellable>()\n private var dataSource: DataSource?\n private let alertPresenter: AlertPresenter\n private var validationErrors: Set<CustomListFieldValidationError> = []\n\n private var persistedCustomList: CustomList? {\n return interactor.fetchAll().first(where: { $0.id == subject.value.id })\n }\n\n var hasUnsavedChanges: Bool {\n persistedCustomList != subject.value.customList\n }\n\n private lazy var cellConfiguration: CustomListCellConfiguration = {\n CustomListCellConfiguration(tableView: tableView, subject: subject)\n }()\n\n private lazy var dataSourceConfiguration: CustomListDataSourceConfiguration? = {\n dataSource.flatMap { dataSource in\n CustomListDataSourceConfiguration(dataSource: dataSource)\n }\n }()\n\n lazy var saveBarButton: UIBarButtonItem = {\n let barButtonItem = UIBarButtonItem(\n title: NSLocalizedString(\n "CUSTOM_LIST_NAVIGATION_SAVE_BUTTON",\n tableName: "CustomLists",\n value: "Save",\n comment: ""\n ),\n primaryAction: UIAction { [weak self] _ in\n self?.onSave()\n }\n )\n barButtonItem.style = .done\n barButtonItem.setAccessibilityIdentifier(.saveCreateCustomListButton)\n\n return barButtonItem\n }()\n\n weak var delegate: CustomListViewControllerDelegate?\n\n init(\n interactor: CustomListInteractorProtocol,\n subject: CurrentValueSubject<CustomListViewModel, Never>,\n alertPresenter: AlertPresenter\n ) {\n self.subject = subject\n self.interactor = interactor\n self.alertPresenter = alertPresenter\n\n super.init(nibName: nil, bundle: nil)\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n override func viewDidLoad() {\n super.viewDidLoad()\n\n navigationItem.rightBarButtonItem = saveBarButton\n view.directionalLayoutMargins = UIMetrics.contentLayoutMargins\n view.backgroundColor = .secondaryColor\n view.setAccessibilityIdentifier(.newCustomListView)\n isModalInPresentation = true\n\n addSubviews()\n configureDataSource()\n configureTableView()\n\n subject.sink { [weak self] viewModel in\n self?.saveBarButton.isEnabled = !viewModel.name.isEmpty\n self?.validationErrors.removeAll()\n }.store(in: &cancellables)\n }\n\n private func configureTableView() {\n tableView.delegate = dataSourceConfiguration\n tableView.backgroundColor = .secondaryColor\n tableView.registerReusableViews(from: CustomListItemIdentifier.CellIdentifier.self)\n tableView.setAccessibilityIdentifier(.customListEditTableView)\n }\n\n private func configureDataSource() {\n cellConfiguration.onDelete = { [weak self] in\n self?.onDelete()\n }\n\n dataSource = DataSource(\n tableView: tableView,\n cellProvider: { [weak self] _, indexPath, itemIdentifier in\n guard let self else { return nil }\n return cellConfiguration.dequeueCell(\n at: indexPath,\n for: itemIdentifier,\n validationErrors: self.validationErrors\n )\n }\n )\n\n dataSourceConfiguration?.didSelectItem = { [weak self] item in\n guard let self else { return }\n self.view.endEditing(false)\n\n switch item {\n case .name, .deleteList:\n break\n case .addLocations, .editLocations:\n delegate?.showLocations(self.subject.value.customList)\n }\n }\n\n dataSourceConfiguration?.updateDataSource(\n sections: subject.value.tableSections,\n validationErrors: validationErrors,\n animated: false\n )\n }\n\n private func addSubviews() {\n view.addConstrainedSubviews([tableView]) {\n tableView.pinEdgesToSuperview()\n }\n }\n\n private func onSave() {\n do {\n try interactor.save(viewModel: subject.value)\n delegate?.customListDidSave(subject.value.customList)\n } catch {\n if let error = error as? CustomRelayListError {\n validationErrors.insert(.name(error))\n dataSourceConfiguration?.set(validationErrors: validationErrors)\n }\n }\n }\n\n private func onDelete() {\n let message = NSMutableAttributedString(\n markdownString: NSLocalizedString(\n "CUSTOM_LISTS_DELETE_PROMPT",\n tableName: "CustomLists",\n value: "Do you want to delete the list **\(subject.value.name)**?",\n comment: ""\n ),\n options: MarkdownStylingOptions(font: .preferredFont(forTextStyle: .body))\n )\n\n let presentation = AlertPresentation(\n id: "api-custom-lists-delete-list-alert",\n icon: .alert,\n attributedMessage: message,\n buttons: [\n AlertAction(\n title: NSLocalizedString(\n "CUSTOM_LISTS_DELETE_BUTTON",\n tableName: "CustomLists",\n value: "Delete list",\n comment: ""\n ),\n style: .destructive,\n accessibilityId: .confirmDeleteCustomListButton,\n handler: {\n self.interactor.delete(id: self.subject.value.id)\n self.delegate?.customListDidDelete(self.subject.value.customList)\n }\n ),\n AlertAction(\n title: NSLocalizedString(\n "CUSTOM_LISTS_CANCEL_BUTTON",\n tableName: "CustomLists",\n value: "Cancel",\n comment: ""\n ),\n style: .default,\n accessibilityId: .cancelDeleteCustomListButton\n ),\n ]\n )\n\n alertPresenter.showAlert(presentation: presentation, animated: true)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\CustomLists\CustomListViewController.swift | CustomListViewController.swift | Swift | 7,074 | 0.95 | 0.028708 | 0.038889 | react-lib | 961 | 2024-02-02T12:21:12.658561 | GPL-3.0 | false | 5a0d8d8af5625dff459eb65f57fb2ffe |
//\n// CustomListViewModel.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-02-14.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadSettings\nimport MullvadTypes\n\nstruct CustomListViewModel {\n var id: UUID\n var name: String\n var locations: [RelayLocation]\n let tableSections: [CustomListSectionIdentifier]\n\n var customList: CustomList {\n CustomList(id: id, name: name, locations: locations)\n }\n\n mutating func update(with list: CustomList) {\n name = list.name\n locations = list.locations\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\CustomLists\CustomListViewModel.swift | CustomListViewModel.swift | Swift | 577 | 0.95 | 0 | 0.318182 | python-kit | 720 | 2023-09-15T01:31:43.229610 | MIT | false | c58fad006c331459174bf56f49578277 |
//\n// EditCustomListCoordinator.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-02-15.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport MullvadSettings\nimport Routing\nimport UIKit\n\nclass EditCustomListCoordinator: Coordinator, Presentable, Presenting {\n enum FinishAction {\n case save, delete\n }\n\n let navigationController: UINavigationController\n let customListInteractor: CustomListInteractorProtocol\n let customList: CustomList\n let nodes: [LocationNode]\n let subject: CurrentValueSubject<CustomListViewModel, Never>\n private lazy var alertPresenter: AlertPresenter = {\n AlertPresenter(context: self)\n }()\n\n var presentedViewController: UIViewController {\n navigationController\n }\n\n var didFinish: ((EditCustomListCoordinator, FinishAction, CustomList) -> Void)?\n var didCancel: ((EditCustomListCoordinator) -> Void)?\n\n init(\n navigationController: UINavigationController,\n customListInteractor: CustomListInteractorProtocol,\n customList: CustomList,\n nodes: [LocationNode]\n ) {\n self.navigationController = navigationController\n self.customListInteractor = customListInteractor\n self.customList = customList\n self.nodes = nodes\n self.subject = CurrentValueSubject(CustomListViewModel(\n id: customList.id,\n name: customList.name,\n locations: customList.locations,\n tableSections: [.name, .editLocations, .deleteList]\n ))\n }\n\n func start() {\n let controller = CustomListViewController(\n interactor: customListInteractor,\n subject: subject,\n alertPresenter: alertPresenter\n )\n controller.delegate = self\n\n controller.navigationItem.title = NSLocalizedString(\n "CUSTOM_LIST_NAVIGATION_TITLE",\n tableName: "CustomLists",\n value: subject.value.name,\n comment: ""\n )\n\n navigationController.interactivePopGestureRecognizer?.delegate = self\n navigationController.pushViewController(controller, animated: true)\n\n guard let interceptibleNavigationController = navigationController as? InterceptibleNavigationController else {\n return\n }\n\n interceptibleNavigationController.shouldPopViewController = { [weak self] viewController in\n guard\n let self,\n let customListViewController = viewController as? CustomListViewController,\n customListViewController.hasUnsavedChanges\n else { return true }\n\n presentUnsavedChangesDialog()\n return false\n }\n\n interceptibleNavigationController.shouldPopToViewController = { [weak self] viewController in\n guard\n let self,\n let customListViewController = viewController as? CustomListViewController,\n customListViewController.hasUnsavedChanges\n else { return true }\n\n presentUnsavedChangesDialog()\n return false\n }\n }\n\n private func presentUnsavedChangesDialog() {\n let message = NSMutableAttributedString(\n markdownString: NSLocalizedString(\n "CUSTOM_LISTS_UNSAVED_CHANGES_PROMPT",\n tableName: "CustomLists",\n value: "You have unsaved changes.",\n comment: ""\n ),\n options: MarkdownStylingOptions(font: .preferredFont(forTextStyle: .body))\n )\n\n let presentation = AlertPresentation(\n id: "api-custom-lists-unsaved-changes-alert",\n icon: .alert,\n attributedMessage: message,\n buttons: [\n AlertAction(\n title: NSLocalizedString(\n "CUSTOM_LISTS_DISCARD_CHANGES_BUTTON",\n tableName: "CustomLists",\n value: "Discard changes",\n comment: ""\n ),\n style: .destructive,\n handler: {\n self.didCancel?(self)\n }\n ),\n AlertAction(\n title: NSLocalizedString(\n "CUSTOM_LISTS_BACK_TO_EDITING_BUTTON",\n tableName: "CustomLists",\n value: "Back to editing",\n comment: ""\n ),\n style: .default\n ),\n ]\n )\n\n alertPresenter.showAlert(presentation: presentation, animated: true)\n }\n}\n\nextension EditCustomListCoordinator: @preconcurrency CustomListViewControllerDelegate {\n func customListDidSave(_ list: CustomList) {\n didFinish?(self, .save, list)\n }\n\n func customListDidDelete(_ list: CustomList) {\n didFinish?(self, .delete, list)\n }\n\n func showLocations(_ list: CustomList) {\n let coordinator = EditLocationsCoordinator(\n navigationController: navigationController,\n nodes: nodes,\n subject: subject\n )\n\n coordinator.didFinish = { locationsCoordinator in\n Task { @MainActor in\n locationsCoordinator.removeFromParent()\n }\n }\n\n coordinator.start()\n\n addChild(coordinator)\n }\n}\n\nextension EditCustomListCoordinator: UIGestureRecognizerDelegate {\n // For some reason, intercepting `popViewController(animated: Bool)` in `InterceptibleNavigationController`\n // by SWIPING back leads to weird behaviour where subsequent navigation seem to happen systemwise but not\n // UI-wise. This leads to the UI freezing up, and the only remedy is to restart the app.\n //\n // To get around this issue we can intercept the back swipe gesture and manually perform the transition\n // instead, thereby bypassing the inner mechanisms that seem to go out of sync.\n func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {\n guard gestureRecognizer == navigationController.interactivePopGestureRecognizer else {\n return true\n }\n navigationController.popViewController(animated: true)\n return false\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\CustomLists\EditCustomListCoordinator.swift | EditCustomListCoordinator.swift | Swift | 6,318 | 0.95 | 0.005435 | 0.08125 | node-utils | 126 | 2023-12-20T15:21:54.414821 | Apache-2.0 | false | 0637feb78d5ba302a8105a603341228c |
//\n// EditLocationsCoordinator.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2024-03-07.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Combine\nimport MullvadSettings\nimport MullvadTypes\nimport Routing\nimport UIKit\n\n@MainActor\nclass EditLocationsCoordinator: Coordinator, Presentable, Presenting, Sendable {\n private let navigationController: UINavigationController\n private let nodes: [LocationNode]\n private var subject: CurrentValueSubject<CustomListViewModel, Never>\n\n nonisolated(unsafe) var didFinish: (@Sendable (EditLocationsCoordinator) -> Void)?\n\n var presentedViewController: UIViewController {\n navigationController\n }\n\n init(\n navigationController: UINavigationController,\n nodes: [LocationNode],\n subject: CurrentValueSubject<CustomListViewModel, Never>\n ) {\n self.navigationController = navigationController\n self.nodes = nodes\n self.subject = subject\n }\n\n func start() {\n let controller = AddLocationsViewController(\n allLocationsNodes: nodes,\n subject: subject\n )\n controller.delegate = self\n\n controller.navigationItem.title = NSLocalizedString(\n "EDIT_LOCATIONS_NAVIGATION_TITLE",\n tableName: "EditLocations",\n value: "Edit locations",\n comment: ""\n )\n navigationController.pushViewController(controller, animated: true)\n }\n}\n\nextension EditLocationsCoordinator: AddLocationsViewControllerDelegate {\n nonisolated func didBack() {\n didFinish?(self)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Coordinators\CustomLists\EditLocationsCoordinator.swift | EditLocationsCoordinator.swift | Swift | 1,602 | 0.95 | 0.017241 | 0.14 | node-utils | 869 | 2024-10-30T02:32:16.474476 | BSD-3-Clause | false | 3100d0b2cec42d4c7f09f9600c37493d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.