Your home as a live 3D model in the Mac menu bar and on iPhone — lights and ACs via Smart Life, Home Assistant, Philips Hue and Apple Home.
Widgets: let the app show what a widget did instead of its own older state
0xProbabilityf4d4e5aef5e8
diff --git a/core/Sources/HouseCore/SharedHome.swift b/core/Sources/HouseCore/SharedHome.swiftindex e9054d0..12962d4 100644--- a/core/Sources/HouseCore/SharedHome.swift+++ b/core/Sources/HouseCore/SharedHome.swift@@ -139,7 +139,8 @@ public final class SharedHome: @unchecked Sendable {// A tap the app could not carry out within a few minutes (it was not running) is// dropped: nobody expects a lamp to switch on an hour after they asked.let horizon = Date().timeIntervalSince1970 - Self.patience- return ((try? JSONDecoder().decode([Queued].self, from: data)) ?? []).filter { $0.at > horizon }+ // One the widget delivered itself only tells the app what to show: it never goes stale.+ return ((try? JSONDecoder().decode([Queued].self, from: data)) ?? []).filter { $0.delivered || $0.at > horizon }}private func writeQueue(_ queue: [Queued]) {diff --git a/core/Sources/HouseCore/WidgetBridge.swift b/core/Sources/HouseCore/WidgetBridge.swiftindex 7b7a70f..fb06922 100644--- a/core/Sources/HouseCore/WidgetBridge.swift+++ b/core/Sources/HouseCore/WidgetBridge.swift@@ -34,17 +34,21 @@ public final class WidgetBridge {onSnapshot?(snapshot)let first = identity == nilidentity = snapshot.identity- if first { takeActions() } // the queue waited to learn which home this is+ // The queue waited to learn which home this is. When it held something, this+ // snapshot is already out of date: the panel posts a new one once it has caught up.+ if first, takeActions() { return }if shared?.publish(snapshot) == true { scheduleReload() }}/// Takes the queue (when the app comes to the foreground, or a widget says it added to it).- public func takeActions() {- guard isReady, identity != nil, let shared, shared.hasPendingActions else { return }+ /// True when there was something for the panel.+ @discardableResult+ public func takeActions() -> Bool {+ guard isReady, identity != nil, let shared, shared.hasPendingActions else { return false }let (all, snapshot) = shared.takeActions()// Made for another home than the one on screen: never carry those out here.let queued = all.filter { $0.home == identity }- guard !queued.isEmpty else { scheduleReload(); return }+ guard !queued.isEmpty else { scheduleReload(); return false }let encoder = JSONEncoder()let run = queued.filter { !$0.delivered }.compactMap { entry -> [String: Any]? inguard let data = try? encoder.encode(entry.action) else { return nil }@@ -52,6 +56,7 @@ public final class WidgetBridge {}let adopt = queued.contains(where: \.delivered) ? snapshot?.panelState : nilonActions?(run, adopt)+ return true}/// Widgets redraw at most a couple of times a second, however fast the panel changes.diff --git a/core/Tests/HouseCoreTests/WidgetTests.swift b/core/Tests/HouseCoreTests/WidgetTests.swiftindex fa622a7..c710b96 100644--- a/core/Tests/HouseCoreTests/WidgetTests.swift+++ b/core/Tests/HouseCoreTests/WidgetTests.swift@@ -102,4 +102,27 @@ final class WidgetTests: XCTestCase {XCTAssertTrue(shared.isTaken(done.entry.id))XCTAssertTrue(shared.publish(home()))}++ /// The app starting up must show what a widget did, not overwrite it with its own older view.+ @MainActor+ func testBridgeAdoptsBeforePublishing() throws {+ let dir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ defer { try? FileManager.default.removeItem(at: dir) }+ let shared = SharedHome(directory: dir)+ shared.publish(home())+ let done = try XCTUnwrap(shared.perform(.light("main")))+ shared.markDelivered([done.entry.id])++ let bridge = WidgetBridge(shared: shared)+ var adopted: [String: Any]?+ var ran: [[String: Any]] = []+ bridge.onActions = { run, adopt in ran = run; adopted = adopt }+ bridge.isReady = true+ let stale = try JSONSerialization.jsonObject(with: JSONEncoder().encode(home()))+ bridge.publish(["snapshot": stale])+ XCTAssertTrue(ran.isEmpty, "delivered by the widget: not sent again")+ let lights = try XCTUnwrap(adopted?["lights"] as? [String: Any])+ XCTAssertEqual((lights["main"] as? [String: Any])?["on"] as? Bool, true)+ XCTAssertTrue(shared.snapshot()!.light("main")!.on, "the stale snapshot was not stored")+ }}diff --git a/docs/widgets.md b/docs/widgets.mdindex 6bd5ec9..7c5c7a1 100644--- a/docs/widgets.md+++ b/docs/widgets.md@@ -47,7 +47,8 @@ widget tap ─▶ AppIntent ─▶ HomeSnapshot.apply ─▶ home.json (at once)Smart Life, with the connections the app keeps in the Keychain group it shares with its widgets (the Smart Lifesession is re-read when the other process refreshed it). Apple Home cannot be reached from a widget: those actionswait in the queue and the app carries them out when it opens. The app then shows what the widgets did.-- Queued actions older than ten minutes are dropped, and an action is only ever run for the home it was made in.+- An action the app still has to carry out is dropped after ten minutes (nobody expects a lamp to switch an hour+ later), and an action is only ever run for the home it was made in.- Files are read and written under one `flock`, so the app and a widget never see half of each other's work.## Codediff --git a/widgets/Render/main.swift b/widgets/Render/main.swiftindex f884070..f9f0ada 100644--- a/widgets/Render/main.swift+++ b/widgets/Render/main.swift@@ -1,5 +1,5 @@-// Renders every widget as a PNG (2x) from a home snapshot, the way WidgetKit lays them out:-// swift run render-widgets [snapshot.json] [output folder] [--tinted] [--size iphone|mac]+// Renders every widget as a PNG (2x by default) from a home snapshot, the way WidgetKit lays them out:+// swift run render-widgets [snapshot.json] [output folder] [--tinted] [--size iphone|mac] [--scale 2]// Without a snapshot it uses Resources/sample-home.json. A snapshot from a running app is// in its App Group container, Widgets/home.json.import SwiftUI@@ -11,6 +11,8 @@ import HouseCorevar arguments = Array(CommandLine.arguments.dropFirst())let tinted = arguments.contains("--tinted")let mac = arguments.firstIndex(of: "--size").map { arguments.indices.contains($0 + 1) && arguments[$0 + 1] == "mac" } ?? false+let scale = arguments.firstIndex(of: "--scale").flatMap { arguments.indices.contains($0 + 1) ? Double(arguments[$0 + 1]) : nil } ?? 2+if let i = arguments.firstIndex(of: "--scale"), arguments.indices.contains(i + 1) { arguments.remove(at: i + 1) }arguments.removeAll { $0.hasPrefix("--") || $0 == "mac" || $0 == "iphone" }let here = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()let input = arguments.first.map { URL(fileURLWithPath: $0) } ?? here.appendingPathComponent("Resources/sample-home.json")@@ -50,7 +52,7 @@ struct Still<Content: View>: View {@MainActorfunc render<V: View>(_ name: String, _ family: WidgetFamily, _ view: V) {let renderer = ImageRenderer(content: Still(family: family) { view })- renderer.scale = 2+ renderer.scale = scaleguard let image = renderer.cgImage else { print("✗ \(name)"); return }let rep = NSBitmapImageRep(cgImage: image)let url = output.appendingPathComponent("\(name).png")