1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
|
//
// ConnectViewController.swift
// MullvadVPN
//
// Created by pronebird on 20/03/2019.
// Copyright © 2019 Mullvad VPN AB. All rights reserved.
//
import UIKit
import MapKit
import Logging
class CustomOverlayRenderer: MKOverlayRenderer {
override func draw(_ mapRect: MKMapRect, zoomScale: MKZoomScale, in context: CGContext) {
let drawRect = self.rect(for: mapRect)
context.setFillColor(UIColor.secondaryColor.cgColor)
context.fill(drawRect)
}
}
protocol ConnectViewControllerDelegate: AnyObject {
func connectViewControllerShouldShowSelectLocationPicker(_ controller: ConnectViewController)
}
class ConnectViewController: UIViewController, MKMapViewDelegate, RootContainment, TunnelObserver, AccountObserver {
weak var delegate: ConnectViewControllerDelegate?
let notificationController = NotificationController()
private let mainContentView: ConnectMainContentView = {
let view = ConnectMainContentView(frame: UIScreen.main.bounds)
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private let logger = Logger(label: "ConnectViewController")
private var lastLocation: CLLocationCoordinate2D?
private let locationMarker = MKPointAnnotation()
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
var preferredHeaderBarPresentation: HeaderBarPresentation {
if !Account.shared.isLoggedIn {
return HeaderBarPresentation(style: .default, showsDivider: true)
}
switch tunnelState {
case .connecting, .reconnecting, .connected:
return HeaderBarPresentation(style: .secured, showsDivider: false)
case .disconnecting, .disconnected, .pendingReconnect:
return HeaderBarPresentation(style: .unsecured, showsDivider: false)
}
}
var prefersHeaderBarHidden: Bool {
return false
}
private var tunnelState: TunnelState = .disconnected {
didSet {
setNeedsHeaderBarStyleAppearanceUpdate()
updateTunnelConnectionInfo()
updateUserInterfaceForTunnelStateChange()
// Avoid unnecessary animations, particularly when this property is changed from inside
// the `viewDidLoad`.
let isViewVisible = self.viewIfLoaded?.window != nil
updateLocation(animated: isViewVisible)
}
}
override func viewDidLoad() {
super.viewDidLoad()
mainContentView.connectButton.addTarget(self, action: #selector(handleConnect(_:)), for: .touchUpInside)
mainContentView.cancelButton.addTarget(self, action: #selector(handleDisconnect(_:)), for: .touchUpInside)
mainContentView.splitDisconnectButton.primaryButton.addTarget(self, action: #selector(handleDisconnect(_:)), for: .touchUpInside)
mainContentView.splitDisconnectButton.secondaryButton.addTarget(self, action: #selector(handleReconnect(_:)), for: .touchUpInside)
mainContentView.selectLocationButton.addTarget(self, action: #selector(handleSelectLocation(_:)), for: .touchUpInside)
TunnelManager.shared.addObserver(self)
self.tunnelState = TunnelManager.shared.tunnelState
addSubviews()
setupMapView()
updateLocation(animated: false)
addNotificationController()
Account.shared.addObserver(self)
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if previousTraitCollection?.userInterfaceIdiom != traitCollection.userInterfaceIdiom ||
previousTraitCollection?.horizontalSizeClass != traitCollection.horizontalSizeClass {
updateTraitDependentViews()
}
}
func setMainContentHidden(_ isHidden: Bool, animated: Bool) {
let actions = {
self.mainContentView.containerView.alpha = isHidden ? 0 : 1
}
if animated {
UIView.animate(withDuration: 0.25, animations: actions)
} else {
actions()
}
}
private func addSubviews() {
view.addSubview(mainContentView)
NSLayoutConstraint.activate([
mainContentView.topAnchor.constraint(equalTo: view.topAnchor),
mainContentView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
mainContentView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
mainContentView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
// MARK: - AccountObserver
func account(_ account: Account, didLoginWithToken token: String, expiry: Date) {
setNeedsHeaderBarStyleAppearanceUpdate()
}
func account(_ account: Account, didUpdateExpiry expiry: Date) {
// no-op
}
func accountDidLogout(_ account: Account) {
setNeedsHeaderBarStyleAppearanceUpdate()
}
// MARK: - TunnelObserver
func tunnelManager(_ manager: TunnelManager, didUpdateTunnelSettings tunnelInfo: TunnelInfo?) {
// no-op
}
func tunnelManager(_ manager: TunnelManager, didUpdateTunnelState tunnelState: TunnelState) {
self.tunnelState = tunnelState
}
func tunnelManager(_ manager: TunnelManager, didFailWithError error: TunnelManager.Error) {
// no-op
}
// MARK: - Private
private func updateUserInterfaceForTunnelStateChange() {
mainContentView.secureLabel.text = tunnelState.localizedTitleForSecureLabel.uppercased()
mainContentView.secureLabel.textColor = tunnelState.textColorForSecureLabel
mainContentView.connectButton.setTitle(
NSLocalizedString(
"CONNECT_BUTTON_TITLE",
tableName: "Main",
value: "Secure connection",
comment: ""
), for: .normal
)
mainContentView.selectLocationButton.setTitle(tunnelState.localizedTitleForSelectLocationButton, for: .normal)
mainContentView.cancelButton.setTitle(
NSLocalizedString(
"CANCEL_BUTTON_TITLE",
tableName: "Main",
value: "Cancel",
comment: ""
), for: .normal)
mainContentView.splitDisconnectButton.primaryButton.setTitle(
NSLocalizedString(
"DISCONNECT_BUTTON_TITLE",
tableName: "Main",
value: "Disconnect",
comment: ""
), for: .normal
)
mainContentView.splitDisconnectButton.secondaryButton.accessibilityLabel = NSLocalizedString(
"RECONNECT_BUTTON_ACCESSIBILITY_LABEL",
tableName: "Main",
value: "Reconnect",
comment: ""
)
updateTraitDependentViews()
}
private func updateTraitDependentViews() {
mainContentView.setActionButtons(tunnelState.actionButtons(traitCollection: self.traitCollection))
}
private func attributedStringForLocation(string: String) -> NSAttributedString {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 0
paragraphStyle.lineHeightMultiple = 0.80
return NSAttributedString(string: string, attributes: [
.paragraphStyle: paragraphStyle])
}
private func updateTunnelConnectionInfo() {
switch tunnelState {
case .connecting(let connectionInfo):
setConnectionInfo(connectionInfo)
case .connected(let connectionInfo), .reconnecting(let connectionInfo):
setConnectionInfo(connectionInfo)
case .disconnected, .disconnecting, .pendingReconnect:
setConnectionInfo(nil)
}
mainContentView.locationContainerView.accessibilityLabel = tunnelState.localizedAccessibilityLabel
}
private func setConnectionInfo(_ connectionInfo: TunnelConnectionInfo?) {
if let connectionInfo = connectionInfo {
mainContentView.cityLabel.attributedText = attributedStringForLocation(string: connectionInfo.location.city)
mainContentView.countryLabel.attributedText = attributedStringForLocation(string: connectionInfo.location.country)
mainContentView.connectionPanel.dataSource = ConnectionPanelData(
inAddress: "\(connectionInfo.ipv4Relay) UDP",
outAddress: nil
)
mainContentView.connectionPanel.isHidden = false
mainContentView.connectionPanel.connectedRelayName = connectionInfo.hostname
} else {
mainContentView.countryLabel.attributedText = attributedStringForLocation(string: " ")
mainContentView.cityLabel.attributedText = attributedStringForLocation(string: " ")
mainContentView.connectionPanel.dataSource = nil
mainContentView.connectionPanel.isHidden = true
}
}
private func locationMarkerOffset() -> CGPoint {
// The spacing between the secure label and the marker
let markerSecureLabelSpacing = CGFloat(22)
// Compute the secure label's frame within the view coordinate system
let secureLabelFrame = mainContentView.secureLabel.convert(mainContentView.secureLabel.bounds, to: view)
// The marker's center coincides with the geo coordinate
let markerAnchorOffsetInPoints = locationMarkerSecureImage.size.height * 0.5
// Compute the distance from the top of the label's frame to the center of the map
let secureLabelDistanceToMapCenterY = secureLabelFrame.minY - mainContentView.mapView.frame.midY
// Compute the marker offset needed to position it above the secure label
let offsetY = secureLabelDistanceToMapCenterY - markerAnchorOffsetInPoints - markerSecureLabelSpacing
return CGPoint(x: 0, y: offsetY)
}
private func computeCoordinateRegion(centerCoordinate: CLLocationCoordinate2D, centerOffsetInPoints: CGPoint) -> MKCoordinateRegion {
let span = MKCoordinateSpan(latitudeDelta: 30, longitudeDelta: 30)
var region = MKCoordinateRegion(center: centerCoordinate, span: span)
region = mainContentView.mapView.regionThatFits(region)
let latitudeDeltaPerPoint = region.span.latitudeDelta / Double(mainContentView.mapView.frame.height)
var offsetCenter = centerCoordinate
offsetCenter.latitude += CLLocationDegrees(latitudeDeltaPerPoint * Double(centerOffsetInPoints.y))
region.center = offsetCenter
return region
}
private func updateLocation(animated: Bool) {
switch tunnelState {
case .connecting(let connectionInfo):
if let connectionInfo = connectionInfo {
setLocation(coordinate: connectionInfo.location.geoCoordinate, animated: animated)
} else {
unsetLocation(animated: animated)
}
case .connected(let connectionInfo), .reconnecting(let connectionInfo):
setLocation(coordinate: connectionInfo.location.geoCoordinate, animated: animated)
case .disconnected, .disconnecting, .pendingReconnect:
unsetLocation(animated: animated)
}
}
private func setLocation(coordinate: CLLocationCoordinate2D, animated: Bool) {
if let lastLocation = self.lastLocation, coordinate.approximatelyEqualTo(lastLocation) {
return
}
let markerOffset = locationMarkerOffset()
let region = computeCoordinateRegion(centerCoordinate: coordinate, centerOffsetInPoints: markerOffset)
locationMarker.coordinate = coordinate
mainContentView.mapView.addAnnotation(locationMarker)
mainContentView.mapView.setRegion(region, animated: animated)
self.lastLocation = coordinate
}
private func unsetLocation(animated: Bool) {
let coordinate = CLLocationCoordinate2D(latitude: 0, longitude: 0)
if let lastLocation = self.lastLocation, coordinate.approximatelyEqualTo(lastLocation) {
return
}
let span = MKCoordinateSpan(latitudeDelta: 90, longitudeDelta: 90)
let region = MKCoordinateRegion(center: coordinate, span: span)
mainContentView.mapView.removeAnnotation(locationMarker)
mainContentView.mapView.setRegion(region, animated: animated)
self.lastLocation = coordinate
}
private func addNotificationController() {
let notificationView = notificationController.view!
notificationView.translatesAutoresizingMaskIntoConstraints = false
addChild(notificationController)
view.addSubview(notificationView)
notificationController.didMove(toParent: self)
NSLayoutConstraint.activate([
notificationView.topAnchor.constraint(equalTo: view.topAnchor),
notificationView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
notificationView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
notificationView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
// MARK: - Actions
@objc func handleConnect(_ sender: Any) {
TunnelManager.shared.startTunnel()
}
@objc func handleDisconnect(_ sender: Any) {
TunnelManager.shared.stopTunnel()
}
@objc func handleReconnect(_ sender: Any) {
TunnelManager.shared.reconnectTunnel()
}
@objc func handleSelectLocation(_ sender: Any) {
delegate?.connectViewControllerShouldShowSelectLocationPicker(self)
}
// MARK: - MKMapViewDelegate
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if let polygon = overlay as? MKPolygon {
let renderer = MKPolygonRenderer(polygon: polygon)
renderer.fillColor = UIColor.primaryColor
renderer.strokeColor = UIColor.secondaryColor
renderer.lineWidth = 1.0
renderer.lineCap = .round
renderer.lineJoin = .round
return renderer
}
if #available(iOS 13, *) {
if let multiPolygon = overlay as? MKMultiPolygon {
let renderer = MKMultiPolygonRenderer(multiPolygon: multiPolygon)
renderer.fillColor = UIColor.primaryColor
renderer.strokeColor = UIColor.secondaryColor
renderer.lineWidth = 1.0
renderer.lineCap = .round
renderer.lineJoin = .round
return renderer
}
}
if let tileOverlay = overlay as? MKTileOverlay {
return CustomOverlayRenderer(overlay: tileOverlay)
}
fatalError()
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation === locationMarker {
let view = mapView.dequeueReusableAnnotationView(withIdentifier: "location", for: annotation)
view.isDraggable = false
view.canShowCallout = false
view.image = self.locationMarkerSecureImage
return view
}
return nil
}
// MARK: - Private
private var locationMarkerSecureImage: UIImage {
return UIImage(named: "LocationMarkerSecure")!
}
private func setupMapView() {
mainContentView.mapView.insetsLayoutMarginsFromSafeArea = false
mainContentView.mapView.delegate = self
mainContentView.mapView.register(MKAnnotationView.self, forAnnotationViewWithReuseIdentifier: "location")
if #available(iOS 13.0, *) {
// Use dark style for the map to dim the map grid
mainContentView.mapView.overrideUserInterfaceStyle = .dark
}
addTileOverlay()
loadGeoJSONData()
}
private func addTileOverlay() {
// Use `nil` for template URL to make sure that Apple maps do not load
// tiles from remote.
let tileOverlay = MKTileOverlay(urlTemplate: nil)
// Replace the default map tiles
tileOverlay.canReplaceMapContent = true
mainContentView.mapView.addOverlay(tileOverlay)
}
private func loadGeoJSONData() {
let fileURL = Bundle.main.url(forResource: "countries.geo", withExtension: "json")!
let data = try! Data(contentsOf: fileURL)
let overlays = try! GeoJSON.decodeGeoJSON(data)
mainContentView.mapView.addOverlays(overlays, level: .aboveLabels)
}
}
private extension TunnelState {
var textColorForSecureLabel: UIColor {
switch self {
case .connecting, .reconnecting:
return .white
case .connected:
return .successColor
case .disconnecting, .disconnected, .pendingReconnect:
return .dangerColor
}
}
var localizedTitleForSecureLabel: String {
switch self {
case .connecting, .reconnecting:
return NSLocalizedString(
"TUNNEL_STATE_CONNECTING",
tableName: "Main",
value: "Creating secure connection",
comment: ""
)
case .connected:
return NSLocalizedString(
"TUNNEL_STATE_CONNECTED",
tableName: "Main",
value: "Secure connection",
comment: ""
)
case .disconnecting(.nothing):
return NSLocalizedString(
"TUNNEL_STATE_DISCONNECTING",
tableName: "Main",
value: "Disconnecting",
comment: ""
)
case .disconnecting(.reconnect), .pendingReconnect:
return NSLocalizedString(
"TUNNEL_STATE_PENDING_RECONNECT",
tableName: "Main",
value: "Reconnecting",
comment: ""
)
case .disconnected:
return NSLocalizedString(
"TUNNEL_STATE_DISCONNECTED",
tableName: "Main",
value: "Unsecured connection",
comment: ""
)
}
}
var localizedTitleForSelectLocationButton: String? {
switch self {
case .disconnecting(.reconnect), .pendingReconnect:
return NSLocalizedString(
"SWITCH_LOCATION_BUTTON_TITLE",
tableName: "Main",
value: "Select location",
comment: ""
)
case .disconnected, .disconnecting(.nothing):
return NSLocalizedString(
"SELECT_LOCATION_BUTTON_TITLE",
tableName: "Main",
value: "Select location",
comment: ""
)
case .connecting, .connected, .reconnecting:
return NSLocalizedString(
"SWITCH_LOCATION_BUTTON_TITLE",
tableName: "Main",
value: "Switch location",
comment: ""
)
}
}
var localizedAccessibilityLabel: String {
switch self {
case .connecting:
return NSLocalizedString(
"TUNNEL_STATE_CONNECTING_ACCESSIBILITY_LABEL",
tableName: "Main",
value: "Creating secure connection",
comment: ""
)
case .connected(let tunnelInfo):
return String(
format: NSLocalizedString(
"TUNNEL_STATE_CONNECTED_ACCESSIBILITY_LABEL",
tableName: "Main",
value: "Secure connection. Connected to %@, %@",
comment: ""
),
tunnelInfo.location.city,
tunnelInfo.location.country
)
case .disconnected:
return NSLocalizedString(
"TUNNEL_STATE_DISCONNECTED_ACCESSIBILITY_LABEL",
tableName: "Main",
value: "Unsecured connection",
comment: ""
)
case .reconnecting(let tunnelInfo):
return String(
format: NSLocalizedString(
"TUNNEL_STATE_RECONNECTING_ACCESSIBILITY_LABEL",
tableName: "Main",
value: "Reconnecting to %@, %@",
comment: ""
),
tunnelInfo.location.city,
tunnelInfo.location.country
)
case .disconnecting(.nothing):
return NSLocalizedString(
"TUNNEL_STATE_DISCONNECTING_ACCESSIBILITY_LABEL",
tableName: "Main",
value: "Disconnecting",
comment: ""
)
case .disconnecting(.reconnect), .pendingReconnect:
return NSLocalizedString(
"TUNNEL_STATE_PENDING_RECONNECT_ACCESSIBILITY_LABEL",
tableName: "Main",
value: "Reconnecting",
comment: ""
)
}
}
func actionButtons(traitCollection: UITraitCollection) -> [ConnectMainContentView.ActionButton] {
switch (traitCollection.userInterfaceIdiom, traitCollection.horizontalSizeClass) {
case (.phone, _), (.pad, .compact):
switch self {
case .disconnected, .disconnecting(.nothing):
return [.selectLocation, .connect]
case .connecting, .pendingReconnect, .disconnecting(.reconnect):
return [.selectLocation, .cancel]
case .connected, .reconnecting:
return [.selectLocation, .disconnect]
}
case (.pad, .regular):
switch self {
case .disconnected, .disconnecting(.nothing):
return [.connect]
case .disconnecting(.reconnect), .pendingReconnect:
return [.cancel]
case .connecting, .connected, .reconnecting:
return [.disconnect]
}
default:
return []
}
}
}
private extension CLLocationCoordinate2D {
func approximatelyEqualTo(_ other: CLLocationCoordinate2D) -> Bool {
return fabs(self.latitude - other.latitude) <= .ulpOfOne &&
fabs(self.longitude - other.longitude) <= .ulpOfOne
}
}
|