diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 14799e2..467b1d5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,9 +2,13 @@ name: CI on: push: - branches: [main] + branches: [main, master] pull_request: - branches: [main] + branches: [main, master] + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true jobs: test: @@ -20,6 +24,20 @@ jobs: - name: Run tests run: bundle exec fastlane test + # The console output is condensed by xcbeautify; keep the raw log, the result + # bundle and any crash reports so failures can be diagnosed. + - name: Upload test diagnostics + if: failure() + uses: actions/upload-artifact@v4 + with: + name: test-diagnostics + path: | + ~/Library/Logs/scan + ~/Library/Developer/Xcode/DerivedData/*/Logs/Test/*.xcresult + ~/Library/Logs/DiagnosticReports + if-no-files-found: ignore + retention-days: 7 + periphery: runs-on: macos-latest steps: @@ -30,8 +48,17 @@ jobs: ruby-version: '3.3' bundler-cache: true + # The periphery Homebrew tap's cask fails on current Homebrew, so install a + # pinned release binary instead. - name: Install periphery - run: brew install peripheryapp/periphery/periphery + env: + PERIPHERY_VERSION: '3.8.0' + run: | + curl -fsSL -o "$RUNNER_TEMP/periphery.zip" \ + "https://github.com/peripheryapp/periphery/releases/download/${PERIPHERY_VERSION}/periphery-${PERIPHERY_VERSION}.zip" + unzip -q "$RUNNER_TEMP/periphery.zip" -d "$RUNNER_TEMP/periphery" + echo "$RUNNER_TEMP/periphery" >> "$GITHUB_PATH" + "$RUNNER_TEMP/periphery/periphery" version - name: Scan for dead code run: bundle exec fastlane periphery diff --git a/CLAUDE.md b/CLAUDE.md index d923945..2dcb3c6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,7 +11,7 @@ PCVolumeControl is an iOS application that allows users to remotely control appl - **Platform**: iOS 17+ Swift app using SwiftUI - **Architecture Pattern**: MVVM (Model-View-ViewModel) - **Networking**: TCP socket communication using Apple's Network framework -- **Protocol**: JSON-based protocol (version 7) for client-server communication +- **Protocol**: JSON-based protocol (version 8) for client-server communication ## Key Components @@ -58,7 +58,8 @@ The project uses [periphery](https://github.com/peripheryapp/periphery) to detec In CI this runs as the `periphery` fastlane lane (`bundle exec fastlane periphery`), which adds `--strict` so the scan exits non-zero on findings. The -`.github/workflows/ci.yml` workflow runs it on every push and pull request. +`.github/workflows/ci.yml` workflow runs it, with a pinned periphery release, on +pushes to and pull requests against `master` (and `main`). Configuration lives in the committed `.periphery.yml`; `periphery scan` reads it automatically. A clean run reports `No unused code detected.`. Notes: @@ -84,13 +85,64 @@ automatically. A clean run reports `No unused code detected.`. Notes: ## Protocol -The app communicates with the PC server using a JSON protocol: - -- **Server → Client**: Sends `FullState` with all devices and sessions information -- **Client → Server**: Sends updates for: - - Default device changes - - Master volume/mute changes - - Individual application volume/mute changes +The app speaks protocol version 8 only, a JSON protocol with one message per line: + +- **Server → Client**: full states (all devices and the default device's sessions) and + icon replies to the client's own icon requests +- **Client → Server**: updates for the default device, master volume/mute and session + volume/mute, and `iconRequest` for application icons + +The canonical spec is `docs/PROTOCOL.md` in the PcVolumeControlServer repo; sample +messages are in `examples/` of the PcVolumeControlProtocol repo. This app does not work +with the original C# PcVolumeControlWindows server (version 7). +Paths below are relative to `PcVolumeControl/`. + +### Version and ids + +- Every outgoing message carries `protocolVersion` 8 (`WireProtocol.version` in + `models/ServerLine.swift`). A full state with another version throws + `ProtocolVersionMismatch`, checked before the rest of the state is decoded; the view + model then disconnects (no reconnect) and shows a localised message saying whether the + server (lower number) or the app (higher number) needs updating. +- Session ids are opaque. A session update is sent with the current state's + `defaultDevice.deviceId`, the device whose sessions the app shows. +- mDNS discovery does not read TXT records (servers advertise `protocol=8`); a server of + another version shows up in the list and is rejected with the message above when + connecting, which tells the user what to update instead of hiding the server. + +### Lines and icons + +- Lines are classified in `models/ServerLine.swift`: `defaultDevice` means a full + state, `icon` means an icon reply, anything else is ignored. Not every line is a + full state. A full state that cannot be decoded ends the stream, which goes through + the normal connection-lost and reconnect path (so a server that keeps sending one + makes the app reconnect repeatedly). +- `datasources/LineFramer.swift` frames the byte stream; icon lines can be several + hundred KiB. +- Sessions may carry an `iconId` (`[a-z0-9]{1,64}`, content-derived). Every server + answers `iconRequest`; one that serves no icons never sends an `iconId`. +- `usecases/IconRequestPlanner.swift` decides what to request: at most 32 ids per + `iconRequest`, at most 64 outstanding, outstanding ids reset when the connection + drops or the app goes to the background (both end the stream). Ids without a usable + image (`notFound` or any other `error`, missing or bad data, a PNG that does not + decode) are not asked for again until the user connects anew. +- `repos/IconRepository.swift` is the entry point for icons: an actor that decodes + PNGs off the main thread and keeps a bounded memory cache over + `datasources/IconDiskCacheDataSource.swift` (Caches/AppIcons, not thread-safe, used + only through the actor). Both are keyed by icon id and requested pixel size. +- Rows show `views/SessionIconView.swift`: the icon, or a placeholder of the same size. + +### Session details + +- A session may carry an optional `detail` (one line, at most 120 characters), such as a + browser tab title, that tells apart sessions with the same `name`. It is shown + whenever present; servers may be configured never to send it. +- It is display text only. Aliases, saved order and anything else remembered about a + session keep keying on the session `id`; outgoing updates never include it. +- `SessionCell` shows it under the name (or alias) in a smaller, dimmer style on one + line, truncated at the tail. Every row reserves that line, so heights do not change + when a detail appears, changes (up to once a second) or disappears; it is not + animated, and VoiceOver reads it after the name. ## Related Resources diff --git a/Localizable.xcstrings b/Localizable.xcstrings index dc5be65..bd8e614 100644 --- a/Localizable.xcstrings +++ b/Localizable.xcstrings @@ -20,7 +20,7 @@ "About" : { }, - "Adjust the volume of every application on your Windows PC remotely. Turn the game down without leaving voice chat behind." : { + "Adjust the volume of every application on your PC remotely. Turn the game down without leaving voice chat behind." : { "comment" : "A description of the main feature of the app.", "isCommentAutoGenerated" : true }, @@ -98,8 +98,8 @@ "Done" : { }, - "Download PcVolumeControlWindows releases on GitHub" : { - "comment" : "A link that, when tapped, directs the user to the GitHub releases page for the PcVolumeControlWindows app.", + "Download PcVolumeControlServer releases on GitHub" : { + "comment" : "A link that, when tapped, directs the user to the GitHub releases page for the PcVolumeControlServer app.", "isCommentAutoGenerated" : true }, "Edit Custom Name" : { @@ -110,6 +110,9 @@ }, "Enter a custom name for \"%@\"" : { + }, + "Enter a custom name for \"%@\" (%@)" : { + }, "Enter new name" : { @@ -133,7 +136,7 @@ "Leave" : { }, - "Make sure this device and PC are on the same network, the server is allowed through Windows Firewall, and no VPN is active on either device. VPNs often block local discovery." : { + "Make sure this device and PC are on the same network, the PC's firewall allows TCP port 3000 and mDNS (UDP 5353), and no VPN is active on either device. VPNs often block local discovery." : { "comment" : "A description of troubleshooting steps for connecting to the server.", "isCommentAutoGenerated" : true }, @@ -181,14 +184,14 @@ "comment" : "A description of how to connect to the PcVolumeControl server.", "isCommentAutoGenerated" : true }, - "On your Windows PC, download the latest installer from GitHub." : { + "On your PC (Windows or Linux), download the latest release from GitHub." : { "comment" : "A step in the guide that instructs the user to download the latest installer from GitHub.", "isCommentAutoGenerated" : true }, "Opens a picker to choose the active output device" : { }, - "Opens the Windows server setup guide" : { + "Opens the server setup guide" : { "comment" : "A hint that appears when hovering over the button to", "isCommentAutoGenerated" : true }, @@ -203,12 +206,12 @@ "comment" : "The accessibility label for the app logo.", "isCommentAutoGenerated" : true }, - "PcVolumeControl needs a small, free server running on your Windows PC. Set it up once and this app can find it automatically." : { - "comment" : "A description of the purpose of the Windows server.", + "PcVolumeControl needs a small, free server running on your PC. Set it up once and this app can find it automatically." : { + "comment" : "A description of the purpose of the server.", "isCommentAutoGenerated" : true }, - "PcVolumeControlWindows releases" : { - "comment" : "A link label that, when tapped, takes the user to the GitHub releases page for the PcVolumeControlWindows repository.", + "PcVolumeControlServer releases" : { + "comment" : "A link label that, when tapped, takes the user to the GitHub releases page for the PcVolumeControlServer repository.", "isCommentAutoGenerated" : true }, "Please enter a valid TCP port (1-65535)" : { @@ -239,8 +242,8 @@ "comment" : "A button that, when pressed, replays the introductory tour.", "isCommentAutoGenerated" : true }, - "Run the installer, then start the server. If Windows Firewall asks, click Allow so the server can accept connections on private networks." : { - "comment" : "A step in the guide that instructs the user to run the installer and start the server, with a note about Windows Firewall.", + "Install the server as its README describes, then start it. On Windows, if Windows Firewall asks, click Allow so the server can accept connections on private networks." : { + "comment" : "A step in the guide that instructs the user to install and start the server, with a note about Windows Firewall.", "isCommentAutoGenerated" : true }, "Save" : { @@ -288,7 +291,7 @@ "isCommentAutoGenerated" : true }, "Share the download link to open on your PC" : { - "comment" : "A button that allows the user to share the download link to open the PcVolumeControlWindows installer on their PC.", + "comment" : "A button that allows the user to share the download link to open the PcVolumeControlServer installer on their PC.", "isCommentAutoGenerated" : true }, "Show me how to set it up" : { @@ -299,11 +302,17 @@ "comment" : "A button that lets a user skip the first-launch welcome tour.", "isCommentAutoGenerated" : true }, - "The server window shows your PC's IP address and port. The default port is 3000." : { + "The server's Status page shows your PC's IP address and port. The default port is 3000." : { "comment" : "A description of how to find the IP address and port of the server.", "isCommentAutoGenerated" : true }, - "This app talks to the PcVolumeControl server, a small program that runs on your Windows PC." : { + "This PC server is newer than this app (protocol version %lld). Update PcVolumeControl on this device to connect to it." : { + "comment" : "Error shown when the server speaks a newer protocol version than the app." + }, + "This PC server is too old (protocol version %lld). Install the latest PcVolumeControlServer on your PC to use this version of the app." : { + "comment" : "Error shown when the server speaks an older protocol version than the app." + }, + "This app talks to the PcVolumeControl server, a small program that runs on your PC." : { "comment" : "A description of how the app interacts with the server.", "isCommentAutoGenerated" : true }, diff --git a/PcVolumeControl/datasources/IconDiskCacheDataSource.swift b/PcVolumeControl/datasources/IconDiskCacheDataSource.swift new file mode 100644 index 0000000..e1d69ee --- /dev/null +++ b/PcVolumeControl/datasources/IconDiskCacheDataSource.swift @@ -0,0 +1,80 @@ +import Foundation + +protocol IconDiskCacheDataSourceProtocol { + func load(id: String, size: Int) -> Data? + func store(_ png: Data, id: String, size: Int) +} + +/// Icon PNGs on disk, one file per icon id and requested pixel size, bounded by file +/// count. When the bound is exceeded the least recently used files are evicted down to +/// three quarters of it. Invalid ids are never turned into paths. Not thread-safe: use +/// from one isolation domain. +final class IconDiskCacheDataSource: IconDiskCacheDataSourceProtocol { + private let directory: URL + private let maxEntries: Int + // Counted from the directory on first store, then maintained; eviction recounts. + private var entryCount: Int? + + init( + directory: URL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0] + .appendingPathComponent("AppIcons", isDirectory: true), + maxEntries: Int = 256 + ) { + self.directory = directory + self.maxEntries = maxEntries + } + + func load(id: String, size: Int) -> Data? { + guard let url = fileURL(for: id, size: size), let data = try? Data(contentsOf: url) else { return nil } + // The modification date doubles as the last-used date for eviction. + try? FileManager.default.setAttributes([.modificationDate: Date()], ofItemAtPath: url.path) + return data + } + + func store(_ png: Data, id: String, size: Int) { + guard let url = fileURL(for: id, size: size) else { return } + let isNewFile = !FileManager.default.fileExists(atPath: url.path) + do { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try png.write(to: url, options: .atomic) + } catch { + appLog("Failed to cache icon \(id): \(error)") + return + } + let count = entryCount.map { $0 + (isNewFile ? 1 : 0) } ?? cachedFiles().count + entryCount = count + if count > maxEntries { + evict() + } + } + + private func fileURL(for id: String, size: Int) -> URL? { + guard IconId.isValid(id) else { return nil } + return directory.appendingPathComponent("\(id)_\(size).png", isDirectory: false) + } + + private func cachedFiles() -> [URL] { + (try? FileManager.default.contentsOfDirectory( + at: directory, + includingPropertiesForKeys: [.contentModificationDateKey], + options: .skipsHiddenFiles + )) ?? [] + } + + private func evict() { + let files = cachedFiles() + let keep = maxEntries * 3 / 4 + let byLastUse = files + .map { url in + (url, (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate ?? .distantPast) + } + .sorted { $0.1 < $1.1 } + var removed = 0 + for (url, _) in byLastUse.prefix(max(files.count - keep, 0)) { + if (try? FileManager.default.removeItem(at: url)) != nil { + removed += 1 + } + } + entryCount = files.count - removed + } +} diff --git a/PcVolumeControl/datasources/LineFramer.swift b/PcVolumeControl/datasources/LineFramer.swift new file mode 100644 index 0000000..cf31cce --- /dev/null +++ b/PcVolumeControl/datasources/LineFramer.swift @@ -0,0 +1,53 @@ +import Foundation + +/// Splits a byte stream into newline-terminated lines, independent of how the bytes +/// were chunked by the socket. A trailing `\r` is dropped and blank lines are skipped. +/// A line longer than `maxLineLength` is discarded up to its terminator so one bad +/// line cannot grow the buffer without bound or end the stream. +struct LineFramer { + /// Icon replies can be several hundred KiB; the protocol requires accepting at least 1 MiB. + static let defaultMaxLineLength = 4 * 1024 * 1024 + + private let maxLineLength: Int + private var buffer: [UInt8] = [] + // Bytes at the front of `buffer` already searched for a newline. + private var searchedCount = 0 + private var discardingOverlongLine = false + + init(maxLineLength: Int = LineFramer.defaultMaxLineLength) { + self.maxLineLength = maxLineLength + } + + /// Appends `chunk` and returns every line it completes, in order. + mutating func append(_ chunk: Data) -> [Data] { + buffer.append(contentsOf: chunk) + + var lines: [Data] = [] + var lineStart = 0 + var searchFrom = searchedCount + while let newline = buffer[searchFrom...].firstIndex(of: 0x0A) { + if discardingOverlongLine { + discardingOverlongLine = false + } else { + var lineEnd = newline + if lineEnd > lineStart, buffer[lineEnd - 1] == 0x0D { + lineEnd -= 1 + } + if lineEnd > lineStart, lineEnd - lineStart <= maxLineLength { + lines.append(Data(buffer[lineStart.. maxLineLength { + buffer.removeAll() + searchedCount = 0 + discardingOverlongLine = true + } + return lines + } +} diff --git a/PcVolumeControl/datasources/VolumeTransportDataSource.swift b/PcVolumeControl/datasources/VolumeTransportDataSource.swift index e36bd0a..ab73ef0 100644 --- a/PcVolumeControl/datasources/VolumeTransportDataSource.swift +++ b/PcVolumeControl/datasources/VolumeTransportDataSource.swift @@ -15,7 +15,7 @@ struct VolumeTransportDataSource: VolumeTransportDataSourceProtocol { } func incoming() -> AsyncThrowingStream { - .streamNewlineDelimitedBytes(from: connection.bytes()) + .streamLines(from: connection.bytes()) } func close() { @@ -24,19 +24,16 @@ struct VolumeTransportDataSource: VolumeTransportDataSourceProtocol { } private extension AsyncThrowingStream where Element == Data, Failure == Error { - static func streamNewlineDelimitedBytes(from upstream: AsyncThrowingStream) + static func streamLines(from upstream: AsyncThrowingStream) -> AsyncThrowingStream { AsyncThrowingStream { continuation in - var buffer = Data() let task = Task { + var framer = LineFramer() do { for try await chunk in upstream { - buffer.append(chunk) - while let nl = buffer.firstIndex(of: 0x0A) { - let frame = buffer.prefix(upTo: nl) - buffer.removeSubrange(...nl) - continuation.yield(Data(frame)) + for line in framer.append(chunk) { + continuation.yield(line) } } continuation.finish() diff --git a/PcVolumeControl/models/IconId.swift b/PcVolumeControl/models/IconId.swift new file mode 100644 index 0000000..6d18656 --- /dev/null +++ b/PcVolumeControl/models/IconId.swift @@ -0,0 +1,10 @@ +import Foundation + +enum IconId { + /// Icon ids are 1 to 64 characters of `[a-z0-9]`, which also makes them safe file names. + static func isValid(_ id: String) -> Bool { + let bytes = id.utf8 + return (1...64).contains(bytes.count) + && bytes.allSatisfy { (0x30...0x39).contains($0) || (0x61...0x7A).contains($0) } + } +} diff --git a/PcVolumeControl/models/ServerLine.swift b/PcVolumeControl/models/ServerLine.swift new file mode 100644 index 0000000..a124a4c --- /dev/null +++ b/PcVolumeControl/models/ServerLine.swift @@ -0,0 +1,114 @@ +import Foundation + +enum WireProtocol { + /// The only protocol version this app speaks, sent in every message and required in + /// every full state. + static let version = 8 +} + +/// One line received from the server. Every line carries `protocolVersion` and exactly +/// one of `defaultDevice` (a full state) or `icon` (an icon reply). +enum ServerLine { + case state(FullState) + case icon(IconReply) + + /// Returns nil for a line to ignore: one that is not a JSON object, has neither or both + /// of the keys, or is an icon reply without an id. Throws `ProtocolVersionMismatch` for + /// a full state of another protocol version (checked before the rest is decoded, so the + /// shape of other versions does not matter) and `MalformedStateError` for a full state + /// that cannot be decoded. + static func classify(_ line: Data) throws -> ServerLine? { + do { + return try decoder.decode(Envelope.self, from: line).line + } catch let error as ProtocolVersionMismatch { + throw error + } catch let error as MalformedStateError { + throw error + } catch { + return nil + } + } + + private static let decoder = JSONDecoder() + + // Decodes the document once and picks the line type by which key is present. + private struct Envelope: Decodable { + let line: ServerLine? + + private enum CodingKeys: String, CodingKey { + case protocolVersion, defaultDevice, icon + } + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + switch (container.contains(.defaultDevice), container.contains(.icon)) { + case (true, false): + let version: Int + do { + version = try container.decode(Int.self, forKey: .protocolVersion) + } catch { + throw MalformedStateError(underlying: error) + } + guard version == WireProtocol.version else { + throw ProtocolVersionMismatch(serverVersion: version) + } + do { + line = .state(try FullState(from: decoder)) + } catch { + throw MalformedStateError(underlying: error) + } + case (false, true): + line = .icon(try container.decode(IconReply.self, forKey: .icon)) + default: + line = nil + } + } + } +} + +struct MalformedStateError: LocalizedError { + let underlying: Error + + var errorDescription: String? { + "The server sent a full state that could not be read: \(underlying.localizedDescription)" + } +} + +/// The server speaks another protocol version; the connection cannot be used. +struct ProtocolVersionMismatch: LocalizedError { + let serverVersion: Int + + /// True when the server needs updating, false when this app does. + var serverIsOlder: Bool { + serverVersion < WireProtocol.version + } + + var errorDescription: String? { + if serverIsOlder { + return String(localized: "This PC server is too old (protocol version \(serverVersion)). Install the latest PcVolumeControlServer on your PC to use this version of the app.") + } + return String(localized: "This PC server is newer than this app (protocol version \(serverVersion)). Update PcVolumeControl on this device to connect to it.") + } +} + +/// The server's answer for one requested icon id. +struct IconReply: Decodable { + let id: String + /// The PNG bytes, or nil when the server has no image for the id or sent an unusable payload. + let png: Data? + + private enum CodingKeys: String, CodingKey { + case id, data, error + } + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + id = try container.decode(String.self, forKey: .id) + // Any non-null `error` means "no image". A bad payload must still answer the id, + // so it maps to "no image" instead of failing the whole line. + let hasError = container.contains(.error) && (try? container.decodeNil(forKey: .error)) != true + let base64 = try? container.decodeIfPresent(String.self, forKey: .data) + let decoded = hasError ? nil : base64.flatMap { Data(base64Encoded: $0) } + png = decoded?.isEmpty == false ? decoded : nil + } +} diff --git a/PcVolumeControl/models/VolumeUpdateDTOs.swift b/PcVolumeControl/models/VolumeUpdateDTOs.swift index 1081254..5195a02 100644 --- a/PcVolumeControl/models/VolumeUpdateDTOs.swift +++ b/PcVolumeControl/models/VolumeUpdateDTOs.swift @@ -38,3 +38,13 @@ struct OneSession : Codable { let volume: Double let muted: Bool } + +// ask for application icons by icon id +struct AIconRequest : Codable { + struct Payload : Codable { + let ids: [String] + let size: Int + } + let protocolVersion: Int + let iconRequest: Payload +} diff --git a/PcVolumeControl/repos/IconRepository.swift b/PcVolumeControl/repos/IconRepository.swift new file mode 100644 index 0000000..c7f3c8d --- /dev/null +++ b/PcVolumeControl/repos/IconRepository.swift @@ -0,0 +1,46 @@ +import UIKit + +/// Decoded application icons by icon id and requested pixel size, cached in memory +/// (bounded) and on disk. Ids are content-derived, so entries never need invalidating. +/// Decoding runs on this actor, off the main thread. +actor IconRepository { + private let disk: IconDiskCacheDataSourceProtocol + private let memory = NSCache() + + init(disk: IconDiskCacheDataSourceProtocol = IconDiskCacheDataSource()) { + self.disk = disk + memory.countLimit = 128 + } + + /// The icons among `ids` that are cached at `size`, from memory or disk. + func cachedIcons(for ids: [String], size: Int) -> [String: UIImage] { + var found: [String: UIImage] = [:] + for id in ids { + let key = Self.key(id, size) + if let image = memory.object(forKey: key) { + found[id] = image + } else if let png = disk.load(id: id, size: size), let image = Self.decode(png) { + memory.setObject(image, forKey: key) + found[id] = image + } + } + return found + } + + /// Decodes `png`, requested at `size`, and caches it under `id`. Returns nil, caching + /// nothing, when the data is not a usable image. + func store(png: Data, for id: String, size: Int) -> UIImage? { + guard let image = Self.decode(png) else { return nil } + memory.setObject(image, forKey: Self.key(id, size)) + disk.store(png, id: id, size: size) + return image + } + + private static func key(_ id: String, _ size: Int) -> NSString { + NSString(string: "\(id)_\(size)") + } + + private static func decode(_ png: Data) -> UIImage? { + UIImage(data: png)?.preparingForDisplay() + } +} diff --git a/PcVolumeControl/repos/ServersRepository.swift b/PcVolumeControl/repos/ServersRepository.swift index 30e7215..0e30aec 100644 --- a/PcVolumeControl/repos/ServersRepository.swift +++ b/PcVolumeControl/repos/ServersRepository.swift @@ -3,11 +3,12 @@ import Network struct ServersRepository { let local: ServersLocalDataSourceProtocol let remote: TCPConnectionDataSourceProtocol + // Tests substitute a scripted transport to drive the view model without a socket. + var makeTransport: (Connection) -> VolumeTransportDataSourceProtocol = { VolumeTransportDataSource(connection: $0) } func connect(to server: DiscoveredServer) async throws -> VolumeControlRepository { let connection = try await remote.openConnection(to: server) - let transport = VolumeTransportDataSource(connection: connection) - return VolumeControlRepository(transport: transport) + return VolumeControlRepository(transport: makeTransport(connection)) } func recent() -> [DiscoveredServer] { local.loadRecent() } diff --git a/PcVolumeControl/repos/VolumeControlRepository.swift b/PcVolumeControl/repos/VolumeControlRepository.swift index a1dc78d..ca8415f 100644 --- a/PcVolumeControl/repos/VolumeControlRepository.swift +++ b/PcVolumeControl/repos/VolumeControlRepository.swift @@ -1,19 +1,21 @@ import Foundation struct VolumeControlRepository { - static let protocolVersion = 7 - let transport: VolumeTransportDataSourceProtocol - let deviceIdLookup = DeviceIdLookup() - func fullStateStream() -> AsyncThrowingStream { + /// Full states and icon replies from the server; lines of any other kind are dropped. + /// Ends with `ProtocolVersionMismatch` for a full state of another protocol version and + /// with `MalformedStateError` for one that cannot be decoded. + func serverLines() -> AsyncThrowingStream { AsyncThrowingStream { continuation in let task = Task { do { - for try await msgBytes in transport.incoming() { - let state = try JSONDecoder().decode(FullState.self, from: msgBytes) - deviceIdLookup.ingest(state.deviceIds) - continuation.yield(state) + for try await bytes in transport.incoming() { + guard let line = try ServerLine.classify(bytes) else { + appLog("Ignoring unrecognized server line (\(bytes.count) bytes)") + continue + } + continuation.yield(line) } continuation.finish() } catch { @@ -27,7 +29,7 @@ struct VolumeControlRepository { func pushDefaultDevice(id: String) async throws { let dto = ADefaultDeviceUpdate( - protocolVersion: VolumeControlRepository.protocolVersion, + protocolVersion: WireProtocol.version, defaultDevice: ADefaultDeviceUpdate.adflDevice(deviceId: id) ) try await send(dto) @@ -35,7 +37,7 @@ struct VolumeControlRepository { func pushMasterValues(id: String, muted: Bool, volume: Double) async throws { let dto = AMasterChannelUpdate( - protocolVersion: VolumeControlRepository.protocolVersion, + protocolVersion: WireProtocol.version, defaultDevice: AMasterChannelUpdate.adflDevice( deviceId: id, masterMuted: muted, @@ -45,29 +47,27 @@ struct VolumeControlRepository { try await send(dto) } - func pushSessionValues(name: String, id: String, volume: Double, muted: Bool) async throws { - let shortId = deviceIdLookup.shortId(for: id) ?? id + /// `deviceId` is the id of the device the session plays on; session ids are opaque. + func pushSessionValues(name: String, id: String, volume: Double, muted: Bool, deviceId: String) async throws { let dto = ASessionUpdate( - protocolVersion: VolumeControlRepository.protocolVersion, + protocolVersion: WireProtocol.version, defaultDevice: ASessionUpdate.adflDevice( sessions: [OneSession(name: name, id: id, volume: volume, muted: muted)], - deviceId: shortId + deviceId: deviceId ) ) try await send(dto) } - private func send(_ dto: T) async throws { - try await transport.outgoing(JSONEncoder().encode(dto)) + func requestIcons(ids: [String], size: Int) async throws { + let dto = AIconRequest( + protocolVersion: WireProtocol.version, + iconRequest: AIconRequest.Payload(ids: ids, size: size) + ) + try await send(dto) } -} -final class DeviceIdLookup { - private var table = [String: String]() - func ingest(_ mapping: [String: String]) { - table.merge(mapping) { _, new in new } - } - func shortId(for longName: String) -> String? { - table.first { longName.contains($0.key) }?.key + private func send(_ dto: T) async throws { + try await transport.outgoing(JSONEncoder().encode(dto)) } } diff --git a/PcVolumeControl/usecases/IconRequestPlanner.swift b/PcVolumeControl/usecases/IconRequestPlanner.swift new file mode 100644 index 0000000..37ea9f1 --- /dev/null +++ b/PcVolumeControl/usecases/IconRequestPlanner.swift @@ -0,0 +1,72 @@ +import CoreGraphics + +/// Decides which icon ids to request, within the protocol's limits: at most +/// `maxIdsPerRequest` ids per request and `maxOutstanding` unanswered ids per connection. +struct IconRequestPlanner { + static let maxIdsPerRequest = 32 + static let maxOutstanding = 64 + + /// Ids requested on the current connection and not answered yet, with the pixel size + /// each was requested at. + private(set) var outstanding: [String: Int] = [:] + // Ids the server had no usable image for. Kept across reconnects so they are not + // asked for again in a loop; a new planner starts clean. + private var unavailable = Set() + + /// True when a full request fits under the outstanding limit. + var hasRoomForFullBatch: Bool { + outstanding.count + Self.maxIdsPerRequest <= Self.maxOutstanding + } + + /// The requests to send now for `ids`, in order, at `size` pixels. Leaves out ids that + /// are invalid, repeated, in `skipping` (cached or being resolved locally), already + /// outstanding, or unavailable, and stops at the outstanding limit; the rest are + /// planned once replies free up room. + mutating func requests(for ids: [String], size: Int, skipping: Set) -> [[String]] { + let capacity = Self.maxOutstanding - outstanding.count + var planned: [String] = [] + var seen = Set() + for id in ids where planned.count < capacity { + guard IconId.isValid(id), + seen.insert(id).inserted, + !skipping.contains(id), + outstanding[id] == nil, + !unavailable.contains(id) + else { continue } + planned.append(id) + } + for id in planned { + outstanding[id] = size + } + + return stride(from: 0, to: planned.count, by: Self.maxIdsPerRequest).map { + Array(planned[$0.. Int? { + guard let size = outstanding.removeValue(forKey: id) else { return nil } + if !available { + unavailable.insert(id) + } + return size + } + + /// For an image that arrived but could not be decoded. + mutating func markUnavailable(_ id: String) { + unavailable.insert(id) + } + + /// Replies to ids requested on a dropped connection never arrive. + mutating func connectionDropped() { + outstanding.removeAll() + } + + /// The edge length in pixels to request for icons drawn at `points` on a display of `scale`. + static func pixelSize(points: CGFloat, scale: CGFloat) -> Int { + Int(min(max((points * scale).rounded(), 16), 256)) + } +} diff --git a/PcVolumeControl/usecases/VolumeControlUseCases.swift b/PcVolumeControl/usecases/VolumeControlUseCases.swift index 6b6dcff..662a981 100644 --- a/PcVolumeControl/usecases/VolumeControlUseCases.swift +++ b/PcVolumeControl/usecases/VolumeControlUseCases.swift @@ -12,7 +12,7 @@ struct SendMasterChannelUpdateUseCase { struct SendSessionUpdateUseCase { let repo: VolumeControlRepository - func execute(name: String, id: String, vol: Double, muted: Bool) async throws { - try await repo.pushSessionValues(name: name, id: id, volume: vol, muted: muted) + func execute(name: String, id: String, vol: Double, muted: Bool, deviceId: String) async throws { + try await repo.pushSessionValues(name: name, id: id, volume: vol, muted: muted, deviceId: deviceId) } } diff --git a/PcVolumeControl/viewmodels/MainViewModel.swift b/PcVolumeControl/viewmodels/MainViewModel.swift index 9d0c192..ffe941b 100644 --- a/PcVolumeControl/viewmodels/MainViewModel.swift +++ b/PcVolumeControl/viewmodels/MainViewModel.swift @@ -28,6 +28,9 @@ final class MainViewModel: ObservableObject { /// True only when the connection is live; controls are interactive only then. var isConnectionLive: Bool { connectionStatus == .connected } + /// Decoded icons for the current sessions, by icon id. + @Published private(set) var icons: [String: UIImage] = [:] + private let connect: ConnectToServerUseCase private var defUpdate: SendDefaultDeviceUpdateUseCase private var masterUpdate: SendMasterChannelUpdateUseCase @@ -53,17 +56,35 @@ final class MainViewModel: ObservableObject { private var connectedOverWiFi = false private var connectedOverCellular = false + // Icons. The sets describe ids at the current pixel size; + // `icons` keeps showing images of an earlier size until replacements arrive. + private let iconRepo: IconRepository + private var iconPlanner = IconRequestPlanner() + // Set by the session list; no icons are requested until then. + private var iconPixelSize: Int? + private var iconsAtCurrentSize = Set() + // A cache lookup or decode is in flight. + private var iconsResolving = Set() + // Looked up in the local cache and not found there: only these are requested. + private var iconsMissingFromCache = Set() + // Bumped when in-flight lookups and decodes no longer apply (new pixel size, user disconnect). + private var iconGeneration = 0 + // Bumped when `iconPlanner` is replaced. + private var iconPlannerEpoch = 0 + init(connect: ConnectToServerUseCase, defUpdate: SendDefaultDeviceUpdateUseCase, masterUpdate: SendMasterChannelUpdateUseCase, sessionUpdate: SendSessionUpdateUseCase, - serversRepo: ServersRepository) + serversRepo: ServersRepository, + iconRepo: IconRepository = IconRepository()) { self.connect = connect self.defUpdate = defUpdate self.masterUpdate = masterUpdate self.sessionUpdate = sessionUpdate self.serversRepo = serversRepo + self.iconRepo = iconRepo NotificationCenter.default.addObserver( forName: UIApplication.didEnterBackgroundNotification, @@ -156,6 +177,11 @@ final class MainViewModel: ObservableObject { closeConnection(repo) currentRepo = nil } + // The next connection may be to another server, so forget its unavailable icons too. + iconPlanner = IconRequestPlanner() + iconPlannerEpoch += 1 + icons = [:] + resetIconResolution() // Clear the full state to trigger UI reset fullState = nil @@ -177,6 +203,8 @@ final class MainViewModel: ObservableObject { reconnectTask?.cancel() reconnectTask = nil stopPathMonitor() + // Replies still in flight are no longer read once the stream is cancelled. + iconPlanner.connectionDropped() } private func appWillEnterForeground() { @@ -198,6 +226,7 @@ final class MainViewModel: ObservableObject { repo.transport.close() currentRepo = nil } + iconPlanner.connectionDropped() startReconnectLoop(to: server) } @@ -223,6 +252,7 @@ final class MainViewModel: ObservableObject { repo.transport.close() currentRepo = nil } + iconPlanner.connectionDropped() updateSharedStateDisconnected() guard let server = lastConnectedServer else { @@ -341,15 +371,27 @@ final class MainViewModel: ObservableObject { private func subscribe(to repo: VolumeControlRepository) { streamTask = Task { do { - for try await state in repo.fullStateStream() { + for try await line in repo.serverLines() { // Stop applying updates after cancellation so an in-flight value can't resurrect state. if Task.isCancelled { break } - fullState = state // view state only here - connectionStatus = .connected - updateSharedState(with: state) // Update widget state + switch line { + case .state(let state): + fullState = state // view state only here + connectionStatus = .connected + updateSharedState(with: state) // Update widget state + resolveIcons(for: state) + case .icon(let reply): + handleIconReply(reply) + } } // Stream ended without throwing (server closed the connection). if !Task.isCancelled { handleConnectionLost() } + } catch let mismatch as ProtocolVersionMismatch { + // Reconnecting cannot help: leave the server and tell the user which side to update. + if !Task.isCancelled { + disconnect() + self.error = mismatch.localizedDescription + } } catch { // RST / keepalive timeout / read error. if !Task.isCancelled { handleConnectionLost() } @@ -378,6 +420,100 @@ final class MainViewModel: ObservableObject { } } + // MARK: - Icons + + /// Called by the session list with the pixel size it draws icons at. + func setIconPixelSize(_ size: Int) { + guard size != iconPixelSize else { return } + iconPixelSize = size + resetIconResolution() + if let state = fullState { resolveIcons(for: state) } + } + + private func resetIconResolution() { + iconGeneration += 1 + iconsAtCurrentSize.removeAll() + iconsResolving.removeAll() + iconsMissingFromCache.removeAll() + } + + private func resolveIcons(for state: FullState) { + guard let size = iconPixelSize else { return } + let ids = state.iconIds + let current = Set(ids) + if icons.keys.contains(where: { !current.contains($0) }) { + icons = icons.filter { current.contains($0.key) } + } + iconsAtCurrentSize.formIntersection(current) + iconsMissingFromCache.formIntersection(current) + + let unchecked = ids.filter { + !iconsAtCurrentSize.contains($0) && !iconsResolving.contains($0) && !iconsMissingFromCache.contains($0) + } + if !unchecked.isEmpty { + loadCachedIcons(unchecked, size: size) + } + requestMissingIcons() + } + + private func loadCachedIcons(_ ids: [String], size: Int) { + let generation = iconGeneration + iconsResolving.formUnion(ids) + Task { + let found = await iconRepo.cachedIcons(for: ids, size: size) + guard generation == iconGeneration else { return } + iconsResolving.subtract(ids) + if !found.isEmpty { + icons.merge(found) { _, cached in cached } + } + iconsAtCurrentSize.formUnion(found.keys) + iconsMissingFromCache.formUnion(ids.filter { found[$0] == nil }) + requestMissingIcons() + } + } + + private func requestMissingIcons() { + guard let state = fullState, let size = iconPixelSize, let repo = currentRepo else { return } + let skipping = Set(state.iconIds).subtracting(iconsMissingFromCache).union(iconsResolving) + let batches = iconPlanner.requests(for: state.iconIds, size: size, skipping: skipping) + // A failed send means the connection is failing; its loss resets the outstanding ids. + for ids in batches { + Task { try? await repo.requestIcons(ids: ids, size: size) } + } + } + + private func handleIconReply(_ reply: IconReply) { + defer { + // Ids left out at the outstanding limit are requested as replies free up room. + if iconPlanner.hasRoomForFullBatch { requestMissingIcons() } + } + // A reply this connection did not ask for is dropped. + guard let size = iconPlanner.recordReply(for: reply.id, available: reply.png != nil), + let png = reply.png + else { return } + + let id = reply.id + let generation = iconGeneration + let plannerEpoch = iconPlannerEpoch + let isCurrentSize = size == iconPixelSize + if isCurrentSize { + iconsResolving.insert(id) + } + Task { + let image = await iconRepo.store(png: png, for: id, size: size) + // An undecodable image stays unavailable whatever size is drawn now. + if image == nil, plannerEpoch == iconPlannerEpoch { + iconPlanner.markUnavailable(id) + } + guard generation == iconGeneration, isCurrentSize else { return } + iconsResolving.remove(id) + guard let image else { return } + icons[id] = image + iconsAtCurrentSize.insert(id) + iconsMissingFromCache.remove(id) + } + } + // MARK: - Shared State Management (for Widget) private func updateSharedState(with state: FullState) { @@ -423,12 +559,12 @@ final class MainViewModel: ObservableObject { func updateMaster(id: String, muted: Bool, vol: Double) { Task { try? await masterUpdate.execute(id: id, muted: muted, volume: vol) } } - func updateSession(name: String, id: String, vol: Double, muted: Bool) { - Task { try? await sessionUpdate.execute(name: name, id: id, vol: vol, muted: muted) } - } - + // Sessions shown are those of the current default device, so updates go to it. func updateSession(_ session: FullState.Session) async throws { - try await sessionUpdate.execute(name: session.name, id: session.id, vol: session.volume, muted: session.muted) + guard let deviceId = fullState?.defaultDevice.deviceId else { return } + try await sessionUpdate.execute( + name: session.name, id: session.id, vol: session.volume, muted: session.muted, deviceId: deviceId + ) } // MARK: - Server Management @@ -628,6 +764,11 @@ class FullState: Codable, Equatable { var muted: Bool var name: String var volume: Double + // Content-derived icon id; absent until the server resolves the icon, or if it has none. + var iconId: String? = nil + // Display-only label telling same-named sessions apart (a browser tab title). + // Never an identity: aliases and saved state key on `id`. + var detail: String? = nil } var defaultDevice: theDefaultDevice let deviceIds: [String: String] @@ -638,4 +779,10 @@ class FullState: Codable, Equatable { self.deviceIds = deviceIds self.defaultDevice = defaultDevice } + + /// Distinct icon ids of the default device's sessions, in session order. + var iconIds: [String] { + var seen = Set() + return defaultDevice.sessions.compactMap(\.iconId).filter { seen.insert($0).inserted } + } } diff --git a/PcVolumeControl/viewmodels/SliderViewModel.swift b/PcVolumeControl/viewmodels/SliderViewModel.swift index eae5f81..154ad76 100644 --- a/PcVolumeControl/viewmodels/SliderViewModel.swift +++ b/PcVolumeControl/viewmodels/SliderViewModel.swift @@ -55,7 +55,7 @@ final class SliderViewModel: ObservableObject { func reorder(from source: IndexSet, to destination: Int) { sessions.move(fromOffsets: source, toOffset: destination) if preserveSessionOrder { - savedOrder = sessions.map { $0.id } + saveOrderIfChanged() } } @@ -145,71 +145,25 @@ final class SliderViewModel: ObservableObject { devices = state.deviceIds } - // Parse session name from ID and fallback name using new protocol - private func parseSessionDisplayName(sessionId: String, fallbackName: String) -> String { - // Check for new protocol format: |PCVC# - if let pcvcRange = sessionId.range(of: "|PCVC#") { - let purposeStart = sessionId.index(pcvcRange.upperBound, offsetBy: 0) - let purpose = String(sessionId[purposeStart...]) - - // Convert purpose to user-friendly display name - switch purpose.lowercased() { - case "discord-voice": - return "Discord (Voice)" - case "discord-notifications": - return "Discord (Notifications)" - default: - // For other purposes, capitalize and format nicely - let formattedPurpose = purpose.replacingOccurrences(of: "-", with: " ") - .split(separator: " ") - .map { $0.prefix(1).uppercased() + $0.dropFirst().lowercased() } - .joined(separator: " ") - return "\(fallbackName) (\(formattedPurpose))" - } - } - - // Use existing backward compatible logic - return fallbackName - } - private func updateSessionsRespectingDebounce(with incoming: [FullState.Session]) { - // Apply new naming protocol to sessions - let processedSessions = incoming.map { session in - let displayName = parseSessionDisplayName(sessionId: session.id, fallbackName: session.name) - return FullState.Session( - id: session.id, - muted: session.muted, - name: displayName, - volume: session.volume - ) - } - // If preserving order and we have a saved order, use it if preserveSessionOrder && !savedOrder.isEmpty { - updateWithSavedOrder(incomingSessions: processedSessions) + updateWithSavedOrder(incomingSessions: incoming) } // If we have sessions and user has reordered, preserve current order else if !sessions.isEmpty { - updatePreservingCurrentOrder(incomingSessions: processedSessions) + updatePreservingCurrentOrder(incomingSessions: incoming) } // Otherwise sort alphabetically, but respect editingIds else { - let sortedSessions = processedSessions.sorted { - $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending - } + let sortedSessions = incoming.sorted(by: Self.inDisplayOrder) // If any sessions are being edited, preserve their values if !editingIds.isEmpty { sessions = sortedSessions.map { incoming in if editingIds.contains(incoming.id), let existing = sessions.first(where: { $0.id == incoming.id }) { - // Keep current values for editing session - return FullState.Session( - id: existing.id, - muted: existing.muted, - name: incoming.name, - volume: existing.volume - ) + return incoming.keepingUserValues(of: existing) } else { return incoming } @@ -249,18 +203,13 @@ final class SliderViewModel: ObservableObject { var remainingSessions = [FullState.Session]() // Add sessions in saved order - for sessionId in savedOrder { + let saved = savedOrder + let savedIds = Set(saved) + for sessionId in saved { if let session = incomingDict[sessionId] { if editingIds.contains(sessionId), let existingIdx = sessions.firstIndex(where: { $0.id == sessionId }) { - // Keep current values for editing session - let existing = sessions[existingIdx] - orderedSessions.append(FullState.Session( - id: sessionId, - muted: existing.muted, - name: session.name, - volume: existing.volume - )) + orderedSessions.append(session.keepingUserValues(of: sessions[existingIdx])) } else { orderedSessions.append(session) } @@ -269,16 +218,16 @@ final class SliderViewModel: ObservableObject { // Add new sessions not in saved order for session in incomingSessions { - if !savedOrder.contains(session.id) { + if !savedIds.contains(session.id) { remainingSessions.append(session) } } - remainingSessions.sort { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending } + remainingSessions.sort(by: Self.inDisplayOrder) sessions = orderedSessions + remainingSessions // Update saved order - savedOrder = sessions.map { $0.id } + saveOrderIfChanged() } private func updatePreservingCurrentOrder(incomingSessions: [FullState.Session]) { @@ -296,13 +245,7 @@ final class SliderViewModel: ObservableObject { guard let incoming = incomingDict[session.id] else { continue } if editingIds.contains(session.id) { - // Keep current values for editing session - updatedSessions.append(FullState.Session( - id: session.id, - muted: session.muted, - name: incoming.name, - volume: session.volume - )) + updatedSessions.append(incoming.keepingUserValues(of: session)) } else { updatedSessions.append(incoming) } @@ -311,14 +254,45 @@ final class SliderViewModel: ObservableObject { // Add new sessions at the end let existingIds = Set(sessions.map { $0.id }) let newSessions = incomingSessions.filter { !existingIds.contains($0.id) } - let sortedNewSessions = newSessions.sorted { - $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending - } + let sortedNewSessions = newSessions.sorted(by: Self.inDisplayOrder) sessions = updatedSessions + sortedNewSessions if preserveSessionOrder { - savedOrder = sessions.map { $0.id } + saveOrderIfChanged() } } + + // States can arrive every second (session details), so skip writes that change nothing. + private func saveOrderIfChanged() { + let order = sessions.map { $0.id } + if order != savedOrder { + savedOrder = order + } + } + + // By name; same-named sessions (told apart only by their detail) by id, numbers in ids + // compared numerically, so their order is stable and never depends on the detail. + private static func inDisplayOrder(_ lhs: FullState.Session, _ rhs: FullState.Session) -> Bool { + switch lhs.name.localizedCaseInsensitiveCompare(rhs.name) { + case .orderedAscending: return true + case .orderedDescending: return false + case .orderedSame: + switch lhs.id.localizedStandardCompare(rhs.id) { + case .orderedAscending: return true + case .orderedDescending: return false + case .orderedSame: return lhs.id < rhs.id + } + } + } +} + +private extension FullState.Session { + /// This incoming session with the volume and mute of `existing`, for a session the user is editing. + func keepingUserValues(of existing: FullState.Session) -> FullState.Session { + var merged = self + merged.muted = existing.muted + merged.volume = existing.volume + return merged + } } diff --git a/PcVolumeControl/views/IntroTourView.swift b/PcVolumeControl/views/IntroTourView.swift index 10a5366..b3e3dd9 100644 --- a/PcVolumeControl/views/IntroTourView.swift +++ b/PcVolumeControl/views/IntroTourView.swift @@ -54,7 +54,7 @@ struct IntroTourView: View { .fontWeight(.bold) .foregroundColor(.white) .multilineTextAlignment(.center) - Text("Adjust the volume of every application on your Windows PC remotely. Turn the game down without leaving voice chat behind.") + Text("Adjust the volume of every application on your PC remotely. Turn the game down without leaving voice chat behind.") .font(.subheadline) .foregroundColor(.gray) .multilineTextAlignment(.center) @@ -76,7 +76,7 @@ struct IntroTourView: View { .fontWeight(.bold) .foregroundColor(.white) .multilineTextAlignment(.center) - Text("This app talks to the PcVolumeControl server, a small program that runs on your Windows PC.") + Text("This app talks to the PcVolumeControl server, a small program that runs on your PC.") .font(.subheadline) .foregroundColor(.gray) .multilineTextAlignment(.center) diff --git a/PcVolumeControl/views/MainView.swift b/PcVolumeControl/views/MainView.swift index bf585ae..7068b97 100644 --- a/PcVolumeControl/views/MainView.swift +++ b/PcVolumeControl/views/MainView.swift @@ -109,7 +109,7 @@ struct MainView: View { .padding(.vertical, 12) .accessibilityElement(children: .combine) } - .accessibilityHint("Opens the Windows server setup guide") + .accessibilityHint("Opens the server setup guide") } .readableContentWidth() } @@ -269,7 +269,7 @@ struct MainView: View { // Multiple output devices so the master-device selector has a // meaningful list; "mock-device" is the selected default. viewModel.fullState = FullState( - protocolVersion: 7, + protocolVersion: WireProtocol.version, deviceIds: [ "mock-device": "Speakers (HDMI)", "headphones": "Headphones (Bluetooth)", diff --git a/PcVolumeControl/views/ServerSetupGuideView.swift b/PcVolumeControl/views/ServerSetupGuideView.swift index fabb9e4..4a48664 100644 --- a/PcVolumeControl/views/ServerSetupGuideView.swift +++ b/PcVolumeControl/views/ServerSetupGuideView.swift @@ -2,39 +2,38 @@ // ServerSetupGuideView.swift // PcVolumeControl // -// Step-by-step guide for installing the Windows companion server. +// Step-by-step guide for installing the companion server. // Designed to work both pushed onto a NavigationStack (intro tour, // Settings) and wrapped in a sheet (connect screen footer). // import SwiftUI -// Single source of truth for the Windows server download location. +// Single source of truth for the server download location. enum ServerDownload { - static let releasesURL = URL(string: "https://github.com/PcVolumeControl/PcVolumeControlWindows/releases/latest")! + static let releasesURL = URL(string: "https://github.com/PcVolumeControl/PcVolumeControlServer/releases/latest")! static let organizationURL = URL(string: "https://github.com/PcVolumeControl")! - static var supportedProtocolVersion: Int { VolumeControlRepository.protocolVersion } } struct ServerSetupGuideView: View { var body: some View { ScrollView { VStack(alignment: .leading, spacing: 16) { - Text("PcVolumeControl needs a small, free server running on your Windows PC. Set it up once and this app can find it automatically.") + Text("PcVolumeControl needs a small, free server running on your PC. Set it up once and this app can find it automatically.") .font(.subheadline) .foregroundColor(.gray) SetupStepRow(number: 1, title: "Download the server") { - Text("On your Windows PC, download the latest installer from GitHub.") + Text("On your PC (Windows or Linux), download the latest release from GitHub.") Link(destination: ServerDownload.releasesURL) { HStack(spacing: 4) { Image(systemName: "link") - Text("PcVolumeControlWindows releases") + Text("PcVolumeControlServer releases") } .font(.footnote) .foregroundColor(.sliderPink) } - .accessibilityLabel("Download PcVolumeControlWindows releases on GitHub") + .accessibilityLabel("Download PcVolumeControlServer releases on GitHub") ShareLink(item: ServerDownload.releasesURL) { HStack(spacing: 4) { Image(systemName: "square.and.arrow.up") @@ -47,11 +46,11 @@ struct ServerSetupGuideView: View { } SetupStepRow(number: 2, title: "Install and run it") { - Text("Run the installer, then start the server. If Windows Firewall asks, click Allow so the server can accept connections on private networks.") + Text("Install the server as its README describes, then start it. On Windows, if Windows Firewall asks, click Allow so the server can accept connections on private networks.") } SetupStepRow(number: 3, title: "Find the address") { - Text("The server window shows your PC's IP address and port. The default port is 3000.") + Text("The server's Status page shows your PC's IP address and port. The default port is 3000.") } SetupStepRow(number: 4, title: "Connect from this app") { @@ -63,7 +62,7 @@ struct ServerSetupGuideView: View { .font(.subheadline) .fontWeight(.semibold) .foregroundColor(.white) - Text("Make sure this device and PC are on the same network, the server is allowed through Windows Firewall, and no VPN is active on either device. VPNs often block local discovery.") + Text("Make sure this device and PC are on the same network, the PC's firewall allows TCP port 3000 and mDNS (UDP 5353), and no VPN is active on either device. VPNs often block local discovery.") .font(.footnote) .foregroundColor(.gray) } @@ -85,7 +84,7 @@ struct ServerSetupGuideView: View { } .padding(.top, 4) - Text("App \(Bundle.main.appVersion) · Server protocol v\(ServerDownload.supportedProtocolVersion)") + Text("App \(Bundle.main.appVersion) · Server protocol v\(WireProtocol.version)") .font(.caption2) .foregroundColor(.gray.opacity(0.5)) .frame(maxWidth: .infinity, alignment: .center) diff --git a/PcVolumeControl/views/SessionCell.swift b/PcVolumeControl/views/SessionCell.swift index 234ffc5..1973181 100644 --- a/PcVolumeControl/views/SessionCell.swift +++ b/PcVolumeControl/views/SessionCell.swift @@ -140,6 +140,7 @@ struct RecessedCapsuleToggleStyle: ToggleStyle { struct SessionCell: View { @Binding var session: FullState.Session + var icon: UIImage? = nil var isChat: Bool = false var chatMode: Bool = false var isMasterMuted: Bool = false @@ -165,6 +166,8 @@ struct SessionCell: View { // Show a dialog to edit the alias for this session @State private var isEditingAlias = false @State private var newAlias = "" + // Captured when the prompt opens: the live detail can change while the user types. + @State private var aliasPromptDetail: String? = nil private var isInEditMode: Bool { editMode?.wrappedValue == .active @@ -178,6 +181,58 @@ struct SessionCell: View { (muted || masterMuted) ? 0 : volume } + // Alias if the user set one, otherwise the session's name. + private var displayName: String { + aliasManager.displayNameForSession(sessionId: session.id, originalName: session.name) + } + + private var detail: String? { + guard let detail = session.detail?.trimmingCharacters(in: .whitespacesAndNewlines), + !detail.isEmpty else { return nil } + return detail + } + + /// The row's spoken name: the display name, then the detail when there is one. + static func spokenName(_ displayName: String, detail: String?) -> String { + guard let detail else { return displayName } + return "\(displayName), \(detail)" + } + + // The hidden stack reserves the detail's line in every row, so a row keeps its height + // when a detail appears, changes or disappears; without one the name is centred in it. + private var nameAndDetail: some View { + ZStack(alignment: .leading) { + VStack(alignment: .leading, spacing: 1) { + nameLine("X") + detailLine("X") + } + .hidden() + + VStack(alignment: .leading, spacing: 1) { + nameLine(displayName) + .foregroundColor(.white) + .truncationMode(.middle) + if let detail { + detailLine(detail) + .foregroundColor(.white.opacity(0.6)) + .truncationMode(.tail) + } + } + } + .animation(nil, value: detail) + .accessibilityElement(children: .ignore) + .accessibilityLabel(SessionCell.spokenName(displayName, detail: detail)) + } + + // Shared by the visible lines and the hidden ones that reserve their height. + private func nameLine(_ text: String) -> some View { + Text(text).font(.subheadline).fontWeight(.medium).lineLimit(1) + } + + private func detailLine(_ text: String) -> some View { + Text(text).font(.caption).lineLimit(1) + } + private var displayVolume: Double { SessionCell.displayVolume( volume: session.volume, @@ -201,6 +256,8 @@ struct SessionCell: View { } HStack { + SessionIconView(image: icon) + // Chat balance indicator if isChat { Image(systemName: "arrow.up.arrow.down.circle.fill") @@ -208,13 +265,7 @@ struct SessionCell: View { .font(.system(size: 16)) } - // Use alias if available, otherwise use original name - Text(aliasManager.displayNameForSession(sessionId: session.id, originalName: session.name)) - .font(.subheadline) - .fontWeight(.medium) - .foregroundColor(.white) - .lineLimit(1) - .truncationMode(.middle) + nameAndDetail Spacer() @@ -267,7 +318,7 @@ struct SessionCell: View { value: $localVolume, range: 0...100, steps: 10, - accessibilityLabel: "Volume for \(aliasManager.displayNameForSession(sessionId: session.id, originalName: session.name))", + accessibilityLabel: "Volume for \(SessionCell.spokenName(displayName, detail: detail))", onEditingChanged: { editing in if editing { ignoreServerUpdates = true @@ -380,13 +431,18 @@ struct SessionCell: View { Button("Cancel", role: .cancel) {} } message: { - Text("Enter a custom name for \"\(session.name)\"") + if let detail = aliasPromptDetail { + Text("Enter a custom name for \"\(session.name)\" (\(detail))") + } else { + Text("Enter a custom name for \"\(session.name)\"") + } } } private func showAliasEditingPrompt() { // Initialize with current alias if exists newAlias = aliasManager.sessionAliases[session.id] ?? "" + aliasPromptDetail = detail isEditingAlias = true } } @@ -396,7 +452,8 @@ struct SessionCell: View { id: "radio.exe", muted: false, name: "Radio", - volume: 75.0 + volume: 75.0, + detail: "Morning Show - Live" ) SessionCell( diff --git a/PcVolumeControl/views/SessionIconView.swift b/PcVolumeControl/views/SessionIconView.swift new file mode 100644 index 0000000..982e4a6 --- /dev/null +++ b/PcVolumeControl/views/SessionIconView.swift @@ -0,0 +1,50 @@ +import SwiftUI + +/// An application's icon in a session row, or a neutral placeholder of the same size +/// while the icon is unknown, loading or unavailable. Decorative for VoiceOver: the +/// row's name already identifies the application. +struct SessionIconView: View { + let image: UIImage? + + @Environment(\.dynamicTypeSize) private var dynamicTypeSize + + /// Edge length in points: 22 at the default Dynamic Type size, scaled like `.subheadline` + /// (the row's name). + nonisolated static func pointSize(for dynamicTypeSize: DynamicTypeSize) -> CGFloat { + let traits = UITraitCollection(preferredContentSizeCategory: UIContentSizeCategory(dynamicTypeSize)) + return UIFontMetrics(forTextStyle: .subheadline).scaledValue(for: 22, compatibleWith: traits) + } + + var body: some View { + let size = Self.pointSize(for: dynamicTypeSize) + ZStack { + if let image { + Image(uiImage: image) + .resizable() + .interpolation(.high) + .scaledToFit() + } else { + RoundedRectangle(cornerRadius: size * 0.22, style: .continuous) + .fill(Color.white.opacity(0.12)) + Image(systemName: "waveform") + .resizable() + .scaledToFit() + .padding(size * 0.25) + .foregroundColor(.white.opacity(0.45)) + } + } + .frame(width: size, height: size) + .accessibilityHidden(true) + } +} + +#Preview { + HStack { + SessionIconView(image: nil) + Text("Spotify") + .font(.subheadline) + .foregroundColor(.white) + } + .padding() + .background(Color.almostBlack) +} diff --git a/PcVolumeControl/views/SliderView.swift b/PcVolumeControl/views/SliderView.swift index 8f84fdb..08a999a 100644 --- a/PcVolumeControl/views/SliderView.swift +++ b/PcVolumeControl/views/SliderView.swift @@ -8,6 +8,12 @@ struct SliderView: View { @State private var showSettings = false @State private var showOverlay = false + @Environment(\.displayScale) private var displayScale + @Environment(\.dynamicTypeSize) private var dynamicTypeSize + private var iconPixelSize: Int { + IconRequestPlanner.pixelSize(points: SessionIconView.pointSize(for: dynamicTypeSize), scale: displayScale) + } + // Connection-status banner; lives outside the disabled content so its buttons stay tappable. @ViewBuilder private var connectionBanner: some View { @@ -85,6 +91,7 @@ struct SliderView: View { ForEach($vm.sessions) { $session in SessionCell( session: $session, + icon: session.iconId.flatMap { mainVM.icons[$0] }, isChat: vm.chatBalanceSessionId == session.id, chatMode: vm.chatBalanceMode, isMasterMuted: vm.isMasterMuted, @@ -134,6 +141,10 @@ struct SliderView: View { .onReceive(mainVM.$fullState) { newState in vm.fullState = newState } + .onAppear { mainVM.setIconPixelSize(iconPixelSize) } + .onChange(of: iconPixelSize) { _, newSize in + mainVM.setIconPixelSize(newSize) + } } } diff --git a/PcVolumeControlTests/IconCacheTests.swift b/PcVolumeControlTests/IconCacheTests.swift new file mode 100644 index 0000000..3d9b36c --- /dev/null +++ b/PcVolumeControlTests/IconCacheTests.swift @@ -0,0 +1,126 @@ +// +// IconCacheTests.swift +// PcVolumeControlTests +// +// The on-disk icon cache and the repository that decodes and caches icons. +// + +import XCTest +import UIKit +@testable import PcVolumeControl + +final class IconCacheTests: XCTestCase { + + private var directory: URL! + + override func setUpWithError() throws { + try super.setUpWithError() + directory = FileManager.default.temporaryDirectory + .appendingPathComponent("IconCacheTests-\(UUID().uuidString)", isDirectory: true) + } + + override func tearDownWithError() throws { + try? FileManager.default.removeItem(at: directory) + try super.tearDownWithError() + } + + private func samplePNG() throws -> Data { + guard case .icon(let reply) = try ServerLine.classify(Data(ServerLineTests.iconImageReply.utf8)) else { + throw XCTSkip("Sample icon reply did not decode") + } + return try XCTUnwrap(reply.png) + } + + private func cachedFileNames() -> [String] { + ((try? FileManager.default.contentsOfDirectory(atPath: directory.path)) ?? []).sorted() + } + + // MARK: - Disk cache + + func testStoreThenLoad() { + let disk = IconDiskCacheDataSource(directory: directory) + let data = Data([1, 2, 3]) + disk.store(data, id: "abc123", size: 66) + XCTAssertEqual(disk.load(id: "abc123", size: 66), data) + XCTAssertEqual(cachedFileNames(), ["abc123_66.png"]) + } + + func testLoadOfUnknownIdOrSizeIsNil() { + let disk = IconDiskCacheDataSource(directory: directory) + XCTAssertNil(disk.load(id: "abc123", size: 66)) + disk.store(Data([1]), id: "abc123", size: 66) + XCTAssertNil(disk.load(id: "abc123", size: 132)) + } + + func testInvalidIdsAreNeverUsedAsPaths() { + let disk = IconDiskCacheDataSource(directory: directory) + for id in ["../escape", "a/b", "ABC", "", ".hidden", String(repeating: "a", count: 65)] { + disk.store(Data([1]), id: id, size: 66) + XCTAssertNil(disk.load(id: id, size: 66), id) + } + XCTAssertEqual(cachedFileNames(), []) + XCTAssertFalse(FileManager.default.fileExists( + atPath: directory.deletingLastPathComponent().appendingPathComponent("escape_66.png").path + )) + } + + func testCacheIsBoundedByEntryCount() throws { + let disk = IconDiskCacheDataSource(directory: directory, maxEntries: 4) + for index in 0..<4 { + disk.store(Data([UInt8(index)]), id: "old\(index)", size: 66) + } + // Make the existing files clearly older than anything stored next, oldest first. + for (offset, name) in cachedFileNames().enumerated() { + try FileManager.default.setAttributes( + [.modificationDate: Date(timeIntervalSinceNow: Double(offset - 10) * 60)], + ofItemAtPath: directory.appendingPathComponent(name).path + ) + } + // Loading refreshes "old0", so "old1" and "old2" are now the least recently used. + XCTAssertNotNil(disk.load(id: "old0", size: 66)) + + // Exceeding 4 entries evicts down to 3 (three quarters). + disk.store(Data([9]), id: "new0", size: 66) + XCTAssertEqual(cachedFileNames(), ["new0_66.png", "old0_66.png", "old3_66.png"]) + + disk.store(Data([9]), id: "new1", size: 66) + XCTAssertEqual(cachedFileNames(), ["new0_66.png", "new1_66.png", "old0_66.png", "old3_66.png"]) + } + + func testRewritingAnEntryDoesNotCountTwice() { + let disk = IconDiskCacheDataSource(directory: directory, maxEntries: 2) + disk.store(Data([1]), id: "a", size: 66) + disk.store(Data([2]), id: "b", size: 66) + disk.store(Data([3]), id: "b", size: 66) + XCTAssertEqual(cachedFileNames(), ["a_66.png", "b_66.png"]) + } + + // MARK: - Repository + + func testRepositoryStoresDecodedIconsAndReadsThemBack() async throws { + let png = try samplePNG() + let id = "6b58026ae167f8f2e802f2531657443c" + let repo = IconRepository(disk: IconDiskCacheDataSource(directory: directory)) + + let before = await repo.cachedIcons(for: [id], size: 16) + XCTAssertTrue(before.isEmpty) + let stored = await repo.store(png: png, for: id, size: 16) + XCTAssertNotNil(stored) + XCTAssertEqual(cachedFileNames(), ["\(id)_16.png"]) + + // A fresh repository (empty memory cache) finds it on disk, at that size only. + let reloaded = IconRepository(disk: IconDiskCacheDataSource(directory: directory)) + let found = await reloaded.cachedIcons(for: [id, "other"], size: 16) + XCTAssertEqual(Array(found.keys), [id]) + XCTAssertEqual(found[id].map { $0.size.width * $0.scale }, 16) + let otherSize = await reloaded.cachedIcons(for: [id], size: 32) + XCTAssertTrue(otherSize.isEmpty) + } + + func testRepositoryRejectsDataThatIsNotAnImage() async { + let repo = IconRepository(disk: IconDiskCacheDataSource(directory: directory)) + let stored = await repo.store(png: Data("not a png".utf8), for: "abc", size: 16) + XCTAssertNil(stored) + XCTAssertEqual(cachedFileNames(), []) + } +} diff --git a/PcVolumeControlTests/IconRequestPlannerTests.swift b/PcVolumeControlTests/IconRequestPlannerTests.swift new file mode 100644 index 0000000..3c2d6fc --- /dev/null +++ b/PcVolumeControlTests/IconRequestPlannerTests.swift @@ -0,0 +1,140 @@ +// +// IconRequestPlannerTests.swift +// PcVolumeControlTests +// +// Which icon ids are requested, and when, within the protocol's limits. +// + +import XCTest +import SwiftUI +@testable import PcVolumeControl + +final class IconRequestPlannerTests: XCTestCase { + + private func ids(_ count: Int) -> [String] { + (0.. = []) -> [[String]] { + planner.requests(for: ids, size: 66, skipping: skipping) + } + + func testDuplicatesAreRequestedOnce() { + var planner = IconRequestPlanner() + XCTAssertEqual(plan(&planner, ["a", "b", "a", "b", "c"]), [["a", "b", "c"]]) + } + + func testSkippedAndInvalidIdsAreNotRequested() { + var planner = IconRequestPlanner() + let batches = plan( + &planner, + ["cached", "UPPER", "", "has-dash", String(repeating: "a", count: 65), "wanted"], + skipping: ["cached"] + ) + XCTAssertEqual(batches, [["wanted"]]) + } + + func testOutstandingIdsAreNotRequestedAgain() { + var planner = IconRequestPlanner() + XCTAssertEqual(plan(&planner, ["a", "b"]), [["a", "b"]]) + XCTAssertEqual(plan(&planner, ["a", "b", "c"]), [["c"]]) + XCTAssertEqual(planner.outstanding, ["a": 66, "b": 66, "c": 66]) + } + + func testBatchesHoldAtMost32Ids() { + var planner = IconRequestPlanner() + let batches = plan(&planner, ids(40)) + XCTAssertEqual(batches.map(\.count), [32, 8]) + XCTAssertEqual(batches.flatMap { $0 }, ids(40)) + } + + func testAtMost64IdsAreOutstanding() { + var planner = IconRequestPlanner() + let all = ids(100) + XCTAssertEqual(plan(&planner, all).map(\.count), [32, 32]) + XCTAssertEqual(planner.outstanding.count, 64) + XCTAssertFalse(planner.hasRoomForFullBatch) + + // Full: nothing more until replies arrive. + XCTAssertEqual(plan(&planner, all), []) + + for id in all.prefix(10) { + XCTAssertEqual(planner.recordReply(for: id, available: true), 66) + } + // Answered ids are now cached by the caller and skipped. + XCTAssertEqual(plan(&planner, all, skipping: Set(all.prefix(10))), [Array(all[64..<74])]) + XCTAssertEqual(planner.outstanding.count, 64) + } + + func testRoomForFullBatchOnceEnoughRepliesArrive() { + var planner = IconRequestPlanner() + let all = ids(64) + _ = plan(&planner, all) + for id in all.prefix(31) { + _ = planner.recordReply(for: id, available: true) + } + XCTAssertFalse(planner.hasRoomForFullBatch) + _ = planner.recordReply(for: all[31], available: true) + XCTAssertTrue(planner.hasRoomForFullBatch) + } + + func testUnavailableIdsAreNotRequestedAgain() { + var planner = IconRequestPlanner() + _ = plan(&planner, ["a", "b", "c"]) + _ = planner.recordReply(for: "a", available: false) + _ = planner.recordReply(for: "b", available: true) + _ = planner.recordReply(for: "c", available: true) + planner.markUnavailable("c") + XCTAssertTrue(planner.outstanding.isEmpty) + XCTAssertEqual(plan(&planner, ["a", "b", "c"], skipping: ["b"]), []) + } + + func testReplyThatWasNotRequestedIsReported() { + var planner = IconRequestPlanner() + XCTAssertNil(planner.recordReply(for: "a", available: false)) + // ... and does not mark the id unavailable. + XCTAssertEqual(plan(&planner, ["a"]), [["a"]]) + } + + func testReplyReportsTheRequestedSize() { + var planner = IconRequestPlanner() + _ = planner.requests(for: ["a"], size: 48, skipping: []) + _ = planner.requests(for: ["b"], size: 96, skipping: []) + XCTAssertEqual(planner.recordReply(for: "a", available: true), 48) + XCTAssertEqual(planner.recordReply(for: "b", available: true), 96) + } + + func testDroppedConnectionClearsOutstandingButRemembersUnavailable() { + var planner = IconRequestPlanner() + _ = plan(&planner, ["a", "b", "c"]) + _ = planner.recordReply(for: "a", available: false) + + planner.connectionDropped() + XCTAssertTrue(planner.outstanding.isEmpty) + + // After reconnecting only the still-unknown ids are requested again. + XCTAssertEqual(plan(&planner, ["a", "b", "c"]), [["b", "c"]]) + } + + func testNewPlannerRetriesUnavailableIds() { + var planner = IconRequestPlanner() + _ = plan(&planner, ["a"]) + _ = planner.recordReply(for: "a", available: false) + + planner = IconRequestPlanner() + XCTAssertEqual(plan(&planner, ["a"]), [["a"]]) + } + + func testPixelSizeIsRoundedAndClamped() { + XCTAssertEqual(IconRequestPlanner.pixelSize(points: 22, scale: 3), 66) + XCTAssertEqual(IconRequestPlanner.pixelSize(points: 22.4, scale: 2), 45) + XCTAssertEqual(IconRequestPlanner.pixelSize(points: 4, scale: 2), 16) + XCTAssertEqual(IconRequestPlanner.pixelSize(points: 120, scale: 3), 256) + } + + func testIconPointSizeFollowsDynamicType() { + XCTAssertEqual(SessionIconView.pointSize(for: .large), 22, accuracy: 0.5) + XCTAssertGreaterThan(SessionIconView.pointSize(for: .accessibility3), SessionIconView.pointSize(for: .large)) + XCTAssertLessThan(SessionIconView.pointSize(for: .xSmall), SessionIconView.pointSize(for: .large)) + } +} diff --git a/PcVolumeControlTests/LineFramerTests.swift b/PcVolumeControlTests/LineFramerTests.swift new file mode 100644 index 0000000..88be359 --- /dev/null +++ b/PcVolumeControlTests/LineFramerTests.swift @@ -0,0 +1,79 @@ +// +// LineFramerTests.swift +// PcVolumeControlTests +// +// Newline framing of the server byte stream, independent of socket read sizes. +// + +import XCTest +@testable import PcVolumeControl + +final class LineFramerTests: XCTestCase { + + private func strings(_ lines: [Data]) -> [String] { + lines.map { String(decoding: $0, as: UTF8.self) } + } + + func testCompleteLinesInOneRead() { + var framer = LineFramer() + XCTAssertEqual(strings(framer.append(Data("a\nbb\nccc\n".utf8))), ["a", "bb", "ccc"]) + } + + func testLineSplitAcrossReads() { + var framer = LineFramer() + XCTAssertEqual(framer.append(Data(#"{"protocol"#.utf8)), []) + XCTAssertEqual(framer.append(Data(#"Version":8,"#.utf8)), []) + XCTAssertEqual(strings(framer.append(Data((#""x":1}"# + "\n{").utf8))), [#"{"protocolVersion":8,"x":1}"#]) + XCTAssertEqual(strings(framer.append(Data("}\n".utf8))), ["{}"]) + } + + func testTerminatorSplitFromCarriageReturn() { + var framer = LineFramer() + XCTAssertEqual(framer.append(Data("abc\r".utf8)), []) + XCTAssertEqual(strings(framer.append(Data("\n".utf8))), ["abc"]) + } + + func testBlankLinesAreSkipped() { + var framer = LineFramer() + XCTAssertEqual(strings(framer.append(Data("\n\r\na\n\n".utf8))), ["a"]) + } + + func testVeryLongLineInSocketSizedReads() { + // Larger than any icon reply the protocol allows, delivered in 64 KiB reads. + let longLine = Data(repeating: UInt8(ascii: "A"), count: 1_500_000) + let stream = longLine + Data("\nnext\n".utf8) + var framer = LineFramer() + var lines: [Data] = [] + var offset = 0 + while offset < stream.count { + let end = min(offset + 65_536, stream.count) + lines += framer.append(stream.subdata(in: offset.. MainViewModel { + let serversRepo = ServersRepository( + local: MockLocalDataSource(), + remote: UnstartedConnectionDataSource(), + makeTransport: { _ in ScriptedTransport(lines: serverLines) } + ) + let placeholder = VolumeControlRepository(transport: MockVolumeTransport()) + let viewModel = MainViewModel( + connect: ConnectToServerUseCase(repo: serversRepo), + defUpdate: SendDefaultDeviceUpdateUseCase(repo: placeholder), + masterUpdate: SendMasterChannelUpdateUseCase(repo: placeholder), + sessionUpdate: SendSessionUpdateUseCase(repo: placeholder), + serversRepo: serversRepo + ) + // Short enough that a reconnect, if one were started, would show within the test. + viewModel.reconnectInitialDelaySeconds = 0.01 + viewModel.reconnectMaxDelaySeconds = 0.01 + viewModel.reconnectWindowSeconds = 0.2 + return viewModel + } + + private func connectAndWaitForError(_ sut: MainViewModel) async throws -> [MainViewModel.ConnectionStatus] { + var statuses: [MainViewModel.ConnectionStatus] = [] + let statusSubscription = sut.$connectionStatus.sink { statuses.append($0) } + let errorShown = expectation(description: "Error shown") + errorShown.assertForOverFulfill = false + let errorSubscription = sut.$error.sink { if $0 != nil { errorShown.fulfill() } } + + sut.connectToServer(address: "192.0.2.1", port: 3000) + await fulfillment(of: [errorShown], timeout: 5) + // Leave time for a reconnect attempt to begin if the view model started one. + try await Task.sleep(nanoseconds: 300_000_000) + + statusSubscription.cancel() + errorSubscription.cancel() + return statuses + } + + func testOlderServerIsLeftWithAMessageAndNoReconnect() async throws { + let sut = makeViewModel(serverLines: [ServerLineTests.olderServerState]) + + let statuses = try await connectAndWaitForError(sut) + + XCTAssertEqual(sut.error, ProtocolVersionMismatch(serverVersion: 7).localizedDescription) + XCTAssertTrue(sut.error?.contains("PcVolumeControlServer") ?? false) + XCTAssertNil(sut.fullState) + XCTAssertFalse(sut.hasActiveConnection) + XCTAssertFalse(statuses.contains(.reconnecting)) + XCTAssertEqual(sut.connectionStatus, .connected) + } + + func testNewerServerAsksToUpdateTheApp() async throws { + let newer = ServerLineTests.plainState.replacingOccurrences( + of: #""protocolVersion":8"#, with: #""protocolVersion":9"# + ) + let sut = makeViewModel(serverLines: [newer]) + + let statuses = try await connectAndWaitForError(sut) + + XCTAssertEqual(sut.error, ProtocolVersionMismatch(serverVersion: 9).localizedDescription) + XCTAssertNil(sut.fullState) + XCTAssertFalse(statuses.contains(.reconnecting)) + } +} + +/// Hands out a connection that is never started; the scripted transport replaces it. +final class UnstartedConnectionDataSource: TCPConnectionDataSourceProtocol { + func openConnection(to server: DiscoveredServer) async throws -> Connection { + Connection(nw: NWConnection(host: "192.0.2.1", port: 3000, using: .tcp)) + } +} diff --git a/PcVolumeControlTests/ServerLineTests.swift b/PcVolumeControlTests/ServerLineTests.swift new file mode 100644 index 0000000..e318d1c --- /dev/null +++ b/PcVolumeControlTests/ServerLineTests.swift @@ -0,0 +1,256 @@ +// +// ServerLineTests.swift +// PcVolumeControlTests +// +// Decoding and classification of protocol version 8 server lines, including icon +// replies captured from a server, and the version check. +// + +import XCTest +import UIKit +@testable import PcVolumeControl + +final class ServerLineTests: XCTestCase { + + // A server that serves no icons or details: no `iconId`, no `detail`. + static let plainState = #""" + {"protocolVersion":8,"applicationVersion":"v10","deviceIds":{"dev-a":"Speakers"},"defaultDevice":{"deviceId":"dev-a","name":"Speakers","masterVolume":80.0,"masterMuted":false,"sessions":[{"name":"Chrome","id":"{0.0.0.00000000}.{dev-a}|chrome.exe","volume":35.0,"muted":false}]}} + """# + + // The original C# Windows server: the same shape, but protocol version 7. + static let olderServerState = #""" + {"protocolVersion":7,"applicationVersion":"v10","deviceIds":{"dev-a":"Speakers"},"defaultDevice":{"deviceId":"dev-a","name":"Speakers","masterVolume":80.0,"masterMuted":false,"sessions":[{"name":"Chrome","id":"{0.0.0.00000000}.{dev-a}|chrome.exe","volume":35.0,"muted":false}]}} + """# + + // examples/full-state.json from the protocol repo (the reference mock server), on one line. + static let referenceState = #""" + {"protocolVersion":8,"applicationVersion":"v10","deviceIds":{"0f4090a9-dee2-4563-ba29-0ad6b93d9e22":"Speakers (Mock Audio)","c5a32106-264d-40b2-a2e0-74eda397454c":"Headphones (Mock Audio)","c98e4030-926b-4e62-8c83-1c529574cc51":"Headset (Mock USB Audio)"},"defaultDevice":{"deviceId":"0f4090a9-dee2-4563-ba29-0ad6b93d9e22","name":"Speakers (Mock Audio)","masterVolume":80.0,"masterMuted":false,"sessions":[{"name":"Firefox","id":"mock-9ff8bf89-firefox","volume":100.0,"muted":false,"iconId":"demo1d94c5a"},{"name":"Spotify","id":"mock-9ff8bf89-spotify","volume":65.0,"muted":false,"iconId":"demo1b64cd9"},{"name":"Discord","id":"mock-9ff8bf89-discord","volume":40.0,"muted":false,"iconId":"demo174d94c"},{"name":"Musique été","id":"mock-9ff8bf89-musique","volume":55.0,"muted":false,"iconId":"demo14cd968"},{"name":"Firefox","id":"mock-9ff8bf89-firefox-radio","volume":70.0,"muted":false,"iconId":"demo1d94c5a","detail":"Radio Paradise - Main Mix"},{"name":"Firefox","id":"mock-9ff8bf89-firefox-video","volume":90.0,"muted":false,"iconId":"demo1d94c5a","detail":"Tears of Steel - YouTube"}]}} + """# + + // Shape captured from a v8 server (device names shortened): one session without an + // icon id yet, and two sessions sharing an id. + static let v8State = #""" + {"protocolVersion":8,"applicationVersion":"v10","deviceIds":{"dev-a":"Headset","dev-b":"Speakers"},"defaultDevice":{"deviceId":"dev-a","name":"Headset","masterVolume":100.0,"masterMuted":false,"sessions":[{"name":"speech-dispatcher-dummy","id":"dev-a|413","volume":100.0,"muted":false},{"name":"Firefox","id":"dev-a|961","volume":100.0,"muted":false,"iconId":"4b13f0d55a3779a6ff892414f951be3f"},{"name":"Firefox","id":"dev-a|6492","volume":100.0,"muted":false,"iconId":"4b13f0d55a3779a6ff892414f951be3f"},{"name":"Spotify","id":"dev-a|6565","volume":100.0,"muted":false,"iconId":"6b58026ae167f8f2e802f2531657443c"}]}} + """# + + // Captured from a v8 server on Linux with Firefox playing in three tabs. Device names + // are shortened and the tab titles replaced; field order and shape are as sent. + static let v8StateWithDetails = #""" + {"protocolVersion":8,"applicationVersion":"v10","deviceIds":{"dev-a":"Speakers","dev-b":"Headset"},"defaultDevice":{"deviceId":"dev-a","name":"Speakers","masterVolume":36.439514,"masterMuted":false,"sessions":[{"name":"speech-dispatcher-dummy","id":"dev-a|413","volume":100.0,"muted":false},{"name":"Firefox","id":"dev-a|961","volume":100.0,"muted":false,"iconId":"4b13f0d55a3779a6ff892414f951be3f","detail":"Big Buck Bunny - YouTube"},{"name":"Firefox","id":"dev-a|6622","volume":100.0,"muted":false,"iconId":"4b13f0d55a3779a6ff892414f951be3f","detail":"Radio Paradise - Main Mix"},{"name":"Firefox","id":"dev-a|6974","volume":100.0,"muted":false,"iconId":"4b13f0d55a3779a6ff892414f951be3f","detail":"Café Concert: You've Got a Friend…"}]}} + """# + + // Captured verbatim from a v8 server: a 16 px PNG reply and a notFound reply. + static let iconImageReply = #""" + {"protocolVersion":8,"icon":{"id":"6b58026ae167f8f2e802f2531657443c","size":16,"mime":"image/png","data":"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAACWUlEQVR4Ae3AA6AkWZbG8f937o3IzKdyS2Oubdu2bdu2bdu2bWmMnpZKr54yMyLu+Xa3anqmhztr1U/8+yCej1se/14vZ8Vby34UgKQn5qifuf0lvvPPeU6IB7j2b97jmllfvh14C56/n1sP7f3vfanvu48rEM/0sKe8xzXjWH4feAQvjP2Urs9Xe+rDv+8+APFMtzz+fX4O/Oa8KMwv3vbY734zAAE8+G/e45WyL388/fodDN/3FPLeJawb9EGcWRCP2KG8whnqa16PtjoAYuBVbn2p7/5jAdzy9+/9xRQ+qf31efJvzqMbNtGi4FXD9yxpj9+l/fl9eDLdWz2I2Ue+OJgvue2x3/3JAnjQP7zXTzn01qwaw088nbz9AI4mWFTihg3iJU5SH3Oc6bfvpv35OWaf/jIY//Ttj/2etxHALf/wnj9NxFv50sDwXU8ibthAmxUvG3n7Ae0vz5O7a/p3eCj9ez6Cy1r+zG0v/r1vLYCb/+Y9v0x9fDzA9Mf30f7mPD4Y0aISD9mmvuIZfG7F9Ot30X/IYyAEw/Rlt73U93+iAG75/Xd5dU7Nfg9g+p270ayg7Q4fTuRT95h+/250cs78014a5pXLdo9e/bZX+dE/EFfolr95j1+lL6/PC5BP2nU8dEfUwKv2a7e/zPe9EWDxTDf+xJvcVB5++vfpy4N4YaZ8RnvS2Ve/8+1+6Q4A8QAnv/MNb954iTPfFVvd6/F85MH4G/l3Z9/nrvf91du5AvG84rqfeuvXrNcs3pqiRxLA6CdN9y1/+p63+enfBZJnQ/z78I+X+d0RjTFkMwAAAABJRU5ErkJggg=="}} + """# + static let iconNotFoundReply = #""" + {"protocolVersion":8,"icon":{"id":"0000notarealid","error":"notFound"}} + """# + + private func classify(_ text: String) throws -> ServerLine? { + try ServerLine.classify(Data(text.utf8)) + } + + // MARK: - Full state decoding + + func testStateWithoutIconsOrDetailsDecodes() throws { + guard case .state(let state) = try classify(Self.plainState) else { + return XCTFail("Expected a full state") + } + XCTAssertEqual(state.protocolVersion, 8) + XCTAssertEqual(state.defaultDevice.sessions.count, 1) + XCTAssertNil(state.defaultDevice.sessions[0].iconId) + XCTAssertEqual(state.defaultDevice.sessions[0].volume, 35.0) + } + + func testReferenceExampleDecodes() throws { + guard case .state(let state) = try classify(Self.referenceState) else { + return XCTFail("Expected a full state") + } + let sessions = state.defaultDevice.sessions + XCTAssertEqual(sessions.count, 6) + // Session ids are opaque: none contains the device id. + XCTAssertFalse(sessions.contains { $0.id.contains(state.defaultDevice.deviceId) }) + XCTAssertEqual(state.iconIds, ["demo1d94c5a", "demo1b64cd9", "demo174d94c", "demo14cd968"]) + XCTAssertEqual(sessions.compactMap(\.detail), ["Radio Paradise - Main Mix", "Tears of Steel - YouTube"]) + XCTAssertEqual(sessions[3].name, "Musique \u{E9}t\u{E9}") + } + + func testStateDecodesIconIds() throws { + guard case .state(let state) = try classify(Self.v8State) else { + return XCTFail("Expected a full state") + } + XCTAssertEqual(state.defaultDevice.sessions.map(\.iconId), [ + nil, + "4b13f0d55a3779a6ff892414f951be3f", + "4b13f0d55a3779a6ff892414f951be3f", + "6b58026ae167f8f2e802f2531657443c", + ]) + } + + func testIconIdsAreDistinctAndInSessionOrder() throws { + guard case .state(let withIcons) = try classify(Self.v8State), + case .state(let plain) = try classify(Self.plainState) else { + return XCTFail("Expected full states") + } + XCTAssertEqual(withIcons.iconIds, ["4b13f0d55a3779a6ff892414f951be3f", "6b58026ae167f8f2e802f2531657443c"]) + XCTAssertEqual(plain.iconIds, []) + } + + func testSessionDetailsDecode() throws { + guard case .state(let state) = try classify(Self.v8StateWithDetails) else { + return XCTFail("Expected a full state") + } + XCTAssertEqual(state.defaultDevice.sessions.map(\.detail), [ + nil, + "Big Buck Bunny - YouTube", + "Radio Paradise - Main Mix", + "Caf\u{E9} Concert: You've Got a Friend\u{2026}", + ]) + // Same application, told apart only by the detail. + XCTAssertEqual(Set(state.defaultDevice.sessions.dropFirst().map(\.name)), ["Firefox"]) + } + + func testStatesWithoutDetailsDecodeWithNone() throws { + for text in [Self.plainState, Self.v8State] { + guard case .state(let state) = try classify(text) else { + return XCTFail("Expected a full state") + } + XCTAssertTrue(state.defaultDevice.sessions.allSatisfy { $0.detail == nil }) + } + } + + func testUnknownFieldsAreIgnored() throws { + let text = Self.plainState.replacingOccurrences( + of: #""applicationVersion":"v10","#, + with: #""applicationVersion":"v10","features":["icons"],"somethingNew":{"a":1},"# + ) + guard case .state(let state) = try classify(text) else { + return XCTFail("Expected a full state") + } + XCTAssertEqual(state.defaultDevice.sessions.count, 1) + } + + // MARK: - Protocol version + + func testOlderServerIsRejected() { + XCTAssertThrowsError(try classify(Self.olderServerState)) { error in + guard let mismatch = error as? ProtocolVersionMismatch else { + return XCTFail("Expected a version mismatch, got \(error)") + } + XCTAssertEqual(mismatch.serverVersion, 7) + XCTAssertTrue(mismatch.serverIsOlder) + } + } + + func testNewerServerIsRejectedEvenIfItsStateCannotBeDecoded() { + XCTAssertThrowsError(try classify(#"{"protocolVersion":9,"defaultDevice":{"somethingElse":true}}"#)) { error in + guard let mismatch = error as? ProtocolVersionMismatch else { + return XCTFail("Expected a version mismatch, got \(error)") + } + XCTAssertEqual(mismatch.serverVersion, 9) + XCTAssertFalse(mismatch.serverIsOlder) + } + } + + func testMismatchMessagesSayWhichSideToUpdate() { + let older = ProtocolVersionMismatch(serverVersion: 7).localizedDescription + let newer = ProtocolVersionMismatch(serverVersion: 9).localizedDescription + XCTAssertTrue(older.contains("PcVolumeControlServer"), older) + XCTAssertTrue(older.contains("7"), older) + XCTAssertTrue(newer.contains("Update PcVolumeControl on this device"), newer) + XCTAssertTrue(newer.contains("9"), newer) + } + + func testStateWithoutVersionIsMalformed() { + XCTAssertThrowsError(try classify(#"{"defaultDevice":{"deviceId":"x"}}"#)) { error in + XCTAssertTrue(error is MalformedStateError) + } + } + + // MARK: - Icon replies + + func testIconImageReplyDecodesToPNG() throws { + guard case .icon(let reply) = try classify(Self.iconImageReply) else { + return XCTFail("Expected an icon reply") + } + XCTAssertEqual(reply.id, "6b58026ae167f8f2e802f2531657443c") + let png = try XCTUnwrap(reply.png) + XCTAssertEqual(Array(png.prefix(4)), [0x89, 0x50, 0x4E, 0x47]) + let image = try XCTUnwrap(UIImage(data: png)) + XCTAssertEqual(image.size.width * image.scale, 16) + XCTAssertEqual(image.size.height * image.scale, 16) + } + + func testIconNotFoundReplyHasNoImage() throws { + guard case .icon(let reply) = try classify(Self.iconNotFoundReply) else { + return XCTFail("Expected an icon reply") + } + XCTAssertEqual(reply.id, "0000notarealid") + XCTAssertNil(reply.png) + } + + func testIconReplyWithUnknownErrorHasNoImage() throws { + let text = #"{"protocolVersion":8,"icon":{"id":"abc","error":"somethingElse","data":"iVBORw0KGgo="}}"# + guard case .icon(let reply) = try classify(text) else { + return XCTFail("Expected an icon reply") + } + XCTAssertNil(reply.png) + } + + func testIconReplyWithInvalidBase64StillAnswersTheId() throws { + let text = #"{"protocolVersion":8,"icon":{"id":"abc","size":16,"mime":"image/png","data":"not base64!"}}"# + guard case .icon(let reply) = try classify(text) else { + return XCTFail("Expected an icon reply") + } + XCTAssertEqual(reply.id, "abc") + XCTAssertNil(reply.png) + } + + func testIconReplyWithNonStringErrorHasNoImage() throws { + let text = #"{"protocolVersion":8,"icon":{"id":"abc","error":{"code":3},"data":"iVBORw0KGgo="}}"# + guard case .icon(let reply) = try classify(text) else { + return XCTFail("Expected an icon reply") + } + XCTAssertNil(reply.png) + } + + func testIconReplyWithEmptyDataHasNoImage() throws { + let text = #"{"protocolVersion":8,"icon":{"id":"abc","size":16,"mime":"image/png","data":""}}"# + guard case .icon(let reply) = try classify(text) else { + return XCTFail("Expected an icon reply") + } + XCTAssertNil(reply.png) + } + + // MARK: - Classification + + func testUnknownLineIsIgnored() throws { + XCTAssertNil(try classify(#"{"protocolVersion":8,"somethingNew":{"a":1}}"#)) + } + + func testMalformedLinesAreIgnored() throws { + for text in [ + #"{"protocolVersion":8,"defaultDevice":{"deviceId":"#, + #"{"protocolVersion":8,"icon":{"error":"notFound"}}"#, + "[1,2,3]", + "not json", + ] { + XCTAssertNil(try classify(text), text) + } + } + + func testLineWithBothStateAndIconIsIgnored() throws { + let text = Self.plainState.replacingOccurrences( + of: #""protocolVersion":8,"#, + with: #""protocolVersion":8,"icon":{"id":"abc","error":"notFound"},"# + ) + XCTAssertNil(try classify(text)) + } + + func testUndecodableFullStateThrows() { + XCTAssertThrowsError(try classify(#"{"protocolVersion":8,"defaultDevice":{"deviceId":"x"}}"#)) { error in + XCTAssertTrue(error is MalformedStateError) + } + } +} diff --git a/PcVolumeControlTests/SessionDetailTests.swift b/PcVolumeControlTests/SessionDetailTests.swift new file mode 100644 index 0000000..c1f8646 --- /dev/null +++ b/PcVolumeControlTests/SessionDetailTests.swift @@ -0,0 +1,71 @@ +// +// SessionDetailTests.swift +// PcVolumeControlTests +// +// Session details are display text: a state that only changes details must not +// disturb what the user is editing, the row order or row identity. +// + +import XCTest +@testable import PcVolumeControl + +@MainActor +final class SessionDetailTests: XCTestCase { + + private func state(details: [String?], volumes: [Double] = [50, 50, 50]) -> FullState { + let sessions = zip(details, volumes).enumerated().map { index, pair in + FullState.Session( + id: "dev-a|\(index)", muted: false, name: "Firefox", volume: pair.1, + iconId: "4b13f0d55a3779a6ff892414f951be3f", detail: pair.0 + ) + } + return FullState( + protocolVersion: 8, + deviceIds: ["dev-a": "Speakers"], + defaultDevice: FullState.theDefaultDevice( + deviceId: "dev-a", masterMuted: false, masterVolume: 80, name: "Speakers", sessions: sessions + ) + ) + } + + func testDetailOnlyUpdateKeepsOrderAndIdentity() { + let vm = SliderViewModel() + vm.fullState = state(details: ["Tab A", "Tab B", nil]) + let ids = vm.sessions.map(\.id) + // Same-named sessions are ordered by id, never by detail. + XCTAssertEqual(ids, ["dev-a|0", "dev-a|1", "dev-a|2"]) + + vm.fullState = state(details: ["Tab A2", nil, "Tab C"]) + + XCTAssertEqual(vm.sessions.map(\.id), ids) + let details = Dictionary(uniqueKeysWithValues: vm.sessions.map { ($0.id, $0.detail) }) + XCTAssertEqual(details["dev-a|0"], "Tab A2") + XCTAssertEqual(details["dev-a|1"], .some(nil)) + XCTAssertEqual(details["dev-a|2"], "Tab C") + } + + func testDetailOnlyUpdateKeepsValuesOfASessionBeingEdited() throws { + let vm = SliderViewModel() + vm.fullState = state(details: ["Tab A", "Tab B", nil]) + let index = try XCTUnwrap(vm.sessions.firstIndex { $0.id == "dev-a|1" }) + + // The user is dragging this session's slider. + vm.beginEditing("dev-a|1") + vm.sessions[index].volume = 85 + vm.sessions[index].muted = true + + vm.fullState = state(details: ["Tab A", "Tab B changed", nil]) + + let edited = try XCTUnwrap(vm.sessions.first { $0.id == "dev-a|1" }) + XCTAssertEqual(edited.volume, 85) + XCTAssertTrue(edited.muted) + XCTAssertEqual(edited.detail, "Tab B changed") + XCTAssertEqual(edited.iconId, "4b13f0d55a3779a6ff892414f951be3f") + vm.endEditing("dev-a|1") + } + + func testSpokenNameAddsTheDetailOnlyWhenPresent() { + XCTAssertEqual(SessionCell.spokenName("Firefox", detail: nil), "Firefox") + XCTAssertEqual(SessionCell.spokenName("Firefox", detail: "Big Buck Bunny - YouTube"), "Firefox, Big Buck Bunny - YouTube") + } +} diff --git a/PcVolumeControlTests/VolumeControlRepositoryTests.swift b/PcVolumeControlTests/VolumeControlRepositoryTests.swift new file mode 100644 index 0000000..fe47217 --- /dev/null +++ b/PcVolumeControlTests/VolumeControlRepositoryTests.swift @@ -0,0 +1,121 @@ +// +// VolumeControlRepositoryTests.swift +// PcVolumeControlTests +// +// The repository's line stream: states and icon replies are delivered, anything +// else is dropped without ending the stream. +// + +import XCTest +@testable import PcVolumeControl + +final class VolumeControlRepositoryTests: XCTestCase { + + func testUnknownAndMalformedLinesDoNotEndTheStream() async throws { + let transport = ScriptedTransport(lines: [ + ServerLineTests.plainState, + "not json", + #"{"protocolVersion":8,"somethingNew":true}"#, + ServerLineTests.iconNotFoundReply, + ServerLineTests.v8State, + ]) + let repo = VolumeControlRepository(transport: transport) + + var kinds: [String] = [] + for try await line in repo.serverLines() { + switch line { + case .state: kinds.append("state") + case .icon: kinds.append("icon") + } + } + XCTAssertEqual(kinds, ["state", "icon", "state"]) + } + + func testUndecodableFullStateEndsTheStream() async { + let transport = ScriptedTransport(lines: [ + ServerLineTests.plainState, + #"{"protocolVersion":8,"defaultDevice":{"deviceId":"x"}}"#, + ServerLineTests.plainState, + ]) + let repo = VolumeControlRepository(transport: transport) + + var states = 0 + do { + for try await _ in repo.serverLines() { + states += 1 + } + XCTFail("Expected the stream to end with an error") + } catch { + XCTAssertTrue(error is MalformedStateError) + } + XCTAssertEqual(states, 1) + } + + func testOlderServerEndsTheStreamWithAVersionMismatch() async { + let transport = ScriptedTransport(lines: [ServerLineTests.olderServerState, ServerLineTests.plainState]) + let repo = VolumeControlRepository(transport: transport) + + var states = 0 + do { + for try await _ in repo.serverLines() { + states += 1 + } + XCTFail("Expected the stream to end with an error") + } catch { + XCTAssertEqual((error as? ProtocolVersionMismatch)?.serverVersion, 7) + } + XCTAssertEqual(states, 0) + } + + func testEveryOutgoingMessageSaysVersion8() async throws { + let transport = MockVolumeTransport() + let repo = VolumeControlRepository(transport: transport) + try await repo.pushDefaultDevice(id: "dev-a") + try await repo.pushMasterValues(id: "dev-a", muted: false, volume: 50) + try await repo.pushSessionValues(name: "Firefox", id: "s1", volume: 40, muted: false, deviceId: "dev-a") + try await repo.requestIcons(ids: ["abc"], size: 66) + + XCTAssertEqual(transport.sentData.count, 4) + for data in transport.sentData { + let json = try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any]) + XCTAssertEqual(json["protocolVersion"] as? Int, 8) + } + } + + func testIconRequestEncoding() async throws { + let transport = MockVolumeTransport() + let repo = VolumeControlRepository(transport: transport) + try await repo.requestIcons(ids: ["abc", "def"], size: 66) + + let sent = try XCTUnwrap(transport.sentData.first) + let json = try XCTUnwrap(JSONSerialization.jsonObject(with: sent) as? [String: Any]) + XCTAssertEqual(json["protocolVersion"] as? Int, 8) + XCTAssertNil(json["defaultDevice"]) + let request = try XCTUnwrap(json["iconRequest"] as? [String: Any]) + XCTAssertEqual(request["ids"] as? [String], ["abc", "def"]) + XCTAssertEqual(request["size"] as? Int, 66) + } +} + +/// A transport that delivers a fixed list of lines, then ends. +final class ScriptedTransport: VolumeTransportDataSourceProtocol { + private let lines: [String] + + init(lines: [String]) { + self.lines = lines + } + + func outgoing(_ data: Data) async throws {} + + func incoming() -> AsyncThrowingStream { + let lines = lines + return AsyncThrowingStream { continuation in + for line in lines { + continuation.yield(Data(line.utf8)) + } + continuation.finish() + } + } + + func close() {} +} diff --git a/README.md b/README.md index f0e0428..c502e1a 100644 --- a/README.md +++ b/README.md @@ -1,20 +1,23 @@ # PC Volume Control — iOS -Control your Windows PC's application audio volumes remotely from your iPhone or iPad. +Control your PC's application audio volumes remotely from your iPhone or iPad. ## What it does -PC Volume Control lets you adjust the volume of individual applications running on your Windows PC from your iOS device. This was designed primarily for remote volume control while gaming or streaming. +PC Volume Control lets you adjust the volume of individual applications running on your PC from your iOS device. This was designed primarily for remote volume control while gaming or streaming. -The app connects to a free companion Windows server over your local network, displaying all running applications and their volume levels in a clean, responsive interface. Adjust volumes, mute/unmute, and switch between output devices (speakers, headphones, etc.) all from your phone or tablet. +The app connects to a free companion server on your PC (Windows or Linux) over your local network, displaying all running applications and their volume levels in a clean, responsive interface. Adjust volumes, mute/unmute, and switch between output devices (speakers, headphones, etc.) all from your phone or tablet. **Features:** - Remote application volume control - Per-app mute/unmute - Master volume and mute for the default output device - Auto-discovery of the server on your local network (or manual IP/port entry) +- Application icons next to each app, and details such as a browser tab's title under the app name, when the server sends them + +This version of the app needs [PcVolumeControlServer](https://github.com/PcVolumeControl/PcVolumeControlServer) (protocol version 8) on the PC. It does not work with the original PcVolumeControlWindows server; if you connect to one, the app says the server needs updating. ## Demo @@ -40,13 +43,13 @@ The app connects to a free companion Windows server over your local network, dis [Get it on the App Store](https://itunes.apple.com/us/app/pcvolumecontrol/id1336171942?ls=1&mt=8) -### 2. Install the Windows Server +### 2. Install the Server -PC Volume Control requires the free companion server on your Windows PC. +PC Volume Control requires the free companion server, [PcVolumeControlServer](https://github.com/PcVolumeControl/PcVolumeControlServer), on your PC (Windows or Linux). The older PcVolumeControlWindows server does not work with this version of the app; uninstall it first, as both use port 3000. -1. **Download** the latest [PC Volume Control Server release](https://github.com/PcVolumeControl/PcVolumeControlWindows/releases/latest) for Windows. -2. **Install and run** the server on your PC. Allow it through Windows Firewall when prompted (private networks). -3. **Note the server address** — the server window displays your PC's IP address and port (default 3000). +1. **Download** the latest [PcVolumeControlServer release](https://github.com/PcVolumeControl/PcVolumeControlServer/releases/latest) for your system; its README has the install steps. +2. **Install and run** the server on your PC. On Windows, allow it through Windows Firewall when prompted (private networks). +3. **Note the server address**: your PC's IP address and the port (default 3000). ### 3. Connect Your Device @@ -56,7 +59,7 @@ PC Volume Control requires the free companion server on your Windows PC. ### Troubleshooting -- **Can't connect?** Check Windows Firewall isn't blocking the server. +- **Can't connect?** Check that the PC's firewall allows TCP port 3000 and mDNS (UDP 5353); on Windows, that Windows Firewall isn't blocking the server. - **No audio output?** Use the master device selector (top of the volume screen) to switch between multiple audio outputs. ## Contributing