diff --git a/Documentation/Plan.md b/Documentation/Plan.md index 3da5b60..65a1bae 100644 --- a/Documentation/Plan.md +++ b/Documentation/Plan.md @@ -100,12 +100,12 @@ timers for `schedule`. | `LinuxWebKit` | `WebContent` over WPE WebKit, loaded at run time; the player's `WebView` view shows it (§8) | | `LinuxCoreModel` | `LinuxModelStore`: the model store over CoreModel-SQLite, through AppRuntime's `HostModelStore` (§9) | | `LinuxDevice` | `Device` from `/etc`, DMI, the device tree, and power and heat in sysfs; orientation and proximity from iio-sensor-proxy (§10) | -| `LinuxDBus` | `Bus`: the system and session buses, for the modules that talk to system services: method calls, properties and signals by match rule, delivered on the main loop (§11.1) | +| `LinuxDBus` | `Bus`: the system and session buses, for the modules that talk to system services: method calls, properties and signals by match rule, delivered on the main loop; and objects the host serves, with the names it owns (§11.1) | | `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) | -| `LinuxMedia` | `MediaPlayback` over GStreamer's `playbin`, loaded at run time; the player's `VideoPlayer` view shows its pictures (§15) | +| `LinuxMedia` | `MediaPlayback` over GStreamer's `playbin`, loaded at run time; the player's `VideoPlayer` view shows its pictures, and MPRIS what's playing (§15) | | `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 (§17, [Packager.md](Packager.md)) | @@ -515,8 +515,8 @@ 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), NFC (neard) and the desktop portal -share. `Bus.system` +proximity (iio-sensor-proxy), NFC (neard), the desktop portal and what's +playing (MPRIS) 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 values are `DBusMessageArgument`s, whose arrays and dictionaries carry @@ -543,6 +543,15 @@ their element types. `org.freedesktop.DBus.Local.Disconnected` signal; the next request connects again, and the rules are added again. Without a bus, calls fail with `NoServer`. +- **Serving**, for MPRIS: `export` serves an object's `BusInterface`s at a + path, through PureSwift/DBus's object server, which answers + `Introspectable`, `Peer` and `Properties` for it. A method call or a + property read or write comes in on the connection's threads, is posted to + the main loop, and its answer goes back, so handlers run on the main + thread like everything else. `requestName` asks for a well-known name + without queueing, and `releaseName` gives it up; `emit` and + `emitPropertiesChanged` send signals. Objects and names are served and + asked for again on a new connection. ## 12. Documents @@ -746,11 +755,30 @@ gives it a player per `MediaPlayback`, `GStreamerEngine`. no `VideoPlayer` case yet, so `HostNodeViews` draws it; DarwinUI's later revisions draw `GLSurface`, `WebView` and `VideoPlayer` through providers, which a sync will have to set instead. -- **`audio`** asks for nothing, as everywhere. +- **What's playing** (AppRuntime's `NowPlaying.md`) is an MPRIS player on + the session bus, `org.mpris.MediaPlayer2.` (characters a bus + name can't have become `_`), which the shell shows with its media + controls and media keys. The name is owned while the app describes a + player and given up when it stops; the object is served at + `/org/mpris/MediaPlayer2`: + +| | MPRIS | +|---|---| +| `org.mpris.MediaPlayer2` | `Identity`, the app's name; `DesktopEntry`, its identifier, as the packager names the entry. No `Raise`, `Quit` or track list | +| `Metadata` | `xesam:title`, `xesam:artist`, `xesam:album`, `mpris:length` when the duration is known, `mpris:trackid` (one per player), `mpris:artUrl`: an artwork file's URL, or bytes written to a temporary file | +| `PlaybackStatus`, `Rate`, `Position` | Playing or Paused, from `HostMediaPlayback`'s reports; `Position` worked out when it's read from the last report and the rate, as the contract has the guest do. `Rate` is the last one played at, never 0 | +| Buttons | `Play`, `Pause`, `PlayPause`, `Stop` (a pause), `Seek` and `SetPosition` (for this track) are `HostMediaPlayback.remote`'s, answered without the guest; `Next` and `Previous` go to the guest when it offered them (`CanGoNext`, `CanGoPrevious`). `OpenUri` is `NotSupported` | +| Changes | `PropertiesChanged` at each report, with what changed; `Seeked` when the position jumps | + +- **`audio`** asks for nothing, as everywhere. The desktop doesn't send an + app to the background, so a player plays on with its window hidden; + `.audio(background: true)` (`RTCapabilityOptions.audio.background`) + makes `canPlayInBackground` say so. - **Not yet**: - - What's playing outside the window (NowPlaying): MPRIS on the session - bus. The desktop doesn't send an app to the background, so a player - plays on with its window hidden, and `setPlaysInBackground` is refused. + - `Volume` is 1 and read-only from the shell, and there's no + `LoopStatus` or `Shuffle`. + - Artwork as a file is named by its path, which a shell in another + sandbox may not read. - Interruptions and unplugged headphones: the sound server doesn't tell a client, short of PulseAudio's corking. - Hardware decoding: GStreamer's VA-API and V4L2 decoders would need the @@ -808,7 +836,9 @@ gives it a player per `MediaPlayback`, `GStreamerEngine`. and, where `dbus-daemon` is installed, a daemon of the test's own: calls waited for and on the main loop, properties, an error, a signal by match rule from another connection, and connecting again, with the rules, once - the daemon's gone and another is in its place. + the daemon's gone and another is in its place; an object served, its + methods, an error, its properties read and written, introspection, its + signals, and a name owned and given up. - `LinuxCoreModel`: where stores are; about 500 requests answered as CoreModel's in-memory store answers them; every value there and back; batches applied whole or not at all; a store kept between launches, @@ -854,7 +884,11 @@ gives it a player per `MediaPlayback`, `GStreamerEngine`. file; what isn't media, a missing file, and a URL without `network`; a video's size, its preroll's picture, pictures while playing and after a seek; what the registry plays. GStreamer's errors and MIME types as the - contract has them. `VideoPlayer` nodes lay out in `LinuxUI`'s tests, + contract has them. What's playing as an MPRIS player, against a bus + daemon of the test's own with another connection as the shell: the name, + the properties and metadata, the position moving on, play, seeking with + `Seeked`, a seek for another track ignored, next to the guest, a pause + that's the user's, `OpenUri` refused, and the name given up. `VideoPlayer` nodes lay out in `LinuxUI`'s tests, with and without controls. The packager accepts the contracts with `audio`. - End to end: AppRuntime's `ExampleUI`, `ExampleGL` and `ExampleModel` diff --git a/Package.swift b/Package.swift index eecab78..e487dbb 100644 --- a/Package.swift +++ b/Package.swift @@ -224,11 +224,12 @@ let package = Package( // MARK: - Media - // GStreamer's playbin, opened at run time. + // GStreamer's playbin, opened at run time, and MPRIS on the session + // bus. .target( name: "LinuxMedia", - dependencies: ["LinuxHost", runtime("DynamicMedia"), runtime("DynamicRuntime"), runtime("RuntimeMedia"), runtime("RuntimeHost"), - runtime("RuntimeCore"), runtime("RuntimeNative")], + dependencies: ["LinuxHost", "LinuxDBus", runtime("DynamicMedia"), runtime("DynamicRuntime"), runtime("RuntimeMedia"), + runtime("RuntimeHost"), runtime("RuntimeCore"), runtime("RuntimeNative"), .product(name: "DBus", package: "DBus")], swiftSettings: host ), @@ -299,7 +300,8 @@ let package = Package( runtime("DynamicFiles"), runtime("RuntimeHost"), runtime("RuntimeNative"), .product(name: "DBus", package: "DBus")], swiftSettings: host), - .testTarget(name: "LinuxMediaTests", dependencies: ["LinuxMedia", runtime("DynamicMedia"), runtime("RuntimeMedia"), runtime("RuntimeHost")], + .testTarget(name: "LinuxMediaTests", dependencies: ["LinuxMedia", "LinuxDBus", runtime("DynamicMedia"), runtime("RuntimeMedia"), + runtime("RuntimeHost"), .product(name: "DBus", package: "DBus")], swiftSettings: host), .testTarget(name: "LinuxMotionTests", dependencies: ["LinuxMotion", runtime("DynamicMotion")], swiftSettings: host), .testTarget(name: "LinuxWebKitTests", dependencies: ["LinuxWebKit", runtime("DynamicWebKit")], swiftSettings: host), diff --git a/README.md b/README.md index bf64be6..f8b4cb4 100644 --- a/README.md +++ b/README.md @@ -60,12 +60,12 @@ added to its database between launches: | `LinuxWebKit` | `WebContent`: WPE WebKit pages, loaded at run time, drawn into shared memory and shown by the player's `WebView` view ([plan](Documentation/Plan.md) §8) | | `LinuxCoreModel` | `LinuxModelStore`: the app's CoreModel stores in SQLite, through AppRuntime's `HostModelStore` and CoreModel-SQLite ([plan](Documentation/Plan.md) §9) | | `LinuxDevice` | `Device`: the machine, its battery, power mode and heat, from `/etc`, DMI, the device tree and sysfs, and its orientation and proximity from iio-sensor-proxy ([plan](Documentation/Plan.md) §10) | -| `LinuxDBus` | `Bus`: the system and session buses for the modules that talk to system services, over PureSwift/DBus, with calls, properties and signals delivered on the main loop ([plan](Documentation/Plan.md) §11.1) | +| `LinuxDBus` | `Bus`: the system and session buses for the modules that talk to system services, over PureSwift/DBus, with calls, properties and signals delivered on the main loop, and objects the host serves ([plan](Documentation/Plan.md) §11.1) | | `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) | -| `LinuxMedia` | `MediaPlayback`: songs and videos through GStreamer's `playbin`, opened at run time, from files, bytes or URLs; the player's `VideoPlayer` view shows the pictures, with play, pause and a scrubber ([plan](Documentation/Plan.md) §15) | +| `LinuxMedia` | `MediaPlayback`: songs and videos through GStreamer's `playbin`, opened at run time, from files, bytes or URLs; the player's `VideoPlayer` view shows the pictures, with play, pause and a scrubber; what's playing is an MPRIS player on the session bus, for the shell's media controls ([plan](Documentation/Plan.md) §15) | | `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 | diff --git a/Sources/LinuxDBus/Bus.swift b/Sources/LinuxDBus/Bus.swift index 35cd998..f956171 100644 --- a/Sources/LinuxDBus/Bus.swift +++ b/Sources/LinuxDBus/Bus.swift @@ -5,12 +5,14 @@ import LinuxHost /// A D-Bus bus, for the modules that talk to system services (`Plan.md` /// §11): method calls, property reads and writes, and signals by match -/// rule. Main loop only. +/// rule; and objects this process serves, with the names it owns +/// (`BusObjects.swift`). Main loop only. /// /// The connection, PureSwift/DBus's, lives on Swift's own threads; every /// reply and signal is posted to the main loop. It's made on first use /// and, if it closes, made again on the next, with the subscriptions' match -/// rules added again; subscribers to `MatchRule.disconnected` hear when it +/// rules added again, and its objects served and its names asked for +/// again; subscribers to `MatchRule.disconnected` hear when it /// closes. Requests are started in the order they're made, and one to the /// bus itself, such as `AddMatch`, is answered before the next starts. /// @@ -31,14 +33,21 @@ public final class Bus { /// The system bus: BlueZ's, GeoClue's, iio-sensor-proxy's, neard's. nonisolated(unsafe) public static let system = Bus(.system) - /// The session bus: the desktop portal's. + /// The session bus: the desktop portal's, and the shell's media + /// controls'. nonisolated(unsafe) public static let session = Bus(.session) public let kind: Kind - private let loop: MainLoop + let loop: MainLoop - private let link: BusLink + let link: BusLink + + /// The objects this process serves, by path, and the names it asked + /// for. + var exports: [String: [BusInterface]] = [:] + + var names: Set = [] private var subscriptions: [UInt64: (rule: MatchRule, handler: (BusSignal) -> Void)] = [:] @@ -273,6 +282,7 @@ public final class Bus { for rule in Set(subscriptions.values.map(\.rule)) { addMatch(rule) } + serveAgain() case .signal(let signal): deliver(signal) case .closed(let error): diff --git a/Sources/LinuxDBus/BusLink.swift b/Sources/LinuxDBus/BusLink.swift index b4431c3..725c9d1 100644 --- a/Sources/LinuxDBus/BusLink.swift +++ b/Sources/LinuxDBus/BusLink.swift @@ -12,6 +12,10 @@ final class BusLink: @unchecked Sendable { typealias Completion = @Sendable (Result<[DBusMessageArgument], BusError>) -> Void + /// Work on the connection itself, such as exporting an object or + /// emitting a signal, in order with the requests. + typealias Action = @Sendable (DBusConnection) async -> Void + enum Event: Sendable { /// Connected and said `Hello`; requests made while connecting are /// on their way. @@ -22,14 +26,15 @@ final class BusLink: @unchecked Sendable { } private struct Outgoing: Sendable { - let message: DBusMessage + let message: DBusMessage? let completion: Completion + var action: Action? /// A request to the bus itself (`AddMatch`, `RemoveMatch`): the /// next isn't started until it's answered, so a match rule is in /// place before what was asked after it. var isBarrier: Bool { - message.destination == DBusWellKnown.busName + message?.destination == DBusWellKnown.busName } } @@ -60,7 +65,17 @@ final class BusLink: @unchecked Sendable { /// Sends `message`; `completion` gets its reply's values or its error, /// on Swift's threads. func send(_ message: DBusMessage, _ completion: @escaping Completion) { - let item = Outgoing(message: message, completion: completion) + enqueue(Outgoing(message: message, completion: completion)) + } + + /// Runs `action` on the connection, connecting first if need be, after + /// what was asked before it. Without a connection it's dropped. + func perform(_ action: @escaping Action) { + enqueue(Outgoing(message: nil, completion: { _ in }, action: action)) + } + + private func enqueue(_ item: Outgoing) { + let completion = item.completion lock.lock() switch status { case .connected(let outgoing): @@ -119,10 +134,14 @@ final class BusLink: @unchecked Sendable { let (outgoing, continuation) = AsyncStream.makeStream(of: Outgoing.self) let writer = Task { for await item in outgoing { - if item.isBarrier { - item.completion(await Self.send(item.message, on: connection)) - } else { - await connection.begin(item.message, item.completion) + if let action = item.action { + await action(connection) + } else if let message = item.message { + if item.isBarrier { + item.completion(await Self.send(message, on: connection)) + } else { + await connection.begin(message, item.completion) + } } } } diff --git a/Sources/LinuxDBus/BusObjects.swift b/Sources/LinuxDBus/BusObjects.swift new file mode 100644 index 0000000..c4ef425 --- /dev/null +++ b/Sources/LinuxDBus/BusObjects.swift @@ -0,0 +1,231 @@ +import DBus +import LinuxHost + +/// An interface of an object this process serves on a bus: its methods and +/// properties, answered on the main loop. +public struct BusInterface { + + public var name: String + + public var methods: [BusMethod] + + public var properties: [BusProperty] + + public init(_ name: String, methods: [BusMethod] = [], properties: [BusProperty] = []) { + self.name = name + self.methods = methods + self.properties = properties + } +} + +/// A method of a served interface. `handler` runs on the main loop with +/// the call's arguments, which the bus has checked against `input`; it +/// gives the reply's values, of signature `output`, or an error. +public struct BusMethod { + + public var name: String + + public var input: String + + public var output: String + + public var handler: ([DBusMessageArgument]) -> Result<[DBusMessageArgument], BusError> + + public init(_ name: String, input: String = "", output: String = "", + _ handler: @escaping ([DBusMessageArgument]) -> Result<[DBusMessageArgument], BusError>) { + self.name = name + self.input = input + self.output = output + self.handler = handler + } +} + +/// A property of a served interface, read on the main loop each time it's +/// asked for; writable when it has `set`. +public struct BusProperty { + + public var name: String + + /// Its value's signature, such as `s` or `a{sv}`. + public var type: String + + public var get: () -> DBusMessageArgument + + public var set: ((DBusMessageArgument) -> Result)? + + public init(_ name: String, _ type: String, get: @escaping () -> DBusMessageArgument, + set: ((DBusMessageArgument) -> Result)? = nil) { + self.name = name + self.type = type + self.get = get + self.set = set + } +} + +// MARK: Serving + +extension Bus { + + /// Serves an object at `path`, in place of any there: calls to its + /// methods and reads of its properties go to the main loop, and the + /// bus answers `Introspectable`, `Peer` and `Properties` for it. It's + /// served again on a new connection. + public func export(_ path: String, _ interfaces: [BusInterface]) { + guard let objectPath = DBusObjectPath(rawValue: path) else { + HostLog.error("dbus: not an object path: \(path)") + return + } + exports[path] = interfaces + let object = Self.object(interfaces, loop: loop) + link.perform { connection in + await connection.export(object, at: objectPath) + } + } + + /// Stops serving the object at `path`. + public func unexport(_ path: String) { + guard exports.removeValue(forKey: path) != nil, let objectPath = DBusObjectPath(rawValue: path) else { return } + link.perform { connection in + _ = await connection.unexport(at: objectPath) + } + } + + /// Asks for a well-known name, without queueing for it: `reply` says + /// whether this connection owns it. It's asked for again on a new + /// connection, until `releaseName`. + public func requestName(_ name: String, reply: @escaping (Result) -> Void = { _ in }) { + names.insert(name) + ask(for: name, reply: reply) + } + + /// Gives up a name `requestName` asked for; `reply` says when the bus + /// has. + public func releaseName(_ name: String, reply: @escaping (Result) -> Void = { _ in }) { + guard names.remove(name) != nil else { + loop.post { reply(.success(())) } + return + } + call("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "ReleaseName", [.string(name)]) { result in + reply(result.map { _ in }) + } + } + + /// Emits a signal from an object this process serves. + public func emit(_ path: String, _ interface: String, _ member: String, _ arguments: [DBusMessageArgument] = []) { + guard let objectPath = DBusObjectPath(rawValue: path), let interfaceName = DBusInterface(rawValue: interface), + let memberName = DBusMember(rawValue: member) else { + HostLog.error("dbus: not a signal: \(path) \(interface).\(member)") + return + } + let signal = DBusMessage.Signal(path: objectPath, interface: interfaceName, name: memberName) + link.perform { connection in + do { + try await connection.emit(signal, arguments: arguments) + } catch { + HostLog.debug("dbus: couldn't emit \(interface).\(member): \(error)") + } + } + } + + /// Emits `Properties.PropertiesChanged` with properties' new values. + public func emitPropertiesChanged(_ path: String, _ interface: String, _ changed: [String: DBusMessageArgument]) { + guard !changed.isEmpty, let objectPath = DBusObjectPath(rawValue: path), + let interfaceName = DBusInterface(rawValue: interface) else { return } + link.perform { connection in + do { + try await connection.emitPropertiesChanged(at: objectPath, interface: interfaceName, changed: changed) + } catch { + HostLog.debug("dbus: couldn't emit PropertiesChanged: \(error)") + } + } + } + + /// What this connection served and owned, on a new connection. + func serveAgain() { + for (path, interfaces) in exports { + export(path, interfaces) + } + for name in names { + ask(for: name) { _ in } + } + } + + private func ask(for name: String, reply: @escaping (Result) -> Void) { + // DBUS_NAME_FLAG_DO_NOT_QUEUE; 1 is the primary owner, 4 already + // the owner. + call("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "RequestName", + [.string(name), .uint32(4)]) { result in + reply(result.map { $0.first == .uint32(1) || $0.first == .uint32(4) }) + } + } + + // MARK: PureSwift/DBus's objects + + /// The main loop's closures, for the connection's threads, which only + /// post them back to the main loop. + private final class Handlers: @unchecked Sendable { + let interfaces: [BusInterface] + init(_ interfaces: [BusInterface]) { self.interfaces = interfaces } + } + + static func object(_ interfaces: [BusInterface], loop: MainLoop) -> DBusExportedObject { + let handlers = Handlers(interfaces) + var object = DBusExportedObject() + for (interfaceIndex, interface) in interfaces.enumerated() { + guard let name = DBusInterface(rawValue: interface.name) else { continue } + var methods: [DBusInterfaceImplementation.Method] = [] + for (index, method) in interface.methods.enumerated() { + guard let member = DBusMember(rawValue: method.name), let input = DBusSignature(rawValue: method.input), + let output = DBusSignature(rawValue: method.output) else { continue } + let handler: @Sendable (DBusMethodCall) async throws -> [DBusMessageArgument] = { call in + let arguments = call.arguments + let result: Result<[DBusMessageArgument], BusError> = await onLoop(loop) { + handlers.interfaces[interfaceIndex].methods[index].handler(arguments) + } + return try result.mapError(Self.dbusError).get() + } + methods.append(DBusInterfaceImplementation.Method(name: member, inputSignature: input, outputSignature: output, + handler: handler)) + } + var properties: [DBusInterfaceImplementation.Property] = [] + for (index, property) in interface.properties.enumerated() { + guard let type = DBusSignature(rawValue: property.type)?.first else { continue } + let get: @Sendable () async throws -> DBusMessageArgument = { + await onLoop(loop) { handlers.interfaces[interfaceIndex].properties[index].get() } + } + var set: (@Sendable (DBusMessageArgument) async throws -> Void)? + if property.set != nil { + set = { value in + let result: Result = await onLoop(loop) { + handlers.interfaces[interfaceIndex].properties[index].set?(value) ?? .success(()) + } + try result.mapError(Self.dbusError).get() + } + } + properties.append(DBusInterfaceImplementation.Property(name: property.name, type: type, + access: set == nil ? .read : .readwrite, get: get, set: set)) + } + object.add(DBusInterfaceImplementation(name: name, methods: methods, properties: properties)) + } + return object + } + + /// A handler's error, as PureSwift/DBus replies with it. + private static func dbusError(_ error: BusError) -> DBusError { + let failed = DBusError.Name(rawValue: "org.freedesktop.DBus.Error.Failed")! + return DBusError(name: DBusError.Name(rawValue: error.name) ?? failed, message: error.message) + } + + /// Runs `body` on the main loop, and waits for what it gives. + private static func onLoop(_ loop: MainLoop, _ body: @escaping () -> T) async -> T { + let box = Box(body) + return await withCheckedContinuation { continuation in + loop.post { continuation.resume(returning: box.body()) } + } + } + + private final class Box: @unchecked Sendable { + let body: () -> T + init(_ body: @escaping () -> T) { self.body = body } + } +} diff --git a/Sources/LinuxHostApp/HostApp.swift b/Sources/LinuxHostApp/HostApp.swift index 2f6c463..05ad05f 100644 --- a/Sources/LinuxHostApp/HostApp.swift +++ b/Sources/LinuxHostApp/HostApp.swift @@ -57,6 +57,14 @@ public enum HostApp { HostNetworkingModule.log = { HostLog.error("networking: \($0)") } } + /// `.audio(background: true)`: `RTCapabilityOptions.audio.background`, + /// which the packager copies from the universal bundle as it is. + static func playsInBackground(_ info: [String: Any]) -> Bool { + let options = info["RTCapabilityOptions"] as? [String: Any] + let background = (options?["audio"] as? [String: Any])?["background"] + return background as? String == "true" || background as? Bool == true + } + /// The window's title: the app's name. nonisolated(unsafe) static var title = "" @@ -84,6 +92,7 @@ public enum HostApp { info = try AppInfo(propertyList: data) let dictionary = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any] executable = dictionary?["CFBundleExecutable"] as? String + LinuxMedia.allowsBackground = playsInBackground(dictionary ?? [:]) } catch { fail("\(bundle): \(error)") } diff --git a/Sources/LinuxMedia/LinuxMedia.swift b/Sources/LinuxMedia/LinuxMedia.swift index 468b379..a3c59a8 100644 --- a/Sources/LinuxMedia/LinuxMedia.swift +++ b/Sources/LinuxMedia/LinuxMedia.swift @@ -1,5 +1,6 @@ import DynamicMedia import DynamicRuntime +import LinuxDBus import LinuxHost import RuntimeCore import RuntimeHost @@ -12,7 +13,8 @@ import RuntimeNative /// /// The contract is AppRuntime's `HostMediaPlayback`, which checks each /// source, finds files through `HostFiles`, and keeps the rules every host -/// shares. This module gives it `playbin`s (`GStreamerEngine`). Without +/// shares. This module gives it `playbin`s (`GStreamerEngine`), and shows +/// what's playing as an MPRIS player on the session bus (`MPRIS`). Without /// GStreamer installed it has no players, and every load fails with /// `unavailable`. public enum LinuxMedia: HostModule { @@ -35,9 +37,9 @@ public enum LinuxMedia: HostModule { HostMediaPlayback.platform = GStreamer.shared == nil ? nil : platform HostMediaPlayback.clock = clock HostMediaPlayback.allowsNetwork = networkOverride ?? HostPermissions.declared.contains(.network) - // The desktop doesn't send an app to the background, and nothing - // here shows what's playing outside its window yet. - HostMediaPlayback.allowsBackground = false + // The desktop doesn't send an app to the background, so a player + // plays on; the manifest's option says the app wants it to. + HostMediaPlayback.allowsBackground = allowsBackground } public static func permissionProviders() -> [Capability: any PermissionProvider] { @@ -64,6 +66,13 @@ public enum LinuxMedia: HostModule { /// In place of the app's capabilities, for tests: whether URLs play. nonisolated(unsafe) public static var networkOverride: Bool? = nil + /// `.audio(background: true)`: the bundle's + /// `RTCapabilityOptions.audio.background`, which `HostApp` reads. + nonisolated(unsafe) public static var allowsBackground = false + + /// The bus what's playing is shown on: the session bus, or a test's. + nonisolated(unsafe) public static var nowPlayingBus: Bus? = nil + nonisolated(unsafe) static let platform = GStreamerPlatform() } @@ -71,6 +80,10 @@ public enum LinuxMedia: HostModule { /// registry can play. final class GStreamerPlatform: MediaPlatform { + /// What's playing, on the session bus, made when there's first + /// something to show. + private(set) var mpris: MPRIS? + func makeEngine(for player: HostMediaPlayback) -> any MediaEngine { GStreamerEngine(playback: player) ?? UnavailableEngine(playback: player) } @@ -80,6 +93,21 @@ final class GStreamerPlatform: MediaPlatform { return MediaValues.support(mimeType, reads: { gst.hasElement(GStreamer.readers, accepting: $0) }, decodes: { gst.hasElement(GStreamer.decoders, accepting: $0) }) } + + func showNowPlaying(_ nowPlaying: HostNowPlaying?) { + if mpris == nil, nowPlaying != nil { + let info = LinuxBundle.info + mpris = MPRIS(bus: LinuxMedia.nowPlayingBus ?? .session, identifier: info.identifier, + identity: info.name.isEmpty ? info.identifier : info.name) + } + mpris?.show(nowPlaying) + } + + /// Forgets the MPRIS player, for tests. + func reset() { + mpris?.show(nil) + mpris = nil + } } /// A player GStreamer couldn't make: every load fails. diff --git a/Sources/LinuxMedia/MPRIS.swift b/Sources/LinuxMedia/MPRIS.swift new file mode 100644 index 0000000..1aa0cd3 --- /dev/null +++ b/Sources/LinuxMedia/MPRIS.swift @@ -0,0 +1,279 @@ +import DBus +import DynamicMedia +import Foundation +import LinuxDBus +import LinuxHost +import RuntimeMedia + +/// What's playing, on the session bus as an MPRIS player (`Plan.md` §15): +/// `org.mpris.MediaPlayer2.`, which the shell shows with its media +/// controls, and whose buttons and media keys come back as +/// `HostMediaPlayback.remote`'s commands. Main loop only. +/// +/// The name is owned while the app describes a player, and given up when +/// it stops. Properties are read when the shell asks; what changes is said +/// with `PropertiesChanged` at each report, and a jump in the position with +/// `Seeked`. +final class MPRIS { + + static let root = "org.mpris.MediaPlayer2" + + static let player = "org.mpris.MediaPlayer2.Player" + + static let path = "/org/mpris/MediaPlayer2" + + let bus: Bus + + /// The well-known name. + let name: String + + /// The app's name, and its desktop entry's (`.desktop`). + let identity: String + + let desktopEntry: String + + /// The last report, and when it came, on the main loop's clock. + private(set) var current: HostNowPlaying? + + private var stamp: Int64 = 0 + + /// The rate playback goes at when it plays: MPRIS's `Rate` isn't 0 + /// while paused. + private var rate = 1.0 + + /// `artUrl`'s file, for artwork that came as bytes. + private var artworkFile: String? + + private var artworkData: [UInt8]? + + private var published: [String: DBusMessageArgument] = [:] + + private(set) var isServing = false + + init(bus: Bus, identifier: String, identity: String) { + self.bus = bus + // A bus name's elements are letters, digits and underscores. + let element = String(identifier.map { $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "." || $0 == "_") ? $0 : "_" }) + .split(separator: ".").map { $0.first?.isNumber == true ? "_" + $0 : String($0) }.joined(separator: ".") + name = Self.root + "." + (element.isEmpty ? "AppRuntime" : element) + self.identity = identity + desktopEntry = identifier + } + + deinit { + removeArtwork() + } + + /// Shows what's playing, or, with `nil`, nothing. + func show(_ nowPlaying: HostNowPlaying?) { + guard let nowPlaying else { + stop() + return + } + let previous = current.map { (position: position, at: $0) } + current = nowPlaying + stamp = MainLoop.now() + if nowPlaying.rate > 0 { + rate = Double(nowPlaying.rate) + } + updateArtwork(nowPlaying.artwork) + if !isServing { + isServing = true + published = [:] + bus.export(Self.path, interfaces) + bus.requestName(name) { [name] result in + if case .success(false) = result { + HostLog.warning("media: \(name) is another's; what's playing isn't shown") + } else if case .failure(let error) = result { + HostLog.debug("media: no MPRIS: \(error)") + } + } + } + let properties = changing + let changed = properties.filter { published[$0.key] != $0.value } + published = properties + if !changed.isEmpty, previous != nil { + bus.emitPropertiesChanged(Self.path, Self.player, changed) + } + // A jump: the shell's position moves on its own from the last one + // it read, at the rate. + if let previous, previous.at.player == nowPlaying.player, abs(previous.position - nowPlaying.position) > 0.5 { + bus.emit(Self.path, Self.player, "Seeked", [.int64(Self.microseconds(nowPlaying.position))]) + } + } + + private func stop() { + guard isServing else { return } + isServing = false + current = nil + published = [:] + bus.releaseName(name) + bus.unexport(Self.path) + removeArtwork() + } + + // MARK: Properties + + /// Where playback is now: the last report, moved on at its rate. + var position: Double { + guard let current else { return 0 } + var seconds = current.position + if current.isPlaying { + seconds += Double(MainLoop.now() - stamp) / 1e9 * Double(current.rate) + } + if let duration = current.duration { + seconds = min(seconds, duration) + } + return max(seconds, 0) + } + + var playbackStatus: String { + guard let current else { return "Stopped" } + return current.isPlaying ? "Playing" : "Paused" + } + + /// The track's identifier: one per player, since a track's changes + /// come as the player's. + var trackID: String { + "/org/pureswift/AppRuntime/track/\(current?.player ?? 0)" + } + + var metadata: [String: DBusMessageArgument] { + guard let current else { return [:] } + var metadata: [String: DBusMessageArgument] = [ + "mpris:trackid": .path(trackID), + "xesam:title": .string(current.title), + ] + if let artist = current.artist { + metadata["xesam:artist"] = .stringArray([artist]) + } + if let album = current.album { + metadata["xesam:album"] = .string(album) + } + if let duration = current.duration { + metadata["mpris:length"] = .int64(Self.microseconds(duration)) + } + if let url = artURL { + metadata["mpris:artUrl"] = .string(url) + } + return metadata + } + + private var artURL: String? { + switch current?.artwork { + case .file(let path)?: + return URL(fileURLWithPath: path).absoluteString + case .data?: + return artworkFile.map { URL(fileURLWithPath: $0).absoluteString } + case nil: + return nil + } + } + + /// The `Player` properties a report can change, as they're published. + var changing: [String: DBusMessageArgument] { + let commands = current?.commands ?? [] + return [ + "PlaybackStatus": .string(playbackStatus), + "Metadata": .vardict(metadata), + "Rate": .double(rate), + "CanGoNext": .boolean(commands.contains(.next)), + "CanGoPrevious": .boolean(commands.contains(.previous)), + "CanSeek": .boolean(current?.duration != nil), + ] + } + + static func microseconds(_ seconds: Double) -> Int64 { + Int64((seconds * 1e6).rounded()) + } + + // MARK: Artwork + + private func updateArtwork(_ artwork: HostArtwork?) { + guard case .data(let bytes, let mimeType)? = artwork else { + removeArtwork() + return + } + guard bytes != artworkData else { return } + removeArtwork() + let type = mimeType.lowercased() + let suffix = type.hasSuffix("png") ? "png" : type.hasSuffix("jpeg") || type.hasSuffix("jpg") ? "jpg" : "image" + let path = NSTemporaryDirectory() + "/mpris-\(getpid())-\(UUID().uuidString).\(suffix)" + if FileManager.default.createFile(atPath: path, contents: Data(bytes)) { + artworkFile = path + artworkData = bytes + } + } + + private func removeArtwork() { + if let artworkFile { + try? FileManager.default.removeItem(atPath: artworkFile) + } + artworkFile = nil + artworkData = nil + } + + // MARK: The object + + private var interfaces: [BusInterface] { + [ + BusInterface(Self.root, methods: [ + // The app's window isn't the host's to raise, and quitting + // is the app's. + BusMethod("Raise") { _ in .success([]) }, + BusMethod("Quit") { _ in .success([]) }, + ], properties: [ + BusProperty("CanQuit", "b") { .boolean(false) }, + BusProperty("CanRaise", "b") { .boolean(false) }, + BusProperty("HasTrackList", "b") { .boolean(false) }, + BusProperty("Identity", "s") { [identity] in .string(identity) }, + BusProperty("DesktopEntry", "s") { [desktopEntry] in .string(desktopEntry) }, + BusProperty("SupportedUriSchemes", "as") { .stringArray([]) }, + BusProperty("SupportedMimeTypes", "as") { .stringArray([]) }, + ]), + BusInterface(Self.player, methods: [ + BusMethod("Next") { _ in Self.command(.next) }, + BusMethod("Previous") { _ in Self.command(.previous) }, + BusMethod("Pause") { _ in Self.command(.pause) }, + BusMethod("PlayPause") { _ in Self.command(.togglePlayPause) }, + // There's no stopped state to go to: a pause. + BusMethod("Stop") { _ in Self.command(.pause) }, + BusMethod("Play") { _ in Self.command(.play) }, + BusMethod("Seek", input: "x") { [weak self] arguments in + guard let self, let offset = arguments.first?.int64Value else { return .success([]) } + return Self.command(.seek(to: self.position + Double(offset) / 1e6)) + }, + BusMethod("SetPosition", input: "ox") { [weak self] arguments in + // One for another track is ignored, as MPRIS says. + guard let self, arguments.first?.text == self.trackID, let position = arguments.last?.int64Value, + position >= 0 else { return .success([]) } + return Self.command(.seek(to: Double(position) / 1e6)) + }, + BusMethod("OpenUri", input: "s") { _ in + .failure(BusError(name: "org.freedesktop.DBus.Error.NotSupported", message: "the app chooses what it plays")) + }, + ], properties: [ + BusProperty("PlaybackStatus", "s") { [weak self] in .string(self?.playbackStatus ?? "Stopped") }, + BusProperty("Rate", "d") { [weak self] in .double(self?.rate ?? 1) }, + BusProperty("Metadata", "a{sv}") { [weak self] in .vardict(self?.metadata ?? [:]) }, + BusProperty("Volume", "d") { .double(1) }, + BusProperty("Position", "x") { [weak self] in .int64(Self.microseconds(self?.position ?? 0)) }, + BusProperty("MinimumRate", "d") { .double(0.5) }, + BusProperty("MaximumRate", "d") { .double(2) }, + BusProperty("CanGoNext", "b") { [weak self] in .boolean(self?.current?.commands.contains(.next) ?? false) }, + BusProperty("CanGoPrevious", "b") { [weak self] in .boolean(self?.current?.commands.contains(.previous) ?? false) }, + BusProperty("CanPlay", "b") { [weak self] in .boolean(self?.current != nil) }, + BusProperty("CanPause", "b") { [weak self] in .boolean(self?.current != nil) }, + BusProperty("CanSeek", "b") { [weak self] in .boolean(self?.current?.duration != nil) }, + BusProperty("CanControl", "b") { .boolean(true) }, + ]), + ] + } + + /// A button, to the now-playing player; one nothing answers is ignored, + /// as MPRIS asks. + private static func command(_ command: HostRemoteCommand) -> Result<[DBusMessageArgument], BusError> { + HostMediaPlayback.remote(command) + return .success([]) + } +} diff --git a/Tests/LinuxDBusTests/LinuxDBusTests.swift b/Tests/LinuxDBusTests/LinuxDBusTests.swift index 11e54f5..a04fc79 100644 --- a/Tests/LinuxDBusTests/LinuxDBusTests.swift +++ b/Tests/LinuxDBusTests/LinuxDBusTests.swift @@ -234,4 +234,85 @@ final class Daemon { run(loop) { !signals.isEmpty } #expect(signals.first?.body.first?.text == "org.example.LinuxDBusTests.Again") } + + @Test(.enabled(if: Daemon.executable != nil, "needs dbus-daemon")) + func servesObjectsAndOwnsNames() throws { + let daemon = try Daemon() + let loop = MainLoop() + let bus = Bus(.address(daemon.address), loop: loop) + let other = Bus(.address(daemon.address), loop: loop) + var volume = 0.5 + var greeted: [String] = [] + bus.export("/org/example/Thing", [BusInterface("org.example.Thing", methods: [ + BusMethod("Greet", input: "s", output: "s") { arguments in + greeted.append(arguments.first?.text ?? "") + return .success([.string("Hello, \(arguments.first?.text ?? "")")]) + }, + BusMethod("Refuse") { _ in .failure(BusError(name: "org.example.Error.No", message: "no")) }, + ], properties: [ + BusProperty("Name", "s") { .string("thing") }, + BusProperty("Volume", "d", get: { .double(volume) }, set: { value in + volume = value.doubleValue ?? volume + return .success(()) + }), + ])]) + var owned: Bool? + bus.requestName("org.example.Served") { owned = try? $0.get() } + run(loop) { owned != nil } + #expect(owned == true) + + func call(_ method: String, _ arguments: [DBusMessageArgument] = [], interface: String = "org.example.Thing") + -> Result<[DBusMessageArgument], BusError>? { + var result: Result<[DBusMessageArgument], BusError>? + other.call("org.example.Served", "/org/example/Thing", interface, method, arguments) { result = $0 } + run(loop) { result != nil } + return result + } + // Answered on the main loop, which the handlers run on. + #expect(try call("Greet", [.string("bus")])?.get().first?.text == "Hello, bus") + #expect(greeted == ["bus"]) + if case .failure(let error)? = call("Refuse") { + #expect(error.name == "org.example.Error.No") + } else { + Issue.record("Refuse succeeded") + } + + var all: [String: DBusMessageArgument]? + other.properties("org.example.Served", "/org/example/Thing", "org.example.Thing") { all = try? $0.get() } + run(loop) { all != nil } + #expect(all?["Name"]?.text == "thing" && all?["Volume"]?.doubleValue == 0.5) + var set: Result? + other.setProperty("org.example.Served", "/org/example/Thing", "org.example.Thing", "Volume", .double(0.8)) { set = $0 } + run(loop) { set != nil } + #expect(volume == 0.8) + var introspected: String? + if case .success(let values)? = call("Introspect", interface: "org.freedesktop.DBus.Introspectable") { + introspected = values.first?.text + } + #expect(introspected?.contains("org.example.Thing") == true) + + // Signals from the object. + var changes: [BusSignal] = [] + other.subscribe(MatchRule(path: "/org/example/Thing", member: "PropertiesChanged")) { changes.append($0) } + var pings: [BusSignal] = [] + other.subscribe(MatchRule(interface: "org.example.Thing", member: "Pinged")) { pings.append($0) } + _ = call("Greet", [.string("again")]) + bus.emitPropertiesChanged("/org/example/Thing", "org.example.Thing", ["Volume": .double(0.8)]) + bus.emit("/org/example/Thing", "org.example.Thing", "Pinged", [.int64(7)]) + run(loop) { !changes.isEmpty && !pings.isEmpty } + #expect(changes.first?.body.first?.text == "org.example.Thing") + #expect(changes.first?.body.dropFirst().first?.entries["Volume"]?.doubleValue == 0.8) + #expect(pings.first?.body.first?.int64Value == 7) + + // Given up. + var released = false + bus.releaseName("org.example.Served") { _ in released = true } + run(loop) { released } + bus.unexport("/org/example/Thing") + var has: Bool? + other.call("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "NameHasOwner", + [.string("org.example.Served")]) { has = (try? $0.get())?.first?.flag } + run(loop) { has != nil } + #expect(has == false) + } } diff --git a/Tests/LinuxMediaTests/GStreamerTests.swift b/Tests/LinuxMediaTests/GStreamerTests.swift index ee85af6..1c5a4d0 100644 --- a/Tests/LinuxMediaTests/GStreamerTests.swift +++ b/Tests/LinuxMediaTests/GStreamerTests.swift @@ -293,5 +293,7 @@ final class RecordingPlaybackDelegate: MediaPlaybackDelegate { func didFail(_ code: Int32, message: String) { failures.append((code, message)) } - func didReceiveCommand(_ command: Int32) { } + var commands: [Int32] = [] + + func didReceiveCommand(_ command: Int32) { commands.append(command) } } diff --git a/Tests/LinuxMediaTests/MPRISTests.swift b/Tests/LinuxMediaTests/MPRISTests.swift new file mode 100644 index 0000000..13528e2 --- /dev/null +++ b/Tests/LinuxMediaTests/MPRISTests.swift @@ -0,0 +1,151 @@ +import DBus +import DynamicMedia +import Foundation +import LinuxDBus +import LinuxHost +import RuntimeHost +import RuntimeMedia +import Testing +@testable import LinuxMedia + +/// A bus daemon of its own, where `dbus-daemon` is installed. +final class SessionDaemon { + + static let executable = ["/usr/bin/dbus-daemon", "/bin/dbus-daemon"].first { FileManager.default.isExecutableFile(atPath: $0) } + + let directory = NSTemporaryDirectory() + "/bus-\(UUID().uuidString)" + + let process = Process() + + var address: String { + "unix:path=\(directory)/bus" + } + + init() throws { + try FileManager.default.createDirectory(atPath: directory, withIntermediateDirectories: true) + process.executableURL = URL(fileURLWithPath: Self.executable!) + process.arguments = ["--session", "--nofork", "--nopidfile", "--address=\(address)"] + process.standardInput = FileHandle.nullDevice + process.standardOutput = FileHandle.nullDevice + process.standardError = FileHandle.nullDevice + try process.run() + let deadline = Date().addingTimeInterval(10) + while !FileManager.default.fileExists(atPath: directory + "/bus"), Date() < deadline { + usleep(10_000) + } + } + + deinit { + kill(process.processIdentifier, SIGKILL) + try? FileManager.default.removeItem(atPath: directory) + } +} + +// In GStreamerTests' suite, which runs one at a time: both use +// `HostMediaPlayback`'s players. +extension GStreamerTests { + + @Test(.enabled(if: SessionDaemon.executable != nil, "needs dbus-daemon")) + func whatsPlayingIsAnMPRISPlayer() throws { + let daemon = try SessionDaemon() + LinuxBundle.info = AppInfo(identifier: "org.pureswift.MediaTests", abiVersion: 0) + LinuxMedia.nowPlayingBus = Bus(.address(daemon.address)) + defer { + LinuxMedia.platform.reset() + LinuxMedia.nowPlayingBus = nil + } + let shell = Bus(.address(daemon.address)) + let name = "org.mpris.MediaPlayer2.org.pureswift.MediaTests" + + func call(_ interface: String, _ method: String, _ arguments: [DBusMessageArgument] = []) -> Result<[DBusMessageArgument], BusError>? { + var result: Result<[DBusMessageArgument], BusError>? + shell.call(name, MPRIS.path, interface, method, arguments) { result = $0 } + run { result != nil } + return result + } + func properties(_ interface: String = MPRIS.player) -> [String: DBusMessageArgument] { + var all: [String: DBusMessageArgument]? + shell.properties(name, MPRIS.path, interface) { all = try? $0.get() } + run { all != nil } + return all ?? [:] + } + var changes: [[String: DBusMessageArgument]] = [] + shell.subscribe(MatchRule(path: MPRIS.path, member: "PropertiesChanged")) { signal in + changes.append(signal.body.dropFirst().first?.entries ?? [:]) + } + var seeked: [Int64] = [] + shell.subscribe(MatchRule(interface: MPRIS.player, member: "Seeked")) { seeked.append($0.body.first?.int64Value ?? -1) } + + let path = file("song.wav", Self.wav(seconds: 10)) + let delegate = RecordingPlaybackDelegate() + let player = HostMediaPlayback.make(delegate) + player.loadFile(1, path: path) + run { delegate.states.last?.state == 2 } + player.setNowPlaying("Morning", artist: "The Examples", album: "Examples") + player.setRemoteCommands(MediaRemoteCommands([.next, .previous]).rawValue, skipBackward: 0, skipForward: 0) + + // What the shell reads. + var owner: Bool? + shell.call("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "NameHasOwner", [.string(name)]) { + owner = (try? $0.get())?.first?.flag + } + run { owner != nil } + #expect(owner == true) + let root = properties(MPRIS.root) + #expect(root["DesktopEntry"]?.text == "org.pureswift.MediaTests" && root["Identity"]?.text == "MediaTests") + let state = properties() + #expect(state["PlaybackStatus"]?.text == "Paused") + #expect(state["CanGoNext"]?.flag == true && state["CanSeek"]?.flag == true) + let metadata = state["Metadata"]?.entries ?? [:] + #expect(metadata["xesam:title"]?.text == "Morning" && metadata["xesam:album"]?.text == "Examples") + #expect(metadata["xesam:artist"]?.elements?.first?.text == "The Examples") + #expect(metadata["mpris:length"]?.int64Value.map { abs($0 - 10_000_000) < 50_000 } == true) + let track = try #require(metadata["mpris:trackid"]?.text) + + // Its buttons: play, from the shell. + _ = call(MPRIS.player, "Play") + run { delegate.states.last?.state == 3 && changes.contains { $0["PlaybackStatus"]?.text == "Playing" } } + #expect(delegate.states.last?.state == 3) + #expect(changes.contains { $0["PlaybackStatus"]?.text == "Playing" }) + wait(0.3) + let position = properties()["Position"]?.int64Value ?? 0 + #expect(position > 150_000 && position < 1_500_000, "moved on: \(position)") + + // Seeking there, which says where it went. + _ = call(MPRIS.player, "SetPosition", [.path(track), .int64(2_000_000)]) + run { !seeked.isEmpty } + #expect(seeked.first.map { abs($0 - 2_000_000) < 100_000 } == true, "\(seeked)") + // Another track's is ignored. + _ = call(MPRIS.player, "SetPosition", [.path("/org/example/other"), .int64(0)]) + + // Next is the app's; pause is the user's. + _ = call(MPRIS.player, "Next") + run { delegate.commands == [1] } + #expect(delegate.commands == [1]) + _ = call(MPRIS.player, "PlayPause") + run { delegate.states.last?.state == 2 } + #expect(delegate.states.last.map { $0.state == 2 && $0.reason == 1 } == true, "the user's pause") + if case .failure(let error)? = call(MPRIS.player, "OpenUri", [.string("https://example.com")]) { + #expect(error.name == "org.freedesktop.DBus.Error.NotSupported") + } else { + Issue.record("OpenUri succeeded") + } + + // Nothing described: the name goes. + player.setNowPlaying("", artist: nil, album: nil) + wait(0.3) + owner = nil + shell.call("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "NameHasOwner", [.string(name)]) { + owner = (try? $0.get())?.first?.flag + } + run { owner != nil } + #expect(owner == false) + } + + @Test func mprisNamesAreBusNames() { + let bus = Bus(.address("unix:path=/nonexistent")) + #expect(MPRIS(bus: bus, identifier: "org.example.My-App", identity: "").name == "org.mpris.MediaPlayer2.org.example.My_App") + #expect(MPRIS(bus: bus, identifier: "com.3d.viewer", identity: "").name == "org.mpris.MediaPlayer2.com._3d.viewer") + #expect(MPRIS(bus: bus, identifier: "", identity: "").name == "org.mpris.MediaPlayer2.AppRuntime") + } +}