From 2be7d28f13153e528e54a6842535d8c665984208 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 3 Dec 2026 03:28:11 -0500 Subject: [PATCH 01/20] Handed work the bus connection once it's made --- Sources/LinuxDBus/BusLink.swift | 44 +++++++++++++++++++++++++++++++-- 1 file changed, 42 insertions(+), 2 deletions(-) diff --git a/Sources/LinuxDBus/BusLink.swift b/Sources/LinuxDBus/BusLink.swift index b4431c3..6c0608b 100644 --- a/Sources/LinuxDBus/BusLink.swift +++ b/Sources/LinuxDBus/BusLink.swift @@ -51,6 +51,14 @@ final class BusLink: @unchecked Sendable { /// Requests made while connecting. private var waiting: [Outgoing] = [] + /// The connection, while there's one. + private var connection: DBusConnection? + + /// Work that needs the connection, waiting for it to be made. + private var waitingWork: [Work] = [] + + typealias Work = @Sendable (Result) -> Void + init(connect: @escaping @Sendable () async throws -> DBusConnection) { self.connect = connect } @@ -80,6 +88,26 @@ final class BusLink: @unchecked Sendable { } } + /// Hands `work` the connection, on Swift's threads: at once if there's + /// one, once it's made, or the error it couldn't be made with. + func withConnection(_ work: @escaping Work) { + lock.lock() + switch status { + case .connected: + let connection = self.connection + lock.unlock() + work(connection.map { .success($0) } ?? .failure(.disconnected)) + case .connecting: + waitingWork.append(work) + lock.unlock() + case .idle: + status = .connecting + waitingWork.append(work) + lock.unlock() + start() + } + } + // MARK: The connection private func start() { @@ -126,7 +154,7 @@ final class BusLink: @unchecked Sendable { } } } - open(continuation) + open(continuation, connection) handler(.connected) for await _ in closing { } @@ -136,25 +164,37 @@ final class BusLink: @unchecked Sendable { } /// Sends what waited, and from now on sends at once. - private func open(_ continuation: AsyncStream.Continuation) { + private func open(_ continuation: AsyncStream.Continuation, _ connection: DBusConnection) { lock.lock() status = .connected(continuation) + self.connection = connection for item in waiting { continuation.yield(item) } waiting = [] + let work = waitingWork + waitingWork = [] lock.unlock() + for item in work { + item(.success(connection)) + } } private func closed(_ failure: BusError) { lock.lock() status = .idle + connection = nil let stranded = waiting waiting = [] + let strandedWork = waitingWork + waitingWork = [] lock.unlock() for item in stranded { item.completion(.failure(failure)) } + for item in strandedWork { + item(.failure(failure)) + } handler(.closed(failure)) } From b1521b6bc7d09837df744646ebf3323ae1931545 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 3 Dec 2026 03:28:11 -0500 Subject: [PATCH 02/20] Added Bus.perform for generated clients, and removed the calls that waited on the main thread --- Sources/LinuxDBus/Bus.swift | 84 +++++++++++++------------------------ 1 file changed, 29 insertions(+), 55 deletions(-) diff --git a/Sources/LinuxDBus/Bus.swift b/Sources/LinuxDBus/Bus.swift index 35cd998..a6556f6 100644 --- a/Sources/LinuxDBus/Bus.swift +++ b/Sources/LinuxDBus/Bus.swift @@ -1,5 +1,4 @@ import DBus -import Dispatch import Foundation import LinuxHost @@ -99,33 +98,6 @@ public final class Bus { } } - /// Calls `method` and waits up to `timeout` seconds for the reply, for - /// a contract that answers at once. The reply doesn't need the main - /// loop, so the main thread can wait for it. - public func callAndWait( - _ destination: String, - _ path: String, - _ interface: String, - _ method: String, - _ arguments: [DBusMessageArgument] = [], - signature: String? = nil, - timeout: Double = 2 - ) -> Result<[DBusMessageArgument], BusError> { - let message: DBusMessage - switch Self.message(destination, path, interface, method, arguments, signature: signature) { - case .success(let made): - message = made - case .failure(let error): - return .failure(error) - } - let answer = Answer() - link.send(message) { result in - answer.set(result) - } - return answer.wait(timeout: timeout) - ?? .failure(BusError(name: "org.freedesktop.DBus.Error.NoReply", message: "no reply in \(timeout) s")) - } - /// A method call; `signature`, if given, must be the arguments'. static func message( _ destination: String, @@ -150,21 +122,6 @@ public final class Bus { return .success(DBusMessage(methodCall: call, arguments: arguments)) } - private final class Answer: @unchecked Sendable { - private let semaphore = DispatchSemaphore(value: 0) - private var result: Result<[DBusMessageArgument], BusError>? - - func set(_ result: Result<[DBusMessageArgument], BusError>) { - self.result = result - semaphore.signal() - } - - func wait(timeout: Double) -> Result<[DBusMessageArgument], BusError>? { - guard semaphore.wait(timeout: .now() + timeout) == .success else { return nil } - return result - } - } - // MARK: Properties static let properties = "org.freedesktop.DBus.Properties" @@ -182,18 +139,6 @@ public final class Bus { } } - /// One property's value, waiting up to `timeout` seconds. - public func propertyAndWait( - _ destination: String, - _ path: String, - _ interface: String, - _ name: String, - timeout: Double = 2 - ) -> Result { - callAndWait(destination, path, Self.properties, "Get", [.string(interface), .string(name)], timeout: timeout) - .flatMap(Self.single) - } - /// Every property of `interface`, the variants unwrapped /// (`Properties.GetAll`). public func properties( @@ -253,6 +198,35 @@ public final class Bus { /// `org.freedesktop.DBus.Local`, whose signals don't come over the wire. static let local = "org.freedesktop.DBus.Local" + // MARK: Generated clients + + /// Runs `body` with the connection, made if there isn't one, on Swift's + /// threads: for PureSwift/DBus's generated service clients, which are + /// `async`. Its value, or its error, arrives on the main loop. Nothing + /// here waits for it. + public func perform( + _ body: @escaping @Sendable (DBusConnection) async throws -> Value, + reply: @escaping (Result) -> Void + ) { + let loop = self.loop + link.withConnection { connection in + Task { + let result: Result + switch connection { + case .failure(let error): + result = .failure(error) + case .success(let connection): + do { + result = .success(try await body(connection)) + } catch { + result = .failure(BusLink.error(error, connected: await connection.isConnected)) + } + } + loop.post { reply(result) } + } + } + } + static let localPath = "/org/freedesktop/DBus/Local" private func addMatch(_ rule: MatchRule) { From 2d58e7a53542e40eea200fd24748b5ed677c93a1 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 3 Dec 2026 03:28:11 -0500 Subject: [PATCH 03/20] Tested perform, and answered calls through the main loop instead of waiting --- Tests/LinuxDBusTests/LinuxDBusTests.swift | 61 +++++++++++++++++------ 1 file changed, 47 insertions(+), 14 deletions(-) diff --git a/Tests/LinuxDBusTests/LinuxDBusTests.swift b/Tests/LinuxDBusTests/LinuxDBusTests.swift index 11e54f5..3c434e2 100644 --- a/Tests/LinuxDBusTests/LinuxDBusTests.swift +++ b/Tests/LinuxDBusTests/LinuxDBusTests.swift @@ -50,6 +50,18 @@ final class Daemon { } } +extension Bus { + + /// Calls one of the bus's own methods and runs `loop` until the reply + /// is in: what the tests do where a host never waits. + func answer(_ loop: MainLoop, _ method: String, _ arguments: [DBusMessageArgument] = []) -> Result<[DBusMessageArgument], BusError> { + var result: Result<[DBusMessageArgument], BusError>? + call("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", method, arguments) { result = $0 } + run(loop) { result != nil } + return result ?? .failure(BusError(name: "org.freedesktop.DBus.Error.NoReply")) + } +} + @Suite struct LinuxDBusTests { // MARK: Match rules @@ -143,8 +155,18 @@ final class Daemon { return } #expect(error.isServiceMissing) - let waited = bus.callAndWait("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "GetId") - #expect((try? waited.get()) == nil, "and again, connecting afresh") + #expect((try? bus.answer(loop, "GetId").get()) == nil, "and again, connecting afresh") + + // A generated client's work fails the same way, on the main loop. + var performed: Result? + bus.perform({ _ in 1 }) { performed = $0 } + #expect(performed == nil, "never inside the call") + run(loop) { performed != nil } + guard case .failure(let performError)? = performed else { + Issue.record("expected a failure, got \(String(describing: performed))") + return + } + #expect(performError.isServiceMissing) } @Test(.enabled(if: Daemon.executable != nil, "needs dbus-daemon")) @@ -154,11 +176,24 @@ final class Daemon { let bus = Bus(.address(daemon.address), loop: loop) let other = Bus(.address(daemon.address), loop: loop) - // Waiting, without the main loop. - let id = try bus.callAndWait("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "GetId").get() + let id = try bus.answer(loop, "GetId").get() #expect(id.first?.text?.count == 32) - let features = bus.propertyAndWait("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "Features") - #expect((try? features.get()) != nil) + var features: DBusMessageArgument? + bus.property("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "Features") { features = try? $0.get() } + run(loop) { features != nil } + + // A generated client's call, on the connection, answered on the + // main loop. + var performed: Result? + bus.perform({ connection in + let reply = try await connection.callMethod( + destination: DBusBusName(rawValue: "org.freedesktop.DBus")!, path: DBusObjectPath(rawValue: "/org/freedesktop/DBus")!, + interface: DBusInterface(rawValue: "org.freedesktop.DBus")!, method: DBusMember(rawValue: "GetId")!, arguments: []) + return reply.first?.text ?? "" + }) { performed = $0 } + #expect(performed == nil, "never inside the call") + run(loop) { performed != nil } + #expect((try? performed?.get()) == id.first?.text) // A reply on the main loop. var names: [String]? @@ -192,9 +227,8 @@ final class Daemon { var unrelated = 0 bus.subscribe(MatchRule(member: "PropertiesChanged")) { _ in unrelated += 1 } // Requests go in order, so the rule is in place once this answers. - _ = bus.callAndWait("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "GetId") - let owner = try other.callAndWait("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "RequestName", - [.string("org.example.LinuxDBusTests"), .uint32(0)]).get() + _ = bus.answer(loop, "GetId") + let owner = try other.answer(loop, "RequestName", [.string("org.example.LinuxDBusTests"), .uint32(0)]).get() #expect(owner.first == .uint32(1), "the primary owner") run(loop) { !signals.isEmpty } #expect(signals.first?.member == "NameOwnerChanged") @@ -215,7 +249,7 @@ final class Daemon { arg0: "org.example.LinuxDBusTests.Again")) { signals.append($0) } var disconnected = 0 bus.subscribe(.disconnected) { _ in disconnected += 1 } - _ = try bus.callAndWait("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "GetId").get() + _ = try bus.answer(loop, "GetId").get() // The daemon goes, and another comes at the same address. daemon = nil @@ -225,12 +259,11 @@ final class Daemon { defer { withExtendedLifetime(again) { } } // The next request connects again, and the rule is added again. - _ = try bus.callAndWait("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "GetId").get() + _ = try bus.answer(loop, "GetId").get() run(loop, for: 0.2) { false } - _ = bus.callAndWait("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "GetId") + _ = bus.answer(loop, "GetId") let other = Bus(.address(again.address), loop: loop) - _ = try other.callAndWait("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "RequestName", - [.string("org.example.LinuxDBusTests.Again"), .uint32(0)]).get() + _ = try other.answer(loop, "RequestName", [.string("org.example.LinuxDBusTests.Again"), .uint32(0)]).get() run(loop) { !signals.isEmpty } #expect(signals.first?.body.first?.text == "org.example.LinuxDBusTests.Again") } From 41d64ccad82d7123211e145629f04d1cb55ff9d1 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 3 Dec 2026 03:28:11 -0500 Subject: [PATCH 04/20] Removed objectsAndWait from NeardBus --- Sources/LinuxNFC/NeardBus.swift | 7 ------- 1 file changed, 7 deletions(-) diff --git a/Sources/LinuxNFC/NeardBus.swift b/Sources/LinuxNFC/NeardBus.swift index 6d7d2cf..de5a585 100644 --- a/Sources/LinuxNFC/NeardBus.swift +++ b/Sources/LinuxNFC/NeardBus.swift @@ -25,9 +25,6 @@ public protocol NeardBus: AnyObject { /// Every object neard manages (`GetManagedObjects`). func objects(reply: @escaping (Result<[String: NeardInterfaces], BusError>) -> Void) - /// The same, waiting for them: for `availability`, which answers at once. - func objectsAndWait() -> Result<[String: NeardInterfaces], BusError> - /// Calls a method of one of neard's objects. func call( _ path: String, @@ -74,10 +71,6 @@ public final class SystemNeard: NeardBus { } } - public func objectsAndWait() -> Result<[String: NeardInterfaces], BusError> { - bus.callAndWait(Neard.service, "/", Neard.objectManager, "GetManagedObjects").map(Self.objects) - } - public func call( _ path: String, _ interface: String, From 86ee0b8b64e8cfb5500c76f32706c97a21e8c126 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 3 Dec 2026 03:28:11 -0500 Subject: [PATCH 05/20] Answered NFC availability once neard has --- Sources/LinuxNFC/LinuxNFCReader.swift | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/Sources/LinuxNFC/LinuxNFCReader.swift b/Sources/LinuxNFC/LinuxNFCReader.swift index 0689f50..c9aa8f5 100644 --- a/Sources/LinuxNFC/LinuxNFCReader.swift +++ b/Sources/LinuxNFC/LinuxNFCReader.swift @@ -82,18 +82,25 @@ public final class LinuxNFCReader: NFCReader { // MARK: Availability /// No neard, or no adapter: `unsupported`; adapters all off: `disabled`. - public static func availability() -> Int32 { - switch neard.objectsAndWait() { + /// Answered once neard has, on the main loop. + public static func availability(_ callback: any NFCAvailabilityCallback) { + neard.objects { result in + callback.didGetAvailability(availability(result).rawValue) + } + } + + static func availability(_ result: Result<[String: NeardInterfaces], BusError>) -> NFCAvailability { + switch result { case .success(let objects): guard let adapter = adapter(in: objects) else { - return NFCAvailability.unsupported.rawValue + return .unsupported } - return (adapter.powered ? NFCAvailability.available : .disabled).rawValue + return adapter.powered ? .available : .disabled case .failure(let error): if !error.isServiceMissing { HostLog.error("nfc: can't ask neard: \(error)") } - return NFCAvailability.unsupported.rawValue + return .unsupported } } From 78b46ae7c3fa6e2922ab03e3000d91e1c1d2a16a Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 3 Dec 2026 03:28:11 -0500 Subject: [PATCH 06/20] Listed and registered NFCAvailabilityCallback --- Sources/LinuxNFC/LinuxNFC.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Sources/LinuxNFC/LinuxNFC.swift b/Sources/LinuxNFC/LinuxNFC.swift index 2746850..04103cd 100644 --- a/Sources/LinuxNFC/LinuxNFC.swift +++ b/Sources/LinuxNFC/LinuxNFC.swift @@ -11,6 +11,7 @@ public enum LinuxNFC: HostModule { [ NFCReaderProxy.descriptor, NFCReaderDelegateProxy.descriptor, + NFCAvailabilityCallbackProxy.descriptor, NFCTagProxy.descriptor, NDEFMessageProxy.descriptor, NDEFRecordProxy.descriptor, @@ -20,6 +21,7 @@ public enum LinuxNFC: HostModule { public static func register(in registrar: some ContractRegistrar) { NFCReaderProxy.register(LinuxNFCReader.self, in: registrar) NFCReaderDelegateProxy.registerInterface(in: registrar) + NFCAvailabilityCallbackProxy.registerInterface(in: registrar) NFCTagProxy.register(LinuxNFCTag.self, in: registrar) NDEFMessageProxy.register(LinuxNDEFMessage.self, in: registrar) NDEFRecordProxy.register(LinuxNDEFRecord.self, in: registrar) From 650fc184fdfdbfe6c1b187699d49ce4c7ab73cc3 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 3 Dec 2026 03:28:11 -0500 Subject: [PATCH 07/20] Recorded availability answers, and dropped the fake's objectsAndWait --- Tests/LinuxNFCTests/FakeNeard.swift | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/Tests/LinuxNFCTests/FakeNeard.swift b/Tests/LinuxNFCTests/FakeNeard.swift index 1ca9859..6e1f40d 100644 --- a/Tests/LinuxNFCTests/FakeNeard.swift +++ b/Tests/LinuxNFCTests/FakeNeard.swift @@ -44,10 +44,6 @@ final class FakeNeard: NeardBus { MainLoop.shared.post { reply(answer) } } - func objectsAndWait() -> Result<[String: NeardInterfaces], BusError> { - unavailable.map { .failure($0) } ?? .success(objects) - } - func call( _ path: String, _ interface: String, @@ -173,3 +169,13 @@ final class RecordingReaderDelegate: NFCReaderDelegate { events.append("invalidate \(error)") } } + +/// Records `availability(_:)`'s answers. +final class AvailabilityAnswers: NFCAvailabilityCallback { + + var received: [NFCAvailability] = [] + + func didGetAvailability(_ availability: Int32) { + received.append(NFCAvailability(rawValue: availability) ?? .unsupported) + } +} From 9cbefaf38285ed7576944f67f4e31de9a57b034d Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 3 Dec 2026 03:28:11 -0500 Subject: [PATCH 08/20] Tested availability answered once, after neard --- Tests/LinuxNFCTests/LinuxNFCTests.swift | 31 ++++++++++++++----------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/Tests/LinuxNFCTests/LinuxNFCTests.swift b/Tests/LinuxNFCTests/LinuxNFCTests.swift index 7d2de40..dda718b 100644 --- a/Tests/LinuxNFCTests/LinuxNFCTests.swift +++ b/Tests/LinuxNFCTests/LinuxNFCTests.swift @@ -57,23 +57,27 @@ let textRecord: [String: DBusMessageArgument] = [ // MARK: Availability - @Test func availability() { - with(FakeNeard()) { - #expect(LinuxNFCReader.availability() == NFCAvailability.available.rawValue) - } - with(FakeNeard(powered: false)) { - #expect(LinuxNFCReader.availability() == NFCAvailability.disabled.rawValue) + /// `availability(_:)`'s answer: none before neard's, then exactly one, + /// on the main loop. + func availability(_ neard: FakeNeard) -> [NFCAvailability] { + with(neard) { + let answers = AvailabilityAnswers() + LinuxNFCReader.availability(answers) + #expect(answers.received.isEmpty, "never answered before neard has") + MainLoop.shared.drain() + return answers.received } + } + + @Test func availability() { + #expect(availability(FakeNeard()) == [.available]) + #expect(availability(FakeNeard(powered: false)) == [.disabled]) let none = FakeNeard() none.objects = [:] - with(none) { - #expect(LinuxNFCReader.availability() == NFCAvailability.unsupported.rawValue, "no adapter") - } + #expect(availability(none) == [.unsupported], "no adapter") let missing = FakeNeard() missing.unavailable = BusError(name: "org.freedesktop.DBus.Error.ServiceUnknown") - with(missing) { - #expect(LinuxNFCReader.availability() == NFCAvailability.unsupported.rawValue, "no neard") - } + #expect(availability(missing) == [.unsupported], "no neard") // One adapter on of two is enough. let two = FakeNeard(powered: false) two.objects["/org/neard/nfc1"] = [Neard.adapter: ["Powered": .boolean(true)]] @@ -442,7 +446,8 @@ let textRecord: [String: DBusMessageArgument] = [ @Test func moduleRegistersTheContracts() { #expect(LinuxNFC.contracts.map(\.name) == [ - "org.pureswift.nfc.Reader", "org.pureswift.nfc.ReaderDelegate", "org.pureswift.nfc.Tag", + "org.pureswift.nfc.Reader", "org.pureswift.nfc.ReaderDelegate", "org.pureswift.nfc.AvailabilityCallback", + "org.pureswift.nfc.Tag", "org.pureswift.nfc.NDEFMessage", "org.pureswift.nfc.NDEFRecord", ]) #expect(LinuxNFC.permissionProviders().keys.contains(.nfc)) From 5aaf0663f32c60ec21e27d93fd78d621a596411f Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 3 Dec 2026 03:28:11 -0500 Subject: [PATCH 09/20] Removed propertyAndWait from SensorProxyBus --- Sources/LinuxDevice/SensorProxy.swift | 7 ------- 1 file changed, 7 deletions(-) diff --git a/Sources/LinuxDevice/SensorProxy.swift b/Sources/LinuxDevice/SensorProxy.swift index e18783f..ba41e94 100644 --- a/Sources/LinuxDevice/SensorProxy.swift +++ b/Sources/LinuxDevice/SensorProxy.swift @@ -15,9 +15,6 @@ public protocol SensorProxyBus: AnyObject { /// Every property. func properties(reply: @escaping (Result<[String: DBusMessageArgument], BusError>) -> Void) - /// One property, waiting for it: for the contract's synchronous calls. - func propertyAndWait(_ name: String) -> Result - /// Calls `handler` with the properties each `PropertiesChanged` signal /// changes. func subscribeToChanges(_ handler: @escaping ([String: DBusMessageArgument]) -> Void) -> BusSubscription @@ -66,10 +63,6 @@ public final class SystemSensorProxy: SensorProxyBus { bus.properties(SensorProxy.service, SensorProxy.path, SensorProxy.interface, reply: reply) } - public func propertyAndWait(_ name: String) -> Result { - bus.propertyAndWait(SensorProxy.service, SensorProxy.path, SensorProxy.interface, name) - } - public func subscribeToChanges(_ handler: @escaping ([String: DBusMessageArgument]) -> Void) -> BusSubscription { let rule = MatchRule(sender: SensorProxy.service, path: SensorProxy.path, interface: "org.freedesktop.DBus.Properties", member: "PropertiesChanged", arg0: SensorProxy.interface) From 7954d2023e7fd76bbd8f50e8f249273fca55b3db Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 3 Dec 2026 03:28:11 -0500 Subject: [PATCH 10/20] Turned proximity monitoring off once the proxy says there's no sensor, instead of waiting --- Sources/LinuxDevice/LinuxDevice.swift | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/Sources/LinuxDevice/LinuxDevice.swift b/Sources/LinuxDevice/LinuxDevice.swift index b39bb2b..5f583b0 100644 --- a/Sources/LinuxDevice/LinuxDevice.swift +++ b/Sources/LinuxDevice/LinuxDevice.swift @@ -195,15 +195,18 @@ public final class LinuxDevice: Device { currentOrientation.rawValue } - /// Asks the proxy whether there's a proximity sensor, waiting for the - /// answer, and claims it if there is; it stays off if not. + /// Claims the proxy's proximity sensor, if it has one. It's on until + /// the proxy says there's no sensor, then off again: the main loop + /// never waits for the proxy. public func setProximityMonitoringEnabled(_ enabled: Bool) { guard enabled != proximityMonitoring else { return } if enabled { - guard (try? Self.sensorProxy.propertyAndWait("HasProximity").get())?.flag == true else { return } proximityMonitoring = true subscribe() - claim(has: "HasProximity", "ClaimProximity", wanted: { $0.proximityMonitoring }) { device, properties in + claim(has: "HasProximity", "ClaimProximity", wanted: { $0.proximityMonitoring }, missing: { device in + device.proximityMonitoring = false + device.unsubscribeIfIdle() + }) { device, properties in device.proximityClaimed = true device.approach(properties["ProximityNear"]?.flag ?? false) } @@ -229,8 +232,10 @@ public final class LinuxDevice: Device { // MARK: iio-sensor-proxy /// Claims a sensor the proxy has, while it's still `wanted`, and hands - /// over the properties once it's claimed. + /// over the properties once it's claimed; `missing` hears if there's no + /// such sensor, or no proxy. private func claim(has: String, _ method: String, wanted: @escaping (LinuxDevice) -> Bool, + missing: @escaping (LinuxDevice) -> Void = { _ in }, claimed: @escaping (LinuxDevice, [String: DBusMessageArgument]) -> Void) { let proxy = Self.sensorProxy proxy.properties { [weak self] result in @@ -239,6 +244,7 @@ public final class LinuxDevice: Device { if case .failure(let error) = result, !error.isServiceMissing { HostLog.error("device: iio-sensor-proxy: \(error)") } + missing(self) return } proxy.call(method) { [weak self] result in From 879936bdbf8184ffd42b3aad96152926769e3ebc Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 3 Dec 2026 03:28:11 -0500 Subject: [PATCH 11/20] Tested proximity turning itself off without a sensor --- Tests/LinuxDeviceTests/SensorProxyTests.swift | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/Tests/LinuxDeviceTests/SensorProxyTests.swift b/Tests/LinuxDeviceTests/SensorProxyTests.swift index 0bbcc79..bc57188 100644 --- a/Tests/LinuxDeviceTests/SensorProxyTests.swift +++ b/Tests/LinuxDeviceTests/SensorProxyTests.swift @@ -38,13 +38,6 @@ final class FakeSensorProxy: SensorProxyBus { MainLoop.shared.post { reply(answer) } } - func propertyAndWait(_ name: String) -> Result { - if let error { - return .failure(error) - } - return properties[name].map { .success($0) } ?? .failure(BusError(name: "org.freedesktop.DBus.Error.UnknownProperty")) - } - func subscribeToChanges(_ handler: @escaping ([String: DBusMessageArgument]) -> Void) -> BusSubscription { next += 1 handlers[next] = handler @@ -168,18 +161,21 @@ extension LinuxDeviceTests { } } - @Test func proximityStaysOffWithoutASensor() { + @Test func proximityTurnsOffWithoutASensor() { let proxy = FakeSensorProxy(["HasProximity": .boolean(false)]) withProxy(proxy) { device, _ in device.setProximityMonitoringEnabled(true) - #expect(!device.isProximityMonitoringEnabled()) + #expect(device.isProximityMonitoringEnabled(), "on until the proxy answers: nothing waits for it") MainLoop.shared.drain() + #expect(!device.isProximityMonitoringEnabled()) #expect(proxy.calls.isEmpty) + #expect(proxy.subscribers == 0, "nothing left to hear about") } let missing = FakeSensorProxy() missing.error = BusError(name: "org.freedesktop.DBus.Error.ServiceUnknown") withProxy(missing) { device, _ in device.setProximityMonitoringEnabled(true) + MainLoop.shared.drain() #expect(!device.isProximityMonitoringEnabled()) } } From 13d67e0c0954671e779b50d4ab0e5ec38da6182f Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 3 Dec 2026 03:28:11 -0500 Subject: [PATCH 12/20] Left proximity to the sensor proxy tests --- Tests/LinuxDeviceTests/LinuxDeviceTests.swift | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Tests/LinuxDeviceTests/LinuxDeviceTests.swift b/Tests/LinuxDeviceTests/LinuxDeviceTests.swift index c5ff718..3d40606 100644 --- a/Tests/LinuxDeviceTests/LinuxDeviceTests.swift +++ b/Tests/LinuxDeviceTests/LinuxDeviceTests.swift @@ -185,8 +185,7 @@ struct Machine { #expect(device.physicalMemory() > 0 && device.processorCount() > 0) #expect(!device.isSimulator()) #expect(device.orientation() == DeviceOrientation.unknown.rawValue) - device.setProximityMonitoringEnabled(true) - #expect(!device.isProximityMonitoringEnabled()) + // Proximity is iio-sensor-proxy's: `SensorProxyTests`. } @Test func changesReachTheDelegate() throws { From 60f11d403fa1cb405ed10796902b67a67aafbce9 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 3 Dec 2026 03:28:11 -0500 Subject: [PATCH 13/20] Depended on DBus 0.3.2 and its GeoClue2 client --- Package.swift | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Package.swift b/Package.swift index a481926..dbb1cff 100644 --- a/Package.swift +++ b/Package.swift @@ -93,9 +93,9 @@ let package = Package( cacao, webKit, // D-Bus, in Swift without libdbus, which Bluetooth talks to BlueZ - // over, and Location to GeoClue. 0.3.1 is the release Cacao needs, - // with the StatusNotifier service. - .package(url: "https://github.com/PureSwift/DBus.git", from: "0.3.1"), + // over, and Location to GeoClue through its generated GeoClue2 + // client, which 0.3.2 adds. Cacao needs 0.3.1's StatusNotifier. + .package(url: "https://github.com/PureSwift/DBus.git", from: "0.3.2"), .package(url: "https://github.com/apple/swift-argument-parser.git", from: "1.5.0"), // SHA-256, for bundles' CodeResources. .package(url: "https://github.com/apple/swift-crypto.git", "3.0.0"..<"5.0.0"), @@ -219,7 +219,8 @@ let package = Package( // GeoClue 2 on the system bus. .target( name: "LinuxLocation", - dependencies: ["LinuxHost", "LinuxDBus", runtime("DynamicLocation"), runtime("DynamicRuntime"), .product(name: "DBus", package: "DBus")], + dependencies: ["LinuxHost", "LinuxDBus", runtime("DynamicLocation"), runtime("DynamicRuntime"), .product(name: "DBus", package: "DBus"), + .product(name: "GeoClue2", package: "DBus")], swiftSettings: host ), From ce75b51bead46934890e96563cfa6d25b5085a5f Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 3 Dec 2026 03:28:11 -0500 Subject: [PATCH 14/20] Named what Location asks GeoClue, over DBus's generated GeoClue2 client --- Sources/LinuxLocation/GeoClueBus.swift | 133 +++++++++++++++++-------- 1 file changed, 94 insertions(+), 39 deletions(-) diff --git a/Sources/LinuxLocation/GeoClueBus.swift b/Sources/LinuxLocation/GeoClueBus.swift index 9c55ab0..c651bd5 100644 --- a/Sources/LinuxLocation/GeoClueBus.swift +++ b/Sources/LinuxLocation/GeoClueBus.swift @@ -1,44 +1,46 @@ import DBus +import GeoClue2 import LinuxDBus -/// GeoClue 2 on the system bus (`Plan.md` §11), or a fake one in tests. -/// Every call goes to `org.freedesktop.GeoClue2`, and everything it reports +/// GeoClue 2 on the system bus (`Plan.md` §11), or a fake one in tests: +/// what the location host asks of it, by name. Everything it answers /// arrives on the main loop. public protocol GeoClueBus: AnyObject { - /// Calls a method of one of GeoClue's objects. - func call(_ path: String, _ interface: String, _ method: String, _ arguments: [DBusMessageArgument], - reply: @escaping (Result<[DBusMessageArgument], BusError>) -> Void) + /// A client of the app's own (`Manager.CreateClient`). + func createClient(reply: @escaping (Result) -> Void) - /// Reads one property, waiting for it: for the contract's synchronous - /// calls. - func propertyAndWait(_ path: String, _ interface: String, _ name: String) -> Result + /// The process's one client (`Manager.GetClient`), for a GeoClue + /// before 2.5, which has no `CreateClient`. + func getClient(reply: @escaping (Result) -> Void) - /// Every property of one of GeoClue's objects. - func properties(_ path: String, _ interface: String, reply: @escaping (Result<[String: DBusMessageArgument], BusError>) -> Void) + /// Deletes a client `createClient` made. + func deleteClient(_ client: String) - func setProperty(_ path: String, _ interface: String, _ name: String, _ value: DBusMessageArgument, - reply: @escaping (Result) -> Void) + /// Sets one of a client's properties. + func set(_ client: String, _ setting: GeoClue.Setting, reply: @escaping (Result) -> Void) - /// Calls `handler` with the arguments of each of the object's `member` - /// signals. - func subscribe(_ path: String, _ interface: String, _ member: String, _ handler: @escaping ([DBusMessageArgument]) -> Void) -> BusSubscription + func start(_ client: String, reply: @escaping (Result) -> Void) - func unsubscribe(_ subscription: BusSubscription) -} + func stop(_ client: String, reply: @escaping (Result) -> Void) -/// GeoClue's names and values. -public enum GeoClue { + /// A `Location` object's properties. + func location(_ path: String, reply: @escaping (Result<[String: DBusMessageArgument], BusError>) -> Void) - public static let service = "org.freedesktop.GeoClue2" + /// The manager's `AvailableAccuracyLevel`: `none` when GeoClue has no + /// source. + func availableAccuracy(reply: @escaping (Result) -> Void) - public static let managerPath = "/org/freedesktop/GeoClue2/Manager" + /// Calls `handler` with the path of each `Location` a client's + /// `LocationUpdated` names. + func subscribeToLocations(_ client: String, _ handler: @escaping (String) -> Void) -> BusSubscription - public static let manager = "org.freedesktop.GeoClue2.Manager" - - public static let client = "org.freedesktop.GeoClue2.Client" + func unsubscribe(_ subscription: BusSubscription) +} - public static let location = "org.freedesktop.GeoClue2.Location" +/// GeoClue's values. Its names are PureSwift/DBus's generated `GeoClue2` +/// client's. +public enum GeoClue { /// `GClueAccuracyLevel`. public enum Accuracy: UInt32, Sendable { @@ -50,40 +52,93 @@ public enum GeoClue { case exact = 8 } + /// A client's writable properties. + public enum Setting: Equatable, Sendable { + case desktopID(String) + case accuracy(Accuracy) + /// In meters. + case distanceThreshold(UInt32) + /// In seconds. + case timeThreshold(UInt32) + + /// The property's name. + public var name: String { + switch self { + case .desktopID: "DesktopId" + case .accuracy: "RequestedAccuracyLevel" + case .distanceThreshold: "DistanceThreshold" + case .timeThreshold: "TimeThreshold" + } + } + } + /// The altitude of a location without one (`-G_MAXDOUBLE`). public static let unknownAltitude = -Double.greatestFiniteMagnitude } -/// GeoClue on the system bus, through LinuxDBus. +/// GeoClue on the system bus, through PureSwift/DBus's generated +/// `GeoClue2` client on LinuxDBus's connection: nothing waits for it. public final class SystemGeoClue: GeoClueBus { + static let service = "org.freedesktop.GeoClue2" + + static let client = "org.freedesktop.GeoClue2.Client" + private let bus: Bus public init(bus: Bus = .system) { self.bus = bus } - public func call(_ path: String, _ interface: String, _ method: String, _ arguments: [DBusMessageArgument], - reply: @escaping (Result<[DBusMessageArgument], BusError>) -> Void) { - bus.call(GeoClue.service, path, interface, method, arguments, reply: reply) + public func createClient(reply: @escaping (Result) -> Void) { + bus.perform({ try await GeoClue2.Manager(connection: $0).createClient().rawValue }, reply: reply) + } + + public func getClient(reply: @escaping (Result) -> Void) { + bus.perform({ try await GeoClue2.Manager(connection: $0).getClient().rawValue }, reply: reply) + } + + public func deleteClient(_ client: String) { + guard let path = DBusObjectPath(rawValue: client) else { return } + bus.perform({ try await GeoClue2.Manager(connection: $0).deleteClient(client: path) }) { _ in } + } + + public func set(_ client: String, _ setting: GeoClue.Setting, reply: @escaping (Result) -> Void) { + bus.perform({ connection in + let geoClue = try GeoClue2.Client(connection: connection, path: client) + switch setting { + case .desktopID(let id): try await geoClue.setDesktopId(id) + case .accuracy(let accuracy): try await geoClue.setRequestedAccuracyLevel(accuracy.rawValue) + case .distanceThreshold(let meters): try await geoClue.setDistanceThreshold(meters) + case .timeThreshold(let seconds): try await geoClue.setTimeThreshold(seconds) + } + }, reply: reply) + } + + public func start(_ client: String, reply: @escaping (Result) -> Void) { + bus.perform({ try await GeoClue2.Client(connection: $0, path: client).start() }, reply: reply) } - public func propertyAndWait(_ path: String, _ interface: String, _ name: String) -> Result { - bus.propertyAndWait(GeoClue.service, path, interface, name) + public func stop(_ client: String, reply: @escaping (Result) -> Void) { + bus.perform({ try await GeoClue2.Client(connection: $0, path: client).stop() }, reply: reply) } - public func properties(_ path: String, _ interface: String, reply: @escaping (Result<[String: DBusMessageArgument], BusError>) -> Void) { - bus.properties(GeoClue.service, path, interface, reply: reply) + public func location(_ path: String, reply: @escaping (Result<[String: DBusMessageArgument], BusError>) -> Void) { + // One `GetAll`, not a call for each property. + bus.perform({ try await GeoClue2.Location(connection: $0, path: path).properties() }, reply: reply) } - public func setProperty(_ path: String, _ interface: String, _ name: String, _ value: DBusMessageArgument, - reply: @escaping (Result) -> Void) { - bus.setProperty(GeoClue.service, path, interface, name, value, reply: reply) + public func availableAccuracy(reply: @escaping (Result) -> Void) { + bus.perform({ try await GeoClue2.Manager(connection: $0).availableAccuracyLevel }, reply: reply) } - public func subscribe(_ path: String, _ interface: String, _ member: String, _ handler: @escaping ([DBusMessageArgument]) -> Void) -> BusSubscription { - bus.subscribe(MatchRule(sender: GeoClue.service, path: path, interface: interface, member: member)) { signal in - handler(signal.body) + /// A match rule on LinuxDBus's bus, which adds it again if the + /// connection is made again. + public func subscribeToLocations(_ client: String, _ handler: @escaping (String) -> Void) -> BusSubscription { + bus.subscribe(MatchRule(sender: Self.service, path: client, interface: Self.client, member: "LocationUpdated")) { signal in + // (o old, o new) + guard signal.body.count >= 2, let new = signal.body[1].text, new != "/" else { return } + handler(new) } } From caa6c8507a55fbda677842c43b44f4eb166053aa Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 3 Dec 2026 03:28:12 -0500 Subject: [PATCH 15/20] Made GeoClue clients through GeoClueBus's named calls --- Sources/LinuxLocation/GeoClueClient.swift | 57 ++++++++++------------- 1 file changed, 24 insertions(+), 33 deletions(-) diff --git a/Sources/LinuxLocation/GeoClueClient.swift b/Sources/LinuxLocation/GeoClueClient.swift index c1c3e20..77f4653 100644 --- a/Sources/LinuxLocation/GeoClueClient.swift +++ b/Sources/LinuxLocation/GeoClueClient.swift @@ -50,7 +50,7 @@ final class GeoClueClient { func setAccuracy(_ accuracy: GeoClue.Accuracy) { self.accuracy = accuracy if let path { - set(path, "RequestedAccuracyLevel", .uint32(accuracy.rawValue)) + set(path, .accuracy(accuracy)) } } @@ -58,14 +58,14 @@ final class GeoClueClient { func setDistanceThreshold(_ meters: UInt32) { distanceThreshold = meters if let path { - set(path, "DistanceThreshold", .uint32(meters)) + set(path, .distanceThreshold(meters)) } } - private func set(_ path: String, _ name: String, _ value: DBusMessageArgument) { - bus.setProperty(path, GeoClue.client, name, value) { result in + private func set(_ path: String, _ setting: GeoClue.Setting) { + bus.set(path, setting) { result in if case .failure(let error) = result { - HostLog.error("location: GeoClue didn't take \(name): \(error)") + HostLog.error("location: GeoClue didn't take \(setting.name): \(error)") } } } @@ -90,8 +90,8 @@ final class GeoClueClient { case .failure(let error): self.finishStarting(.failure(error)) case .success(let path): - self.bus.call(path, GeoClue.client, "Start", []) { [weak self] result in - self?.finishStarting(result.map { _ in }) + self.bus.start(path) { [weak self] result in + self?.finishStarting(result) } } } @@ -112,7 +112,7 @@ final class GeoClueClient { func stop() { guard isActive, let path else { return } isActive = false - bus.call(path, GeoClue.client, "Stop", []) { result in + bus.stop(path) { result in if case .failure(let error) = result { HostLog.debug("location: GeoClue's Stop: \(error)") } @@ -127,7 +127,7 @@ final class GeoClueClient { self.subscription = nil } if let path, !shared { - bus.call(GeoClue.managerPath, GeoClue.manager, "DeleteClient", [.path(path)]) { _ in } + bus.deleteClient(path) } path = nil } @@ -151,14 +151,12 @@ final class GeoClueClient { switch result { case .failure: if !self.shared { - self.bus.call(GeoClue.managerPath, GeoClue.manager, "DeleteClient", [.path(path)]) { _ in } + self.bus.deleteClient(path) } case .success: self.path = path - self.subscription = self.bus.subscribe(path, GeoClue.client, "LocationUpdated") { [weak self] arguments in - // (o old, o new) - guard arguments.count >= 2, let new = arguments[1].text, new != "/" else { return } - self?.onLocation(new) + self.subscription = self.bus.subscribeToLocations(path) { [weak self] location in + self?.onLocation(location) } } completion(result.map { path }) @@ -168,15 +166,15 @@ final class GeoClueClient { } private func create(_ completion: @escaping (Result) -> Void) { - bus.call(GeoClue.managerPath, GeoClue.manager, "CreateClient", []) { [weak self] result in + bus.createClient { [weak self] result in guard let self else { return } switch result { - case .success(let values): - completion(Self.path(values)) + case .success(let path): + completion(.success(path)) case .failure(let error) where error.isUnknownMember: - self.bus.call(GeoClue.managerPath, GeoClue.manager, "GetClient", []) { [weak self] result in + self.bus.getClient { [weak self] result in self?.shared = true - completion(result.flatMap(Self.path)) + completion(result) } case .failure(let error): completion(.failure(error)) @@ -184,22 +182,15 @@ final class GeoClueClient { } } - private static func path(_ values: [DBusMessageArgument]) -> Result { - guard let path = values.first?.text else { - return .failure(BusError(name: "org.freedesktop.DBus.Error.InvalidSignature", message: "no client path")) - } - return .success(path) - } - /// Sets the desktop ID, which GeoClue needs, then the accuracy and /// thresholds, in order. An older GeoClue without `TimeThreshold` is /// fine. private func configure(_ path: String, _ completion: @escaping (Result) -> Void) { - let settings: [(name: String, value: DBusMessageArgument, required: Bool)] = [ - ("DesktopId", .string(desktopID), true), - ("RequestedAccuracyLevel", .uint32(accuracy.rawValue), true), - ("DistanceThreshold", .uint32(distanceThreshold), false), - ("TimeThreshold", .uint32(0), false), + let settings: [(setting: GeoClue.Setting, required: Bool)] = [ + (.desktopID(desktopID), true), + (.accuracy(accuracy), true), + (.distanceThreshold(distanceThreshold), false), + (.timeThreshold(0), false), ] func apply(_ index: Int) { guard index < settings.count else { @@ -207,10 +198,10 @@ final class GeoClueClient { return } let setting = settings[index] - bus.setProperty(path, GeoClue.client, setting.name, setting.value) { result in + bus.set(path, setting.setting) { result in if case .failure(let error) = result { if setting.required || !error.isUnknownMember { - HostLog.error("location: GeoClue didn't take \(setting.name): \(error)") + HostLog.error("location: GeoClue didn't take \(setting.setting.name): \(error)") } if setting.required { completion(.failure(error)) From 985997f161ff57610d8c87dfcfc432f8c17f7e31 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 3 Dec 2026 03:28:12 -0500 Subject: [PATCH 16/20] Answered whether location services are on once GeoClue has, and kept the answer --- .../LinuxLocation/LinuxLocationManager.swift | 53 ++++++++++++++----- 1 file changed, 40 insertions(+), 13 deletions(-) diff --git a/Sources/LinuxLocation/LinuxLocationManager.swift b/Sources/LinuxLocation/LinuxLocationManager.swift index c64eecc..0cc93ff 100644 --- a/Sources/LinuxLocation/LinuxLocationManager.swift +++ b/Sources/LinuxLocation/LinuxLocationManager.swift @@ -78,10 +78,12 @@ public final class LinuxLocationManager: LocationManager { LocationAccuracyAuthorization.full.rawValue } - /// Asks GeoClue for its `AvailableAccuracyLevel`, waiting up to two - /// seconds: GeoClue starts when it's first asked. - public static func isLocationServicesEnabled() -> Bool { - LocationAuthority.servicesEnabled(bus) + /// Asks GeoClue for its `AvailableAccuracyLevel`, answering once it + /// has: GeoClue starts when it's first asked, which can take a while. + public static func isLocationServicesEnabled(_ callback: any LocationServicesCallback) { + LocationAuthority.shared.checkServices(bus) { enabled in + callback.didGetServicesEnabled(enabled) + } } public static func isHeadingAvailable() -> Bool { @@ -232,7 +234,7 @@ public final class LinuxLocationManager: LocationManager { private func locationUpdated(_ path: String) { guard updating || oneShot else { return } - client.bus.properties(path, GeoClue.location) { [weak self] result in + client.bus.location(path) { [weak self] result in guard let self, self.updating || self.oneShot else { return } switch result { case .success(let properties): @@ -350,6 +352,14 @@ final class LocationAuthority { /// A request found GeoClue missing or the desktop's switch off. private(set) var servicesOff = false + /// Whether GeoClue answered with an accuracy above none when last + /// asked, or let a client start since; `nil` before either. + private(set) var servicesEnabled: Bool? + + /// Waiting for `checkServices`'s question, which is asked once at a + /// time. + private var servicesWaiting: [(Bool) -> Void] = [] + /// The answer, or `denied` while a request found location off. var status: LocationAuthorization { answer == .notDetermined && servicesOff ? .denied : answer @@ -375,11 +385,15 @@ final class LocationAuthority { self.answer = answer servicesOff = false } + if answer != .denied { + servicesEnabled = true + } } /// A request found location off: `denied` until GeoClue answers. func servicesUnavailable() { change { servicesOff = true } + servicesEnabled = false } private func change(_ body: () -> Void) { @@ -414,14 +428,27 @@ final class LocationAuthority { } } - /// Whether GeoClue answers with an accuracy above none. - static func servicesEnabled(_ bus: any GeoClueBus) -> Bool { - switch bus.propertyAndWait(GeoClue.managerPath, GeoClue.manager, "AvailableAccuracyLevel") { - case .success(let level): - return (level.int64Value ?? 0) > 0 - case .failure(let error): - HostLog.debug("location: GeoClue isn't available: \(error)") - return false + /// Asks GeoClue whether it has an accuracy above none, and keeps the + /// answer in `servicesEnabled`. On the main loop, once GeoClue answers. + func checkServices(_ bus: any GeoClueBus, _ completion: @escaping (Bool) -> Void = { _ in }) { + servicesWaiting.append(completion) + guard servicesWaiting.count == 1 else { return } + bus.availableAccuracy { [weak self] result in + let enabled: Bool + switch result { + case .success(let level): + enabled = level > GeoClue.Accuracy.none.rawValue + case .failure(let error): + HostLog.debug("location: GeoClue isn't available: \(error)") + enabled = false + } + guard let self else { return } + servicesEnabled = enabled + let waiting = servicesWaiting + servicesWaiting = [] + for completion in waiting { + completion(enabled) + } } } } From d3333a671e4b73b850fe37e52a3891d4dba96006 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 3 Dec 2026 03:28:12 -0500 Subject: [PATCH 17/20] Registered LocationServicesCallback, and never waited for GeoClue in Permissions --- Sources/LinuxLocation/LinuxLocation.swift | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/Sources/LinuxLocation/LinuxLocation.swift b/Sources/LinuxLocation/LinuxLocation.swift index d499da0..d2a5c1e 100644 --- a/Sources/LinuxLocation/LinuxLocation.swift +++ b/Sources/LinuxLocation/LinuxLocation.swift @@ -10,6 +10,7 @@ public enum LinuxLocation: HostModule { [ LocationManagerProxy.descriptor, LocationManagerDelegateProxy.descriptor, + LocationServicesCallbackProxy.descriptor, LocationProxy.descriptor, HeadingProxy.descriptor, ] @@ -18,6 +19,7 @@ public enum LinuxLocation: HostModule { public static func register(in registrar: some ContractRegistrar) { LocationManagerProxy.register(LinuxLocationManager.self, in: registrar) LocationManagerDelegateProxy.registerInterface(in: registrar) + LocationServicesCallbackProxy.registerInterface(in: registrar) LocationProxy.register(LinuxLocationFix.self, in: registrar) HeadingProxy.register(LinuxHeading.self, in: registrar) } @@ -44,7 +46,14 @@ final class LocationPermission: PermissionProvider { case .restricted: return .restricted case .notDetermined: - return LocationAuthority.servicesEnabled(LinuxLocationManager.bus) ? .notDetermined : .unavailable + // Never waits for GeoClue: until it has answered, location may + // be there, so it's `notDetermined`, and GeoClue is asked for + // next time. + let authority = LocationAuthority.shared + if authority.servicesEnabled == nil { + authority.checkServices(LinuxLocationManager.bus) + } + return authority.servicesEnabled == false ? .unavailable : .notDetermined } } From 0bc8ad107ad6c9b2ac5a2b7cb80670997f20023a Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 3 Dec 2026 03:28:12 -0500 Subject: [PATCH 18/20] Played GeoClue through GeoClueBus's named calls --- Tests/LinuxLocationTests/FakeGeoClue.swift | 68 ++++++++++++++++------ 1 file changed, 51 insertions(+), 17 deletions(-) diff --git a/Tests/LinuxLocationTests/FakeGeoClue.swift b/Tests/LinuxLocationTests/FakeGeoClue.swift index cf1954a..50d1f75 100644 --- a/Tests/LinuxLocationTests/FakeGeoClue.swift +++ b/Tests/LinuxLocationTests/FakeGeoClue.swift @@ -43,7 +43,7 @@ final class FakeGeoClue: GeoClueBus { private(set) var locations: [String: [String: DBusMessageArgument]] = [:] - private var subscribers: [UInt64: (path: String, member: String, handler: ([DBusMessageArgument]) -> Void)] = [:] + private var subscribers: [UInt64: (path: String, handler: (String) -> Void)] = [:] private var nextClient = 0 @@ -71,13 +71,42 @@ final class FakeGeoClue: GeoClueBus { // MARK: GeoClueBus - func call(_ path: String, _ interface: String, _ method: String, _ arguments: [DBusMessageArgument], - reply: @escaping (Result<[DBusMessageArgument], BusError>) -> Void) { - calls.append(Call(path: path, method: method, arguments: arguments)) - let result = answer(path, method, arguments) + func createClient(reply: @escaping (Result) -> Void) { + manager("CreateClient", [], reply) + } + + func getClient(reply: @escaping (Result) -> Void) { + manager("GetClient", [], reply) + } + + func deleteClient(_ client: String) { + manager("DeleteClient", [.path(client)]) { _ in } + } + + func start(_ client: String, reply: @escaping (Result) -> Void) { + call(client, "Start", reply) + } + + func stop(_ client: String, reply: @escaping (Result) -> Void) { + call(client, "Stop", reply) + } + + /// A manager's method, answering a path or nothing. + private func manager(_ method: String, _ arguments: [DBusMessageArgument], _ reply: @escaping (Result) -> Void) { + calls.append(Call(path: Self.managerPath, method: method, arguments: arguments)) + let result = answer(Self.managerPath, method, arguments).map { $0.first?.text ?? "" } + MainLoop.shared.post { reply(result) } + } + + /// A client's method, answering nothing. + private func call(_ client: String, _ method: String, _ reply: @escaping (Result) -> Void) { + calls.append(Call(path: client, method: method, arguments: [])) + let result = answer(client, method, []).map { _ in } MainLoop.shared.post { reply(result) } } + static let managerPath = "/org/freedesktop/GeoClue2/Manager" + private func answer(_ path: String, _ method: String, _ arguments: [DBusMessageArgument]) -> Result<[DBusMessageArgument], BusError> { guard available else { return .failure(Self.missing) } switch method { @@ -118,13 +147,13 @@ final class FakeGeoClue: GeoClueBus { BusError(name: "org.freedesktop.DBus.Error.UnknownObject", message: path) } - func propertyAndWait(_ path: String, _ interface: String, _ name: String) -> Result { - calls.append(Call(path: path, method: "Get", arguments: [.string(name)])) - guard available else { return .failure(Self.missing) } - return .success(.uint32(availableAccuracy)) + func availableAccuracy(reply: @escaping (Result) -> Void) { + calls.append(Call(path: Self.managerPath, method: "Get", arguments: [.string("AvailableAccuracyLevel")])) + let result: Result = available ? .success(availableAccuracy) : .failure(Self.missing) + MainLoop.shared.post { reply(result) } } - func properties(_ path: String, _ interface: String, reply: @escaping (Result<[String: DBusMessageArgument], BusError>) -> Void) { + func location(_ path: String, reply: @escaping (Result<[String: DBusMessageArgument], BusError>) -> Void) { let result: Result<[String: DBusMessageArgument], BusError> if !available { result = .failure(Self.missing) @@ -136,8 +165,14 @@ final class FakeGeoClue: GeoClueBus { MainLoop.shared.post { reply(result) } } - func setProperty(_ path: String, _ interface: String, _ name: String, _ value: DBusMessageArgument, - reply: @escaping (Result) -> Void) { + func set(_ path: String, _ setting: GeoClue.Setting, reply: @escaping (Result) -> Void) { + let name = setting.name + let value: DBusMessageArgument = switch setting { + case .desktopID(let id): .string(id) + case .accuracy(let accuracy): .uint32(accuracy.rawValue) + case .distanceThreshold(let meters): .uint32(meters) + case .timeThreshold(let seconds): .uint32(seconds) + } calls.append(Call(path: path, method: "Set", arguments: [.string(name), value])) let result: Result if !available { @@ -153,9 +188,9 @@ final class FakeGeoClue: GeoClueBus { MainLoop.shared.post { reply(result) } } - func subscribe(_ path: String, _ interface: String, _ member: String, _ handler: @escaping ([DBusMessageArgument]) -> Void) -> BusSubscription { + func subscribeToLocations(_ client: String, _ handler: @escaping (String) -> Void) -> BusSubscription { nextSubscriber += 1 - subscribers[nextSubscriber] = (path, member, handler) + subscribers[nextSubscriber] = (client, handler) return BusSubscription(id: nextSubscriber) } @@ -175,7 +210,6 @@ final class FakeGeoClue: GeoClueBus { latitude: Double, longitude: Double, accuracy: Double = 20, altitude: Double = GeoClue.unknownAltitude, speed: Double = -1, heading: Double = -1, timestamp: (UInt64, UInt64) = (1_700_000_000, 0) ) { - let old = nextLocation == 0 ? "/" : "/org/freedesktop/GeoClue2/Location/\(nextLocation)" nextLocation += 1 let path = "/org/freedesktop/GeoClue2/Location/\(nextLocation)" locations[path] = [ @@ -184,8 +218,8 @@ final class FakeGeoClue: GeoClueBus { "Description": .string(""), "Timestamp": .structure([.uint64(timestamp.0), .uint64(timestamp.1)]), ] for client in active.sorted() { - for subscriber in subscribers.values where subscriber.path == client && subscriber.member == "LocationUpdated" { - subscriber.handler([.path(old), .path(path)]) + for subscriber in subscribers.values where subscriber.path == client { + subscriber.handler(path) } } } From 3be73a22c73da50cb19dd749e84d4f36a02cad65 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 3 Dec 2026 03:28:12 -0500 Subject: [PATCH 19/20] Tested the location services answer arriving once, after GeoClue --- .../LinuxLocationTests.swift | 32 ++++++++++++++++--- 1 file changed, 27 insertions(+), 5 deletions(-) diff --git a/Tests/LinuxLocationTests/LinuxLocationTests.swift b/Tests/LinuxLocationTests/LinuxLocationTests.swift index caec69f..d76a56d 100644 --- a/Tests/LinuxLocationTests/LinuxLocationTests.swift +++ b/Tests/LinuxLocationTests/LinuxLocationTests.swift @@ -34,6 +34,16 @@ final class LocationLog: LocationManagerDelegate { } } +/// Records `isLocationServicesEnabled(_:)`'s answers. +final class ServicesAnswers: LocationServicesCallback { + + var received: [Bool] = [] + + func didGetServicesEnabled(_ enabled: Bool) { + received.append(enabled) + } +} + /// Records what a module registers. final class Registrar: ContractRegistrar { @@ -63,6 +73,16 @@ let client = "/org/freedesktop/GeoClue2/Client/1" return geoClue } + /// `isLocationServicesEnabled(_:)`'s answers: none before GeoClue's, + /// then exactly one, on the main loop. + func servicesEnabled() -> [Bool] { + let answers = ServicesAnswers() + LinuxLocationManager.isLocationServicesEnabled(answers) + #expect(answers.received.isEmpty, "never answered before GeoClue has") + MainLoop.shared.drain() + return answers.received + } + func manager(_ geoClue: FakeGeoClue) -> (LinuxLocationManager, LocationLog) { let log = LocationLog() let manager = LinuxLocationManager.make(log) @@ -79,7 +99,7 @@ let client = "/org/freedesktop/GeoClue2/Client/1" #expect(geoClue.calls.isEmpty, "no client until one's needed") #expect(LinuxLocationManager.authorizationStatus() == LocationAuthorization.notDetermined.rawValue) #expect(LinuxLocationManager.accuracyAuthorization() == LocationAccuracyAuthorization.full.rawValue) - #expect(LinuxLocationManager.isLocationServicesEnabled()) + #expect(servicesEnabled() == [true]) #expect(geoClue.log == ["Get AvailableAccuracyLevel"]) #expect(!LinuxLocationManager.isHeadingAvailable()) } @@ -340,8 +360,10 @@ let client = "/org/freedesktop/GeoClue2/Client/1" @Test func withoutGeoClue() { let geoClue = self.geoClue() geoClue.available = false - #expect(!LinuxLocationManager.isLocationServicesEnabled()) - #expect(LocationPermission().status() == .unavailable) + #expect(LocationPermission().status() == .notDetermined, "not waiting for GeoClue") + MainLoop.shared.drain() + #expect(LocationPermission().status() == .unavailable, "once it has answered") + #expect(servicesEnabled() == [false]) let (manager, log) = self.manager(geoClue) manager.startUpdatingLocation() MainLoop.shared.drain() @@ -369,7 +391,7 @@ let client = "/org/freedesktop/GeoClue2/Client/1" // GeoClue with no sources has nothing to give. geoClue.available = true geoClue.availableAccuracy = 0 - #expect(!LinuxLocationManager.isLocationServicesEnabled()) + #expect(servicesEnabled() == [false]) } @Test func theDesktopsSwitchOff() { @@ -413,7 +435,7 @@ let client = "/org/freedesktop/GeoClue2/Client/1" @Test func moduleRegistersTheContracts() { let names = [ "org.pureswift.location.LocationManager", "org.pureswift.location.LocationManagerDelegate", - "org.pureswift.location.Location", "org.pureswift.location.Heading", + "org.pureswift.location.ServicesCallback", "org.pureswift.location.Location", "org.pureswift.location.Heading", ] #expect(LinuxLocation.contracts.map(\.name) == names) let registrar = Registrar() From 290c9554672a0048c423308fb52dea52fdc5c2a2 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 3 Dec 2026 03:28:12 -0500 Subject: [PATCH 20/20] Documented D-Bus answers that never wait, and the generated GeoClue2 client --- Documentation/Plan.md | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/Documentation/Plan.md b/Documentation/Plan.md index 833a9e5..5d7b982 100644 --- a/Documentation/Plan.md +++ b/Documentation/Plan.md @@ -451,8 +451,9 @@ asked of D-Bus: is the orientation: `normal` portrait (the device's natural orientation), `bottom-up` upside down, `left-up` (the top to the right) `landscapeRight`, `right-up` `landscapeLeft`; it has no face up or down. - Enabling proximity asks whether it has a sensor, waiting for the answer, - and claims it if so; `ProximityNear` is the state. Each change from + Enabling proximity turns it on at once, asks whether there's a sensor, + and claims it if so, or turns it off again if not; nothing waits for the + proxy. `ProximityNear` is the state. Each change from `PropertiesChanged` reaches the delegate once, and disabling releases the sensor. Without iio-sensor-proxy, orientation reads as unknown and proximity monitoring stays off. @@ -460,8 +461,11 @@ asked of D-Bus: ## 11. Location `LinuxLocation` is the Location contracts (AppRuntime's `Location.md`) over -GeoClue 2, on the system bus. Each `LocationManager` has a GeoClue client -of its own, made when it first needs one: +GeoClue 2, on the system bus, through PureSwift/DBus's generated `GeoClue2` +client (`GeoClue2.Manager`, `.Client`, `.Location`) run with `Bus.perform`; +`GeoClueBus` names what it asks, so tests put a fake in its place. Each +`LocationManager` has a GeoClue client of its own, made when it first +needs one: | | GeoClue | |---|---| @@ -472,7 +476,7 @@ of its own, made when it first needs one: | `startUpdatingLocation`, `requestLocation` | `Start`; `requestLocation` stops again after one location, unless updates are on | | `stopUpdatingLocation` | `Stop` | | Locations | `LocationUpdated(o old, o new)`, then the new `Location` object's `Latitude`, `Longitude`, `Accuracy`, `Altitude` (`-G_MAXDOUBLE` unknown: `nan`), `Speed` and `Heading` (`-1` unknown), and `Timestamp` (`(tt)`, seconds and microseconds). Vertical, speed and course accuracy are unknown, and so is whether it's simulated (`-1`) | -| `isLocationServicesEnabled` | GeoClue answers `Manager.AvailableAccuracyLevel` within two seconds (it's started on demand), above none | +| `isLocationServicesEnabled(_:)` | GeoClue's `Manager.AvailableAccuracyLevel` is above none, answered once GeoClue has (it's started on demand). The answer is kept for `Permissions`, which says `notDetermined` until there is one | | Heading | Not available: Linux has no compass service. `startUpdatingHeading` fails with `headingFailure` | - **Authorization** is GeoClue's agent's. When a client starts, GeoClue @@ -538,9 +542,11 @@ their element types. added to the bus once however many subscriptions share it, and removed with the last. Signals are told apart again on this side by path, interface, member and `arg0`; a well-known sender is the bus's to check. -- `callAndWait` and `propertyAndWait` wait on the calling thread for a - contract that answers at once; replies don't need the main loop, so the - main thread can wait. +- `perform` runs an `async` body with the connection, for PureSwift/DBus's + generated service clients, and posts its value or error to the main + loop. Nothing waits on the main thread: the contracts that used to + answer at once (NFC availability, whether location services are on) now + answer through callbacks. - If the connection closes, waiting calls fail with `Disconnected`, and subscribers to `MatchRule.disconnected` get the local `org.freedesktop.DBus.Local.Disconnected` signal; the next request @@ -660,7 +666,7 @@ ISO 15693 protocol is `ISO-15693`, and there's no `TagFound` signal). | | neard | |---|---| -| `availability` | No neard, or no adapter: `unsupported`; adapters all off (`Powered`): `disabled`. Asked with `GetManagedObjects`, waited for | +| `availability` | No neard, or no adapter: `unsupported`; adapters all off (`Powered`): `disabled`. Asked with `GetManagedObjects`; answered through the callback once neard has | | `begin` | The first adapter that's on: `StartPollLoop("Initiator")`, then `didBecomeActive`. A tag already in the field is found as it is, since neard won't poll over one. One session at a time in the process: neard has one poll loop per adapter | | A tag | `InterfacesAdded` of `org.neard.Tag` under the adapter, then neard's own signal that it read the records, `org.neard.Tag.PropertyChanged("Records", …)`, which can come first; then `didDetect`, with the records as they are then. A tag with no NDEF gets no such signal, so it's found after a second without one. A kind not asked for is left out | | Polling | neard stops polling when it finds a tag, and doesn't start again, with a tag in the field or after one leaves, so `restartPolling`, and a tag left out, poll again once the field is empty |