diff --git a/Contracts/DynamicDevice/Device.swift b/Contracts/DynamicDevice/Device.swift index de86f84..e8ca0fc 100644 --- a/Contracts/DynamicDevice/Device.swift +++ b/Contracts/DynamicDevice/Device.swift @@ -101,7 +101,9 @@ public protocol Device: AnyObject { /// Turns the proximity sensor on; the screen may turn off while /// something is near. Stays off on devices without one; check - /// `isProximityMonitoringEnabled()`. + /// `isProximityMonitoringEnabled()`. Never waits: a host that has to + /// ask a service whether there's a sensor (iio-sensor-proxy on Linux) + /// reports it enabled until the answer says there isn't one. func setProximityMonitoringEnabled(_ enabled: Bool) func isProximityMonitoringEnabled() -> Bool diff --git a/Contracts/DynamicLocation/AsyncLocationManager.swift b/Contracts/DynamicLocation/AsyncLocationManager.swift index 14b88c5..fb77876 100644 --- a/Contracts/DynamicLocation/AsyncLocationManager.swift +++ b/Contracts/DynamicLocation/AsyncLocationManager.swift @@ -53,8 +53,16 @@ public final class AsyncLocationManager: @unchecked Sendable { LocationAccuracyAuthorization(rawValue: LocationManagerProxy.accuracyAuthorization()) ?? .reduced } + /// Whether location services are on system-wide. A cancelled task + /// stops waiting with `false`. public static var isLocationServicesEnabled: Bool { - LocationManagerProxy.isLocationServicesEnabled() + get async { + await withCallback { (callback: Callback) in + LocationManagerProxy.isLocationServicesEnabled(ServicesReceiver(callback)) + } onCancel: { callback in + callback.resume(returning: false) + } + } } /// Prompts for when-in-use permission if it hasn't been decided, and @@ -166,6 +174,20 @@ public extension LocationAuthorization { } /// The delegate behind `AsyncLocationManager`. +/// Hands `isLocationServicesEnabled(_:)`'s answer to the task waiting for it. +final class ServicesReceiver: LocationServicesCallback { + + let callback: Callback + + init(_ callback: Callback) { + self.callback = callback + } + + func didGetServicesEnabled(_ enabled: Bool) { + callback.resume(returning: enabled) + } +} + final class LocationEvents: LocationManagerDelegate { let authorization = PendingCallbacks() diff --git a/Contracts/DynamicLocation/LocationManager.swift b/Contracts/DynamicLocation/LocationManager.swift index 84c2eb9..fcd2e80 100644 --- a/Contracts/DynamicLocation/LocationManager.swift +++ b/Contracts/DynamicLocation/LocationManager.swift @@ -16,16 +16,21 @@ import DynamicRuntime @DynamicRuntime("org.pureswift.location.LocationManager", requires: .location) public protocol LocationManager: AnyObject { - /// A `LocationAuthorization` raw value. Never prompts. + /// A `LocationAuthorization` raw value. Never prompts, and never waits: + /// a host that has to ask a service whether location is there at all + /// (GeoClue on Linux) answers `notDetermined` until it has heard back. static func authorizationStatus() -> Int32 /// A `LocationAccuracyAuthorization` raw value: whether the user granted /// precise or only approximate location. static func accuracyAuthorization() -> Int32 - /// Whether location services are on system-wide. When off, requests - /// fail with `LocationError.servicesDisabled` and no prompt appears. - static func isLocationServicesEnabled() -> Bool + /// Whether location services are on system-wide, through `callback`. + /// When off, requests fail with `LocationError.servicesDisabled` and no + /// prompt appears. Asked of a service on some hosts (Core Location, + /// which mustn't be asked on the main thread; GeoClue over D-Bus), so + /// the answer arrives later. + static func isLocationServicesEnabled(_ callback: LocationServicesCallback) /// Whether the device can report a compass heading. static func isHeadingAvailable() -> Bool diff --git a/Contracts/DynamicLocation/LocationServicesCallback.swift b/Contracts/DynamicLocation/LocationServicesCallback.swift new file mode 100644 index 0000000..8109817 --- /dev/null +++ b/Contracts/DynamicLocation/LocationServicesCallback.swift @@ -0,0 +1,10 @@ +import DynamicRuntime + +/// The answer to `LocationManager.isLocationServicesEnabled(_:)`. The host +/// calls it once, on the main thread, when it knows: Core Location is asked +/// off the main thread, GeoClue over D-Bus. +@DynamicCallback("org.pureswift.location.ServicesCallback") +public protocol LocationServicesCallback: AnyObject { + + func didGetServicesEnabled(_ enabled: Bool) +} diff --git a/Contracts/DynamicNFC/AsyncNFCReader.swift b/Contracts/DynamicNFC/AsyncNFCReader.swift index 5c2a07a..8eea5de 100644 --- a/Contracts/DynamicNFC/AsyncNFCReader.swift +++ b/Contracts/DynamicNFC/AsyncNFCReader.swift @@ -53,10 +53,17 @@ public final class AsyncNFCReader: @unchecked Sendable { } /// The host's NFC hardware state, or `unsupported` if this host doesn't - /// provide NFC or the capability isn't granted. + /// provide NFC or the capability isn't granted. A cancelled task stops + /// waiting with `unsupported`. public static var availability: NFCAvailability { - guard NFCReaderProxy.isAvailable else { return .unsupported } - return NFCAvailability(rawValue: NFCReaderProxy.availability()) ?? .unsupported + get async { + guard NFCReaderProxy.isAvailable else { return .unsupported } + return await withCallback { (callback: Callback) in + NFCReaderProxy.availability(AvailabilityReceiver(callback)) + } onCancel: { callback in + callback.resume(returning: .unsupported) + } + } } // MARK: Session @@ -155,6 +162,20 @@ public final class AsyncNFCReader: @unchecked Sendable { } /// The delegate behind `AsyncNFCReader`. +/// Hands `availability(_:)`'s answer to the task waiting for it. +final class AvailabilityReceiver: NFCAvailabilityCallback { + + let callback: Callback + + init(_ callback: Callback) { + self.callback = callback + } + + func didGetAvailability(_ availability: Int32) { + callback.resume(returning: NFCAvailability(rawValue: availability) ?? .unsupported) + } +} + final class NFCEvents: NFCReaderDelegate { var session: EventStream<[any NFCTag], NFCError>.Continuation? diff --git a/Contracts/DynamicNFC/NFCAvailabilityCallback.swift b/Contracts/DynamicNFC/NFCAvailabilityCallback.swift new file mode 100644 index 0000000..f885ec9 --- /dev/null +++ b/Contracts/DynamicNFC/NFCAvailabilityCallback.swift @@ -0,0 +1,11 @@ +import DynamicRuntime + +/// The answer to `NFCReader.availability(_:)`. The host calls it once, on +/// the main thread, when it knows: at once where the platform answers +/// synchronously (iOS, Android), after asking neard on Linux. +@DynamicCallback("org.pureswift.nfc.AvailabilityCallback") +public protocol NFCAvailabilityCallback: AnyObject { + + /// An `NFCAvailability` raw value. + func didGetAvailability(_ availability: Int32) +} diff --git a/Contracts/DynamicNFC/NFCReader.swift b/Contracts/DynamicNFC/NFCReader.swift index 09c3c37..d51d327 100644 --- a/Contracts/DynamicNFC/NFCReader.swift +++ b/Contracts/DynamicNFC/NFCReader.swift @@ -4,7 +4,7 @@ import DynamicRuntime /// commands to them. Reader role only; card emulation and peer-to-peer /// aren't part of the contract. /// -/// Availability first: check `availability()` before offering an NFC +/// Availability first: ask `availability(_:)` before offering an NFC /// feature. There is no runtime permission prompt. On iOS the system scan /// sheet that `begin` shows is the user's consent; on Android the `NFC` /// permission is granted at install. @@ -17,9 +17,11 @@ import DynamicRuntime @DynamicRuntime("org.pureswift.nfc.Reader", requires: .nfc) public protocol NFCReader: AnyObject { - /// An `NFCAvailability` raw value: whether the device has NFC, and - /// whether the user turned it on (Android). - static func availability() -> Int32 + /// Whether the device has NFC, and whether the user turned it on + /// (Android): an `NFCAvailability` raw value, through `callback`. A host + /// that has to ask a service (neard on Linux) answers once it has, so + /// the main thread never waits for it. + static func availability(_ callback: NFCAvailabilityCallback) static func make(_ delegate: NFCReaderDelegate) -> Self diff --git a/Contracts/DynamicNFC/NFCTypes.swift b/Contracts/DynamicNFC/NFCTypes.swift index e5137fe..56111c1 100644 --- a/Contracts/DynamicNFC/NFCTypes.swift +++ b/Contracts/DynamicNFC/NFCTypes.swift @@ -1,6 +1,6 @@ /// Guest-side names for the integer codes the NFC contracts carry. -/// `NFCReader.availability()`. +/// `NFCReader.availability(_:)`. public enum NFCAvailability: Int32, Sendable { /// No NFC hardware, or no reader support (iPad, Mac, Apple TV). case unsupported = 0 diff --git a/Documentation/Contracts/Device.md b/Documentation/Contracts/Device.md index 6cb27c2..a26f663 100644 --- a/Documentation/Contracts/Device.md +++ b/Documentation/Contracts/Device.md @@ -66,7 +66,9 @@ locked. Renderers own UI orientation (§9). **Proximity** exists on phones only. On other devices, `setProximityMonitoringEnabled(true)` leaves `isProximityMonitoringEnabled()` -false. On iOS the screen turns off while something is near; Android hosts +false. It never waits: where the host has to ask a service whether there's +a sensor (iio-sensor-proxy over D-Bus on Linux), it reports monitoring +enabled until the answer says there isn't one, then false. On iOS the screen turns off while something is near; Android hosts hold a `PROXIMITY_SCREEN_OFF_WAKE_LOCK` for the same behavior. **Not included:** diff --git a/Documentation/Contracts/Location.md b/Documentation/Contracts/Location.md index 7d77298..49b84bd 100644 --- a/Documentation/Contracts/Location.md +++ b/Documentation/Contracts/Location.md @@ -17,13 +17,20 @@ Guest-side Swift: `LocationAuthorization`, `LocationAccuracyAuthorization`, Location is the most layered permission on every platform. The contract exposes each layer instead of hiding it: -1. **Services enabled.** Check the static `isLocationServicesEnabled()`. - When location is off system-wide, no prompt can appear and requests fail - with `.servicesDisabled`. +1. **Services enabled.** Ask the static `isLocationServicesEnabled(_:)`, + which answers through a `LocationServicesCallback`, once, on the main + thread. Hosts ask a service for it (Core Location, off the main thread; + GeoClue over D-Bus), so it never blocks. When location is off + system-wide, no prompt can appear and requests fail with + `.servicesDisabled`. It was `isLocationServicesEnabled() -> Bool` until + Linux had to block the main thread on D-Bus to answer it; the contract + is still version 1, so it changed in place. 2. **Status.** The static `authorizationStatus()` and - `accuracyAuthorization()` never prompt. `make(_:)` never prompts either; - the delegate receives `didChangeAuthorization` once with the current - values. + `accuracyAuthorization()` never prompt and never wait: a host that has + to ask a service whether location is there at all (GeoClue on Linux) + answers `notDetermined` until it has heard back. `make(_:)` never prompts + either; the delegate receives `didChangeAuthorization` once with the + current values. 3. **Foreground.** `requestWhenInUseAuthorization()`, called from a user action. 4. **Precise, on demand.** If the user picked approximate, call @@ -97,6 +104,7 @@ It's guest-side only; hosts never see it. | Call | Returns | |---|---| | `AsyncLocationManager.authorization`, `accuracyAuthorization` | current values, never prompt | +| `await AsyncLocationManager.isLocationServicesEnabled` | whether location is on system-wide; `false` if the task is cancelled | | `requestWhenInUseAuthorization()`, `requestAlwaysAuthorization()` | the outcome; prompt only when the host would | | `requestFullAccuracy(_:)` | the accuracy authorization afterwards | | `currentLocation()` | one fix; throws `LocationError`, `cancelled` if the task is cancelled | @@ -116,8 +124,8 @@ Every delegate method runs on the main thread (§6.4). final class Tracker: LocationManagerDelegate { var manager: LocationManagerProxy? - func start() { - guard LocationManagerProxy.isLocationServicesEnabled() else { return showServicesOff() } + func start() async { + guard await AsyncLocationManager.isLocationServicesEnabled else { return showServicesOff() } manager = LocationManagerProxy.make(self) } diff --git a/Documentation/Contracts/NFC.md b/Documentation/Contracts/NFC.md index a560cae..3c2198b 100644 --- a/Documentation/Contracts/NFC.md +++ b/Documentation/Contracts/NFC.md @@ -21,16 +21,28 @@ NFC has no runtime permission prompt on any platform: - **Android:** the `NFC` permission is granted at install. What varies is whether the device can read at all, so the first step is a -check: +check. It's answered through an `NFCAvailabilityCallback`, once, on the main +thread: at once on iOS and Android, after asking neard over D-Bus on Linux, +so no host makes the main thread wait for a service: ```swift -switch NFCAvailability(rawValue: NFCReaderProxy.availability()) { -case .available: showScanButton() -case .disabled: showHint("Turn on NFC in Settings") // Android only -default: hideNFCFeature() // iPad, Mac, TV, no hardware +final class Availability: NFCAvailabilityCallback { + func didGetAvailability(_ availability: Int32) { + switch NFCAvailability(rawValue: availability) { + case .available: showScanButton() + case .disabled: showHint("Turn on NFC in Settings") // Android only + default: hideNFCFeature() // iPad, Mac, TV, no hardware + } + } } + +NFCReaderProxy.availability(Availability()) ``` +`availability(_:)` was `availability() -> Int32` until Linux's neard host +had to block the main thread on D-Bus to answer it; the contract is still +version 1, so it changed in place. + Then start a session **from a user action, in the foreground**: 1. `make(_:)` 2. `begin(_:alertMessage:)` → `didBecomeActive` @@ -101,7 +113,8 @@ formatting (`NdefFormatable`, Android only), MIFARE Classic. Guest code can use `AsyncNFCReader` instead of the delegate (§6.2.1). It's guest-side only; hosts never see it. -- `AsyncNFCReader.availability`: never starts a session. +- `await AsyncNFCReader.availability`: never starts a session. A cancelled + task stops waiting with `unsupported`. - `session(tagTypes:alertMessage:)`: `EventStream<[any NFCTag], NFCError>`. It finishes normally after `invalidate()`, or by throwing the host's reason (`userCancelled`, `sessionTimeout`, …). Releasing it ends the session. @@ -123,8 +136,8 @@ the host's NFC queue or thread, never on the guest's. final class TagReader: NFCReaderDelegate { var reader: NFCReaderProxy? - func scan() { // from a button tap - guard NFCReaderProxy.availability() == NFCAvailability.available.rawValue else { return } + func scan() async { // from a button tap + guard await AsyncNFCReader.availability == .available else { return } let reader = NFCReaderProxy.make(self) self.reader = reader reader.begin(NFCTagTypes.iso14443.rawValue, alertMessage: "Hold your iPhone near the tag") diff --git a/Documentation/Implementation.md b/Documentation/Implementation.md index 5281855..9d8acbe 100644 --- a/Documentation/Implementation.md +++ b/Documentation/Implementation.md @@ -1914,3 +1914,16 @@ Each of these needs a decision, or is verified only as far as noted: Embedded under the Swift SDK); `Physics3D` after `Physics2D`. Then `DynamicScene` (`SceneView`, rays and hits, the orbit camera, the GLES 2 backend) and `examples/ExampleScene`. +33. Queries that answer later: `NFCReader.availability(_:)` and + `LocationManager.isLocationServicesEnabled(_:)` answer through + `NFCAvailabilityCallback` and `LocationServicesCallback` instead of + returning, and `AsyncNFCReader.availability` and + `AsyncLocationManager.isLocationServicesEnabled` are `async`. Linux + asked neard and GeoClue over D-Bus for them and blocked the main thread + up to 2 s; Core Location's `locationServicesEnabled()` mustn't be asked + on the main thread either. `authorizationStatus()` and + `setProximityMonitoringEnabled(_:)` keep their signatures and never + wait: a host answers `notDetermined`, or reports proximity monitoring + on, until its service has answered. Next: DarwinAppRuntime and + LinuxAppRuntime move to them, LinuxDBus loses `callAndWait`, and + LinuxLocation moves to PureSwift/DBus's generated GeoClue2 client. diff --git a/Tests/DynamicLocationTests/AsyncLocationManagerTests.swift b/Tests/DynamicLocationTests/AsyncLocationManagerTests.swift index c2ed792..fd34b74 100644 --- a/Tests/DynamicLocationTests/AsyncLocationManagerTests.swift +++ b/Tests/DynamicLocationTests/AsyncLocationManagerTests.swift @@ -53,7 +53,9 @@ final class HostLocationManager: LocationManager { static func authorizationStatus() -> Int32 { status } static func accuracyAuthorization() -> Int32 { LocationAccuracyAuthorization.full.rawValue } - static func isLocationServicesEnabled() -> Bool { true } + static func isLocationServicesEnabled(_ callback: any LocationServicesCallback) { + callback.didGetServicesEnabled(true) + } static func isHeadingAvailable() -> Bool { true } static func make(_ delegate: any LocationManagerDelegate) -> HostLocationManager { @@ -114,12 +116,17 @@ final class HostLocationManager: LocationManager { native.capabilities = nil LocationManagerProxy.register(HostLocationManager.self, in: native) LocationManagerDelegateProxy.registerInterface(in: native) + LocationServicesCallbackProxy.registerInterface(in: native) LocationProxy.register(HostLocation.self, in: native) HeadingProxy.register(HostHeading.self, in: native) HostLocationManager.status = LocationAuthorization.notDetermined.rawValue HostLocationManager.last = nil } + @Test func servicesEnabledArrivesThroughTheCallback() async { + #expect(await AsyncLocationManager.isLocationServicesEnabled) + } + @Test func authorizationPromptsOnlyWhenUndecided() async { let manager = AsyncLocationManager() #expect(AsyncLocationManager.authorization == .notDetermined) diff --git a/Tests/DynamicLocationTests/DynamicLocationTests.swift b/Tests/DynamicLocationTests/DynamicLocationTests.swift index e7fbb2c..5c9fd13 100644 --- a/Tests/DynamicLocationTests/DynamicLocationTests.swift +++ b/Tests/DynamicLocationTests/DynamicLocationTests.swift @@ -11,7 +11,7 @@ import DynamicRuntime static let descriptors = [ LocationManagerProxy.descriptor, LocationManagerDelegateProxy.descriptor, - LocationProxy.descriptor, HeadingProxy.descriptor, + LocationServicesCallbackProxy.descriptor, LocationProxy.descriptor, HeadingProxy.descriptor, ] @Test(arguments: ["authorizationStatus", "accuracyAuthorization"]) @@ -22,7 +22,9 @@ import DynamicRuntime @Test func permissionsFirst() { let manager = LocationManagerProxy.descriptor #expect(manager.capability == .location) - #expect(method(manager, "isLocationServicesEnabled")?.kind == .static) + // Answered through a callback, so a host never blocks to find out. + #expect(method(manager, "isLocationServicesEnabled:") == MethodDescriptor("isLocationServicesEnabled:", "(O)V", .static)) + #expect(method(LocationServicesCallbackProxy.descriptor, "didGetServicesEnabled:")?.signature == Signature("(Z)V")) #expect(method(manager, "make:")?.kind == .constructor) // Two steps: foreground first, then background; precise on demand. #expect(method(manager, "requestWhenInUseAuthorization") != nil) diff --git a/Tests/DynamicNFCTests/AsyncNFCReaderTests.swift b/Tests/DynamicNFCTests/AsyncNFCReaderTests.swift index ce73f4d..c2884da 100644 --- a/Tests/DynamicNFCTests/AsyncNFCReaderTests.swift +++ b/Tests/DynamicNFCTests/AsyncNFCReaderTests.swift @@ -65,7 +65,9 @@ final class HostNFCReader: NFCReader { self.delegate = delegate } - static func availability() -> Int32 { NFCAvailability.available.rawValue } + static func availability(_ callback: any NFCAvailabilityCallback) { + callback.didGetAvailability(NFCAvailability.available.rawValue) + } static func make(_ delegate: any NFCReaderDelegate) -> HostNFCReader { let reader = HostNFCReader(delegate: delegate) @@ -113,6 +115,7 @@ final class HostNFCReader: NFCReader { native.capabilities = nil NFCReaderProxy.register(HostNFCReader.self, in: native) NFCReaderDelegateProxy.registerInterface(in: native) + NFCAvailabilityCallbackProxy.registerInterface(in: native) NFCTagProxy.register(HostNFCTag.self, in: native) NDEFMessageProxy.register(HostNDEFMessage.self, in: native) NDEFRecordProxy.register(HostNDEFRecord.self, in: native) @@ -120,7 +123,7 @@ final class HostNFCReader: NFCReader { } @Test func sessionReadsATag() async throws { - #expect(AsyncNFCReader.availability == .available) + #expect(await AsyncNFCReader.availability == .available) let reader = AsyncNFCReader() let session = reader.session(tagTypes: .ndef, alertMessage: "Hold near a tag") let host = try #require(HostNFCReader.last) diff --git a/Tests/DynamicNFCTests/DynamicNFCTests.swift b/Tests/DynamicNFCTests/DynamicNFCTests.swift index 8db3004..cef29cf 100644 --- a/Tests/DynamicNFCTests/DynamicNFCTests.swift +++ b/Tests/DynamicNFCTests/DynamicNFCTests.swift @@ -10,14 +10,17 @@ import DynamicRuntime } static let descriptors = [ - NFCReaderProxy.descriptor, NFCReaderDelegateProxy.descriptor, NFCTagProxy.descriptor, + NFCReaderProxy.descriptor, NFCReaderDelegateProxy.descriptor, NFCAvailabilityCallbackProxy.descriptor, + NFCTagProxy.descriptor, NDEFMessageProxy.descriptor, NDEFRecordProxy.descriptor, ] @Test func availabilityFirst() { let reader = NFCReaderProxy.descriptor #expect(reader.capability == Capability("nfc")) - #expect(method(reader, "availability") == MethodDescriptor("availability", "()I", .static)) + // Answered through a callback, so a host never blocks to find out. + #expect(method(reader, "availability:") == MethodDescriptor("availability:", "(O)V", .static)) + #expect(method(NFCAvailabilityCallbackProxy.descriptor, "didGetAvailability:")?.signature == Signature("(I)V")) #expect(method(reader, "make:")?.kind == .constructor) // The scan sheet is the consent: there is no separate request. #expect(!reader.methods.contains { $0.key.lowercased().contains("authoriz") })