Files
element-x-ios/ElementX/Sources/Other/Extensions/AVMetadataMachineReadableCodeObject.swift
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

186 lines
5.7 KiB
Swift

//
// Copyright 2025 Element Creations Ltd.
// Copyright 2024-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.
//
// Helpers to remove ECI headers from QR Code raw data
// Originally based on https://gist.github.com/PetrusM/267e2ee8c1d8b5dca17eac085afa7d7c
import AVKit
import Foundation
nonisolated enum AVMetadataBinaryValueError: Error {
case unhandledQRSegmentMode(UInt8)
case bitError(BitError)
case unknown(Error)
}
nonisolated extension AVMetadataMachineReadableCodeObject {
var qrBinaryValue: Data? {
get throws(AVMetadataBinaryValueError) {
guard type == .qr else { return nil }
guard let qrCodeDescriptor = descriptor as? CIQRCodeDescriptor else { return nil }
return try Self.removeQRProtocolData(qrCodeDescriptor.errorCorrectedPayload, symbolVersion: qrCodeDescriptor.symbolVersion)
}
}
static func removeQRProtocolData(_ input: Data, symbolVersion: Int) throws(AVMetadataBinaryValueError) -> Data? {
var bits = input.bits()
var segment: [UInt8]
var output: [UInt8] = []
repeat {
segment = try takeSegment(&bits, version: symbolVersion)
output.append(contentsOf: segment)
} while !segment.isEmpty
return Data(output)
}
private static func takeSegment(_ input: inout [Bit], version: Int) throws(AVMetadataBinaryValueError) -> [UInt8] {
do {
let mode = try input.takeBits(4)
return switch mode {
case 0x02: try input.takeAlphanumericSegment(version) // Alphanumeric
case 0x04: try input.takeBinarySegment(version) // Binary
case 0x00: [] // End of data
default: throw AVMetadataBinaryValueError.unhandledQRSegmentMode(mode)
}
} catch let error as BitError {
throw .bitError(error)
} catch let error as AVMetadataBinaryValueError {
throw error
} catch {
throw .unknown(error)
}
}
}
enum BitError: Error {
case moreThan8BitsTaken
case moreThan16BitsTaken
case unhandledAlphanumericCharacter(UInt8)
}
private nonisolated struct Bit {
let value: UInt8
}
private nonisolated extension [Bit] {
mutating func takeBits(_ count: Int) throws(BitError) -> UInt8 {
guard count <= 8 else { throw .moreThan8BitsTaken }
var value: UInt8 = 0
for _ in 0..<count {
value = (value << 1) | remove(at: 0).value
}
return value
}
mutating func takeBits16(_ count: Int) throws(BitError) -> UInt16 {
guard count <= 16 else { throw .moreThan16BitsTaken }
var value: UInt16 = 0
for _ in 0..<count {
value = (value << 1) | UInt16(remove(at: 0).value)
}
return value
}
mutating func takeUInt8() throws(BitError) -> UInt8 {
try takeBits(8)
}
mutating func takeUInt16() throws(BitError) -> UInt16 {
try takeBits16(16)
}
mutating func takeBinarySegment(_ version: Int) throws(BitError) -> [UInt8] {
let characterCountLength = version > 9 ? 16 : 8
let charactersCount = try takeBits16(characterCountLength)
var output = [UInt8]()
for _ in 0..<charactersCount {
try output.append(takeUInt8())
}
return output
}
mutating func takeAlphanumericSegment(_ version: Int) throws(BitError) -> [UInt8] {
let characterCountLength = version > 9 ? (version > 26 ? 13 : 11) : 9
let charactersCount = try takeBits16(characterCountLength)
var output = [UInt8]()
var charactersRemaining = charactersCount
while charactersRemaining > 1 {
if count < 11 {
// done
return output
}
// read the 11 bits
let nextTwoCharacters = try takeBits16(11)
// split into the two characters
try output.append(Self.alphaToByte(UInt8(nextTwoCharacters / 45)))
try output.append(Self.alphaToByte(UInt8(nextTwoCharacters % 45)))
charactersRemaining -= 2
}
if charactersRemaining == 1 {
if count < 6 {
// done
return output
}
let nextCharacter = try takeBits(6)
try output.append(Self.alphaToByte(nextCharacter))
}
return output
}
private static func alphaToByte(_ input: UInt8) throws(BitError) -> UInt8 {
let value: UInt8? = switch input {
case 0...9: input + 0x30 // 0-9
case 10...35: input - 10 + 0x41 // A-Z
case 36: " ".utf8.first
case 37: "$".utf8.first
case 38: "%".utf8.first
case 39: "*".utf8.first
case 40: "+".utf8.first
case 41: "-".utf8.first
case 42: ".".utf8.first
case 43: "/".utf8.first
case 44: ":".utf8.first
default: nil
}
guard let value else { throw .unhandledAlphanumericCharacter(input) }
return value
}
}
private nonisolated extension Data {
func bits() -> [Bit] {
var result = [Bit]()
forEach { (byte: UInt8) in
result.append(contentsOf: byte.bits())
}
return result
}
}
private nonisolated extension UInt8 {
func bits() -> [Bit] {
var bits: [Bit] = []
for i in 0..<8 {
let bitValue = (self >> (7 - i)) & 1
bits.append(Bit(value: bitValue))
}
return bits
}
}