Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
98b7f27
Added NFCAvailabilityCallback, the answer to NFCReader's availability
colemancda Dec 3, 2026
0494682
Answered NFCReader's availability through a callback, so no host bloc…
colemancda Dec 3, 2026
1b72b92
Pointed NFCAvailability at availability(_:)
colemancda Dec 3, 2026
a3bcf69
Made AsyncNFCReader.availability async over the callback
colemancda Dec 3, 2026
6fa7164
Added LocationServicesCallback, the answer to isLocationServicesEnabled
colemancda Dec 3, 2026
0a3787b
Answered isLocationServicesEnabled through a callback, and said autho…
colemancda Dec 3, 2026
bba8dda
Made AsyncLocationManager.isLocationServicesEnabled async over the ca…
colemancda Dec 3, 2026
b499ad0
Said setProximityMonitoringEnabled never waits for a host's sensor se…
colemancda Dec 3, 2026
0b4538e
Pinned availability(_:) and NFCAvailabilityCallback
colemancda Dec 3, 2026
e80a6f0
Answered availability through the callback in the fake NFC host
colemancda Dec 3, 2026
818bb43
Pinned isLocationServicesEnabled(_:) and LocationServicesCallback
colemancda Dec 3, 2026
7ae411a
Tested isLocationServicesEnabled through the callback
colemancda Dec 3, 2026
4ca2fcc
Documented availability answered through a callback
colemancda Dec 3, 2026
3b56558
Documented isLocationServicesEnabled answered through a callback
colemancda Dec 3, 2026
a6b17c4
Documented proximity monitoring that never waits for the sensor service
colemancda Dec 3, 2026
4674dc3
Recorded queries that answer later on the roadmap
colemancda Dec 3, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion Contracts/DynamicDevice/Device.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
24 changes: 23 additions & 1 deletion Contracts/DynamicLocation/AsyncLocationManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<Bool, Never>) 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
Expand Down Expand Up @@ -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<Bool, Never>

init(_ callback: Callback<Bool, Never>) {
self.callback = callback
}

func didGetServicesEnabled(_ enabled: Bool) {
callback.resume(returning: enabled)
}
}

final class LocationEvents: LocationManagerDelegate {

let authorization = PendingCallbacks<LocationAuthorization, Never>()
Expand Down
13 changes: 9 additions & 4 deletions Contracts/DynamicLocation/LocationManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions Contracts/DynamicLocation/LocationServicesCallback.swift
Original file line number Diff line number Diff line change
@@ -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)
}
27 changes: 24 additions & 3 deletions Contracts/DynamicNFC/AsyncNFCReader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<NFCAvailability, Never>) in
NFCReaderProxy.availability(AvailabilityReceiver(callback))
} onCancel: { callback in
callback.resume(returning: .unsupported)
}
}
}

// MARK: Session
Expand Down Expand Up @@ -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<NFCAvailability, Never>

init(_ callback: Callback<NFCAvailability, Never>) {
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?
Expand Down
11 changes: 11 additions & 0 deletions Contracts/DynamicNFC/NFCAvailabilityCallback.swift
Original file line number Diff line number Diff line change
@@ -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)
}
10 changes: 6 additions & 4 deletions Contracts/DynamicNFC/NFCReader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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

Expand Down
2 changes: 1 addition & 1 deletion Contracts/DynamicNFC/NFCTypes.swift
Original file line number Diff line number Diff line change
@@ -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
Expand Down
4 changes: 3 additions & 1 deletion Documentation/Contracts/Device.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:**
Expand Down
24 changes: 16 additions & 8 deletions Documentation/Contracts/Location.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 |
Expand All @@ -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)
}

Expand Down
29 changes: 21 additions & 8 deletions Documentation/Contracts/NFC.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down Expand Up @@ -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.
Expand All @@ -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")
Expand Down
13 changes: 13 additions & 0 deletions Documentation/Implementation.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
9 changes: 8 additions & 1 deletion Tests/DynamicLocationTests/AsyncLocationManagerTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
Expand Down
6 changes: 4 additions & 2 deletions Tests/DynamicLocationTests/DynamicLocationTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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"])
Expand All @@ -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)
Expand Down
7 changes: 5 additions & 2 deletions Tests/DynamicNFCTests/AsyncNFCReaderTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -113,14 +115,15 @@ 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)
HostNFCReader.last = nil
}

@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)
Expand Down
7 changes: 5 additions & 2 deletions Tests/DynamicNFCTests/DynamicNFCTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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") })
Expand Down
Loading