import CottonMacFFI import Foundation /// The Rust core (`crates/cotton-mac-ffi`): three C functions, JSON in and /// out. Every call is synchronous and may block on the network or on a /// source's probe, so callers run it off the main thread (`AppModel.call`). enum Core { /// Open the one core over `config`. The answer is `{ ok, error?, code? }`. static func open(configJSON: String) -> Data { take(cotton_mac_open(configJSON)) } /// One method. `argsJSON` nil sends no arguments. static func call(_ method: String, argsJSON: String?) -> Data { if let argsJSON { return take(cotton_mac_call(method, argsJSON)) } return take(cotton_mac_call(method, nil)) } private static func take(_ pointer: UnsafeMutablePointer?) -> Data { guard let pointer else { return Data(#"{"ok":false,"error":"the core answered nothing"}"#.utf8) } defer { cotton_mac_free(pointer) } return Data(String(cString: pointer).utf8) } } /// What every answer carries. struct CoreAnswer: Decodable, Sendable { let ok: Bool let error: String? let code: String? } /// The configuration the core opens with (camelCase, `cotton_mac::app::Config`). struct CoreConfig: Encodable, Sendable { let dataDir: String let objectUrl: String let deviceId: String let machine: String /// The name the person gave this Mac, and the running version: its device row. let deviceName: String let appVersion: String let home: String let helpersDir: String } /// The arguments of a call, encoded once on the caller's side. enum CoreArgs { static func json(_ object: [String: Any]) -> String { guard let data = try? JSONSerialization.data(withJSONObject: object), let text = String(data: data, encoding: .utf8) else { return "{}" } return text } }