Files
element-x-ios/ElementX/Sources/Application/Settings/UserPreference.swift
T
Mauro a520d94760 Swift 6 Migration (#5733)
* Enable Swift 6.2 with default main actor isolation for the app target

Turn on SWIFT_VERSION 6.2, SWIFT_APPROACHABLE_CONCURRENCY and SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor for the ElementX target, matching the NSE and Share Extension (which already use 6.2 without the main actor default).

# Conflicts:
#	ElementX.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved

* Update the code generation templates for Swift 6

Emit nonisolated/@unchecked Sendable mocks and nonisolated string enums, and mark async mock methods @concurrent so they keep suspending like the real implementations (otherwise intermediate states are unobservable in tests). Includes the regenerated mocks and strings.

# Conflicts:
#	ElementX/Sources/Mocks/Generated/GeneratedMocks.swift

* Make the data layer and services nonisolated and Sendable

Annotate the value-type models, Rust SDK proxy wrappers, timeline item graph, settings, logging and NSE-shared types as nonisolated, and conform the service protocols to Sendable so their existentials can cross isolation boundaries. These types run off the main actor and no longer inherit the target's default main actor isolation.

* Adopt the new isolation across call sites, mocks and signatures

Update call sites, closure signatures and mock configuration helpers to match the nonisolated/Sendable data layer, including the main actor isolated mock inits and the @Sendable filter on recentlyVisitedRooms.

^ Conflicts:
^	ElementX/Sources/Services/SecureBackup/SecureBackupController.swift

* Remove redundant @MainActor annotations

With the app target defaulting to main actor isolation, the explicit @MainActor on view models, coordinators, views and their protocols is no longer required.

* Fix concurrency hotspots surfaced by the migration

Resolve the room summary main-thread deadlock by moving diff processing onto AsyncStreams, add the SDKListener.onMainActor FIFO bridge for SDK callbacks, hop KVO/timer/UIKit callbacks to the main actor via assumeIsolated, add isolated deinits, and apply the few justified nonisolated(unsafe) escapes for queue-confined Apple APIs.

* Fix the unit tests for Swift 6 concurrency

Hop the waitForConfirmation body onto the caller's actor (Swift Testing runs confirmation closures off-actor), and adjust the affected suites and async signatures.

* offload diffs on concurrent threads instead of main actor

* make room info protocols sendable

* use a task group for fetching data so that everything runs concurrently in the TextRoomTimelineView when getting the preview.

* use the generic onMainActor implementation, which already makes a stream and send the continuation on the main actor.

* small pr comments issues being addressed

* update enterprise

* Update StaticCode to 1.1.0 and specify the required Swift isolation.

* fix ElementCallServiceTests

* update enterprise

* re-generate mocks

* update enterprise

* enterprise new code conformed to swift 6

---------

Co-authored-by: Doug <douglase@element.io>
2026-06-18 17:55:31 +02:00

220 lines
7.3 KiB
Swift

//
// Copyright 2025 Element Creations Ltd.
// Copyright 2023-2025 New Vector Ltd.
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial.
// Please see LICENSE files in the repository root for full details.
//
import Combine
import Foundation
/// A property wrapper that allows storing data in a keyed storage while also exposing a Combine publisher
/// to listen for value changes. The publisher does not skip consecutive duplicates, as there is no
/// `Equatable` enforcement at this level.
@propertyWrapper
final nonisolated class UserPreference<T: Codable> {
static var remotePrefix: String {
"remote-"
}
enum Mode {
case localOverRemote
case remoteOverLocal
}
private let key: String
private var remoteKey: String {
"\(Self.remotePrefix)\(key)"
}
private var keyedStorage: any KeyedStorage<T>
private let defaultValue: T
private let subject: PassthroughSubject<T, Never> = .init()
private let mode: Mode
/// This can be used to check if is still possible for the user to change the value or not
/// Can only be accessed by using `_preferenceName.isLockedToRemote`
var isLockedToRemote: Bool {
mode == .remoteOverLocal && remoteValue != nil
}
/// Initializes the property wrapper with a static default value.
///
/// - Parameters:
/// - key: The key used to store and retrieve the value.
/// - defaultValue: The default value to use if no stored value exists or if `forceDefault` is `true`.
/// - keyedStorage: The storage instance where the value is saved.
/// - forceDefault: A publisher that determines whether the default value should always be used. Defaults to publish `false`. Useful in the context of remote settings that need to override the local value.
init(key: any PreferenceKeyable,
defaultValue: T,
keyedStorage: any KeyedStorage<T>,
mode: Mode) {
self.key = key.rawValue
self.defaultValue = defaultValue
self.keyedStorage = keyedStorage
self.mode = mode
}
/// The wrapped value is supposed to be the one updated by the user so it can only control the local value
var wrappedValue: T {
get {
switch mode {
case .localOverRemote:
return keyedStorage[key] ?? keyedStorage[remoteKey] ?? defaultValue
case .remoteOverLocal:
return keyedStorage[remoteKey] ?? keyedStorage[key] ?? defaultValue
}
}
set {
keyedStorage[key] = newValue
subject.send(wrappedValue)
}
}
/// This is supposed to be the value that is set by the remote settings
/// So it can only be accessed by doing `AppSettings._preferenceName.remoteValue`
var remoteValue: T? {
get {
keyedStorage[remoteKey]
} set {
keyedStorage[remoteKey] = newValue
if mode == .remoteOverLocal || keyedStorage[key] == nil {
subject.send(wrappedValue)
}
}
}
var projectedValue: AnyPublisher<T, Never> {
subject
.prepend(wrappedValue)
.eraseToAnyPublisher()
}
}
// MARK: - UserPreference convenience initializers
nonisolated extension UserPreference {
convenience init(key: any PreferenceKeyable, defaultValue: T, storage backingStorage: UserDefaultsProtocol, mode: Mode = .localOverRemote) {
let storage: any KeyedStorage<T> = UserDefaultsStorage(userDefaults: backingStorage)
self.init(key: key, defaultValue: defaultValue, keyedStorage: storage, mode: mode)
}
convenience init(key: any PreferenceKeyable, storage: UserDefaultsProtocol, mode: Mode = .localOverRemote) where T: ExpressibleByNilLiteral {
self.init(key: key, defaultValue: nil, storage: storage, mode: mode)
}
}
// MARK: - Keys
nonisolated protocol PreferenceKeyable: RawRepresentable where RawValue == String { }
// MARK: - Storage
nonisolated protocol KeyedStorage<Value> {
associatedtype Value: Codable
subscript(key: String) -> Value? { get set }
}
/// An implementation of KeyedStorage on the UserDefaults.
///
/// When used with a `Value` that conforms to `PlistRepresentable` the Codable encode/decode
/// phase is skipped, and values are stored natively in the plist.
final nonisolated class UserDefaultsStorage<Value: Codable>: KeyedStorage {
private let userDefaults: UserDefaultsProtocol
init(userDefaults: UserDefaultsProtocol) {
self.userDefaults = userDefaults
}
subscript(key: String) -> Value? {
get {
let value: Value?
if Value.self is PlistRepresentable.Type {
value = decodePlistRepresentableValue(for: key)
} else {
value = decodeValue(for: key)
}
return value
}
set {
if Value.self is PlistRepresentable.Type {
encodePlistRepresentable(value: newValue, for: key)
} else {
encode(value: newValue, for: key)
}
}
}
private func decodeValue(for key: String) -> Value? {
userDefaults
.data(forKey: key)
.flatMap {
try? JSONDecoder().decode(Value.self, from: $0)
}
}
private func decodePlistRepresentableValue(for key: String) -> Value? {
userDefaults.object(forKey: key) as? Value
}
private func encode(value: Value?, for key: String) {
// Detects correctly double optionals like this: String?? = .some(nil)
if value.isNil {
userDefaults.removeObject(forKey: key)
} else {
let encodedValue = try? JSONEncoder().encode(value)
userDefaults.set(encodedValue, forKey: key)
}
}
private func encodePlistRepresentable(value: Value?, for key: String) {
// Detects correctly double optionals like this: String?? = .some(nil)
if value.isNil {
userDefaults.removeObject(forKey: key)
} else {
userDefaults.set(value, forKey: key)
}
}
}
private nonisolated protocol Nullable {
var isNil: Bool { get }
}
nonisolated extension Optional: Nullable {
var isNil: Bool {
switch self {
case .none:
return true
case .some(let nullable as Nullable):
return nullable.isNil
case .some:
return false
}
}
}
nonisolated extension Dictionary: KeyedStorage where Key == String, Value: Codable { }
// MARK: - PlistRepresentable
/// A protocol to mark types as being plist compliant.
/// UserDefaultsStorage uses this protocol to avoid to encode/decode with Codable plist compliant values.
nonisolated protocol PlistRepresentable { }
extension Bool: PlistRepresentable { }
extension String: PlistRepresentable { }
extension Int: PlistRepresentable { }
extension Float: PlistRepresentable { }
extension Double: PlistRepresentable { }
extension Date: PlistRepresentable { }
extension Data: PlistRepresentable { }
extension Array: PlistRepresentable where Element: PlistRepresentable { }
extension Dictionary: PlistRepresentable where Key == String, Value: PlistRepresentable { }
extension Optional: PlistRepresentable where Wrapped: PlistRepresentable { }