Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
2be7d28
Handed work the bus connection once it's made
colemancda Dec 3, 2026
b1521b6
Added Bus.perform for generated clients, and removed the calls that w…
colemancda Dec 3, 2026
2d58e7a
Tested perform, and answered calls through the main loop instead of w…
colemancda Dec 3, 2026
41d64cc
Removed objectsAndWait from NeardBus
colemancda Dec 3, 2026
86ee0b8
Answered NFC availability once neard has
colemancda Dec 3, 2026
78b46ae
Listed and registered NFCAvailabilityCallback
colemancda Dec 3, 2026
650fc18
Recorded availability answers, and dropped the fake's objectsAndWait
colemancda Dec 3, 2026
9cbefaf
Tested availability answered once, after neard
colemancda Dec 3, 2026
5aaf066
Removed propertyAndWait from SensorProxyBus
colemancda Dec 3, 2026
7954d20
Turned proximity monitoring off once the proxy says there's no sensor…
colemancda Dec 3, 2026
879936b
Tested proximity turning itself off without a sensor
colemancda Dec 3, 2026
13d67e0
Left proximity to the sensor proxy tests
colemancda Dec 3, 2026
60f11d4
Depended on DBus 0.3.2 and its GeoClue2 client
colemancda Dec 3, 2026
ce75b51
Named what Location asks GeoClue, over DBus's generated GeoClue2 client
colemancda Dec 3, 2026
caa6c85
Made GeoClue clients through GeoClueBus's named calls
colemancda Dec 3, 2026
985997f
Answered whether location services are on once GeoClue has, and kept …
colemancda Dec 3, 2026
d3333a6
Registered LocationServicesCallback, and never waited for GeoClue in …
colemancda Dec 3, 2026
0bc8ad1
Played GeoClue through GeoClueBus's named calls
colemancda Dec 3, 2026
3be73a2
Tested the location services answer arriving once, after GeoClue
colemancda Dec 3, 2026
290c955
Documented D-Bus answers that never wait, and the generated GeoClue2 …
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
24 changes: 15 additions & 9 deletions Documentation/Plan.md
Original file line number Diff line number Diff line change
Expand Up @@ -451,17 +451,21 @@ 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.

## 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 |
|---|---|
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 |
Expand Down
9 changes: 5 additions & 4 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down Expand Up @@ -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
),

Expand Down
84 changes: 29 additions & 55 deletions Sources/LinuxDBus/Bus.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import DBus
import Dispatch
import Foundation
import LinuxHost

Expand Down Expand Up @@ -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,
Expand All @@ -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"
Expand All @@ -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<DBusMessageArgument, BusError> {
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(
Expand Down Expand Up @@ -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<Value: Sendable>(
_ body: @escaping @Sendable (DBusConnection) async throws -> Value,
reply: @escaping (Result<Value, BusError>) -> Void
) {
let loop = self.loop
link.withConnection { connection in
Task {
let result: Result<Value, BusError>
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) {
Expand Down
44 changes: 42 additions & 2 deletions Sources/LinuxDBus/BusLink.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<DBusConnection, BusError>) -> Void

init(connect: @escaping @Sendable () async throws -> DBusConnection) {
self.connect = connect
}
Expand Down Expand Up @@ -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() {
Expand Down Expand Up @@ -126,7 +154,7 @@ final class BusLink: @unchecked Sendable {
}
}
}
open(continuation)
open(continuation, connection)
handler(.connected)

for await _ in closing { }
Expand All @@ -136,25 +164,37 @@ final class BusLink: @unchecked Sendable {
}

/// Sends what waited, and from now on sends at once.
private func open(_ continuation: AsyncStream<Outgoing>.Continuation) {
private func open(_ continuation: AsyncStream<Outgoing>.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))
}

Expand Down
16 changes: 11 additions & 5 deletions Sources/LinuxDevice/LinuxDevice.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand All @@ -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
Expand All @@ -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
Expand Down
7 changes: 0 additions & 7 deletions Sources/LinuxDevice/SensorProxy.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<DBusMessageArgument, BusError>

/// Calls `handler` with the properties each `PropertiesChanged` signal
/// changes.
func subscribeToChanges(_ handler: @escaping ([String: DBusMessageArgument]) -> Void) -> BusSubscription
Expand Down Expand Up @@ -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<DBusMessageArgument, BusError> {
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)
Expand Down
Loading
Loading