Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 1 addition & 1 deletion Documentation/Packager.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ again at every launch, since it may have changed since.
| … at the same version or later | warning: methods added later resolve as absent |
| The bundle has `_CodeSignature/CodeResources`, and it matches every file's SHA-256 | error: the runner loads no library its bundle doesn't vouch for |
| `lib/<target>/libapp.so` is there, and is a shared library for the target's machine and word size | error |
| A declared capability this host has no contract for (motion, NFC, …) | warning |
| A declared capability this host has no contract for (notifications, …) | warning |

`guest.py` has checked the rest of the library when it built it: that it
names no other library, binds as it loads, exports the three guest exports
Expand Down
87 changes: 77 additions & 10 deletions Documentation/Plan.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ contracts. D-Bus is PureSwift/DBus, in Swift, without libdbus.
| arm64 and x86_64 Linux with glibc (Debian 13, Ubuntu 24.04+) | armv7, musl |
| Native slices, loaded by the runner | `App.wasm`, in an engine in the runner; wasm2c for a target a bundle lacks, before it's installed |
| Wayland and X11 through SDL3; a headless driver for tests | Multiple windows |
| `Renderer`, `BluetoothCentral` and friends, GL surfaces, web views, files, settings, model stores, date and number formatting, HTTP, the device, location, documents, motion, the built-ins | NFC (neard) |
| `Renderer`, `BluetoothCentral` and friends, GL surfaces, web views, files, settings, model stores, date and number formatting, HTTP, the device, location, documents, motion, NFC tags, the built-ins | |

## 2. Process model

Expand Down Expand Up @@ -104,8 +104,9 @@ timers for `schedule`.
| `LinuxLocation` | `LocationManager`, `Location` and `Heading` over GeoClue 2 (§11) |
| `LinuxDocuments` | `Documents`: AppRuntime's `HostDocuments` with the desktop portal's file chooser, and bookmarks (§12) |
| `LinuxMotion` | `MotionManager` and `Altimeter` over the kernel's IIO sensors in sysfs, and an unavailable `Pedometer` and `ActivityRecognizer` (§13) |
| `LinuxNFC` | `NFCReader`, `NFCTag`, `NDEFMessage` and `NDEFRecord` over neard (§14) |
| `LinuxHostApp` | `main`: reads the app's keys, starts the host, and runs Cacao's SDL loop with one window showing the guest's first renderer |
| `LinuxPackager`, `linux-app` | The packager (§15, [Packager.md](Packager.md)) |
| `LinuxPackager`, `linux-app` | The packager (§16, [Packager.md](Packager.md)) |

The package depends on AppRuntime without its `GuestExports` trait, like
DarwinAppRuntime, so the slice's `rt_dispatch` and `rt_finalize` are the
Expand Down Expand Up @@ -513,7 +514,7 @@ of its own, made when it first needs one:
### 11.1 D-Bus

`LinuxDBus` is what Bluetooth, Location, the device's orientation and
proximity (iio-sensor-proxy) and the desktop portal, and later NFC (neard),
proximity (iio-sensor-proxy), NFC (neard) and the desktop portal
share. `Bus.system`
and `Bus.session` are one connection each per process, made on first use
through PureSwift/DBus, which speaks D-Bus in Swift, without libdbus; its
Expand Down Expand Up @@ -641,7 +642,60 @@ polls. Reading them needs no permission.
noticed until it's started again, and the magnetometer isn't calibrated.
None of it has run on real sensors.

## 14. Testing
## 14. NFC

`LinuxNFC` is the NFC contracts (AppRuntime's `NFC.md`) over neard, the
Linux NFC daemon (`org.neard` on the system bus), which drives the
kernel's NFC adapters: the reader role, reading and writing NDEF. neard
publishes its adapters (`/org/neard/nfc0`), the tags in their field
(`…/tag0`) and each tag's records (`…/tag0/record0`) through
`org.freedesktop.DBus.ObjectManager` at `/`. `NeardBus` abstracts the
connection, so the contract is tested with a fake neard. What follows is
from neard's source, not its documentation, which differs in places (the
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 |
| `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 |
| `connect` | neard keeps a tag it found connected: the tag in the field |
| `type` | `Protocol`: `ISO-DEP` `iso7816`, `MIFARE` `miFare` (`Jewel`, NFC Forum Type 1, is `unknown`, and also ISO 14443), `Felica` `feliCa`, `ISO-15693` `iso15693`; all `ndef` in an NDEF session |
| `identifier` | `Uid`; empty in an NDEF session, as on iOS |
| `queryNDEFStatus` | `ReadOnly`: `readOnly` or `readWrite`. neard doesn't say how much a tag holds, so the capacity is 0 |
| `readNDEF` | The tag's records (below); nil for none |
| `writeNDEF` | `Tag.Write(a{sv})`: one record's fields, or each record's under `Records`. neard reads the tag again after a write, and a read after it waits for that (or a second) |
| `writeLock`, `transceive` | neard has no way to lock a tag or send it a raw command: `unsupported` (an NDEF session's `transceive` is `notAvailableInNDEFSession`) |
| `invalidate` | `StopPollLoop`; the delegate told once, on the next turn |

- **Records.** neard parses a tag's message itself and publishes each
record it knows as properties, not bytes, and writes only what it can
make from such properties. So reading gives text (re-encoded as UTF-8),
URIs, MIME types with their payload, Smart Posters (as an `Sp` record
holding the URI and the title) and Android application records
(`android.com:pkg`), and leaves out handovers. Writing takes text, URI
and MIME records, without identifiers, and refuses anything else, an
empty message, and the Wi-Fi type (`application/vnd.wfa.wsc`), for which
neard makes a record of its own, with `invalidParameter`.
- **Operations** run one at a time per tag, in order, each with one
callback on the next turn. A tag leaving (`InterfacesRemoved`) fails what
waits with `tagConnectionLost`; one from an earlier detection, or not
connected, is `tagNotConnected`.
- **Errors.** neard answers most failures as `org.neard.Error.Failed`
with `strerror`'s text: busy is `systemBusy`, no such device `disabled`.
A write it can't make or that fails is `InvalidArguments`, so a failed
write is `unknown`, and logged; `PermissionDenied` is `tagReadOnly`,
`InProgress` `systemBusy`. The adapter turned off or gone, or the bus
closing, ends the session.
- **`nfc`** asks for nothing: NFC has no prompt on any platform.
- **Not yet**: raw commands. The kernel has them (`AF_NFC` raw sockets),
but neard holds the tag it found, so they'd need neard stopped or a
version of it that passes them on. Card emulation (neard's
`StartEmulation`) and peer-to-peer aren't part of the contract. It
hasn't run against real neard and an adapter.

## 15. Testing

- `LinuxUI`: DarwinUI's tests, on Cacao (§5).
- `LinuxBluetooth`: the contract against a fake `BlueZBus` that plays
Expand Down Expand Up @@ -712,6 +766,18 @@ polls. Reading them needs no permission.
kept; the files the app is opened with. The packager accepts the
contracts with `userFiles`, and writes `MimeType=`. It hasn't run
against a real portal.
- `LinuxNFC`: the contract against a fake `NeardBus` that plays neard's
adapter, tags, records and signals, and answers on the main loop:
availability; a session that finds a tag, reads it and ends; the
records' signal before the tag; a tag without NDEF; kinds not asked for,
and polling again once the field is empty; an NDEF session; a tag already
in the field; sessions that can't begin, one at a time, and invalidating
before neard answers; the adapter turned off or gone, and the bus
closing; operations before a connection, and a tag leaving; writing, and
reading after neard read the tag again, or gave up; what neard can't
write, a read-only tag, locking and raw commands. neard's records as NDEF
and back, and the NDEF encoding. The packager accepts the contracts with
`nfc`.
- End to end: AppRuntime's `ExampleUI`, `ExampleGL` and `ExampleModel`
bundles, their `linux-arm64` `libapp.so` loaded by `linux-app-host` and
run headless with SDL's `offscreen` driver, each first frame saved with
Expand All @@ -724,22 +790,23 @@ polls. Reading them needs no permission.
`bluetoothd`. Real GeoClue needs a session with an agent, or the app
allowed in `geoclue.conf`.

## 15. Phases
## 16. Phases

1. **Host runtime and player**: `LinuxHost`, `LinuxUI`, `LinuxBluetooth`,
`LinuxHostApp`; `ExampleUI` runs in Docker.
2. **Packager**: `linux-app` checks an app and installs it: its bundle
thinned to the target's `libapp.so`, a `.desktop` file and icon, for
the runner; later Flatpak and AppImage, whose manifests carry the
capabilities (`--system-talk-name=org.bluez` for `bluetooth`).
3. **More contracts**: NFC (neard). Formatting and HTTP are done:
AppRuntime's `RuntimeFormatting` and `RuntimeNetworking` (§3), and so
are the device (§10), location (§11), over GeoClue2, documents (§12),
over the desktop portal, and motion (§13), over IIO.
3. **More contracts**: formatting and HTTP are done: AppRuntime's
`RuntimeFormatting` and `RuntimeNetworking` (§3), and so are the
device (§10), location (§11), over GeoClue2, documents (§12), over
the desktop portal, motion (§13), over IIO, and NFC (§14), over
neard.
4. **Player**: what DarwinUI and Cacao add: Cacao's AT-SPI bridge, input
replay for end-to-end tests.

## 16. Open questions
## 17. Open questions

- **Permissions.** Desktop Linux has no prompts for Bluetooth; Flatpak's
portals cover location and the camera. `Permissions.request` answers from
Expand Down
17 changes: 15 additions & 2 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ let package = Package(
.library(name: "LinuxDBus", targets: ["LinuxDBus"]),
.library(name: "LinuxLocation", targets: ["LinuxLocation"]),
.library(name: "LinuxMotion", targets: ["LinuxMotion"]),
.library(name: "LinuxNFC", targets: ["LinuxNFC"]),
.library(name: "LinuxHostApp", targets: ["LinuxHostApp"]),
.executable(name: "linux-app-host", targets: ["LinuxAppHost"]),
.executable(name: "linux-app", targets: ["LinuxAppTool"]),
Expand Down Expand Up @@ -210,14 +211,24 @@ let package = Package(
swiftSettings: host
),

// MARK: - NFC

// neard on the system bus.
.target(
name: "LinuxNFC",
dependencies: ["LinuxHost", "LinuxDBus", runtime("DynamicNFC"), runtime("DynamicRuntime"), runtime("RuntimeNative"),
.product(name: "DBus", package: "DBus")],
swiftSettings: host
),

// MARK: - App

// What the runner's process supplies that libc may not
// (arc4random_buf), and prctl, which Swift can't call.
.target(name: "CLinuxHost"),
.target(
name: "LinuxHostApp",
dependencies: ["LinuxHost", "LinuxUI", "LinuxBluetooth", "LinuxGraphics", "LinuxWebKit", "LinuxCoreModel", "LinuxDevice", "LinuxLocation", "LinuxDocuments", "LinuxMotion", "CLinuxHost", runtime("CRuntime"), runtime("RuntimeFormatting"), runtime("RuntimeNetworking"),
dependencies: ["LinuxHost", "LinuxUI", "LinuxBluetooth", "LinuxGraphics", "LinuxWebKit", "LinuxCoreModel", "LinuxDevice", "LinuxLocation", "LinuxDocuments", "LinuxMotion", "LinuxNFC", "CLinuxHost", runtime("CRuntime"), runtime("RuntimeFormatting"), runtime("RuntimeNetworking"),
runtime("DynamicGraphics"), .product(name: "CacaoSDL", package: "Cacao")],
swiftSettings: host
),
Expand All @@ -241,7 +252,7 @@ let package = Package(
// doesn't build Cacao.
.target(
name: "LinuxPackager",
dependencies: ["LinuxHost", "LinuxBluetooth", "LinuxGraphics", "LinuxWebKit", "LinuxCoreModel", "LinuxDevice", "LinuxLocation", "LinuxDocuments", "LinuxMotion", runtime("RuntimeFormatting"), runtime("RuntimeNetworking"), runtime("DynamicUI"),
dependencies: ["LinuxHost", "LinuxBluetooth", "LinuxGraphics", "LinuxWebKit", "LinuxCoreModel", "LinuxDevice", "LinuxLocation", "LinuxDocuments", "LinuxMotion", "LinuxNFC", runtime("RuntimeFormatting"), runtime("RuntimeNetworking"), runtime("DynamicUI"),
.product(name: "Crypto", package: "swift-crypto")]
),
.executableTarget(
Expand Down Expand Up @@ -271,6 +282,8 @@ let package = Package(
.testTarget(name: "LinuxDBusTests", dependencies: ["LinuxDBus", .product(name: "DBus", package: "DBus")], swiftSettings: host),
.testTarget(name: "LinuxLocationTests", dependencies: ["LinuxLocation", "LinuxDBus", runtime("DynamicLocation"), .product(name: "DBus", package: "DBus")],
swiftSettings: host),
.testTarget(name: "LinuxNFCTests", dependencies: ["LinuxNFC", "LinuxDBus", runtime("DynamicNFC"), .product(name: "DBus", package: "DBus")],
swiftSettings: host),
.testTarget(name: "LinuxDocumentsTests", dependencies: ["LinuxDocuments", "LinuxDBus", runtime("DynamicDocuments"), runtime("RuntimeDocuments"),
runtime("DynamicFiles"), runtime("RuntimeHost"), runtime("RuntimeNative"),
.product(name: "DBus", package: "DBus")],
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ added to its database between launches:
| `LinuxLocation` | `LocationManager`: the device's location from GeoClue 2 on the system bus, which its agent authorizes by the app's desktop ID; no heading ([plan](Documentation/Plan.md) §11) |
| `LinuxDocuments` | `Documents`: AppRuntime's `HostDocuments` with the desktop portal's file chooser on the session bus, for opening, folders and saving, and bookmarks in the app's data ([plan](Documentation/Plan.md) §12) |
| `LinuxMotion` | Motion: the accelerometer, gyroscope, magnetometer and barometer from the kernel's IIO sensors in sysfs, device motion fused from them, and a pedometer and activity recognizer that are unavailable ([plan](Documentation/Plan.md) §13) |
| `LinuxNFC` | `NFCReader`, `NFCTag`, `NDEFMessage`, `NDEFRecord`: reading and writing NDEF tags through neard on the system bus; no raw commands or locking ([plan](Documentation/Plan.md) §14) |
| `LinuxHostApp`, `linux-app-host` | The app's `main`: the host, and Cacao's window and loop. It also registers AppRuntime's `RuntimeFormatting`, dates and numbers over Swift Foundation, and `RuntimeNetworking`, HTTP over `URLSession` and libcurl ([plan](Documentation/Plan.md) §3) |
| `LinuxPackager`, `linux-app` | The packager: validation, thinning a bundle to one target, the install tree, PortMaster ports |

Expand Down
5 changes: 3 additions & 2 deletions Sources/LinuxHostApp/HostApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import LinuxDocuments
import LinuxGraphics
import LinuxLocation
import LinuxMotion
import LinuxNFC
import LinuxWebKit
import LinuxUI
import RuntimeFormatting
Expand Down Expand Up @@ -38,11 +39,11 @@ public enum HostApp {
/// Bluetooth, GL surfaces and web pages, which the player shows, the
/// app's files, settings and model stores, AppRuntime's date and number
/// formatting and its HTTP client over Swift Foundation, the device,
/// location, the user's documents, and motion sensors.
/// location, the user's documents, motion sensors and NFC tags.
public static let modules: [any HostModule.Type] = [
DarwinUI.self, LinuxBluetooth.self, LinuxGraphics.self, LinuxWebKit.self, LinuxFiles.self, LinuxDefaults.self,
LinuxModelStore.self, HostFormattingModule.self, HostNetworkingModule.self, LinuxDeviceModule.self, LinuxLocation.self,
LinuxDocuments.self, LinuxMotion.self,
LinuxDocuments.self, LinuxMotion.self, LinuxNFC.self,
]

/// Points AppRuntime's modules at this host: networking's callbacks,
Expand Down
54 changes: 54 additions & 0 deletions Sources/LinuxNFC/LinuxNFC.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import DynamicNFC
import DynamicRuntime
import LinuxHost
import RuntimeNative

/// The NFC contracts over neard (`Plan.md` §14): the reader role, reading
/// and writing NDEF. Main loop only.
public enum LinuxNFC: HostModule {

public static var contracts: [ContractDescriptor] {
[
NFCReaderProxy.descriptor,
NFCReaderDelegateProxy.descriptor,
NFCTagProxy.descriptor,
NDEFMessageProxy.descriptor,
NDEFRecordProxy.descriptor,
]
}

public static func register(in registrar: some ContractRegistrar) {
NFCReaderProxy.register(LinuxNFCReader.self, in: registrar)
NFCReaderDelegateProxy.registerInterface(in: registrar)
NFCTagProxy.register(LinuxNFCTag.self, in: registrar)
NDEFMessageProxy.register(LinuxNDEFMessage.self, in: registrar)
NDEFRecordProxy.register(LinuxNDEFRecord.self, in: registrar)
}

/// NFC has no prompt anywhere: a declared `nfc` capability is granted,
/// and the reader says whether there's hardware.
public static func permissionProviders() -> [Capability: any PermissionProvider] {
[.nfc: GrantedPermission()]
}

// MARK: Objects passed back

/// Finds the Swift object behind a proxy the guest passed back. Replace
/// it if the host runs on a `NativeRuntime` other than `shared`.
nonisolated(unsafe) public static var objectResolver: (DynamicObject) -> AnyObject? = { proxy in
NativeRuntime.shared.swiftObject(for: proxy)
}

/// The implementation object behind a contract object: itself when the
/// caller is Swift, or the object a proxy stands for. Nil for an object
/// the guest made itself.
static func resolve<T: AnyObject>(_ object: AnyObject, as type: T.Type) -> T? {
if let object = object as? T {
return object
}
if let proxy = object as? DynamicObject {
return objectResolver(proxy) as? T
}
return nil
}
}
Loading
Loading