summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadVPN/UserInterfaceInteractionRestriction.swift
blob: 2a07132c09643a12b2f4e080475a6ce4fe3ae8e7 (plain)
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
//
//  UserInterfaceInteractionRestriction.swift
//  MullvadVPN
//
//  Created by pronebird on 20/03/2020.
//  Copyright © 2020 Mullvad VPN AB. All rights reserved.
//

import Foundation

/// A protocol describing a common interface for the implementations of user interaction restriction
protocol UserInterfaceInteractionRestrictionProtocol {
    /// Increase the user interface interaction restrictions
    func increase(animated: Bool)

    /// Decrease the user interface interaction restrictions
    func decrease(animated: Bool)
}

/// A counter based user interface interaction restriction implementation
class UserInterfaceInteractionRestriction: UserInterfaceInteractionRestrictionProtocol
{
    typealias Action = (_ enableUserInteraction: Bool, _ animated: Bool) -> Void

    private let action: Action
    private var counter: UInt = 0

    init(action: @escaping Action) {
        self.action = action
    }

    func increase(animated: Bool) {
        DispatchQueue.main.async {
            if self.counter == 0 {
                self.action(false, animated)
            }
            self.counter += 1
        }
    }

    func decrease(animated: Bool) {
        DispatchQueue.main.async {
            guard self.counter > 0 else { return }

            self.counter -= 1
            if self.counter == 0 {
                self.action(true, animated)
            }
        }
    }
}

/// A user interface restriction implementation that simply combines multiple child restrictions
/// into one and automatically forwards all calls to them in the order in which they are given to
/// the initializer.
class CompoundUserInterfaceInteractionRestriction: UserInterfaceInteractionRestrictionProtocol {
    private let restrictions: [UserInterfaceInteractionRestrictionProtocol]

    init(restrictions: [UserInterfaceInteractionRestrictionProtocol]) {
        self.restrictions = restrictions
    }

    func decrease(animated: Bool) {
        restrictions.forEach { $0.decrease(animated: animated) }
    }

    func increase(animated: Bool) {
        restrictions.forEach { $0.increase(animated: animated) }
    }
}