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.
Add widgets, controls and quick actions for the iPhone and the Mac
0xProbability4296599341fb
diff --git a/.gitignore b/.gitignoreindex 2e7396f..9fbbec0 100644--- a/.gitignore+++ b/.gitignore@@ -34,3 +34,11 @@ ios/Config/Local.xcconfigios/build/core/.build/sync.json++# Widgets: the Mac extension's Xcode project, Info.plists and entitlements are generated+# from widgets/project.yml and ios/project.yml.+widgets/HouseWidgetsMac.xcodeproj/+widgets/Config/Info-*.plist+widgets/Config/*.entitlements+widgets/build/+widgets/.build/diff --git a/README.md b/README.mdindex 6decdf7..b2b3528 100644--- a/README.md+++ b/README.md@@ -35,6 +35,9 @@- **AI Access.** Give ChatGPT, Claude or any AI assistant a private link — or connect it over MCP — and it runs yourlights and air conditioners, and rebuilds rooms in the 3D model from your photos. Served by your Mac; Stop ends it.See [AI Access](#ai-access).+- **Widgets and controls.** The home in 3D on the iPhone's Home Screen and the Mac's desktop, scenes, lamps and+ air conditioners a tap away, Lock Screen and Control Center controls, and quick actions on the app icon.+ See [Widgets](#widgets).- **An iPhone app.** The same home in your pocket, kept in sync with the Mac over your own Wi-Fi.See [iPhone app](#iphone-app).- **Works without any hardware.** Until you sign in, every device is simulated, so you can try everything first.@@ -217,6 +220,28 @@ you are holding — so the paired Mac puts the code on its screen for you. WithoThe session is kept in the iPhone's Keychain and never leaves the device.+## Widgets++<p align="center">+ <img src="docs/widgets.png" width="820" alt="House Control widgets: Home in 3D, scenes, climate, a light and a room">+</p>++Every widget is live: tap a lamp, a scene or an AC and it switches without opening the app.++- **Home** — your home as a small 3D model, every lamp glowing in its own colour; scenes, the climate strip and+ tappable lamps in the bigger sizes (extra large on the Mac).+- **Scenes**, **Light** (one lamp you pick), **Room** (its lamps; the large size shows the room alone in 3D) and+ **Climate** (an AC's dial with the room temperature, power and − / +).+- **Lock Screen:** Home Status, Light and Climate as circles, rectangles and an inline line.+- **Controls** for Control Center, the Lock Screen and the Action button (iOS 18, macOS 26): All Lights, a Light,+ a Scene, an Air Conditioner.+- **Quick actions:** press and hold the app icon on the iPhone. Choose which scenes, lamps and ACs it offers in+ **Settings → Quick Actions**.++On the Mac they need the app running in the menu bar (it carries out what you tap); on the iPhone the widget talks+to Home Assistant, Hue and Smart Life itself, and Apple Home devices switch when the app next opens. How it fits+together, and how to build and try it: [docs/widgets.md](docs/widgets.md).+## Make it your homeRight-click the icon and choose **Edit Home…**diff --git a/core/Sources/HouseCore/HomeSnapshot.swift b/core/Sources/HouseCore/HomeSnapshot.swiftnew file mode 100644index 0000000..bc53f5f--- /dev/null+++ b/core/Sources/HouseCore/HomeSnapshot.swift@@ -0,0 +1,326 @@+import Foundation++/// What the widgets and controls know about the home: the plan's rooms, lamps, ACs and+/// scenes with the state each device was last in. The panel page writes it+/// (`web/src/widgets.js`) whenever something changes; a widget that changes something+/// applies the change here first, so it can show the result at once.+public struct HomeSnapshot: Codable, Equatable, Sendable {+ public struct Room: Codable, Equatable, Sendable, Identifiable {+ public var id: String+ public var name: String+ /// The room's rectangle on the floor plan, in metres.+ public var x: Double, z: Double, w: Double, d: Double+ public var floor: String?+ }++ public struct Light: Codable, Equatable, Sendable, Identifiable {+ public var id: String+ public var name: String+ public var room: String+ /// "ceiling", "pendant", "spots", "floor", "table" or "strip".+ public var type: String+ public var x: Double, z: Double+ /// Which of "brightness", "temp", "color" it supports.+ public var capabilities: [String]+ public var on: Bool+ public var brightness: Double+ /// White temperature in kelvin.+ public var temp: Double+ /// "#rrggbb" while it shows a colour instead of white.+ public var color: String?+ /// The platform it is linked to ("smartlife", "homeassistant", "hue", "homekit"); nil when simulated.+ public var service: String?+ /// The plan's `tuya` / `link` / `sensor` fields, for sending commands from a widget.+ public var links: [String: JSONValue]?+ }++ public struct AC: Codable, Equatable, Sendable, Identifiable {+ public var id: String+ public var name: String+ public var room: String+ public var wall: String+ public var x: Double, z: Double+ public var min: Double, max: Double+ public var on: Bool+ public var target: Double+ public var mode: String+ public var fan: String+ public var roomTemp: Double?+ public var swing: String?+ public var sleep: Bool?+ public var eco: Bool?+ public var service: String?+ public var links: [String: JSONValue]?+ }++ public struct Scene: Codable, Equatable, Sendable, Identifiable {+ public var id: String+ public var name: String+ /// The panel's icon name: "sun", "sofa", "film", "moon", "door", "table"…+ public var icon: String+ /// Device id (or "*" for every device) -> the fields the scene sets.+ public var lights: [String: [String: JSONValue]]+ public var acs: [String: [String: JSONValue]]+ }++ /// A piece of furniture: its footprint on the plan (`w` × `d` metres, turned by `rot` degrees).+ public struct Furniture: Codable, Equatable, Sendable {+ public var type: String+ public var x: Double, z: Double, w: Double, d: Double+ public var rot: Double+ public var color: String?+ }++ public var version = 1+ public var name: String+ /// "home" / "studio" for the bundled demos, "custom" for the user's own plan.+ public var plan: String+ public var outdoorTemp: Double?+ public var rooms: [Room]+ public var lights: [Light]+ public var acs: [AC]+ public var furniture: [Furniture]?+ public var scenes: [Scene]+ /// The scene the home is in, until something is changed by hand.+ public var scene: String?+ /// When the state was last written, in seconds since 1970.+ public var updated: Double++ public init(name: String, plan: String, outdoorTemp: Double? = nil, rooms: [Room], lights: [Light], acs: [AC],+ scenes: [Scene], scene: String? = nil, updated: Double = Date().timeIntervalSince1970) {+ self.name = name+ self.plan = plan+ self.outdoorTemp = outdoorTemp+ self.rooms = rooms+ self.lights = lights+ self.acs = acs+ self.scenes = scenes+ self.scene = scene+ self.updated = updated+ }++ public var lightsOn: Int { lights.filter(\.on).count }+ /// Tells homes apart: the plan and its name.+ public var identity: String { "\(plan):\(name)" }+ public var acsOn: [AC] { acs.filter(\.on) }+ /// True when no device is linked to a real one.+ public var isSimulated: Bool { lights.allSatisfy { $0.service == nil } && acs.allSatisfy { $0.service == nil } }++ public func room(_ id: String) -> Room? { rooms.first { $0.id == id } }+ public func light(_ id: String) -> Light? { lights.first { $0.id == id } }+ public func ac(_ id: String) -> AC? { acs.first { $0.id == id } }+ public func lights(in room: String) -> [Light] { lights.filter { $0.room == room } }++ /// The plan fragment `DeviceHub.setLinks` reads: each device with its links.+ public var linksPlan: [String: Any] {+ func entry(_ id: String, _ links: [String: JSONValue]?) -> [String: Any] {+ var out: [String: Any] = ["id": id]+ for (key, value) in links ?? [:] { out[key] = value.any }+ return out+ }+ return ["lights": lights.map { entry($0.id, $0.links) }, "acs": acs.map { entry($0.id, $0.links) }]+ }+}++/// Something a widget or a control asks the home to do. Stored with explicit values+/// (a toggle is resolved to on or off when it is made), so the app replays exactly what+/// the widget showed.+public struct HomeAction: Codable, Equatable, Sendable {+ public enum Kind: String, Codable, Sendable {+ /// A lamp on or off.+ case light+ /// Every lamp of a room.+ case room+ /// Every lamp of the home.+ case allLights+ case scene+ case acPower+ /// An AC's set-point, in °C.+ case acTarget+ }++ public var kind: Kind+ public var id: String?+ /// For light, room, allLights and acPower; nil means "the other way round".+ public var on: Bool?+ public var target: Double?++ public init(_ kind: Kind, id: String? = nil, on: Bool? = nil, target: Double? = nil) {+ self.kind = kind+ self.id = id+ self.on = on+ self.target = target+ }++ public static func light(_ id: String, on: Bool? = nil) -> HomeAction { .init(.light, id: id, on: on) }+ public static func room(_ id: String, on: Bool? = nil) -> HomeAction { .init(.room, id: id, on: on) }+ public static func allLights(on: Bool) -> HomeAction { .init(.allLights, on: on) }+ public static func scene(_ id: String) -> HomeAction { .init(.scene, id: id) }+ public static func acPower(_ id: String, on: Bool? = nil) -> HomeAction { .init(.acPower, id: id, on: on) }+ public static func acTarget(_ id: String, _ target: Double) -> HomeAction { .init(.acTarget, id: id, target: target) }+}++/// A change one device has to make, as the hub's `command` takes it.+public struct DeviceChange: @unchecked Sendable {+ public var kind: DeviceKind+ public var id: String+ public var patch: [String: Any]+ /// The device's whole new state.+ public var state: [String: Any]++ public var message: [String: Any] { ["kind": kind.rawValue, "id": id, "patch": patch, "state": state] }+}++public extension HomeSnapshot {+ /// Applies `action` the way the panel's store does (`web/src/store.js`): the same+ /// clamping, the same scene rules. Returns the action with every toggle resolved and+ /// what each device has to change; a no-op returns no changes.+ mutating func apply(_ action: HomeAction) -> (resolved: HomeAction, changes: [DeviceChange]) {+ var resolved = action+ var changes: [DeviceChange] = []+ switch action.kind {+ case .light:+ guard let id = action.id, let light = light(id) else { break }+ let on = action.on ?? !light.on+ resolved.on = on+ if let change = writeLight(id, ["on": .bool(on)]) { changes.append(change); scene = nil }+ case .room:+ guard let id = action.id else { break }+ let inRoom = lights(in: id)+ let on = action.on ?? !inRoom.contains(where: \.on)+ resolved.on = on+ changes = inRoom.compactMap { writeLight($0.id, ["on": .bool(on)]) }+ if !changes.isEmpty { scene = nil }+ case .allLights:+ let on = action.on ?? (lightsOn == 0)+ resolved.on = on+ changes = lights.compactMap { writeLight($0.id, ["on": .bool(on)]) }+ if !changes.isEmpty { scene = nil }+ case .scene:+ guard let id = action.id, let definition = scenes.first(where: { $0.id == id }) else { break }+ for light in lights {+ var patch = (definition.lights["*"] ?? [:]).merging(definition.lights[light.id] ?? [:]) { $1 }+ // A scene that sets a white temperature should not be overridden by a stale colour.+ if patch["color"] == nil, patch["temp"] != nil { patch["color"] = .null }+ if let change = writeLight(light.id, patch) { changes.append(change) }+ }+ for ac in acs {+ let patch = (definition.acs["*"] ?? [:]).merging(definition.acs[ac.id] ?? [:]) { $1 }+ if !patch.isEmpty, let change = writeAC(ac.id, patch) { changes.append(change) }+ }+ scene = id+ case .acPower:+ guard let id = action.id, let ac = ac(id) else { break }+ let on = action.on ?? !ac.on+ resolved.on = on+ if let change = writeAC(id, ["on": .bool(on)]) { changes.append(change) }+ case .acTarget:+ guard let id = action.id, let target = action.target, let ac = ac(id) else { break }+ let clamped = Swift.min(ac.max, Swift.max(ac.min, target.rounded()))+ resolved.target = clamped+ if let change = writeAC(id, ["target": .number(clamped)]) { changes.append(change) }+ }+ if !changes.isEmpty { updated = Date().timeIntervalSince1970 }+ return (resolved, changes)+ }++ private mutating func writeLight(_ id: String, _ patch: [String: JSONValue]) -> DeviceChange? {+ guard let index = lights.firstIndex(where: { $0.id == id }) else { return nil }+ var light = lights[index]+ let caps = light.capabilities+ var diff: [String: Any] = [:]+ if let on = patch["on"]?.bool, on != light.on { light.on = on; diff["on"] = on }+ if caps.contains("brightness"), let b = patch["brightness"]?.number {+ let value = Swift.min(1, Swift.max(0.05, b))+ if value != light.brightness { light.brightness = value; diff["brightness"] = value }+ }+ if caps.contains("temp"), let t = patch["temp"]?.number {+ let value = Swift.min(6500, Swift.max(2200, t))+ if value != light.temp { light.temp = value; diff["temp"] = value }+ // Setting a white temperature drops the colour (store.js does the same).+ if light.color != nil { light.color = nil; diff["color"] = NSNull() }+ }+ if caps.contains("color"), let color = patch["color"] {+ let value = color.string+ if value != light.color { light.color = value; diff["color"] = value ?? NSNull() }+ }+ guard !diff.isEmpty else { return nil }+ lights[index] = light+ var state: [String: Any] = ["on": light.on, "brightness": light.brightness, "temp": light.temp]+ state["color"] = light.color ?? NSNull()+ return DeviceChange(kind: .light, id: id, patch: diff, state: state)+ }++ private mutating func writeAC(_ id: String, _ patch: [String: JSONValue]) -> DeviceChange? {+ guard let index = acs.firstIndex(where: { $0.id == id }) else { return nil }+ var ac = acs[index]+ var diff: [String: Any] = [:]+ if let on = patch["on"]?.bool, on != ac.on { ac.on = on; diff["on"] = on }+ if let t = patch["target"]?.number {+ let value = Swift.min(ac.max, Swift.max(ac.min, t.rounded()))+ if value != ac.target { ac.target = value; diff["target"] = value }+ }+ if let mode = patch["mode"]?.string, mode != ac.mode { ac.mode = mode; diff["mode"] = mode }+ if let fan = patch["fan"]?.string, fan != ac.fan { ac.fan = fan; diff["fan"] = fan }+ if let swing = patch["swing"]?.string, swing != ac.swing { ac.swing = swing; diff["swing"] = swing }+ if let sleep = patch["sleep"]?.bool, sleep != ac.sleep { ac.sleep = sleep; diff["sleep"] = sleep }+ if let eco = patch["eco"]?.bool, eco != ac.eco { ac.eco = eco; diff["eco"] = eco }+ guard !diff.isEmpty else { return nil }+ acs[index] = ac+ var state: [String: Any] = ["on": ac.on, "target": ac.target, "mode": ac.mode, "fan": ac.fan]+ if let swing = ac.swing { state["swing"] = swing }+ if let sleep = ac.sleep { state["sleep"] = sleep }+ if let eco = ac.eco { state["eco"] = eco }+ return DeviceChange(kind: .ac, id: id, patch: diff, state: state)+ }++ /// The state in the shape the panel's `adopt` takes.+ var panelState: [String: Any] {+ var lightsOut: [String: Any] = [:]+ for l in lights { lightsOut[l.id] = ["on": l.on, "brightness": l.brightness, "temp": l.temp, "color": (l.color as Any?) ?? NSNull()] }+ var acsOut: [String: Any] = [:]+ for a in acs {+ var s: [String: Any] = ["on": a.on, "target": a.target, "mode": a.mode, "fan": a.fan]+ if let v = a.swing { s["swing"] = v }+ if let v = a.sleep { s["sleep"] = v }+ if let v = a.eco { s["eco"] = v }+ acsOut[a.id] = s+ }+ return ["lights": lightsOut, "acs": acsOut, "scene": (scene as Any?) ?? NSNull(), "source": "Widget"]+ }+}++// SF Symbols for the widgets, the controls and the iPhone's quick actions.+public extension HomeSnapshot.Light {+ var symbol: String {+ switch type {+ case "ceiling": return "light.recessed.fill"+ case "pendant": return "light.cylindrical.ceiling.fill"+ case "spots": return "lightbulb.fill"+ case "floor": return "lamp.floor.fill"+ case "table": return "lamp.table.fill"+ case "strip": return "light.strip.2.fill"+ default: return "lightbulb.fill"+ }+ }++}++public extension HomeSnapshot.Scene {+ var symbol: String {+ switch icon {+ case "sun": return "sun.max.fill"+ case "sofa": return "sofa.fill"+ case "film": return "film.fill"+ case "moon": return "moon.stars.fill"+ case "door": return "door.left.hand.open"+ case "table": return "lamp.desk.fill"+ case "tv": return "tv.fill"+ case "bed": return "bed.double.fill"+ case "leaf": return "leaf.fill"+ case "power": return "power"+ default: return "sparkles"+ }+ }++}diff --git a/core/Sources/HouseCore/JSONValue.swift b/core/Sources/HouseCore/JSONValue.swiftnew file mode 100644index 0000000..e7fd073--- /dev/null+++ b/core/Sources/HouseCore/JSONValue.swift@@ -0,0 +1,65 @@+import Foundation++/// Any JSON value, for the parts of a plan that are passed through rather than read+/// (a scene's settings, a device's links).+public enum JSONValue: Codable, Equatable, Sendable {+ case null+ case bool(Bool)+ case number(Double)+ case string(String)+ case array([JSONValue])+ case object([String: JSONValue])++ public init(from decoder: Decoder) throws {+ let c = try decoder.singleValueContainer()+ if c.decodeNil() { self = .null }+ else if let b = try? c.decode(Bool.self) { self = .bool(b) }+ else if let n = try? c.decode(Double.self) { self = .number(n) }+ else if let s = try? c.decode(String.self) { self = .string(s) }+ else if let a = try? c.decode([JSONValue].self) { self = .array(a) }+ else { self = .object(try c.decode([String: JSONValue].self)) }+ }++ public func encode(to encoder: Encoder) throws {+ var c = encoder.singleValueContainer()+ switch self {+ case .null: try c.encodeNil()+ case .bool(let b): try c.encode(b)+ case .number(let n): try c.encode(n)+ case .string(let s): try c.encode(s)+ case .array(let a): try c.encode(a)+ case .object(let o): try c.encode(o)+ }+ }++ /// The value as `JSONSerialization` gives it.+ public var any: Any {+ switch self {+ case .null: return NSNull()+ case .bool(let b): return b+ case .number(let n): return n+ case .string(let s): return s+ case .array(let a): return a.map(\.any)+ case .object(let o): return o.mapValues(\.any)+ }+ }++ public init?(any value: Any) {+ switch value {+ case is NSNull: self = .null+ // A JSONSerialization boolean is an NSNumber too: tell them apart by its type.+ case let n as NSNumber where CFGetTypeID(n) == CFBooleanGetTypeID(): self = .bool(n.boolValue)+ case let b as Bool: self = .bool(b)+ case let n as NSNumber: self = .number(n.doubleValue)+ case let s as String: self = .string(s)+ case let a as [Any]: self = .array(a.compactMap(JSONValue.init(any:)))+ case let o as [String: Any]: self = .object(o.compactMapValues(JSONValue.init(any:)))+ default: return nil+ }+ }++ public var bool: Bool? { if case .bool(let b) = self { return b } else { return nil } }+ public var number: Double? { if case .number(let n) = self { return n } else { return nil } }+ public var string: String? { if case .string(let s) = self { return s } else { return nil } }+ public var isNull: Bool { self == .null }+}diff --git a/core/Sources/HouseCore/SecretStore.swift b/core/Sources/HouseCore/SecretStore.swiftindex 37fcec7..1226437 100644--- a/core/Sources/HouseCore/SecretStore.swift+++ b/core/Sources/HouseCore/SecretStore.swift@@ -67,7 +67,18 @@ public struct KeychainSecretStore: SecretStore {SecItemAdd(q as CFDictionary, nil)}- public var stamp: Date? { nil }+ /// When the item was last written. The iPhone's widgets share these items with the app+ /// (one Keychain access group), and a Smart Life refresh in one process rotates the token+ /// the other one holds.+ public var stamp: Date? {+ var q = query+ q[kSecReturnAttributes as String] = true+ q[kSecMatchLimit as String] = kSecMatchLimitOne+ var out: CFTypeRef?+ guard SecItemCopyMatching(q as CFDictionary, &out) == errSecSuccess,+ let attributes = out as? [String: Any] else { return nil }+ return attributes[kSecAttrModificationDate as String] as? Date+ }}/// Keeps a secret in memory only (tests, throw-away runs).diff --git a/core/Sources/HouseCore/SharedHome.swift b/core/Sources/HouseCore/SharedHome.swiftnew file mode 100644index 0000000..e9054d0--- /dev/null+++ b/core/Sources/HouseCore/SharedHome.swift@@ -0,0 +1,180 @@+import Foundation++/// The folder the app shares with its widgets (an App Group container): the home's+/// snapshot and the actions widgets made that the app still has to carry out.+///+/// The app writes `home.json` from what the panel shows; a widget applies its change to+/// that file at once (so it can redraw) and queues the action in `actions.json`. The app+/// takes the queue when it is told (a Darwin notification) or when it next comes up, and+/// runs each action through the panel, which sends it to the devices like a tap would.+/// Reads and writes of both files happen under one file lock, so the processes never see+/// half of the other's work.+public final class SharedHome: @unchecked Sendable {+ /// The Info.plist key that holds the App Group id of this build (it carries the+ /// signing team on the Mac, so it is set at build time).+ public static let groupKey = "HouseAppGroup"+ /// Posted by a widget after it queued an action, and by the app after it wrote a new snapshot.+ public static let actionsPosted = "io.github.0xprobabillity.HouseControl.widget-action"+ public static let snapshotWritten = "io.github.0xprobabillity.HouseControl.snapshot"++ public struct Queued: Codable, Equatable, Sendable {+ public var id: UUID+ public var action: HomeAction+ public var at: Double+ /// True when the widget reached the devices itself (the iPhone's Home Assistant, Hue,+ /// Smart Life): the app then only shows the result instead of sending it again.+ public var delivered: Bool+ /// The home it was made in ("custom", "home"…, plus its name): an app showing another+ /// home (a test run, another plan picked meanwhile) drops it.+ public var home: String?++ public init(_ action: HomeAction, home: String? = nil, delivered: Bool = false) {+ id = UUID()+ self.action = action+ at = Date().timeIntervalSince1970+ self.delivered = delivered+ self.home = home+ }+ }++ /// How long a queued action stays worth carrying out, in seconds.+ public static let patience: TimeInterval = 600++ public let directory: URL+ private var snapshotURL: URL { directory.appendingPathComponent("home.json") }+ private var queueURL: URL { directory.appendingPathComponent("actions.json") }+ private var lockURL: URL { directory.appendingPathComponent(".lock") }++ public init(directory: URL) {+ self.directory = directory+ try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ }++ /// The container of this build's App Group, or nil when the build has none (or the+ /// system refuses it, as it does for a Mac build signed without a team).+ public convenience init?(bundle: Bundle = .main) {+ guard let group = bundle.object(forInfoDictionaryKey: Self.groupKey) as? String, !group.isEmpty,+ let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: group) else { return nil }+ self.init(directory: url.appendingPathComponent("Widgets", isDirectory: true))+ }++ // MARK: - Snapshot++ public func snapshot() -> HomeSnapshot? {+ locked { readSnapshot() }+ }++ private func readSnapshot() -> HomeSnapshot? {+ guard let data = try? Data(contentsOf: snapshotURL) else { return nil }+ return try? JSONDecoder().decode(HomeSnapshot.self, from: data)+ }++ private func writeSnapshot(_ snapshot: HomeSnapshot) {+ let encoder = JSONEncoder()+ encoder.outputFormatting = [.sortedKeys]+ guard let data = try? encoder.encode(snapshot) else { return }+ try? data.write(to: snapshotURL, options: .atomic)+ }++ /// Stores what the app shows. Skipped while widget actions wait for the app: the+ /// snapshot already has their result, the app's view of the home does not yet.+ @discardableResult+ public func publish(_ snapshot: HomeSnapshot) -> Bool {+ locked {+ if !readQueue().isEmpty { return false }+ if var current = readSnapshot() {+ current.updated = snapshot.updated+ if current == snapshot { return false } // nothing a widget would draw differently+ }+ writeSnapshot(snapshot)+ return true+ }+ }++ // MARK: - Actions++ /// Applies `action` to the snapshot and queues it for the app. Returns the snapshot as+ /// it is now, the queued entry and what each device has to change; nil when there is no+ /// snapshot yet (the app has never run) or the action changes nothing.+ public func perform(_ action: HomeAction) -> (snapshot: HomeSnapshot, entry: Queued, changes: [DeviceChange])? {+ locked {+ guard var home = readSnapshot() else { return nil }+ let (resolved, changes) = home.apply(action)+ // A scene that is already on still counts: it is applied again (devices may differ).+ guard !changes.isEmpty || action.kind == .scene else { return nil }+ writeSnapshot(home)+ let entry = Queued(resolved, home: home.identity)+ var queue = readQueue()+ queue.append(entry)+ writeQueue(queue)+ return (home, entry, changes)+ }+ }++ /// Records that the widget reached the devices for these entries itself.+ public func markDelivered(_ ids: Set<UUID>) {+ locked {+ var queue = readQueue()+ for i in queue.indices where ids.contains(queue[i].id) { queue[i].delivered = true }+ writeQueue(queue)+ }+ }++ /// The queued actions, oldest first; the queue is empty afterwards.+ public func takeActions() -> (actions: [Queued], snapshot: HomeSnapshot?) {+ locked {+ let queue = readQueue()+ if !queue.isEmpty { writeQueue([]) }+ return (queue, readSnapshot())+ }+ }++ public var hasPendingActions: Bool { locked { !readQueue().isEmpty } }++ /// True once the app took `id` off the queue.+ public func isTaken(_ id: UUID) -> Bool { locked { !readQueue().contains { $0.id == id } } }++ private func readQueue() -> [Queued] {+ guard let data = try? Data(contentsOf: queueURL) else { return [] }+ // 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 }+ }++ private func writeQueue(_ queue: [Queued]) {+ if queue.isEmpty { try? FileManager.default.removeItem(at: queueURL); return }+ guard let data = try? JSONEncoder().encode(queue) else { return }+ try? data.write(to: queueURL, options: .atomic)+ }++ // MARK: - Locking++ private func locked<T>(_ body: () -> T) -> T {+ let fd = open(lockURL.path, O_CREAT | O_RDWR, 0o600)+ guard fd >= 0 else { return body() }+ defer { close(fd) }+ flock(fd, LOCK_EX)+ defer { flock(fd, LOCK_UN) }+ return body()+ }++ // MARK: - Darwin notifications (they cross process boundaries, carry no data)++ public static func post(_ name: String) {+ CFNotificationCenterPostNotification(CFNotificationCenterGetDarwinNotifyCenter(),+ CFNotificationName(name as CFString), nil, nil, true)+ }++ @MainActor private static var observers: [String: () -> Void] = [:]++ /// Calls `handler` on the main queue whenever `name` is posted, by any process.+ @MainActor+ public static func observe(_ name: String, _ handler: @escaping () -> Void) {+ observers[name] = handler+ CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), nil, { _, _, name, _, _ in+ guard let key = name?.rawValue as String? else { return }+ DispatchQueue.main.async { MainActor.assumeIsolated { SharedHome.observers[key]?() } }+ }, name as CFString, nil, .deliverImmediately)+ }+}diff --git a/core/Sources/HouseCore/WidgetBridge.swift b/core/Sources/HouseCore/WidgetBridge.swiftnew file mode 100644index 0000000..7b7a70f--- /dev/null+++ b/core/Sources/HouseCore/WidgetBridge.swift@@ -0,0 +1,69 @@+import Foundation+import WidgetKit++/// The app's side of the widgets: keeps the shared snapshot up to date with what the+/// panel shows, and hands the panel what widgets and controls did while it was not looking.+@MainActor+public final class WidgetBridge {+ public let shared: SharedHome?+ /// Runs actions widgets queued (the panel sends them to the devices) and, when some+ /// were already delivered by a widget itself, the state to show for them.+ public var onActions: ((_ run: [[String: Any]], _ adopt: [String: Any]?) -> Void)?+ /// False until the panel page has started; actions wait for it.+ public var isReady = false {+ didSet { if isReady { takeActions() } else { identity = nil } }+ }+ /// Told about every snapshot the panel posts (the iPhone's quick actions are built from it).+ public var onSnapshot: ((HomeSnapshot) -> Void)?+ /// The home the panel shows, from its last snapshot.+ private var identity: String?+ private var reload: DispatchWorkItem?+ private var lastReload = Date.distantPast++ public init(shared: SharedHome? = SharedHome()) {+ self.shared = shared+ guard shared != nil else { return }+ SharedHome.observe(SharedHome.actionsPosted) { [weak self] in self?.takeActions() }+ }++ /// The panel's `widgets` message.+ public func publish(_ message: [String: Any]) {+ guard let object = message["snapshot"],+ let data = try? JSONSerialization.data(withJSONObject: object),+ let snapshot = try? JSONDecoder().decode(HomeSnapshot.self, from: data) else { return }+ onSnapshot?(snapshot)+ let first = identity == nil+ identity = snapshot.identity+ if first { takeActions() } // the queue waited to learn which home this is+ 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 }+ 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 }+ let encoder = JSONEncoder()+ let run = queued.filter { !$0.delivered }.compactMap { entry -> [String: Any]? in+ guard let data = try? encoder.encode(entry.action) else { return nil }+ return try? JSONSerialization.jsonObject(with: data) as? [String: Any]+ }+ let adopt = queued.contains(where: \.delivered) ? snapshot?.panelState : nil+ onActions?(run, adopt)+ }++ /// Widgets redraw at most a couple of times a second, however fast the panel changes.+ private func scheduleReload() {+ reload?.cancel()+ let work = DispatchWorkItem { [weak self] in+ self?.lastReload = Date()+ WidgetCenter.shared.reloadAllTimelines()+ if #available(iOS 18.0, macOS 26.0, *) { ControlCenter.shared.reloadAllControls() }+ }+ reload = work+ let wait = max(0.15, 0.6 - Date().timeIntervalSince(lastReload))+ DispatchQueue.main.asyncAfter(deadline: .now() + wait, execute: work)+ }+}diff --git a/core/Tests/HouseCoreTests/WidgetTests.swift b/core/Tests/HouseCoreTests/WidgetTests.swiftnew file mode 100644index 0000000..fa622a7--- /dev/null+++ b/core/Tests/HouseCoreTests/WidgetTests.swift@@ -0,0 +1,105 @@+import XCTest+@testable import HouseCore++final class WidgetTests: XCTestCase {+ private func home() -> HomeSnapshot {+ let room = HomeSnapshot.Room(id: "living", name: "Living", x: 0, z: 0, w: 4, d: 3, floor: "oak")+ func lamp(_ id: String, caps: [String], on: Bool, color: String? = nil) -> HomeSnapshot.Light {+ .init(id: id, name: id, room: "living", type: "ceiling", x: 1, z: 1, capabilities: caps,+ on: on, brightness: 0.8, temp: 3000, color: color, service: nil, links: nil)+ }+ let ac = HomeSnapshot.AC(id: "ac", name: "AC", room: "living", wall: "west", x: 0, z: 1, min: 16, max: 30,+ on: false, target: 24, mode: "cool", fan: "auto", roomTemp: 26.5,+ swing: "swing", sleep: false, eco: false, service: nil, links: nil)+ let cozy = HomeSnapshot.Scene(id: "cozy", name: "Cozy", icon: "sofa",+ lights: ["*": ["on": .bool(false)], "tv": ["on": .bool(true), "color": .string("#ff7a3c")],+ "main": ["on": .bool(true), "brightness": .number(0.3), "temp": .number(2400)]],+ acs: ["*": ["on": .bool(true), "target": .number(22)]])+ return HomeSnapshot(name: "Home", plan: "home", rooms: [room],+ lights: [lamp("main", caps: ["brightness", "temp"], on: false),+ lamp("tv", caps: ["brightness", "color"], on: false),+ lamp("plug", caps: [], on: true, color: "#ffffff")],+ acs: [ac], scenes: [cozy])+ }++ func testToggleIsResolved() {+ var h = home()+ let (resolved, changes) = h.apply(.light("main"))+ XCTAssertEqual(resolved.on, true)+ XCTAssertEqual(changes.count, 1)+ XCTAssertEqual(changes[0].patch["on"] as? Bool, true)+ XCTAssertTrue(h.light("main")!.on)+ }++ func testRoomTurnsOffWhenAnyIsOn() {+ var h = home()+ let (resolved, changes) = h.apply(.room("living"))+ XCTAssertEqual(resolved.on, false)+ XCTAssertEqual(changes.map(\.id), ["plug"])+ XCTAssertEqual(h.lightsOn, 0)+ }++ func testSceneFollowsTheStoreRules() {+ var h = home()+ let (_, changes) = h.apply(.scene("cozy"))+ XCTAssertEqual(h.scene, "cozy")+ let main = h.light("main")!+ XCTAssertTrue(main.on)+ XCTAssertEqual(main.brightness, 0.3)+ XCTAssertEqual(main.temp, 2400)+ XCTAssertEqual(h.light("tv")!.color, "#ff7a3c")+ XCTAssertFalse(h.light("plug")!.on)+ // A plug cannot take a colour: the scene's temperature rule leaves it alone.+ XCTAssertEqual(h.light("plug")!.color, "#ffffff")+ let ac = h.ac("ac")!+ XCTAssertTrue(ac.on)+ XCTAssertEqual(ac.target, 22)+ XCTAssertEqual(Set(changes.map(\.id)), ["main", "tv", "plug", "ac"])+ // Changing a lamp by hand leaves the scene.+ _ = h.apply(.light("tv", on: false))+ XCTAssertNil(h.scene)+ }++ func testTargetIsClampedAndRounded() {+ var h = home()+ XCTAssertEqual(h.apply(.acTarget("ac", 40)).resolved.target, 30)+ XCTAssertEqual(h.apply(.acTarget("ac", 21.6)).resolved.target, 22)+ XCTAssertEqual(h.ac("ac")!.target, 22)+ XCTAssertTrue(h.apply(.acTarget("ac", 22)).changes.isEmpty)+ }++ func testSnapshotDecodesThePagesJSON() throws {+ let json = """+ {"version":1,"name":"Home","plan":"home","outdoorTemp":27,"updated":1,"scene":null,+ "rooms":[{"id":"r","name":"R","x":0,"z":0,"w":1,"d":1}],+ "lights":[{"id":"l","name":"L","room":"r","type":"floor","x":0.5,"z":0.5,"capabilities":[],"on":true,+ "brightness":0.8,"temp":3000,"color":null,"service":"smartlife","links":{"tuya":{"deviceId":"abc"}}}],+ "acs":[],"scenes":[{"id":"s","name":"S","icon":"sun","lights":{"*":{"on":true}},"acs":{}}]}+ """+ let h = try JSONDecoder().decode(HomeSnapshot.self, from: Data(json.utf8))+ XCTAssertEqual(h.lights[0].service, "smartlife")+ XCTAssertFalse(h.isSimulated)+ let plan = h.linksPlan+ let lamp = (plan["lights"] as? [[String: Any]])?.first+ XCTAssertEqual((lamp?["tuya"] as? [String: Any])?["deviceId"] as? String, "abc")+ }++ func testQueueAndPublish() throws {+ let dir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ defer { try? FileManager.default.removeItem(at: dir) }+ let shared = SharedHome(directory: dir)+ XCTAssertNil(shared.perform(.light("main")), "no snapshot yet")+ XCTAssertTrue(shared.publish(home()))+ XCTAssertFalse(shared.publish(home()), "unchanged")+ let done = try XCTUnwrap(shared.perform(.light("main")))+ XCTAssertEqual(done.entry.action.on, true)+ XCTAssertTrue(shared.snapshot()!.light("main")!.on)+ // The app's older view must not overwrite what the widget did.+ XCTAssertFalse(shared.publish(home()))+ XCTAssertFalse(shared.isTaken(done.entry.id))+ let taken = shared.takeActions()+ XCTAssertEqual(taken.actions.map(\.id), [done.entry.id])+ XCTAssertTrue(shared.isTaken(done.entry.id))+ XCTAssertTrue(shared.publish(home()))+ }+}diff --git a/docs/widgets.md b/docs/widgets.mdnew file mode 100644index 0000000..6bd5ec9--- /dev/null+++ b/docs/widgets.md@@ -0,0 +1,87 @@+# Widgets, controls and quick actions++House Control puts the home on the iPhone's Home Screen, Lock Screen and Control Center, and on the Mac's+desktop and Control Center. Every widget is live: tap a lamp, a scene or an air conditioner and it switches+without opening the app.++## What there is++| Widget | Sizes | What it does |+| --- | --- | --- |+| **Home** | small, medium, large · extra large on the Mac | The home as a small 3D model, every lamp glowing on the floor of its room in its own colour, ACs blowing on their walls. Medium adds scenes and the power button; large adds the climate strip and makes each lamp in the model a button; the Mac's extra large adds rooms. |+| **Scenes** | small, medium | Four scenes as big buttons; the active one is lit. |+| **Light** | small · Lock Screen (circle) | One lamp you choose, in its colour and brightness. Tap to switch. |+| **Room** | medium, large | Every lamp of one room. Large shows the room on its own in 3D, its AC and **All on / All off**. |+| **Climate** | small, medium · Lock Screen (circle, rectangle) | An AC's set-point on a dial with the room's temperature on it, power and − / +. |+| **Home Status** | Lock Screen (circle, rectangle, inline) | Lamps on, the AC, the active scene. |++Controls (iOS 18 and macOS 26): **All Lights** (toggle), **Light** (toggle, pick the lamp), **Scene** (button, pick the+scene) and **Air Conditioner** (toggle, pick the AC). On the iPhone they go into Control Center, onto the Lock+Screen and onto the Action button; on the Mac into Control Center and the menu bar.++Quick actions (iPhone): press and hold the app icon for up to four of your scenes, lamps and ACs.+Pick them in **Settings → Quick Actions**: add with **+**, drag to reorder, swipe to remove. Each home has its own set;+until you choose, the icon offers three scenes and **All Lights Off**.++The widgets follow the system's looks: full colour, the tinted and clear Home Screen, StandBy and the Lock Screen+(the model turns into a line drawing with the lamps that are on accented).++## How it works++```+panel page (web/src/widgets.js) ──"widgets"──▶ app ──▶ App Group: Widgets/home.json ──▶ widgets redraw+ ▲+widget tap ─▶ AppIntent ─▶ HomeSnapshot.apply ─▶ home.json (at once) + actions.json ──Darwin notification──┘+```++- The panel page posts a **snapshot** after every change: rooms, lamps, ACs, furniture footprints and scenes with+ their state (`HomeSnapshot` in `core/Sources/HouseCore/HomeSnapshot.swift`). The app stores it in the App Group+ container (`SharedHome.swift`) and reloads the widgets, at most a couple of times a second.+- A tap runs an App Intent in the widget extension (`widgets/Sources/Intents.swift`). It applies the change to the+ snapshot with the same rules as the panel's store (scenes, clamping, "a white temperature drops the colour") so the+ widget redraws with the result at once, and queues the action.+- **Mac:** the app runs in the menu bar, takes the queue within milliseconds (a Darwin notification wakes it) and runs+ each action through the panel — the same path as a click there, so it reaches Smart Life, Home Assistant, Hue and+ the island. The widget waits for that and redraws with the real outcome.+- **iPhone:** the app is usually not running. The extension sends the change itself to Home Assistant, Hue and+ Smart Life, with the connections the app keeps in the Keychain group it shares with its widgets (the Smart Life+ session is re-read when the other process refreshed it). Apple Home cannot be reached from a widget: those actions+ wait 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.+- Files are read and written under one `flock`, so the app and a widget never see half of each other's work.++## Code++| Where | What |+| --- | --- |+| `core/Sources/HouseCore/HomeSnapshot.swift` | The snapshot, `HomeAction`, the scene and toggle rules (tested in `WidgetTests.swift`) |+| `core/Sources/HouseCore/SharedHome.swift` | App Group files, the action queue, the lock, Darwin notifications |+| `core/Sources/HouseCore/WidgetBridge.swift` | The app's side: stores snapshots, hands queued actions to the panel |+| `web/src/widgets.js` | Builds the snapshot in the panel page and runs queued actions (`house.widget`) |+| `widgets/Sources/` | Widgets, controls, intents and the isometric model (`HouseModel.swift`), shared by iPhone and Mac |+| `widgets/project.yml` | The Mac's widget extension (built and embedded by `scripts/build-app.sh`) |+| `ios/project.yml` | The iPhone's widget extension (target `HouseWidgets`) |+| `ios/Sources/QuickActions.swift` | The icon's quick actions and their editor |++## Build and try++- **iPhone simulator:** `./scripts/ios-sim.sh`, then long-press the Home Screen → **Edit** → **Add Widget** →+ House Control. The script signs the simulator build with your Apple Development certificate when there is one:+ the simulator offers lamps, rooms and ACs to pick only for an app signed with a team.+- **Mac:** `CODESIGN_IDENTITY="Apple Development: …" ./scripts/build-app.sh`, open the app, then right-click the+ desktop → **Edit Widgets…** → House Control. `SKIP_WIDGETS=1` builds the app without them.+- **Stills of every widget**, without WidgetKit: `cd widgets && swift run render-widgets` (writes PNGs from+ `Resources/sample-home.json`; pass a snapshot to draw another home, `--size mac` for the desktop sizes).+ `node widgets/make-sample.mjs` regenerates the sample from the demo apartment.++## Signing and the App Group++- iPhone: `group.io.github.0xprobabillity.HouseControl` plus the Keychain group+ `$(AppIdentifierPrefix)io.github.0xprobabillity.HouseControl`. Automatic signing registers both for your team.+- Mac: `<TEAM>.io.github.0xprobabillity.HouseControl`, prefixed with the signing team so it needs no provisioning+ profile; `build-app.sh` reads the team from the certificate. The widget extension is sandboxed (WidgetKit requires+ it), the app is not.+- An ad-hoc signed build (the release disk image) has no team: the group is then the bare+ `io.github.0xprobabillity.HouseControl`. The app can write it; whether macOS lets an ad-hoc, sandboxed widget+ extension read it has not been tried yet. If the widgets show the demo apartment there, build the app with your own+ (free) Apple Development certificate.diff --git a/docs/widgets.png b/docs/widgets.pngnew file mode 100644index 0000000..85fa9f1Binary files /dev/null and b/docs/widgets.png differdiff --git a/ios/Resources/Assets.xcassets/AppIconPreview.imageset/Contents.json b/ios/Resources/Assets.xcassets/AppIconPreview.imageset/Contents.jsonnew file mode 100644index 0000000..5ec680a--- /dev/null+++ b/ios/Resources/Assets.xcassets/AppIconPreview.imageset/Contents.json@@ -0,0 +1,4 @@+{+ "images" : [ { "filename" : "icon.png", "idiom" : "universal", "scale" : "3x" } ],+ "info" : { "author" : "xcode", "version" : 1 }+}diff --git a/ios/Resources/Assets.xcassets/AppIconPreview.imageset/icon.png b/ios/Resources/Assets.xcassets/AppIconPreview.imageset/icon.pngnew file mode 100644index 0000000..707eb2bBinary files /dev/null and b/ios/Resources/Assets.xcassets/AppIconPreview.imageset/icon.png differdiff --git a/ios/Sources/AppModel.swift b/ios/Sources/AppModel.swiftindex b92fb04..ee06ab2 100644--- a/ios/Sources/AppModel.swift+++ b/ios/Sources/AppModel.swift@@ -21,6 +21,7 @@ enum HomeKitStatus: Equatable {enum SettingsRoute: Hashable {case pairingcase smartLife+ case quickActions}/// Everything the screens share: the floor plan, the devices, the link to the Mac.@@ -31,10 +32,18 @@ final class AppModel {@ObservationIgnored let hub: DeviceHub@ObservationIgnored let sync: SyncClient@ObservationIgnored let web: HomeWeb+ /// The Home Screen and Lock Screen widgets, and the Control Center controls.+ @ObservationIgnored let widgets = WidgetBridge()+ /// The menu of the app's icon on the Home Screen.+ let quickActions = QuickActions()+ /// A quick action picked before the page was up.+ @ObservationIgnored private var pendingQuick: [(HomeAction, String)] = []@ObservationIgnored private var pollTimer: Timer?@ObservationIgnored private var bannerTask: Task<Void, Never>?@ObservationIgnored private var pageReady = false@ObservationIgnored private var active = false+ /// A device a widget asked to show before the page was up.+ @ObservationIgnored private var pendingDevice: String?// Floor planprivate(set) var activePlan: String@@ -106,6 +115,13 @@ final class AppModel {}sync.onState = { [weak self] in self?.received($0) }+ widgets.onActions = { [weak self] run, adopt in+ guard let self else { return }+ if !run.isEmpty { self.web.call("widget", run) }+ if let adopt { self.web.call("adopt", adopt) }+ }+ widgets.onSnapshot = { [weak self] in self?.quickActions.update(home: $0) }+ QuickActionCenter.handler = { [weak self] id, title in self?.runQuickAction(id, title: title) }web.onMessage = { [weak self] in self?.handle($0) }web.load { [weak self] in self?.bootPayload() ?? [:] }@@ -114,6 +130,7 @@ final class AppModel {case "settings": showSettings = truecase "pairing": showSettings = true; settingsPath = [.pairing]case "smartlife": showSettings = true; settingsPath = [.smartLife]+ case "quickactions": showSettings = true; settingsPath = [.quickActions]case "connections": showSettings = truecase "welcome": showWelcome = truecase "home": break@@ -130,6 +147,7 @@ final class AppModel {if on {sync.start()startPolling()+ widgets.takeActions()} else {sync.stop()pollTimer?.invalidate()@@ -167,10 +185,20 @@ final class AppModel {switch message["type"] as? String {case "ready":pageReady = true+ widgets.isReady = true+ if let device = pendingDevice {+ pendingDevice = nil+ web.call("openDevice", device)+ }+ let quick = pendingQuick+ pendingQuick = []+ for (action, title) in quick { run(action, title: title) }web.call("shown") // the camera sweep and the lights coming on, once per loadstartPolling()case "command":hub.command(message) { [weak self] in self?.web.reply(to: message, $0) }+ case "widgets":+ widgets.publish(message)case "haptic":Haptics.shared.play(message["kind"] as? String ?? "light")case "openSettings":@@ -193,6 +221,7 @@ final class AppModel {customPlanName = plans.customPlanNamereloadLinks()pageReady = false+ widgets.isReady = falseweb.reload()}@@ -218,11 +247,37 @@ final class AppModel {reloadHome()}+ // MARK: - Quick actions++ private func runQuickAction(_ id: String, title: String) {+ guard let action = QuickAction.action(for: id) else { return }+ showSettings = false+ if pageReady { run(action, title: title) } else { pendingQuick.append((action, title)) }+ }++ /// Runs an action from the icon's menu through the panel, which sends it to the devices.+ private func run(_ action: HomeAction, title: String) {+ guard let data = try? JSONEncoder().encode(action),+ let dict = try? JSONSerialization.jsonObject(with: data) else { return }+ web.call("widget", [dict])+ Haptics.shared.play("medium")+ show(Banner(symbol: action.kind == .scene ? "sparkles" : "checkmark.circle.fill", text: title))+ }+// MARK: - Mac sync- /// A `housecontrol://pair?…` link, from the camera, the clipboard or another app.+ /// A `housecontrol://pair?…` link, from the camera, the clipboard or another app, or+ /// `housecontrol://open?device=…` from a widget.@discardableResultfunc open(_ url: URL) -> Bool {+ if url.scheme == SyncPairing.scheme, url.host == "open" {+ showSettings = false+ let device = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems?.first { $0.name == "device" }?.value+ if let device {+ if pageReady { web.call("openDevice", device) } else { pendingDevice = device }+ }+ return true+ }guard let pairing = SyncPairing(link: url.absoluteString) else { return false }pair(pairing)return truediff --git a/ios/Sources/HouseControlApp.swift b/ios/Sources/HouseControlApp.swiftindex 3eddda2..f03de5e 100644--- a/ios/Sources/HouseControlApp.swift+++ b/ios/Sources/HouseControlApp.swift@@ -2,6 +2,7 @@ import SwiftUI@mainstruct HouseControlApp: App {+ @UIApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate@State private var model = AppModel()@Environment(\.scenePhase) private var scenePhasediff --git a/ios/Sources/QuickActions.swift b/ios/Sources/QuickActions.swiftnew file mode 100644index 0000000..d6ffb68--- /dev/null+++ b/ios/Sources/QuickActions.swift@@ -0,0 +1,275 @@+import SwiftUI+import UIKit+import HouseCore++/// One entry of the menu that opens when the app's icon is pressed and held.+struct QuickAction: Identifiable, Hashable {+ enum Group: String, CaseIterable {+ case scenes = "Scenes", home = "Whole home", lights = "Lights", climate = "Air conditioners"+ }++ /// "scene:cozy", "lights:off", "lights:on", "light:<id>", "ac:<id>": stored, and carried by the icon's menu item.+ let id: String+ let title: String+ let subtitle: String?+ let symbol: String+ let group: Group++ /// What it does; toggles stay toggles, decided by the panel when the action runs.+ static func action(for id: String) -> HomeAction? {+ let parts = id.split(separator: ":", maxSplits: 1).map(String.init)+ guard parts.count == 2 else { return nil }+ switch parts[0] {+ case "scene": return .scene(parts[1])+ case "lights": return .allLights(on: parts[1] == "on")+ case "light": return .light(parts[1])+ case "ac": return .acPower(parts[1])+ default: return nil+ }+ }++ /// Everything the home offers, in the order the editor lists it.+ static func catalog(for home: HomeSnapshot) -> [QuickAction] {+ var out = home.scenes.map {+ QuickAction(id: "scene:\($0.id)", title: $0.name, subtitle: "Scene", symbol: $0.symbol, group: .scenes)+ }+ out.append(QuickAction(id: "lights:off", title: "All Lights Off", subtitle: home.name, symbol: "lightbulb.slash", group: .home))+ out.append(QuickAction(id: "lights:on", title: "All Lights On", subtitle: home.name, symbol: "lightbulb.2.fill", group: .home))+ for light in home.lights {+ out.append(QuickAction(id: "light:\(light.id)", title: light.name, subtitle: home.room(light.room)?.name,+ symbol: light.symbol, group: .lights))+ }+ for ac in home.acs {+ out.append(QuickAction(id: "ac:\(ac.id)", title: ac.name, subtitle: home.room(ac.room)?.name,+ symbol: "air.conditioner.horizontal.fill", group: .climate))+ }+ return out+ }+}++/// The quick actions of the app icon: which ones, in which order, for each home.+@MainActor+@Observable+final class QuickActions {+ /// iOS shows four of an app's own items.+ static let limit = 4+ static let itemType = "io.github.0xprobabillity.HouseControl.quick"++ private(set) var available: [QuickAction] = []+ /// The ids on the icon, in order.+ var chosen: [String] = [] {+ didSet {+ guard chosen != oldValue, let identity else { return }+ UserDefaults.standard.set(chosen, forKey: "quickActions.\(identity)")+ apply()+ }+ }+ @ObservationIgnored private var identity: String?++ func lookup(_ id: String) -> QuickAction? { available.first { $0.id == id } }++ /// Follows the home the panel shows: another plan has its own set.+ func update(home: HomeSnapshot) {+ let catalog = QuickAction.catalog(for: home)+ let changed = catalog != available+ available = catalog+ if identity != home.identity {+ identity = nil // no saving while switching+ let saved = UserDefaults.standard.stringArray(forKey: "quickActions.\(home.identity)")+ chosen = (saved ?? Self.defaults(for: home)).filter { id in catalog.contains { $0.id == id } }+ identity = home.identity+ apply()+ } else if changed {+ apply()+ }+ }++ /// Three scenes and "All Lights Off" until the person picks their own.+ private static func defaults(for home: HomeSnapshot) -> [String] {+ let preferred = ["cozy", "movie", "night", "bright"]+ var scenes = preferred.filter { id in home.scenes.contains { $0.id == id } }+ for scene in home.scenes where !scenes.contains(scene.id) { scenes.append(scene.id) }+ return scenes.prefix(3).map { "scene:\($0)" } + ["lights:off"]+ }++ func add(_ id: String) {+ guard chosen.count < Self.limit, !chosen.contains(id) else { return }+ chosen.append(id)+ }++ func remove(_ id: String) { chosen.removeAll { $0 == id } }++ private func apply() {+ UIApplication.shared.shortcutItems = chosen.compactMap(lookup).map {+ UIApplicationShortcutItem(type: Self.itemType, localizedTitle: $0.title, localizedSubtitle: $0.subtitle,+ icon: UIApplicationShortcutIcon(systemImageName: $0.symbol),+ userInfo: ["id": $0.id as NSString])+ }+ }+}++/// Where an item picked from the icon's menu arrives: at launch, or while the app runs.+@MainActor+enum QuickActionCenter {+ static var handler: ((_ id: String, _ title: String) -> Void)? {+ didSet { if handler != nil { flush() } }+ }+ private static var pending: [(String, String)] = []++ static func receive(_ item: UIApplicationShortcutItem) {+ guard item.type == QuickActions.itemType, let id = item.userInfo?["id"] as? String else { return }+ pending.append((id, item.localizedTitle))+ flush()+ }++ private static func flush() {+ guard let handler else { return }+ let items = pending+ pending = []+ for (id, title) in items { handler(id, title) }+ }+}++/// Hands SwiftUI's scenes a delegate that hears about the icon's menu.+final class AppDelegate: NSObject, UIApplicationDelegate {+ func application(_ application: UIApplication, configurationForConnecting session: UISceneSession,+ options: UIScene.ConnectionOptions) -> UISceneConfiguration {+ if let item = options.shortcutItem { MainActor.assumeIsolated { QuickActionCenter.receive(item) } }+ let configuration = UISceneConfiguration(name: nil, sessionRole: session.role)+ configuration.delegateClass = SceneDelegate.self+ return configuration+ }+}++final class SceneDelegate: NSObject, UIWindowSceneDelegate {+ func windowScene(_ windowScene: UIWindowScene, performActionFor shortcutItem: UIApplicationShortcutItem,+ completionHandler: @escaping (Bool) -> Void) {+ MainActor.assumeIsolated { QuickActionCenter.receive(shortcutItem) }+ completionHandler(true)+ }+}++// MARK: - Editor++/// Settings → Quick Actions: what the icon's menu offers, in which order.+struct QuickActionsView: View {+ @Environment(AppModel.self) private var model++ var body: some View {+ let quick = model.quickActions+ List {+ Section {+ IconPreview(items: quick.chosen.compactMap(quick.lookup))+ .listRowInsets(EdgeInsets())+ .listRowBackground(Color.clear)+ }+ Section {+ if quick.chosen.isEmpty {+ Text("Nothing yet: add up to four below.")+ .font(.system(size: 14.5)).foregroundStyle(Theme.muted)+ .listRowBackground(Theme.surface)+ }+ ForEach(quick.chosen, id: \.self) { id in+ if let action = quick.lookup(id) {+ row(action, chosen: true)+ }+ }+ .onMove { quick.chosen.move(fromOffsets: $0, toOffset: $1) }+ .onDelete { quick.chosen.remove(atOffsets: $0) }+ } header: {+ header("On the icon · \(quick.chosen.count) of \(QuickActions.limit)")+ } footer: {+ Text("Press and hold House Control on the Home Screen. Drag to reorder, swipe to remove.")+ .font(.system(size: 13)).foregroundStyle(Theme.faint)+ }+ ForEach(QuickAction.Group.allCases, id: \.self) { group in+ let items = quick.available.filter { $0.group == group && !quick.chosen.contains($0.id) }+ if !items.isEmpty {+ Section {+ ForEach(items) { row($0, chosen: false) }+ } header: {+ header(group.rawValue)+ }+ }+ }+ }+ .environment(\.editMode, .constant(.active))+ .scrollContentBackground(.hidden)+ .background(Theme.background)+ .navigationTitle("Quick Actions")+ .navigationBarTitleDisplayMode(.inline)+ .animation(.snappy, value: quick.chosen)+ }++ private func header(_ text: String) -> some View {+ Text(text.uppercased()).font(.system(size: 12, weight: .bold)).kerning(1.1).foregroundStyle(Theme.faint)+ }++ private func row(_ action: QuickAction, chosen: Bool) -> some View {+ let quick = model.quickActions+ let full = quick.chosen.count >= QuickActions.limit+ return HStack(spacing: 12) {+ IconBadge(symbol: action.symbol, tint: chosen ? Theme.warm : Theme.accent, size: 34)+ VStack(alignment: .leading, spacing: 1) {+ Text(action.title).font(.system(size: 16, weight: .semibold)).foregroundStyle(Theme.text)+ if let subtitle = action.subtitle {+ Text(subtitle).font(.system(size: 13)).foregroundStyle(Theme.muted)+ }+ }+ Spacer(minLength: 8)+ if !chosen {+ Button { quick.add(action.id) } label: {+ Image(systemName: "plus.circle.fill").font(.system(size: 24))+ .foregroundStyle(full ? Theme.faint : Theme.green)+ }+ .buttonStyle(.plain)+ .disabled(full)+ .accessibilityLabel("Add \(action.title)")+ }+ }+ .padding(.vertical, 3)+ .listRowBackground(Theme.surface)+ .deleteDisabled(!chosen)+ .moveDisabled(!chosen)+ }+}++/// The icon's menu as it will look, above the list.+private struct IconPreview: View {+ let items: [QuickAction]++ var body: some View {+ HStack(alignment: .top, spacing: 14) {+ Image("AppIconPreview")+ .resizable()+ .frame(width: 62, height: 62)+ .clipShape(RoundedRectangle(cornerRadius: 15, style: .continuous))+ .shadow(color: .black.opacity(0.4), radius: 8, y: 4)+ VStack(spacing: 0) {+ ForEach(Array(items.enumerated()), id: \.element.id) { index, item in+ if index > 0 { Rectangle().fill(Color.white.opacity(0.08)).frame(height: 0.5) }+ HStack {+ VStack(alignment: .leading, spacing: 0) {+ Text(item.title).font(.system(size: 15, weight: .medium)).foregroundStyle(Theme.text)+ if let subtitle = item.subtitle {+ Text(subtitle).font(.system(size: 12)).foregroundStyle(Theme.muted)+ }+ }+ Spacer()+ Image(systemName: item.symbol).font(.system(size: 15, weight: .medium)).foregroundStyle(Theme.text)+ }+ .padding(.horizontal, 14)+ .frame(height: 46)+ }+ if items.isEmpty {+ Text("No quick actions").font(.system(size: 14)).foregroundStyle(Theme.faint).frame(height: 46)+ }+ }+ .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 16, style: .continuous))+ .overlay(RoundedRectangle(cornerRadius: 16, style: .continuous).strokeBorder(Theme.line))+ }+ .padding(.vertical, 12)+ .accessibilityElement(children: .combine)+ .accessibilityLabel("Preview: \(items.map(\.title).joined(separator: ", "))")+ }+}diff --git a/ios/Sources/SettingsView.swift b/ios/Sources/SettingsView.swiftindex 9e2e0bc..4c2d378 100644--- a/ios/Sources/SettingsView.swift+++ b/ios/Sources/SettingsView.swift@@ -17,6 +17,7 @@ struct SettingsView: View {ScrollView {VStack(spacing: 30) {homeSection+ shortcutsSectionmacSectionsmartLifeSectionconnectionsSection@@ -39,6 +40,7 @@ struct SettingsView: View {switch route {case .pairing: PairingView()case .smartLife: SmartLifeView()+ case .quickActions: QuickActionsView()}}}@@ -105,6 +107,36 @@ struct SettingsView: View {.accessibilityAddTraits(model.activePlan == id ? .isSelected : [])}+ // MARK: - Quick actions++ private var shortcutsSection: some View {+ VStack(spacing: 10) {+ SectionTitle("Shortcuts")+ Card {+ NavigationLink(value: SettingsRoute.quickActions) {+ HStack(spacing: 14) {+ IconBadge(symbol: "hand.tap.fill", tint: Theme.warm)+ VStack(alignment: .leading, spacing: 2) {+ Text("Quick Actions").font(.system(size: 16.5, weight: .semibold)).foregroundStyle(Theme.text)+ Text(quickActionsDetail).font(.system(size: 13.5)).foregroundStyle(Theme.muted).lineLimit(1)+ }+ Spacer(minLength: 8)+ Image(systemName: "chevron.right").font(.system(size: 14, weight: .semibold)).foregroundStyle(Theme.faint)+ }+ .padding(.horizontal, 14)+ .frame(minHeight: 66)+ }+ .buttonStyle(RowButtonStyle())+ }+ footnote("Press and hold the app icon for these. Widgets and Control Center buttons are added from the Home Screen and Control Center.")+ }+ }++ private var quickActionsDetail: String {+ let names = model.quickActions.chosen.compactMap(model.quickActions.lookup).map(\.title)+ return names.isEmpty ? "None" : names.joined(separator: " · ")+ }+// MARK: - Macprivate var macSection: some View {diff --git a/ios/project.yml b/ios/project.ymlindex a005431..be3bec1 100644--- a/ios/project.yml+++ b/ios/project.yml@@ -25,14 +25,20 @@ targets:buildPhase: resourcesdependencies:- package: HouseCore+ - target: HouseWidgets+ embed: trueentitlements:path: Config/HouseControl.entitlementsproperties:com.apple.developer.homekit: true+ # Shared with the widgets: the home they draw, and the connections they use.+ com.apple.security.application-groups: [group.io.github.0xprobabillity.HouseControl]+ keychain-access-groups: [$(AppIdentifierPrefix)io.github.0xprobabillity.HouseControl]info:path: Config/Info.plistproperties:CFBundleDisplayName: House Control+ HouseAppGroup: group.io.github.0xprobabillity.HouseControlCFBundleShortVersionString: $(MARKETING_VERSION)CFBundleVersion: $(CURRENT_PROJECT_VERSION)LSApplicationCategoryType: public.app-category.lifestyle@@ -62,6 +68,40 @@ targets:SWIFT_VERSION: "5.0"ENABLE_USER_SCRIPT_SANDBOXING: YESGENERATE_INFOPLIST_FILE: NO+ # Home Screen, Lock Screen and StandBy widgets plus Control Center controls (../widgets).+ HouseWidgets:+ type: app-extension+ platform: iOS+ sources:+ - path: ../widgets/Sources+ - path: ../widgets/Resources+ buildPhase: resources+ dependencies:+ - package: HouseCore+ - sdk: WidgetKit.framework+ - sdk: SwiftUI.framework+ entitlements:+ path: ../widgets/Config/iOS.entitlements+ properties:+ com.apple.security.application-groups: [group.io.github.0xprobabillity.HouseControl]+ keychain-access-groups: [$(AppIdentifierPrefix)io.github.0xprobabillity.HouseControl]+ info:+ path: ../widgets/Config/Info-iOS.plist+ properties:+ CFBundleDisplayName: House Control+ CFBundleShortVersionString: $(MARKETING_VERSION)+ CFBundleVersion: $(CURRENT_PROJECT_VERSION)+ HouseAppGroup: group.io.github.0xprobabillity.HouseControl+ NSExtension:+ NSExtensionPointIdentifier: com.apple.widgetkit-extension+ settings:+ base:+ PRODUCT_BUNDLE_IDENTIFIER: io.github.0xprobabillity.HouseControl.Widgets+ PRODUCT_NAME: HouseWidgets+ TARGETED_DEVICE_FAMILY: "1"+ SWIFT_VERSION: "5.0"+ GENERATE_INFOPLIST_FILE: NO+ SKIP_INSTALL: YESschemes:HouseControl:build:diff --git a/macos/Sources/HouseControl/AppDelegate.swift b/macos/Sources/HouseControl/AppDelegate.swiftindex 9fe5212..9dd6059 100644--- a/macos/Sources/HouseControl/AppDelegate.swift+++ b/macos/Sources/HouseControl/AppDelegate.swift@@ -31,6 +31,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate {return agent}()private var lastSummary: [String: Any] = [:]+ /// Desktop widgets and Control Center controls: what they show, what they asked for.+ private let widgets = WidgetBridge()func applicationDidFinishLaunching(_ notification: Notification) {buildMainMenu()@@ -51,6 +53,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate {panel = PanelController(host: host)panel.onVisibilityChange = { [weak self] visible in self?.setPolling(visible) }hub.onStale = { [weak self] in self?.poll() }+ widgets.onActions = { [weak self] run, adopt in+ guard let self else { return }+ if !run.isEmpty { self.panel.host.call("widget", run) }+ if let adopt { self.panel.host.call("adopt", adopt) }+ }reloadLinks()host.load()startSync()@@ -83,6 +90,15 @@ final class AppDelegate: NSObject, NSApplicationDelegate {}}+ /// `housecontrol://open[?device=…]`: a click on a widget opens the panel (on that lamp, AC or room).+ func application(_ application: NSApplication, open urls: [URL]) {+ guard let url = urls.first, url.scheme == SyncPairing.scheme, url.host == "open" else { return }+ if !panel.isVisible { togglePanel() }+ if let device = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems?.first(where: { $0.name == "device" })?.value {+ panel.host.call("openDevice", device)+ }+ }+func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { false }func applicationWillTerminate(_ notification: Notification) {@@ -221,6 +237,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {@objc private func reloadAll() {reloadLinks()+ widgets.isReady = falsepanel.host.load()if island?.isShown == true { island?.host.load() }sync.broadcast()@@ -283,6 +300,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {case "ready", "summary":// A view that has just loaded takes over what the panel shows.if message["type"] as? String == "ready", host !== panel.host { panel.host.call("share") }+ if message["type"] as? String == "ready", host === panel.host { widgets.isReady = true }if let summary = (message["summary"] as? [String: Any]) ?? (message["lightsOn"] != nil ? message : nil) {updateStatus(summary)}@@ -294,6 +312,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate {for other in [panel.host, island?.host] where other !== host { other?.call("adopt", state) }case "command":hub.command(message) { [weak host] in host?.reply(to: message, $0) }+ case "widgets":+ if host === panel.host { widgets.publish(message) }case "close":panel.hide()case "selectPlan":diff --git a/scripts/build-app.sh b/scripts/build-app.shindex a279fae..b86ee27 100755--- a/scripts/build-app.sh+++ b/scripts/build-app.sh@@ -3,6 +3,7 @@# UNIVERSAL=1 one binary for Apple silicon and Intel Macs (what scripts/release-mac.sh ships)# CODESIGN_IDENTITY=… sign with your certificate instead of ad hoc (see the end of this file)# APP_PATH=… where to put the app (default build/HouseControl.app)+# SKIP_WIDGETS=1 leave out the desktop and Control Center widgets (they need Xcode and xcodegen)set -euo pipefailROOT="$(cd "$(dirname "$0")/.." && pwd)"APP="${APP_PATH:-$ROOT/build/HouseControl.app}"@@ -23,12 +24,41 @@ swift build -c release ${ARCH_FLAGS[@]+"${ARCH_FLAGS[@]}"} 2>&1 | grep -E "errorBIN="$(swift build -c release ${ARCH_FLAGS[@]+"${ARCH_FLAGS[@]}"} --show-bin-path)/HouseControl"[ -x "$BIN" ] || { echo "Swift build failed"; exit 1; }+# The widgets share an App Group with the app. On the Mac its id carries the signing team,+# taken from the certificate; an ad-hoc build has no team (see docs/widgets.md).+TEAM=""+if [ -n "${CODESIGN_IDENTITY:-}" ]; then+ # CODESIGN_IDENTITY may be the certificate's name or its SHA-1.+ NAME="$(security find-identity -v -p codesigning | grep -F "$CODESIGN_IDENTITY" | sed -n 's/.*"\(.*\)"/\1/p' | head -1)" || true+ TEAM="$(security find-certificate -c "${NAME:-$CODESIGN_IDENTITY}" -p 2>/dev/null | openssl x509 -noout -subject 2>/dev/null \+ | sed -n 's/.*OU *= *\([A-Z0-9]\{10\}\).*/\1/p')" || true+fi+GROUP="${TEAM:+$TEAM.}io.github.0xprobabillity.HouseControl"++if [ -z "${SKIP_WIDGETS:-}" ]; then+ echo "▸ Building widgets"+ cd "$ROOT/widgets"+ xcodegen generate --quiet+ WIDGET_ARCHS=()+ [ -n "${UNIVERSAL:-}" ] && WIDGET_ARCHS=(ARCHS="arm64 x86_64" ONLY_ACTIVE_ARCH=NO)+ xcodebuild -project HouseWidgetsMac.xcodeproj -scheme HouseWidgets -configuration Release \+ -derivedDataPath build/DerivedData -destination 'generic/platform=macOS' \+ CODE_SIGN_IDENTITY="${CODESIGN_IDENTITY:--}" DEVELOPMENT_TEAM="$TEAM" ${WIDGET_ARCHS[@]+"${WIDGET_ARCHS[@]}"} \+ build 2>&1 | grep -E "error:|BUILD FAILED" || true+ APPEX="$ROOT/widgets/build/DerivedData/Build/Products/Release/HouseWidgets.appex"+ [ -d "$APPEX" ] || { echo "Widget build failed"; exit 1; }+fi+echo "▸ Assembling $APP"rm -rf "$APP"mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"cp "$BIN" "$APP/Contents/MacOS/HouseControl"cp -R "$ROOT/web/dist" "$APP/Contents/Resources/web"[ -f "$ROOT/macos/AppIcon.icns" ] && cp "$ROOT/macos/AppIcon.icns" "$APP/Contents/Resources/AppIcon.icns"+if [ -n "${APPEX:-}" ]; then+ mkdir -p "$APP/Contents/PlugIns"+ cp -R "$APPEX" "$APP/Contents/PlugIns/"+ficat > "$APP/Contents/Info.plist" <<PLIST<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">@@ -49,6 +79,11 @@ cat > "$APP/Contents/Info.plist" <<PLIST<key>NSLocalNetworkUsageDescription</key><string>House Control finds your Home Assistant and Hue Bridge on this network, and lets the iPhones you paired find this Mac to receive your floor plan.</string><key>NSBonjourServices</key><array><string>_housecontrol._tcp</string><string>_hue._tcp</string><string>_home-assistant._tcp</string></array><key>NSHighResolutionCapable</key><true/>+ <key>HouseAppGroup</key><string>$GROUP</string>+ <key>CFBundleURLTypes</key><array><dict>+ <key>CFBundleURLName</key><string>io.github.0xprobabillity.HouseControl.open</string>+ <key>CFBundleURLSchemes</key><array><string>housecontrol</string></array>+ </dict></array></dict></plist>PLIST@@ -57,9 +92,21 @@ PLIST# CODESIGN_IDENTITY="Apple Development: …" (see `security find-identity -v -p codesigning`)# signs with your own certificate and the permission sticks.# A real identity also gets the hardened runtime and a secure timestamp, which notarization requires.+# The widget extension inside was signed by xcodebuild with its own (sandbox) entitlements;+# the app gets the App Group it shares with it.+ENTITLEMENTS="$(mktemp -d)/HouseControl.entitlements"+cat > "$ENTITLEMENTS" <<ENT+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0"><dict>+ <key>com.apple.security.application-groups</key><array><string>$GROUP</string></array>+</dict></plist>+ENTif [ -n "${CODESIGN_IDENTITY:-}" ]; then- codesign --force --options runtime --timestamp --sign "$CODESIGN_IDENTITY" "$APP" || { echo "Signing failed"; exit 1; }+ codesign --force --options runtime --timestamp --entitlements "$ENTITLEMENTS" --sign "$CODESIGN_IDENTITY" "$APP" \+ || { echo "Signing failed"; exit 1; }else- codesign --force --sign - "$APP" >/dev/null 2>&1 || echo " (signing skipped)"+ codesign --force --entitlements "$ENTITLEMENTS" --sign - "$APP" >/dev/null 2>&1 || echo " (signing skipped)"fi+rm -rf "$(dirname "$ENTITLEMENTS")"echo "✓ Done: $APP"diff --git a/scripts/ios-sim.sh b/scripts/ios-sim.shindex b6d7e9a..d071c90 100755--- a/scripts/ios-sim.sh+++ b/scripts/ios-sim.sh@@ -20,6 +20,15 @@ xcodebuild -project HouseControl.xcodeproj -scheme HouseControl -configuration DCODE_SIGN_IDENTITY=- build 2>&1 | grep -E "error|warning: |BUILD" | grep -v appintentsmetadataprocessor || trueAPP="build/DerivedData/Build/Products/Debug-iphonesimulator/HouseControl.app"[ -d "$APP" ] || { echo "Build failed"; exit 1; }+# Choosing a lamp, room or AC for a widget needs a signature with a team: the simulator's+# App Intents service ignores the entities of an ad-hoc signed app. Uses your Apple+# Development certificate when there is one (CODESIGN_IDENTITY=… picks another).+SIGN="${CODESIGN_IDENTITY:-$(security find-identity -v -p codesigning | awk '/Apple Development/{print $2; exit}')}"+if [ -n "$SIGN" ]; then+ for bundle in "$APP"/PlugIns/*.appex "$APP"; do+ codesign --force --sign "$SIGN" --preserve-metadata=entitlements "$bundle" >/dev/null 2>&1 || true+ done+fixcrun simctl bootstatus "$DEVICE" -b >/dev/nullxcrun simctl install "$DEVICE" "$APP"diff --git a/web/src/main.js b/web/src/main.jsindex 7558220..c44a6f9 100644--- a/web/src/main.js+++ b/web/src/main.js@@ -6,6 +6,7 @@ import { createAgent } from './agent/tools.js';import { h, openMenu } from './ui/dom.js';import { icon } from './ui/icons.js';import { isNative, isPhone, post, incoming, haptic } from './bridge.js';+import { publishWidgets, runWidgetAction } from './widgets.js';const DEMO_PLANS = [{ id: 'home', name: 'Demo · Apartment' },@@ -111,6 +112,21 @@ async function boot() {incoming.applyRemote = (update) => store.applyRemote(update);incoming.adopt = (state) => store.adopt(state);incoming.share = () => store.share();+ // Widgets and controls: what they changed while the app was away is run here, where it+ // reaches the devices; a widget's tap on a lamp or a scene opens that in the panel.+ incoming.widget = (actions) => {+ store.source = 'Widget';+ try {+ for (const action of [].concat(actions)) runWidgetAction(store, config, action);+ } finally {+ store.source = null;+ }+ };+ incoming.openDevice = (id) => {+ if (store.acCfg.has(id)) panel.openSheet({ kind: 'ac', id });+ else if (store.lightCfg.has(id)) panel.openSheet({ kind: 'light', id });+ else if (config.rooms.some((r) => r.id === id)) { panel.closeSheet(); panel.selectRoom(id); }+ };// AI Access: an AI assistant's requests are run here, where the state of every device lives.const agent = createAgent({store, config, raw,@@ -175,6 +191,7 @@ async function boot() {if (!isNative) show();post('ready', { summary: store.summary() });+ if (isNative) publishWidgets(config, store);window.__house = { store, world, panel, config }; // handy in the dev console}diff --git a/web/src/widgets.js b/web/src/widgets.jsnew file mode 100644index 0000000..117433f--- /dev/null+++ b/web/src/widgets.js@@ -0,0 +1,94 @@+// The home as the widgets and controls draw it (HomeSnapshot in core/…/HomeSnapshot.swift):+// rooms, lamps, ACs and scenes with their current state. Posted to the native shell, which+// keeps it where its widgets can read it; only the panel posts, the other views are copies.+import { post } from './bridge.js';+import { linkOf, LINK_FIELDS } from './config.js';+import { footprint } from './three/furniture.js';++const round = (v, digits = 3) => (Number.isFinite(v) ? Math.round(v * 10 ** digits) / 10 ** digits : v);++function links(device) {+ const out = {};+ for (const key of LINK_FIELDS) if (device[key]) out[key] = device[key];+ return Object.keys(out).length ? out : null;+}++export function widgetSnapshot(config, store, plan) {+ const { state } = store;+ return {+ version: 1,+ name: config.name,+ plan,+ outdoorTemp: config.outdoorTemp,+ updated: Date.now() / 1000,+ scene: state.scene || null,+ rooms: config.rooms.map((r) => ({ id: r.id, name: r.name, x: r.x, z: r.z, w: r.w, d: r.d, floor: r.floor })),+ lights: config.lights.map((l) => {+ const s = state.lights[l.id];+ return {+ id: l.id, name: l.name, room: l.room, type: l.type, x: l.pos[0], z: l.pos[1],+ capabilities: l.capabilities, on: s.on, brightness: round(s.brightness), temp: Math.round(s.temp),+ color: s.color || null, service: linkOf(l)?.service || null, links: links(l),+ };+ }),+ acs: config.acs.map((a) => {+ const s = state.acs[a.id];+ return {+ id: a.id, name: a.name, room: a.room, wall: a.wall, x: a.pos[0], z: a.pos[1], min: a.min, max: a.max,+ on: s.on, target: s.target, mode: s.mode, fan: s.fan, roomTemp: round(s.roomTemp, 1),+ swing: s.swing, sleep: s.sleep, eco: s.eco, service: linkOf(a)?.service || null, links: links(a),+ };+ }),+ furniture: config.furniture.filter((f) => Array.isArray(f.pos)).map((f) => {+ const [w, d] = footprint(f);+ return { type: f.type, x: f.pos[0], z: f.pos[1], w, d, rot: f.rot || 0, color: f.color || null };+ }),+ scenes: config.scenes.map((s) => ({ id: s.id, name: s.name, icon: s.icon, lights: s.lights, acs: s.acs })),+ };+}++/** Posts the snapshot after every change (and now and then while a room's temperature drifts). */+export function publishWidgets(config, store) {+ const plan = window.__HOUSE_BOOT__?.plan || new URLSearchParams(location.search).get('plan') || 'home';+ let timer = 0;+ let lastTick = 0;+ const send = () => { timer = 0; post('widgets', { snapshot: widgetSnapshot(config, store, plan) }); };+ const soon = (delay) => { if (!timer) timer = setTimeout(send, delay); };+ store.on((change) => {+ if (change.type !== 'tick') { soon(250); return; }+ // The simulated room temperature creeps a tenth of a degree at a time: once a minute is plenty.+ if (Date.now() - lastTick > 60000) { lastTick = Date.now(); soon(250); }+ });+ send();+}++/** Runs an action a widget made (HomeAction in Swift), like a tap in the panel would. */+export function runWidgetAction(store, config, action) {+ const { kind, id } = action;+ switch (kind) {+ case 'light':+ if (store.lightCfg.has(id)) store.setLight(id, { on: action.on ?? !store.state.lights[id].on });+ break;+ case 'room': {+ const ids = config.lights.filter((l) => l.room === id).map((l) => l.id);+ const on = action.on ?? !ids.some((l) => store.state.lights[l].on);+ for (const l of ids) store.setLight(l, { on });+ break;+ }+ case 'allLights':+ store.setAllLights(action.on ?? !Object.values(store.state.lights).some((l) => l.on));+ break;+ case 'scene':+ store.applyScene(id);+ break;+ case 'acPower':+ if (store.acCfg.has(id)) store.setAC(id, { on: action.on ?? !store.state.acs[id].on });+ break;+ case 'acTarget':+ if (store.acCfg.has(id) && Number.isFinite(action.target)) store.setAC(id, { target: action.target });+ break;+ default:+ return false;+ }+ return true;+}diff --git a/widgets/Config/Mac.xcconfig b/widgets/Config/Mac.xcconfignew file mode 100644index 0000000..b458891--- /dev/null+++ b/widgets/Config/Mac.xcconfig@@ -0,0 +1,6 @@+// Versions follow the iPhone app; the signing identity and team come from scripts/build-app.sh.+#include "../../ios/Config/Base.xcconfig"+CODE_SIGN_STYLE = Manual+// The App Group the app and its widgets share. On the Mac it is prefixed with the signing+// team (no provisioning profile needed); a build signed without a team has none.+HOUSE_APP_GROUP = $(TeamIdentifierPrefix)io.github.0xprobabillity.HouseControldiff --git a/widgets/Package.swift b/widgets/Package.swiftnew file mode 100644index 0000000..d464e6c--- /dev/null+++ b/widgets/Package.swift@@ -0,0 +1,17 @@+// swift-tools-version:5.9+import PackageDescription++// Draws the widgets as still images, outside WidgetKit: `swift run render-widgets`+// (README images, the promo video). The widget extensions themselves are built by the+// iPhone app's Xcode project and by scripts/build-app.sh for the Mac.+let package = Package(+ name: "HouseWidgets",+ platforms: [.macOS(.v14)],+ dependencies: [.package(path: "../core")],+ targets: [+ .target(name: "WidgetViews", dependencies: [.product(name: "HouseCore", package: "core")],+ path: "Sources", exclude: ["HouseWidgets.swift"]),+ .executableTarget(name: "render-widgets", dependencies: ["WidgetViews", .product(name: "HouseCore", package: "core")],+ path: "Render"),+ ]+)diff --git a/widgets/Render/main.swift b/widgets/Render/main.swiftnew file mode 100644index 0000000..f884070--- /dev/null+++ b/widgets/Render/main.swift@@ -0,0 +1,110 @@+// 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]+// 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+import WidgetKit+import AppIntents+import HouseCore+@testable import WidgetViews++var 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+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")+let output = URL(fileURLWithPath: arguments.dropFirst().first ?? "widget-renders", isDirectory: true)+try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)+let home = try JSONDecoder().decode(HomeSnapshot.self, from: Data(contentsOf: input))++/// Widget sizes in points: an iPhone 17 Pro's home screen, or the Mac's desktop.+let sizes: [WidgetFamily: CGSize] = mac+ ? [.systemSmall: .init(width: 170, height: 170), .systemMedium: .init(width: 364, height: 170),+ .systemLarge: .init(width: 364, height: 376), .systemExtraLarge: .init(width: 760, height: 376)]+ : [.systemSmall: .init(width: 170, height: 170), .systemMedium: .init(width: 364, height: 170),+ .systemLarge: .init(width: 364, height: 382), .systemExtraLarge: .init(width: 752, height: 382)]++struct Still<Content: View>: View {+ let family: WidgetFamily+ @ViewBuilder var content: Content++ var body: some View {+ let size = sizes[family] ?? .init(width: 170, height: 170)+ let accessory = false // Lock Screen widgets exist on the iPhone only; the simulator shows those+ ZStack {+ if !accessory { WidgetBackdrop(warmth: tinted ? 0 : min(1, Double(home.lightsOn) / 4)) }+ if tinted && !accessory { Color.black.opacity(0.35) }+ content+ .padding(accessory ? 0 : 16)+ .environment(\.stillFamily, family)+ .environment(\.stillRenderingMode, tinted || accessory ? .accented : .fullColor)+ }+ .frame(width: size.width, height: size.height)+ .clipShape(RoundedRectangle(cornerRadius: accessory ? 12 : 23,+ style: .continuous))+ .environment(\.colorScheme, .dark)+ }+}++@MainActor+func render<V: View>(_ name: String, _ family: WidgetFamily, _ view: V) {+ let renderer = ImageRenderer(content: Still(family: family) { view })+ renderer.scale = 2+ guard let image = renderer.cgImage else { print("✗ \(name)"); return }+ let rep = NSBitmapImageRep(cgImage: image)+ let url = output.appendingPathComponent("\(name).png")+ try? rep.representation(using: .png, properties: [:])?.write(to: url)+ print("✓ \(url.path)")+}++let entry = HomeEntry(date: .now, home: home, isSample: false)+func configured<C: WidgetConfigurationIntent>(_ c: C) -> ConfiguredEntry<C> {+ ConfiguredEntry(date: .now, home: home, isSample: false, configuration: c)+}++MainActor.assumeIsolated {+ for family in HomeWidget.families {+ render("home-\(family.name)", family, HomeWidgetView(entry: entry))+ }+ for family in [WidgetFamily.systemSmall, .systemMedium] {+ render("scenes-\(family.name)", family, ScenesWidgetView(home: home))+ }+ var light = LightConfiguration()+ if let lamp = home.lights.first(where: { $0.on && $0.color != nil }) ?? home.lights.first {+ light.light = LightEntity(lamp, in: home)+ }+ render("light-small", .systemSmall, LightWidgetView(entry: configured(light)))+ var room = RoomConfiguration()+ if let first = home.roomsWithLights.first { room.room = RoomEntity(id: first.id, name: first.name) }+ render("room-medium", .systemMedium, RoomWidgetView(entry: configured(room)))+ render("room-large", .systemLarge, RoomWidgetView(entry: configured(room)))+ let climate = ClimateConfiguration()+ render("climate-small", .systemSmall, ClimateWidgetView(entry: configured(climate)))+ render("climate-medium", .systemMedium, ClimateWidgetView(entry: configured(climate)))+ #if os(iOS)+ if !mac {+ render("climate-circular", .accessoryCircular, ClimateWidgetView(entry: configured(climate)))+ render("climate-rectangular", .accessoryRectangular, ClimateWidgetView(entry: configured(climate)))+ render("light-circular", .accessoryCircular, LightWidgetView(entry: configured(light)))+ render("status-circular", .accessoryCircular, StatusWidgetView(home: home))+ render("status-rectangular", .accessoryRectangular, StatusWidgetView(home: home))+ render("status-inline", .accessoryInline, StatusWidgetView(home: home))+ }+ #endif+}++extension WidgetFamily {+ var name: String {+ switch self {+ case .systemSmall: return "small"+ case .systemMedium: return "medium"+ case .systemLarge: return "large"+ case .systemExtraLarge: return "xl"+ case .accessoryCircular: return "circular"+ case .accessoryRectangular: return "rectangular"+ case .accessoryInline: return "inline"+ default: return "other"+ }+ }+}diff --git a/widgets/Resources/sample-home.json b/widgets/Resources/sample-home.jsonnew file mode 100644index 0000000..1113684--- /dev/null+++ b/widgets/Resources/sample-home.json@@ -0,0 +1 @@+{"version":1,"name":"Home","plan":"home","outdoorTemp":29,"updated":0,"scene":"cozy","rooms":[{"id":"living","name":"Living","x":0,"z":3.6,"w":6.4,"d":4.6,"floor":"oak"},{"id":"dining","name":"Dining","x":6.4,"z":3.6,"w":4,"d":4.6,"floor":"oak"},{"id":"kitchen","name":"Kitchen","x":6.4,"z":0,"w":4,"d":3.6,"floor":"stone"},{"id":"bedroom","name":"Bedroom","x":0,"z":0,"w":4.2,"d":3.6,"floor":"walnut"},{"id":"bath","name":"Bathroom","x":4.2,"z":0,"w":2.2,"d":3.6,"floor":"tile"}],"lights":[{"id":"living.main","name":"Ceiling","room":"living","type":"ceiling","x":2.9,"z":6,"capabilities":["brightness","temp"],"on":false,"brightness":0.8,"temp":3000,"color":null,"service":null,"links":null},{"id":"living.floor","name":"Floor lamp","room":"living","type":"floor","x":0.6,"z":4.2,"capabilities":[],"on":true,"brightness":0.8,"temp":3000,"color":null,"service":null,"links":null},{"id":"living.tv","name":"TV backlight","room":"living","type":"strip","x":0.13,"z":6,"capabilities":["brightness","color"],"on":true,"brightness":0.7,"temp":3000,"color":"#ff7a3c","service":null,"links":null},{"id":"dining.pendant","name":"Pendant","room":"dining","type":"pendant","x":8.5,"z":6.4,"capabilities":["brightness","temp"],"on":true,"brightness":0.45,"temp":2400,"color":null,"service":null,"links":null},{"id":"kitchen.spots","name":"Spots","room":"kitchen","type":"spots","x":8.4,"z":2,"capabilities":["brightness"],"on":false,"brightness":0.8,"temp":3000,"color":null,"service":null,"links":null},{"id":"kitchen.strip","name":"Counter light","room":"kitchen","type":"strip","x":8.05,"z":0.42,"capabilities":["brightness","temp"],"on":true,"brightness":0.6,"temp":2700,"color":null,"service":null,"links":null},{"id":"bedroom.main","name":"Ceiling","room":"bedroom","type":"ceiling","x":2.1,"z":2.3,"capabilities":["brightness","temp"],"on":false,"brightness":0.8,"temp":3000,"color":null,"service":null,"links":null},{"id":"bedroom.left","name":"Bedside left","room":"bedroom","type":"table","x":0.85,"z":0.4,"capabilities":[],"on":true,"brightness":0.8,"temp":3000,"color":null,"service":null,"links":null},{"id":"bedroom.right","name":"Bedside right","room":"bedroom","type":"table","x":3.35,"z":0.4,"capabilities":[],"on":true,"brightness":0.8,"temp":3000,"color":null,"service":null,"links":null},{"id":"bath.main","name":"Ceiling","room":"bath","type":"ceiling","x":5.2,"z":2,"capabilities":["brightness"],"on":false,"brightness":0.8,"temp":3000,"color":null,"service":null,"links":null},{"id":"bath.mirror","name":"Mirror light","room":"bath","type":"strip","x":4.95,"z":0.14,"capabilities":["brightness","temp"],"on":false,"brightness":0.8,"temp":3000,"color":null,"service":null,"links":null}],"acs":[{"id":"living.ac","name":"Living AC","room":"living","wall":"west","x":0,"z":4.45,"min":16,"max":30,"on":true,"target":23,"mode":"cool","fan":"auto","roomTemp":25.4,"swing":"swing","sleep":false,"eco":false,"service":null,"links":null},{"id":"bedroom.ac","name":"Bedroom AC","room":"bedroom","wall":"north","x":3.3,"z":0,"min":16,"max":30,"on":false,"target":24,"mode":"cool","fan":"auto","roomTemp":25.4,"swing":"swing","sleep":false,"eco":false,"service":null,"links":null}],"furniture":[{"type":"rug","x":2.3,"z":6,"w":2.5,"d":3.1,"rot":0,"color":"#3b4a66"},{"type":"tv","x":0.32,"z":6,"w":1.7,"d":0.4,"rot":90,"color":null},{"type":"sofa","x":3.95,"z":6,"w":2.5,"d":0.95,"rot":-90,"color":"#8b93a7"},{"type":"coffeeTable","x":2.3,"z":6,"w":1.1,"d":0.58,"rot":90,"color":null},{"type":"armchair","x":1.9,"z":4.35,"w":0.92,"d":0.88,"rot":12,"color":"#c28a5a"},{"type":"plant","x":0.5,"z":7.65,"w":0.45,"d":0.45,"rot":0,"color":null},{"type":"sideboard","x":5.2,"z":7.85,"w":1.6,"d":0.42,"rot":180,"color":null},{"type":"diningSet","x":8.5,"z":6.4,"w":1.9,"d":1.9,"rot":0,"color":null},{"type":"plant","x":9.95,"z":7.75,"w":0.45,"d":0.45,"rot":0,"color":null},{"type":"island","x":8.5,"z":3.75,"w":2.2,"d":1.1,"rot":0,"color":null},{"type":"kitchen","x":8.05,"z":0.41,"w":3.1,"d":0.62,"rot":0,"color":null},{"type":"fridge","x":10.02,"z":0.45,"w":0.7,"d":0.68,"rot":0,"color":null},{"type":"rug","x":2.1,"z":2.3,"w":2.6,"d":1.6,"rot":0,"color":"#6a5a52"},{"type":"bed","x":2.1,"z":1.2,"w":1.8,"d":2.14,"rot":0,"color":"#7f8fb5"},{"type":"nightstand","x":0.85,"z":0.4,"w":0.46,"d":0.4,"rot":0,"color":null},{"type":"nightstand","x":3.35,"z":0.4,"w":0.46,"d":0.4,"rot":0,"color":null},{"type":"dresser","x":3.87,"z":2.5,"w":1.3,"d":0.45,"rot":-90,"color":null},{"type":"plant","x":0.45,"z":3.15,"w":0.45,"d":0.45,"rot":0,"color":null},{"type":"vanity","x":4.95,"z":0.38,"w":1,"d":0.5,"rot":0,"color":null},{"type":"bathtub","x":5.92,"z":1.35,"w":1.7,"d":0.78,"rot":90,"color":null},{"type":"toilet","x":4.58,"z":2.5,"w":0.4,"d":0.66,"rot":90,"color":null}],"scenes":[{"id":"bright","name":"Bright","icon":"sun","lights":{"*":{"on":true,"brightness":1,"temp":4200}},"acs":{}},{"id":"cozy","name":"Cozy","icon":"sofa","lights":{"*":{"on":false},"living.floor":{"on":true},"living.tv":{"on":true,"brightness":0.7,"color":"#ff7a3c"},"dining.pendant":{"on":true,"brightness":0.45,"temp":2400},"kitchen.strip":{"on":true,"brightness":0.6,"temp":2700},"bedroom.left":{"on":true},"bedroom.right":{"on":true}},"acs":{}},{"id":"movie","name":"Movie","icon":"film","lights":{"*":{"on":false},"living.tv":{"on":true,"brightness":0.9,"color":"#6a4cff"},"kitchen.strip":{"on":true,"brightness":0.2,"temp":2400}},"acs":{}},{"id":"night","name":"Night","icon":"moon","lights":{"*":{"on":false},"bedroom.left":{"on":true},"bath.mirror":{"on":true,"brightness":0.25,"temp":2300}},"acs":{"bedroom.ac":{"sleep":true}}},{"id":"away","name":"Away","icon":"door","lights":{"*":{"on":false}},"acs":{"*":{"on":false}}}]}diff --git a/widgets/Sources/Actions.swift b/widgets/Sources/Actions.swiftnew file mode 100644index 0000000..e21a39e--- /dev/null+++ b/widgets/Sources/Actions.swift@@ -0,0 +1,71 @@+import Foundation+import WidgetKit+import HouseCore++/// Carries out what a widget or a control asked for.+///+/// The change is applied to the shared snapshot first (so every widget can redraw with it+/// at once) and queued for the app. On the Mac the app is running in the menu bar: it takes+/// the queue straight away and sends the change through the panel, like a click there.+/// On the iPhone the app is usually not running, so the widget reaches Home Assistant, Hue+/// and Smart Life itself, with the connections the app keeps in the shared Keychain group;+/// what it cannot reach from here (Apple Home) waits for the app to open.+enum WidgetActions {+ /// Returns false when the action could not be applied (no home yet, or nothing changed).+ @discardableResult+ static func run(_ action: HomeAction) async -> Bool {+ guard let shared = SharedHome(), let done = shared.perform(action) else { return false }+ SharedHome.post(SharedHome.actionsPosted)+ #if os(iOS)+ if await deliver(done.changes, home: done.snapshot, shared: shared) {+ shared.markDelivered([done.entry.id])+ }+ #else+ // The app takes the action within a few milliseconds when it runs; its panel then+ // posts the new state. Waiting for that lets the widget redraw with the real result.+ for _ in 0..<25 where !shared.isTaken(done.entry.id) {+ try? await Task.sleep(nanoseconds: 80_000_000)+ }+ if shared.isTaken(done.entry.id) { try? await Task.sleep(nanoseconds: 450_000_000) }+ #endif+ reloadEverything()+ return true+ }++ static func reloadEverything() {+ WidgetCenter.shared.reloadAllTimelines()+ if #available(iOS 18.0, macOS 26.0, *) { ControlCenter.shared.reloadAllControls() }+ }++ #if os(iOS)+ /// The platforms a widget can reach without the app.+ private static let reachable: Set<String> = ["smartlife", "homeassistant", "hue"]++ /// True when every change reached its device (simulated devices always do).+ @MainActor+ private static func deliver(_ changes: [DeviceChange], home: HomeSnapshot, shared: SharedHome) async -> Bool {+ let services = Dictionary(uniqueKeysWithValues: home.lights.map { ($0.id, $0.service) } + home.acs.map { ($0.id, $0.service) })+ let real = changes.filter { services[$0.id] ?? nil != nil }+ guard !real.isEmpty else { return true }+ if real.contains(where: { !reachable.contains((services[$0.id] ?? nil) ?? "") }) { return false }+ let app = appBundleIdentifier+ let hub = DeviceHub(directory: shared.directory.appendingPathComponent("Hub", isDirectory: true),+ secret: { KeychainSecretStore(service: app, account: $0) })+ hub.setLinks(from: home.linksPlan)+ var ok = true+ for change in real {+ let reply: [String: Any] = await withCheckedContinuation { done in+ hub.command(change.message) { done.resume(returning: $0) }+ }+ if reply["error"] != nil { ok = false }+ }+ return ok+ }++ /// The app's bundle id ("….HouseControl"): its Keychain items are filed under it.+ private static var appBundleIdentifier: String {+ let own = Bundle.main.bundleIdentifier ?? ""+ return own.components(separatedBy: ".").dropLast().joined(separator: ".")+ }+ #endif+}diff --git a/widgets/Sources/Components.swift b/widgets/Sources/Components.swiftnew file mode 100644index 0000000..066b97a--- /dev/null+++ b/widgets/Sources/Components.swift@@ -0,0 +1,243 @@+import SwiftUI+import WidgetKit+import AppIntents+import HouseCore++/// A scene as a rounded tile: icon over name, lit when it is the home's scene.+struct SceneTile: View {+ let scene: HomeSnapshot.Scene+ let active: Bool+ var compact = false+ private let look = WidgetLook()++ var body: some View {+ Button(intent: ApplySceneIntent(sceneID: scene.id)) {+ VStack(spacing: compact ? 3 : 5) {+ Image(systemName: scene.symbol)+ .font(.system(size: compact ? 15 : 17, weight: .semibold))+ .foregroundStyle(active ? Color.white : scene.tint)+ .widgetAccentable()+ Text(scene.name)+ .font(.system(size: compact ? 10.5 : 11.5, weight: .semibold))+ .foregroundStyle(active ? Color.white : Palette.muted)+ .lineLimit(1)+ .minimumScaleFactor(0.8)+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ .background(background, in: RoundedRectangle(cornerRadius: compact ? 12 : 14, style: .continuous))+ .overlay(RoundedRectangle(cornerRadius: compact ? 12 : 14, style: .continuous)+ .strokeBorder(active ? Color.white.opacity(0.28) : Palette.line))+ }+ .buttonStyle(.plain)+ .accessibilityLabel("\(scene.name) scene\(active ? ", active" : "")")+ }++ private var background: AnyShapeStyle {+ guard look.fullColor else { return AnyShapeStyle(Color.white.opacity(active ? 0.28 : 0.1)) }+ if active {+ return AnyShapeStyle(LinearGradient(colors: [Palette.accent, Color(hex: "#2a63d6")], startPoint: .top, endPoint: .bottom))+ }+ return AnyShapeStyle(Palette.glass)+ }+}++/// A round button: every lamp off (or on, when they all are off).+struct AllLightsButton: View {+ let home: HomeSnapshot+ var size: CGFloat = 34++ var body: some View {+ let anyOn = home.lightsOn > 0+ Button(intent: AllLightsIntent(on: !anyOn)) {+ Image(systemName: "power")+ .font(.system(size: size * 0.42, weight: .bold))+ .foregroundStyle(.white)+ .frame(width: size, height: size)+ .background(Circle().fill(anyOn ? AnyShapeStyle(LinearGradient(colors: [Color(hex: "#5aa2ff"), Palette.accent],+ startPoint: .top, endPoint: .bottom))+ : AnyShapeStyle(Palette.glassHigh)))+ .shadow(color: anyOn ? Palette.accent.opacity(0.55) : .clear, radius: 8, y: 2)+ .widgetAccentable(anyOn)+ }+ .buttonStyle(.plain)+ .accessibilityLabel(anyOn ? "Turn every light off" : "Turn every light on")+ }+}++/// A lamp as the panel draws it: icon in a rounded square, name, state; tap to switch.+struct LightTile: View {+ let light: HomeSnapshot.Light+ var room: String?+ private let look = WidgetLook()++ var body: some View {+ Button(intent: ToggleLightIntent(lightID: light.id)) {+ HStack(spacing: 9) {+ Image(systemName: light.symbol)+ .font(.system(size: 14, weight: .semibold))+ .foregroundStyle(light.on ? Color(hex: "#3a2208") : Palette.muted)+ .frame(width: 30, height: 30)+ .background(RoundedRectangle(cornerRadius: 9, style: .continuous)+ .fill(light.on ? AnyShapeStyle(light.glow.gradient) : AnyShapeStyle(Palette.glassHigh)))+ .widgetAccentable(light.on)+ VStack(alignment: .leading, spacing: 1) {+ Text(light.name)+ .font(.system(size: 12.5, weight: .semibold))+ .foregroundStyle(Palette.text)+ .lineLimit(1)+ Text(room.map { "\($0) · \(light.stateText)" } ?? light.stateText)+ .font(.system(size: 11, weight: .medium))+ .foregroundStyle(light.on ? light.glow.opacity(0.95) : Palette.faint)+ .lineLimit(1)+ }+ Spacer(minLength: 0)+ }+ .padding(.horizontal, 8)+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)+ .background(tileBackground, in: RoundedRectangle(cornerRadius: 13, style: .continuous))+ .overlay(RoundedRectangle(cornerRadius: 13, style: .continuous)+ .strokeBorder(light.on ? light.glow.opacity(0.35) : Palette.line))+ }+ .buttonStyle(.plain)+ .accessibilityLabel("\(light.name), \(light.on ? "on" : "off")")+ }++ private var tileBackground: AnyShapeStyle {+ guard look.fullColor else { return AnyShapeStyle(Color.white.opacity(light.on ? 0.22 : 0.08)) }+ return light.on ? AnyShapeStyle(LinearGradient(colors: [light.glow.opacity(0.26), light.glow.opacity(0.1)],+ startPoint: .topLeading, endPoint: .bottomTrailing))+ : AnyShapeStyle(Palette.glass)+ }+}++/// An AC's set-point on an arc from its minimum to its maximum, with the room's reading.+struct ClimateDial: View {+ let ac: HomeSnapshot.AC+ var lineWidth: CGFloat = 7++ var body: some View {+ let span = max(1, ac.max - ac.min)+ let fraction = (ac.target - ac.min) / span+ let roomFraction = ac.roomTemp.map { min(1, max(0, ($0 - ac.min) / span)) }+ ZStack {+ Circle().trim(from: 0, to: 0.75)+ .stroke(Color.white.opacity(0.1), style: StrokeStyle(lineWidth: lineWidth, lineCap: .round))+ .rotationEffect(.degrees(135))+ Circle().trim(from: 0, to: 0.75 * fraction)+ .stroke(ac.on ? AnyShapeStyle(AngularGradient(colors: [ac.tint.opacity(0.55), ac.tint],+ center: .center, startAngle: .degrees(0), endAngle: .degrees(270 * fraction)))+ : AnyShapeStyle(Color.white.opacity(0.28)),+ style: StrokeStyle(lineWidth: lineWidth, lineCap: .round))+ .rotationEffect(.degrees(135))+ .widgetAccentable()+ if let roomFraction {+ // The room's own temperature, as a small notch on the arc.+ Circle().fill(Color.white).frame(width: lineWidth * 0.62, height: lineWidth * 0.62)+ .offset(y: -1)+ .frame(maxHeight: .infinity, alignment: .top)+ .rotationEffect(.degrees(-135 + 270 * roomFraction))+ }+ }+ .padding(lineWidth / 2)+ }+}++/// − ⏻ + for an AC.+struct ClimateButtons: View {+ let ac: HomeSnapshot.AC+ var size: CGFloat = 30++ var body: some View {+ HStack(spacing: 8) {+ step(-1, "minus")+ Button(intent: ACPowerIntent(acID: ac.id)) {+ Image(systemName: "power")+ .font(.system(size: size * 0.42, weight: .bold))+ .foregroundStyle(.white)+ .frame(width: size, height: size)+ .background(Circle().fill(ac.on ? AnyShapeStyle(ac.tint.gradient) : AnyShapeStyle(Palette.glassHigh)))+ .widgetAccentable(ac.on)+ }+ .buttonStyle(.plain)+ .accessibilityLabel(ac.on ? "Turn \(ac.name) off" : "Turn \(ac.name) on")+ step(1, "plus")+ }+ }++ private func step(_ delta: Int, _ symbol: String) -> some View {+ Button(intent: ACStepIntent(acID: ac.id, step: delta)) {+ Image(systemName: symbol)+ .font(.system(size: size * 0.38, weight: .bold))+ .foregroundStyle(Palette.text)+ .frame(width: size, height: size)+ .background(Circle().fill(Palette.glass))+ .overlay(Circle().strokeBorder(Palette.line))+ }+ .buttonStyle(.plain)+ .disabled(delta < 0 ? ac.target <= ac.min : ac.target >= ac.max)+ .accessibilityLabel(delta < 0 ? "Cooler" : "Warmer")+ }+}++/// "House Control" with the app's mark, for headers.+struct HomeTitle: View {+ let home: HomeSnapshot+ var size: CGFloat = 14++ var body: some View {+ HStack(spacing: 6) {+ Image(systemName: home.lightsOn > 0 || !home.acsOn.isEmpty ? "house.fill" : "house")+ .font(.system(size: size * 0.86, weight: .semibold))+ .foregroundStyle(Palette.warm)+ .widgetAccentable()+ Text(home.name)+ .font(.system(size: size, weight: .semibold))+ .foregroundStyle(Palette.text)+ .lineLimit(1)+ }+ }+}++/// "● 6 of 11 lights on".+struct LightsLine: View {+ let home: HomeSnapshot+ var size: CGFloat = 11.5++ var body: some View {+ HStack(spacing: 5) {+ Circle().fill(home.lightsOn > 0 ? Palette.green : Palette.faint).frame(width: 6, height: 6)+ Text(home.lightsLine)+ .font(.system(size: size, weight: .medium))+ .foregroundStyle(Palette.muted)+ .lineLimit(1)+ .minimumScaleFactor(0.85)+ }+ }+}++/// "❄︎ Cool 23° · 26.6° room" for the first AC that runs (or the first one).+struct ClimateLine: View {+ let home: HomeSnapshot+ var size: CGFloat = 11.5++ var body: some View {+ if let ac = home.acsOn.first ?? home.acs.first {+ HStack(spacing: 5) {+ Image(systemName: ac.on ? ac.modeSymbol : "air.conditioner.horizontal")+ .font(.system(size: size * 0.9, weight: .bold))+ .foregroundStyle(ac.tint)+ .widgetAccentable()+ Text(ac.on ? "\(ac.modeName) \(ac.targetText)" : "AC off")+ .font(.system(size: size, weight: .semibold))+ .foregroundStyle(Palette.text)+ if let room = ac.roomText {+ Text("· \(room) inside")+ .font(.system(size: size, weight: .medium))+ .foregroundStyle(Palette.faint)+ }+ }+ .lineLimit(1)+ .minimumScaleFactor(0.8)+ }+ }+}diff --git a/widgets/Sources/Controls.swift b/widgets/Sources/Controls.swiftnew file mode 100644index 0000000..5961b90--- /dev/null+++ b/widgets/Sources/Controls.swift@@ -0,0 +1,198 @@+import SwiftUI+import WidgetKit+import AppIntents+import HouseCore++// Controls: Control Center, the Lock Screen and the Action button on the iPhone (iOS 18),+// Control Center and the menu bar on the Mac (macOS 26).++// MARK: - Intents the controls run (also offered to Shortcuts)++struct SetLightIntent: SetValueIntent {+ static let title: LocalizedStringResource = "Switch a Light"+ static let description = IntentDescription("Turns a House Control lamp on or off.")+ @Parameter(title: "Light") var light: LightEntity+ @Parameter(title: "On") var value: Bool++ init() {}+ init(light: LightEntity) { self.light = light }++ func perform() async throws -> some IntentResult {+ await WidgetActions.run(.light(light.id, on: value))+ return .result()+ }+}++struct SetAllLightsIntent: SetValueIntent {+ static let title: LocalizedStringResource = "Switch Every Light"+ static let description = IntentDescription("Turns every lamp of the home on or off.")+ @Parameter(title: "On") var value: Bool++ init() {}++ func perform() async throws -> some IntentResult {+ await WidgetActions.run(.allLights(on: value))+ return .result()+ }+}++struct SetClimateIntent: SetValueIntent {+ static let title: LocalizedStringResource = "Switch an Air Conditioner"+ static let description = IntentDescription("Turns a House Control air conditioner on or off.")+ @Parameter(title: "Air Conditioner") var ac: ACEntity+ @Parameter(title: "On") var value: Bool++ init() {}+ init(ac: ACEntity) { self.ac = ac }++ func perform() async throws -> some IntentResult {+ await WidgetActions.run(.acPower(ac.id, on: value))+ return .result()+ }+}++struct RunSceneIntent: AppIntent {+ static let title: LocalizedStringResource = "Apply a Scene"+ static let description = IntentDescription("Sets every lamp and air conditioner the way a House Control scene says.")+ @Parameter(title: "Scene") var scene: SceneEntity++ init() {}+ init(scene: SceneEntity) { self.scene = scene }++ func perform() async throws -> some IntentResult {+ await WidgetActions.run(.scene(scene.id))+ return .result()+ }+}++// MARK: - Control configuration++@available(iOS 18.0, macOS 26.0, *)+struct LightControlConfiguration: ControlConfigurationIntent {+ static let title: LocalizedStringResource = "Light"+ @Parameter(title: "Light") var light: LightEntity?+}++@available(iOS 18.0, macOS 26.0, *)+struct ClimateControlConfiguration: ControlConfigurationIntent {+ static let title: LocalizedStringResource = "Air Conditioner"+ @Parameter(title: "Air Conditioner") var ac: ACEntity?+}++@available(iOS 18.0, macOS 26.0, *)+struct SceneControlConfiguration: ControlConfigurationIntent {+ static let title: LocalizedStringResource = "Scene"+ @Parameter(title: "Scene") var scene: SceneEntity?+}++// MARK: - Controls++@available(iOS 18.0, macOS 26.0, *)+struct LightControl: ControlWidget {+ static let kind = "io.github.0xprobabillity.HouseControl.light-control"++ struct Value {+ var light: LightEntity?+ var isOn: Bool+ }++ struct Provider: AppIntentControlValueProvider {+ func previewValue(configuration: LightControlConfiguration) -> Value {+ Value(light: configuration.light, isOn: true)+ }++ func currentValue(configuration: LightControlConfiguration) async throws -> Value {+ let home = HomeData.orSample+ let id = configuration.light?.id ?? home.lights.first?.id+ let light = id.flatMap(home.light)+ return Value(light: configuration.light ?? light.map { LightEntity($0, in: home) }, isOn: light?.on ?? false)+ }+ }++ var body: some ControlWidgetConfiguration {+ AppIntentControlConfiguration(kind: Self.kind, provider: Provider()) { value in+ ControlWidgetToggle(value.light?.name ?? "Light", isOn: value.isOn,+ action: value.light.map(SetLightIntent.init(light:)) ?? SetLightIntent()) { on in+ Label(on ? "On" : "Off", systemImage: on ? "lightbulb.fill" : "lightbulb")+ }+ .tint(.orange)+ }+ .displayName("Light")+ .description("Switch one lamp.")+ .promptsForUserConfiguration()+ }+}++@available(iOS 18.0, macOS 26.0, *)+struct AllLightsControl: ControlWidget {+ static let kind = "io.github.0xprobabillity.HouseControl.all-lights-control"++ struct Provider: ControlValueProvider {+ var previewValue: Bool { true }+ func currentValue() async throws -> Bool { (HomeData.current?.lightsOn ?? 0) > 0 }+ }++ var body: some ControlWidgetConfiguration {+ StaticControlConfiguration(kind: Self.kind, provider: Provider()) { isOn in+ ControlWidgetToggle("All Lights", isOn: isOn, action: SetAllLightsIntent()) { on in+ Label(on ? "On" : "Off", systemImage: on ? "lightbulb.2.fill" : "lightbulb.2")+ }+ .tint(.orange)+ }+ .displayName("All Lights")+ .description("Every lamp of the home at once.")+ }+}++@available(iOS 18.0, macOS 26.0, *)+struct ClimateControl: ControlWidget {+ static let kind = "io.github.0xprobabillity.HouseControl.climate-control"++ struct Value {+ var ac: ACEntity?+ var isOn: Bool+ var label: String+ }++ struct Provider: AppIntentControlValueProvider {+ func previewValue(configuration: ClimateControlConfiguration) -> Value {+ Value(ac: configuration.ac, isOn: true, label: "Cool 23°")+ }++ func currentValue(configuration: ClimateControlConfiguration) async throws -> Value {+ let home = HomeData.orSample+ let ac = (configuration.ac?.id ?? home.acs.first?.id).flatMap(home.ac)+ return Value(ac: configuration.ac ?? ac.map { ACEntity($0, in: home) }, isOn: ac?.on ?? false,+ label: ac.map { $0.on ? "\($0.modeName) \($0.targetText)" : "Off" } ?? "Off")+ }+ }++ var body: some ControlWidgetConfiguration {+ AppIntentControlConfiguration(kind: Self.kind, provider: Provider()) { value in+ ControlWidgetToggle(value.ac?.name ?? "Air Conditioner", isOn: value.isOn,+ action: value.ac.map(SetClimateIntent.init(ac:)) ?? SetClimateIntent()) { on in+ Label(on ? value.label : "Off", systemImage: on ? "snowflake" : "air.conditioner.horizontal")+ }+ .tint(.cyan)+ }+ .displayName("Air Conditioner")+ .description("Switch an air conditioner on or off.")+ .promptsForUserConfiguration()+ }+}++@available(iOS 18.0, macOS 26.0, *)+struct SceneControl: ControlWidget {+ static let kind = "io.github.0xprobabillity.HouseControl.scene-control"++ var body: some ControlWidgetConfiguration {+ AppIntentControlConfiguration(kind: Self.kind, intent: SceneControlConfiguration.self) { configuration in+ ControlWidgetButton(action: configuration.scene.map(RunSceneIntent.init(scene:)) ?? RunSceneIntent()) {+ Label(configuration.scene?.name ?? "Scene", systemImage: configuration.scene?.symbol ?? "sparkles")+ }+ }+ .displayName("Scene")+ .description("Apply a scene with one tap.")+ .promptsForUserConfiguration()+ }+}diff --git a/widgets/Sources/DeviceWidgets.swift b/widgets/Sources/DeviceWidgets.swiftnew file mode 100644index 0000000..d408cf5--- /dev/null+++ b/widgets/Sources/DeviceWidgets.swift@@ -0,0 +1,466 @@+import SwiftUI+import WidgetKit+import AppIntents+import HouseCore++// MARK: - Scenes++/// One tap sets every lamp and AC: the home's scenes as big buttons.+struct ScenesWidget: Widget {+ static let kind = "scenes"++ var body: some WidgetConfiguration {+ StaticConfiguration(kind: Self.kind, provider: HomeProvider()) { entry in+ ScenesWidgetView(home: entry.home)+ }+ .configurationDisplayName("Scenes")+ .description("Cozy, Movie, Night… one tap sets every light and air conditioner.")+ .supportedFamilies([.systemSmall, .systemMedium])+ }+}++struct ScenesWidgetView: View {+ let home: HomeSnapshot+ private let look = WidgetLook()+ private var family: WidgetFamily { look.family }++ var body: some View {+ let scenes = Array(home.scenes.prefix(4))+ VStack(alignment: .leading, spacing: 8) {+ if family == .systemMedium {+ HStack {+ Caption("Scenes")+ Spacer()+ Text(home.activeScene?.name ?? home.lightsLine)+ .font(.system(size: 11.5, weight: .semibold))+ .foregroundStyle(home.activeScene == nil ? Palette.faint : Palette.text)+ }+ HStack(spacing: 8) {+ ForEach(scenes) { SceneTile(scene: $0, active: $0.id == home.scene) }+ }+ } else {+ Grid(horizontalSpacing: 7, verticalSpacing: 7) {+ GridRow {+ ForEach(scenes.prefix(2)) { SceneTile(scene: $0, active: $0.id == home.scene, compact: true) }+ }+ GridRow {+ ForEach(scenes.dropFirst(2).prefix(2)) { SceneTile(scene: $0, active: $0.id == home.scene, compact: true) }+ }+ }+ }+ }+ .homeBackground()+ .widgetURL(DeepLink.home())+ }+}++// MARK: - One lamp++struct LightWidget: Widget {+ static let kind = "light"++ var body: some WidgetConfiguration {+ AppIntentConfiguration(kind: Self.kind, intent: LightConfiguration.self, provider: ConfiguredProvider<LightConfiguration>()) { entry in+ LightWidgetView(entry: entry)+ }+ .configurationDisplayName("Light")+ .description("One lamp, glowing in its colour. Tap to switch it.")+ .supportedFamilies(Self.families)+ }++ static var families: [WidgetFamily] {+ #if os(iOS)+ [.systemSmall, .accessoryCircular]+ #else+ [.systemSmall]+ #endif+ }+}++struct LightWidgetView: View {+ let entry: ConfiguredEntry<LightConfiguration>+ private let look = WidgetLook()+ private var family: WidgetFamily { look.family }++ var body: some View {+ let home = entry.home+ if let light = entry.configuration.light.flatMap({ home.light($0.id) }) ?? home.lights.first {+ if look.accessory == .circular {+ Button(intent: ToggleLightIntent(lightID: light.id)) {+ ZStack {+ AccessoryWidgetBackground()+ Image(systemName: light.on ? "lightbulb.fill" : "lightbulb")+ .font(.system(size: 22, weight: .semibold))+ .widgetAccentable(light.on)+ }+ }+ .buttonStyle(.plain)+ .containerBackground(for: .widget) { Color.clear }+ .accessibilityLabel("\(light.name), \(light.on ? "on" : "off")")+ } else {+ card(light, home)+ }+ } else {+ EmptyHome(text: "No lamps in this home yet")+ }+ }++ private func card(_ light: HomeSnapshot.Light, _ home: HomeSnapshot) -> some View {+ Button(intent: ToggleLightIntent(lightID: light.id)) {+ VStack(alignment: .leading, spacing: 0) {+ HStack(alignment: .top) {+ ZStack {+ if light.on && look.fullColor {+ Circle().fill(RadialGradient(colors: [light.glow.opacity(0.85), light.glow.opacity(0)],+ center: .center, startRadius: 4, endRadius: 44))+ .frame(width: 88, height: 88)+ }+ Image(systemName: light.symbol)+ .font(.system(size: 24, weight: .semibold))+ .foregroundStyle(light.on ? Color(hex: "#3a2208") : Palette.muted)+ .frame(width: 50, height: 50)+ .background(Circle().fill(light.on ? AnyShapeStyle(light.glow.gradient) : AnyShapeStyle(Palette.glassHigh)))+ .widgetAccentable(light.on)+ }+ .frame(width: 50, height: 50)+ Spacer()+ Image(systemName: "power")+ .font(.system(size: 12, weight: .bold))+ .foregroundStyle(light.on ? Palette.text : Palette.faint)+ .frame(width: 26, height: 26)+ .background(Circle().fill(Palette.glass))+ }+ Spacer(minLength: 4)+ Text(light.name)+ .font(.system(size: 15, weight: .semibold))+ .foregroundStyle(Palette.text)+ .lineLimit(1)+ Text(home.room(light.room)?.name ?? "")+ .font(.system(size: 11.5, weight: .medium))+ .foregroundStyle(Palette.faint)+ .lineLimit(1)+ Text(light.stateText)+ .font(.system(size: 26, weight: .light))+ .foregroundStyle(light.on ? light.glow : Palette.muted)+ .contentTransition(.numericText())+ .widgetAccentable(light.on)+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)+ }+ .buttonStyle(.plain)+ .accessibilityLabel("\(light.name), \(light.on ? "on" : "off")")+ .containerBackground(for: .widget) {+ ZStack {+ WidgetBackdrop()+ if light.on {+ RadialGradient(colors: [light.glow.opacity(0.32), .clear], center: .topLeading, startRadius: 0, endRadius: 190)+ }+ }+ }+ .widgetURL(DeepLink.device(light.id))+ }+}++// MARK: - A room's lamps++struct RoomWidget: Widget {+ static let kind = "room"++ var body: some WidgetConfiguration {+ AppIntentConfiguration(kind: Self.kind, intent: RoomConfiguration.self, provider: ConfiguredProvider<RoomConfiguration>()) { entry in+ RoomWidgetView(entry: entry)+ }+ .configurationDisplayName("Room")+ .description("Every lamp of one room, each a tap away.")+ .supportedFamilies([.systemMedium, .systemLarge])+ }+}++struct RoomWidgetView: View {+ let entry: ConfiguredEntry<RoomConfiguration>+ private let look = WidgetLook()+ private var family: WidgetFamily { look.family }++ var body: some View {+ let home = entry.home+ if let room = entry.configuration.room.flatMap({ home.room($0.id) }) ?? home.roomsWithLights.first {+ let lights = home.lights(in: room.id)+ let on = lights.filter(\.on).count+ let capacity = family == .systemLarge ? 4 : 4+ VStack(alignment: .leading, spacing: 8) {+ HStack {+ VStack(alignment: .leading, spacing: 2) {+ Text(room.name).font(.system(size: 16, weight: .semibold)).foregroundStyle(Palette.text)+ Text(on == 0 ? "All off" : "\(on) of \(lights.count) on")+ .font(.system(size: 11.5, weight: .medium)).foregroundStyle(on == 0 ? Palette.faint : Palette.warm)+ }+ Spacer()+ Button(intent: ToggleRoomIntent(roomID: room.id, on: on == 0)) {+ Text(on == 0 ? "All on" : "All off")+ .font(.system(size: 12, weight: .semibold))+ .foregroundStyle(Palette.text)+ .padding(.horizontal, 12)+ .frame(height: 28)+ .background(Capsule().fill(Palette.glassHigh))+ }+ .buttonStyle(.plain)+ }+ if family == .systemLarge {+ // The room on its own, in 3D: its lamps glow in it and are buttons.+ HouseModel(home: home.only(room.id), padding: 4, interactive: true, boost: 1.2)+ .frame(maxHeight: .infinity)+ if let ac = home.acs.first(where: { $0.room == room.id }) { RoomClimate(ac: ac) }+ }+ LazyVGrid(columns: [GridItem(.flexible(), spacing: 7), GridItem(.flexible(), spacing: 7)], spacing: 7) {+ ForEach(lights.prefix(capacity)) { LightTile(light: $0).frame(height: 44) }+ }+ if family != .systemLarge { Spacer(minLength: 0) }+ }+ .homeBackground(warmth: min(1, Double(on) / 3))+ .widgetURL(DeepLink.device(room.id))+ } else {+ EmptyHome(text: "No room with lamps yet")+ }+ }+}++private struct RoomClimate: View {+ let ac: HomeSnapshot.AC++ var body: some View {+ HStack(spacing: 10) {+ ClimateDial(ac: ac, lineWidth: 5).frame(width: 40, height: 40)+ VStack(alignment: .leading, spacing: 1) {+ Text(ac.name).font(.system(size: 12.5, weight: .semibold)).foregroundStyle(Palette.text)+ Text(ac.on ? "\(ac.modeName) to \(ac.targetText)" : "Off")+ .font(.system(size: 11, weight: .medium)).foregroundStyle(ac.on ? ac.tint : Palette.faint)+ }+ Spacer()+ ClimateButtons(ac: ac, size: 28)+ }+ .padding(8)+ .background(Palette.glass, in: RoundedRectangle(cornerRadius: 14, style: .continuous))+ }+}++// MARK: - Climate++struct ClimateWidget: Widget {+ static let kind = "climate"++ var body: some WidgetConfiguration {+ AppIntentConfiguration(kind: Self.kind, intent: ClimateConfiguration.self, provider: ConfiguredProvider<ClimateConfiguration>()) { entry in+ ClimateWidgetView(entry: entry)+ }+ .configurationDisplayName("Climate")+ .description("An air conditioner's set-point and the room's temperature, with power and − / +.")+ .supportedFamilies(Self.families)+ }++ static var families: [WidgetFamily] {+ #if os(iOS)+ [.systemSmall, .systemMedium, .accessoryCircular, .accessoryRectangular]+ #else+ [.systemSmall, .systemMedium]+ #endif+ }+}++struct ClimateWidgetView: View {+ let entry: ConfiguredEntry<ClimateConfiguration>+ private let look = WidgetLook()+ private var family: WidgetFamily { look.family }++ var body: some View {+ let home = entry.home+ if let ac = entry.configuration.ac.flatMap({ home.ac($0.id) }) ?? home.acs.first {+ #if os(iOS)+ if look.accessory == .circular { circular(ac) } else if look.accessory == .rectangular { rectangular(ac, home) }+ else if family == .systemMedium { medium(ac, home) } else { small(ac) }+ #else+ if family == .systemMedium { medium(ac, home) } else { small(ac) }+ #endif+ } else {+ EmptyHome(text: "No air conditioner in this home")+ }+ }++ private func small(_ ac: HomeSnapshot.AC) -> some View {+ VStack(spacing: 6) {+ ZStack {+ ClimateDial(ac: ac, lineWidth: 8)+ VStack(spacing: -2) {+ Image(systemName: ac.on ? ac.modeSymbol : "power")+ .font(.system(size: 11, weight: .bold))+ .foregroundStyle(ac.tint)+ .widgetAccentable()+ Text(ac.targetText)+ .font(.system(size: 30, weight: .light))+ .foregroundStyle(ac.on ? Palette.text : Palette.muted)+ .contentTransition(.numericText(value: ac.target))+ if let room = ac.roomText {+ Text(room).font(.system(size: 10.5, weight: .semibold)).foregroundStyle(Palette.faint)+ }+ }+ }+ .frame(maxHeight: .infinity)+ ClimateButtons(ac: ac, size: 30)+ }+ .homeBackground()+ .widgetURL(DeepLink.device(ac.id))+ }++ private func medium(_ ac: HomeSnapshot.AC, _ home: HomeSnapshot) -> some View {+ HStack(spacing: 14) {+ ZStack {+ ClimateDial(ac: ac, lineWidth: 9)+ VStack(spacing: -3) {+ Text(ac.targetText)+ .font(.system(size: 34, weight: .light))+ .foregroundStyle(ac.on ? Palette.text : Palette.muted)+ .contentTransition(.numericText(value: ac.target))+ Text("target").font(.system(size: 10.5, weight: .semibold)).foregroundStyle(Palette.faint)+ }+ }+ .frame(width: 118)+ VStack(alignment: .leading, spacing: 4) {+ Text(ac.name).font(.system(size: 15, weight: .semibold)).foregroundStyle(Palette.text).lineLimit(1)+ Text(home.room(ac.room)?.name ?? "").font(.system(size: 11.5, weight: .medium)).foregroundStyle(Palette.faint)+ HStack(spacing: 6) {+ chip(ac.on ? ac.modeName : "Off", ac.on ? ac.modeSymbol : "power", ac.tint)+ if ac.on { chip("Fan \(ac.fan)", "fan", Palette.muted) }+ }+ .padding(.top, 2)+ if let room = ac.roomText {+ HStack(spacing: 4) {+ Image(systemName: "thermometer.medium").font(.system(size: 11, weight: .semibold))+ Text("Room \(room)").font(.system(size: 12, weight: .semibold))+ }+ .foregroundStyle(Palette.muted)+ }+ Spacer(minLength: 2)+ ClimateButtons(ac: ac, size: 32)+ }+ }+ .homeBackground()+ .widgetURL(DeepLink.device(ac.id))+ }++ private func chip(_ text: String, _ symbol: String, _ tint: Color) -> some View {+ Label(text, systemImage: symbol)+ .font(.system(size: 11, weight: .semibold))+ .foregroundStyle(tint)+ .padding(.horizontal, 8)+ .frame(height: 22)+ .background(Capsule().fill(Palette.glass))+ .widgetAccentable()+ }++ #if os(iOS)+ private func circular(_ ac: HomeSnapshot.AC) -> some View {+ Gauge(value: ac.roomTemp ?? ac.target, in: ac.min...ac.max) {+ Image(systemName: ac.on ? ac.modeSymbol : "air.conditioner.horizontal")+ } currentValueLabel: {+ Text(ac.roomTemp.map { "\(Int($0.rounded()))°" } ?? ac.targetText)+ }+ .gaugeStyle(.accessoryCircular)+ .containerBackground(for: .widget) { AccessoryWidgetBackground() }+ .widgetURL(DeepLink.device(ac.id))+ }++ private func rectangular(_ ac: HomeSnapshot.AC, _ home: HomeSnapshot) -> some View {+ VStack(alignment: .leading, spacing: 1) {+ Label(ac.name, systemImage: ac.on ? ac.modeSymbol : "air.conditioner.horizontal")+ .font(.system(size: 13, weight: .semibold))+ .widgetAccentable()+ Text(ac.on ? "\(ac.modeName) to \(ac.targetText)" : "Off")+ .font(.system(size: 13, weight: .medium))+ if let room = ac.roomText { Text("Room \(room)").font(.system(size: 12)).foregroundStyle(.secondary) }+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ .containerBackground(for: .widget) { Color.clear }+ .widgetURL(DeepLink.device(ac.id))+ }+ #endif+}++// MARK: - Lock Screen status++#if os(iOS)+/// The home at a glance on the Lock Screen: how many lamps are on, what the AC does.+struct StatusWidget: Widget {+ static let kind = "status"++ var body: some WidgetConfiguration {+ StaticConfiguration(kind: Self.kind, provider: HomeProvider()) { entry in+ StatusWidgetView(home: entry.home)+ }+ .configurationDisplayName("Home Status")+ .description("Lamps on and the air conditioner, at a glance.")+ .supportedFamilies([.accessoryCircular, .accessoryRectangular, .accessoryInline])+ }+}++struct StatusWidgetView: View {+ let home: HomeSnapshot+ private let look = WidgetLook()+ private var family: WidgetFamily { look.family }++ var body: some View {+ Group {+ switch family {+ case .accessoryCircular:+ Gauge(value: Double(home.lightsOn), in: 0...Double(max(1, home.lights.count))) {+ Image(systemName: "lightbulb.fill")+ } currentValueLabel: {+ Text("\(home.lightsOn)")+ }+ .gaugeStyle(.accessoryCircularCapacity)+ .containerBackground(for: .widget) { AccessoryWidgetBackground() }+ case .accessoryInline:+ ViewThatFits {+ Text(inline(long: true))+ Text(inline(long: false))+ }+ .containerBackground(for: .widget) { Color.clear }+ default:+ VStack(alignment: .leading, spacing: 1) {+ Label(home.name, systemImage: "house.fill")+ .font(.system(size: 13, weight: .semibold))+ .widgetAccentable()+ Text(home.lightsLine).font(.system(size: 13, weight: .medium))+ if let ac = home.acsOn.first {+ Text("\(ac.modeName) \(ac.targetText)\(ac.roomText.map { " · room \($0)" } ?? "")")+ .font(.system(size: 12)).foregroundStyle(.secondary)+ } else if let scene = home.activeScene {+ Text("Scene: \(scene.name)").font(.system(size: 12)).foregroundStyle(.secondary)+ }+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ .containerBackground(for: .widget) { Color.clear }+ }+ }+ .widgetURL(DeepLink.home())+ }++ private func inline(long: Bool) -> String {+ var parts = [home.lightsOn == 0 ? "Lights off" : "\(home.lightsOn) \(long ? "lights " : "")on"]+ if let ac = home.acsOn.first { parts.append("\(ac.modeName) \(ac.targetText)") }+ return "⌂ " + parts.joined(separator: " · ")+ }+}+#endif++/// Shown when the home has nothing of the kind the widget is for.+struct EmptyHome: View {+ let text: String++ var body: some View {+ VStack(spacing: 6) {+ Image(systemName: "house").font(.system(size: 22, weight: .semibold)).foregroundStyle(Palette.warm)+ Text(text).font(.system(size: 12, weight: .medium)).foregroundStyle(Palette.muted).multilineTextAlignment(.center)+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ .homeBackground()+ }+}diff --git a/widgets/Sources/HomeWidget.swift b/widgets/Sources/HomeWidget.swiftnew file mode 100644index 0000000..7ea6ef7--- /dev/null+++ b/widgets/Sources/HomeWidget.swift@@ -0,0 +1,201 @@+import SwiftUI+import WidgetKit+import AppIntents+import HouseCore++/// The home as a live little model: every lamp glows on the floor of its room in its own+/// colour. Medium and larger add scenes; on large ones each lamp in the model is a button.+struct HomeWidget: Widget {+ static let kind = "home"++ var body: some WidgetConfiguration {+ StaticConfiguration(kind: Self.kind, provider: HomeProvider()) { entry in+ HomeWidgetView(entry: entry)+ }+ .configurationDisplayName("Home")+ .description("Your home in 3D, lit the way it is right now. Tap a lamp in the large sizes to switch it.")+ .supportedFamilies(Self.families)+ }++ static var families: [WidgetFamily] {+ #if os(macOS)+ [.systemSmall, .systemMedium, .systemLarge, .systemExtraLarge]+ #else+ [.systemSmall, .systemMedium, .systemLarge]+ #endif+ }+}++struct HomeWidgetView: View {+ let entry: HomeEntry+ private let look = WidgetLook()+ private var family: WidgetFamily { look.family }++ var body: some View {+ let home = entry.home+ Group {+ switch family {+ case .systemSmall: small(home)+ case .systemMedium: medium(home)+ case .systemExtraLarge: extraLarge(home)+ default: large(home)+ }+ }+ .homeBackground(warmth: min(1, Double(home.lightsOn) / 4))+ .widgetURL(DeepLink.home())+ }++ private func small(_ home: HomeSnapshot) -> some View {+ VStack(alignment: .leading, spacing: 2) {+ HouseModel(home: home, padding: 0, boost: 1.6)+ .padding(.horizontal, -4)+ .frame(maxHeight: .infinity)+ HStack(alignment: .firstTextBaseline) {+ Text(home.name)+ .font(.system(size: 14, weight: .semibold))+ .foregroundStyle(Palette.text)+ .lineLimit(1)+ Spacer(minLength: 4)+ if let ac = home.acsOn.first {+ Label(ac.targetText, systemImage: ac.modeSymbol)+ .labelStyle(.titleAndIcon)+ .font(.system(size: 11.5, weight: .bold))+ .foregroundStyle(ac.tint)+ .widgetAccentable()+ }+ }+ LightsLine(home: home, size: 11)+ }+ }++ private func medium(_ home: HomeSnapshot) -> some View {+ HStack(spacing: 10) {+ HouseModel(home: home, padding: 0, boost: 1.25)+ .padding(.vertical, -6)+ .frame(maxWidth: .infinity)+ VStack(alignment: .leading, spacing: 4) {+ HStack {+ HomeTitle(home: home, size: 15)+ Spacer(minLength: 4)+ AllLightsButton(home: home, size: 28)+ }+ LightsLine(home: home)+ ClimateLine(home: home, size: 11)+ Spacer(minLength: 6)+ HStack(spacing: 6) {+ ForEach(home.scenes.prefix(3)) { scene in+ SceneTile(scene: scene, active: scene.id == home.scene, compact: true)+ }+ }+ .frame(height: 50)+ }+ .frame(width: 168)+ }+ }++ private func large(_ home: HomeSnapshot) -> some View {+ VStack(alignment: .leading, spacing: 8) {+ HStack(alignment: .center) {+ VStack(alignment: .leading, spacing: 3) {+ HomeTitle(home: home, size: 16)+ LightsLine(home: home, size: 12)+ }+ Spacer()+ AllLightsButton(home: home, size: 34)+ }+ HouseModel(home: home, padding: 6, interactive: true, boost: 1.1)+ .frame(maxHeight: .infinity)+ if let ac = home.acsOn.first ?? home.acs.first {+ climateStrip(ac)+ }+ HStack(spacing: 6) {+ ForEach(home.scenes.prefix(5)) { scene in+ SceneTile(scene: scene, active: scene.id == home.scene, compact: true)+ }+ }+ .frame(height: 52)+ }+ }++ private func climateStrip(_ ac: HomeSnapshot.AC) -> some View {+ HStack(spacing: 8) {+ Image(systemName: ac.on ? ac.modeSymbol : "air.conditioner.horizontal")+ .font(.system(size: 13, weight: .bold))+ .foregroundStyle(ac.on ? .white : Palette.muted)+ .frame(width: 28, height: 28)+ .background(Circle().fill(ac.on ? AnyShapeStyle(ac.tint.gradient) : AnyShapeStyle(Palette.glassHigh)))+ .widgetAccentable(ac.on)+ VStack(alignment: .leading, spacing: 0) {+ Text(ac.name).font(.system(size: 12.5, weight: .semibold)).foregroundStyle(Palette.text).lineLimit(1)+ Text(ac.on ? "\(ac.modeName)\(ac.roomText.map { " · room \($0)" } ?? "")" : "Off\(ac.roomText.map { " · room \($0)" } ?? "")")+ .font(.system(size: 11, weight: .medium)).foregroundStyle(Palette.faint).lineLimit(1)+ }+ Spacer(minLength: 4)+ Text(ac.targetText)+ .font(.system(size: 20, weight: .light))+ .foregroundStyle(ac.on ? Palette.text : Palette.muted)+ .contentTransition(.numericText(value: ac.target))+ ClimateButtons(ac: ac, size: 26)+ }+ .padding(.horizontal, 9)+ .padding(.vertical, 6)+ .background(Palette.glass, in: RoundedRectangle(cornerRadius: 14, style: .continuous))+ .overlay(RoundedRectangle(cornerRadius: 14, style: .continuous).strokeBorder(ac.on ? ac.tint.opacity(0.3) : Palette.line))+ }++ /// The Mac's widest widget: the model beside scenes, rooms and climate.+ private func extraLarge(_ home: HomeSnapshot) -> some View {+ HStack(spacing: 14) {+ VStack(alignment: .leading, spacing: 6) {+ HStack {+ VStack(alignment: .leading, spacing: 3) {+ HomeTitle(home: home, size: 17)+ LightsLine(home: home, size: 12)+ }+ Spacer()+ AllLightsButton(home: home, size: 34)+ }+ HouseModel(home: home, padding: 8, interactive: true, boost: 1)+ .frame(maxHeight: .infinity)+ }+ .frame(maxWidth: .infinity)+ VStack(alignment: .leading, spacing: 8) {+ Caption("Scenes")+ LazyVGrid(columns: [GridItem(.flexible(), spacing: 6), GridItem(.flexible(), spacing: 6), GridItem(.flexible(), spacing: 6)],+ spacing: 6) {+ ForEach(home.scenes.prefix(6)) { scene in+ SceneTile(scene: scene, active: scene.id == home.scene, compact: true).frame(height: 50)+ }+ }+ Caption("Rooms").padding(.top, 2)+ LazyVGrid(columns: [GridItem(.flexible(), spacing: 6), GridItem(.flexible(), spacing: 6)], spacing: 6) {+ ForEach(home.roomsWithLights.prefix(6)) { room in roomRow(room, home) }+ }+ Spacer(minLength: 0)+ if let ac = home.acsOn.first ?? home.acs.first { climateStrip(ac) }+ }+ .frame(width: 310)+ }+ }++ private func roomRow(_ room: HomeSnapshot.Room, _ home: HomeSnapshot) -> some View {+ let lights = home.lights(in: room.id)+ let on = lights.filter(\.on)+ return Button(intent: ToggleRoomIntent(roomID: room.id, on: on.isEmpty)) {+ HStack(spacing: 8) {+ Circle().fill(on.isEmpty ? AnyShapeStyle(Palette.glassHigh) : AnyShapeStyle((on.first?.glow ?? Palette.warm).gradient))+ .frame(width: 10, height: 10)+ .widgetAccentable(!on.isEmpty)+ Text(room.name).font(.system(size: 12.5, weight: .semibold)).foregroundStyle(Palette.text).lineLimit(1)+ Spacer(minLength: 2)+ Text(on.isEmpty ? "Off" : "\(on.count)/\(lights.count)")+ .font(.system(size: 11.5, weight: .medium)).foregroundStyle(on.isEmpty ? Palette.faint : Palette.warm)+ }+ .padding(.horizontal, 10)+ .frame(height: 28)+ .background(Palette.glass, in: RoundedRectangle(cornerRadius: 9, style: .continuous))+ }+ .buttonStyle(.plain)+ .accessibilityLabel("\(room.name): \(on.isEmpty ? "lights off" : "\(on.count) lights on")")+ }+}diff --git a/widgets/Sources/HouseModel.swift b/widgets/Sources/HouseModel.swiftnew file mode 100644index 0000000..3427d91--- /dev/null+++ b/widgets/Sources/HouseModel.swift@@ -0,0 +1,358 @@+import SwiftUI+import WidgetKit+import AppIntents+import HouseCore++/// Plan coordinates (metres) to a point in the widget: the plan turned by the azimuth+/// and seen from above at the elevation, scaled to fit, the way the panel's camera+/// looks at the home.+struct IsoProjection {+ static let backWall = 1.0+ static let frontWall = 0.16+ static let innerWall = 0.46+ /// Furniture is drawn lower than it is, like the walls, so it never hides the floor.+ static let furniture = 0.5++ private let cosA: Double, sinA: Double, sinE: Double, cosE: Double+ private(set) var scale: CGFloat = 1+ private(set) var origin = CGPoint.zero++ init(home: HomeSnapshot, size: CGSize, padding: CGFloat, azimuth: Double = 36, elevation: Double = 52) {+ let a = azimuth * .pi / 180, e = elevation * .pi / 180+ cosA = cos(a); sinA = sin(a); sinE = sin(e); cosE = cos(e)+ var points: [CGPoint] = []+ for r in home.rooms {+ for (x, z) in [(r.x, r.z), (r.x + r.w, r.z), (r.x + r.w, r.z + r.d), (r.x, r.z + r.d)] {+ points.append(raw(x, z, 0))+ points.append(raw(x, z, Self.backWall))+ }+ }+ guard let minX = points.map(\.x).min(), let maxX = points.map(\.x).max(),+ let minY = points.map(\.y).min(), let maxY = points.map(\.y).max(), maxX > minX, maxY > minY else { return }+ let w = max(1, size.width - padding * 2), h = max(1, size.height - padding * 2)+ scale = min(w / (maxX - minX), h / (maxY - minY))+ origin = CGPoint(x: (size.width - (maxX - minX) * scale) / 2 - minX * scale,+ y: (size.height - (maxY - minY) * scale) / 2 - minY * scale)+ }++ private func raw(_ x: Double, _ z: Double, _ h: Double) -> CGPoint {+ let rx = x * cosA - z * sinA+ let rz = x * sinA + z * cosA+ return CGPoint(x: rx, y: rz * sinE - h * cosE)+ }++ func point(_ x: Double, _ z: Double, _ h: Double = 0) -> CGPoint {+ let p = raw(x, z, h)+ return CGPoint(x: origin.x + p.x * scale, y: origin.y + p.y * scale)+ }++ /// How near a plan point is to the viewer: larger is nearer.+ func depth(_ x: Double, _ z: Double) -> Double { x * sinA + z * cosA }++ /// True when a wall whose outside points along (nx, nz) shows its outside to the viewer.+ func facesViewer(_ nx: Double, _ nz: Double) -> Bool { nx * sinA + nz * cosA > 0.01 }++ /// Light falling on a wall with this normal, 0…1 (the key light comes from the upper left).+ func shade(_ nx: Double, _ nz: Double) -> Double { 0.5 + 0.5 * (nx * cosA - nz * sinA) }++ var squash: Double { sinE }+}++/// A closed polygon through the given points.+struct Polygon: Shape {+ var points: [CGPoint]++ func path(in rect: CGRect) -> Path {+ var p = Path()+ guard let first = points.first else { return p }+ p.move(to: first)+ for point in points.dropFirst() { p.addLine(to: point) }+ p.closeSubpath()+ return p+ }+}++private struct Wall: Identifiable {+ var id: String+ var from: (Double, Double)+ var to: (Double, Double)+ var normal: (Double, Double)+ var height: Double+ var depth: Double+ var outside: Bool+}++/// The home as a small 3D model: floors, walls, every lamp glowing in its colour on the+/// floor of its room, the ACs on their walls. With `interactive`, each lamp is a button.+struct HouseModel: View {+ let home: HomeSnapshot+ var padding: CGFloat = 8+ var interactive = false+ /// Larger dots and glows for a small widget, where the model is tiny.+ var boost: Double = 1+ private let look = WidgetLook()++ var body: some View {+ GeometryReader { geo in+ let iso = IsoProjection(home: home, size: geo.size, padding: padding)+ let full = look.fullColor+ ZStack(alignment: .topLeading) {+ floors(iso, full: full)+ if full { rugs(iso); glows(iso) }+ walls(iso, full: full)+ acs(iso, full: full)+ lamps(iso, full: full)+ }+ .frame(width: geo.size.width, height: geo.size.height, alignment: .topLeading)+ }+ .accessibilityElement(children: interactive ? .contain : .ignore)+ .accessibilityLabel("\(home.name): \(home.lightsLine)")+ }++ private func roomCorners(_ r: HomeSnapshot.Room, _ iso: IsoProjection, inset: Double = 0) -> [CGPoint] {+ [iso.point(r.x + inset, r.z + inset), iso.point(r.x + r.w - inset, r.z + inset),+ iso.point(r.x + r.w - inset, r.z + r.d - inset), iso.point(r.x + inset, r.z + r.d - inset)]+ }++ private static func floorColor(_ kind: String?) -> Color {+ switch kind {+ case "walnut": return Color(hex: "#2b2019")+ case "tile": return Color(hex: "#262c36")+ case "stone": return Color(hex: "#2e3036")+ default: return Color(hex: "#3a2b20")+ }+ }++ @ViewBuilder private func floors(_ iso: IsoProjection, full: Bool) -> some View {+ // A soft shadow under the whole home lifts it off the background.+ if full {+ ForEach(home.rooms) { r in+ Polygon(points: roomCorners(r, iso, inset: -0.15)).fill(Color.black.opacity(0.35))+ .blur(radius: 6).offset(y: 5)+ }+ }+ ForEach(home.rooms) { r in+ let shape = Polygon(points: roomCorners(r, iso))+ if full {+ let lit = home.lights(in: r.id).filter(\.on)+ shape.fill(Self.floorColor(r.floor).opacity(lit.isEmpty ? 0.8 : 1))+ .overlay(shape.stroke(Color.white.opacity(0.06), lineWidth: 0.5))+ } else {+ shape.fill(Color.white.opacity(0.08)).overlay(shape.stroke(Color.white.opacity(0.35), lineWidth: 0.8))+ }+ }+ }++ private func rugs(_ iso: IsoProjection) -> some View {+ ForEach(Array((home.furniture ?? []).enumerated().filter { $0.element.type == "rug" }), id: \.offset) { _, f in+ Polygon(points: Self.footprint(f).map { iso.point($0.0, $0.1) })+ .fill(Color(hex: f.color ?? "#3b4a66").opacity(roomLit(at: f.x, f.z) == nil ? 0.45 : 0.75))+ }+ }++ private func glows(_ iso: IsoProjection) -> some View {+ ForEach(home.rooms) { r in+ ZStack(alignment: .topLeading) {+ ForEach(home.lights(in: r.id).filter(\.on)) { l in+ let c = iso.point(l.x, l.z)+ let radius = (1.25 + 1.35 * l.level) * iso.scale * (0.85 + 0.15 * boost)+ Ellipse()+ .fill(RadialGradient(colors: [l.glow.opacity(0.95 * l.level + 0.05), l.glow.opacity(0.4 * l.level), .clear],+ center: .center, startRadius: 0, endRadius: radius))+ .frame(width: radius * 2, height: radius * 2 * iso.squash)+ .position(c)+ }+ }+ .clipShape(Polygon(points: roomCorners(r, iso)))+ .blendMode(.screen)+ }+ }++ private func wallList(_ iso: IsoProjection) -> [Wall] {+ var walls: [String: Wall] = [:]+ func inside(_ x: Double, _ z: Double, except id: String) -> Bool {+ home.rooms.contains { $0.id != id && x > $0.x && x < $0.x + $0.w && z > $0.z && z < $0.z + $0.d }+ }+ for r in home.rooms {+ let edges: [((Double, Double), (Double, Double), (Double, Double))] = [+ ((r.x, r.z), (r.x + r.w, r.z), (0, -1)),+ ((r.x + r.w, r.z), (r.x + r.w, r.z + r.d), (1, 0)),+ ((r.x + r.w, r.z + r.d), (r.x, r.z + r.d), (0, 1)),+ ((r.x, r.z + r.d), (r.x, r.z), (-1, 0)),+ ]+ for (a, b, n) in edges {+ let mid = ((a.0 + b.0) / 2, (a.1 + b.1) / 2)+ let outside = !inside(mid.0 + n.0 * 0.08, mid.1 + n.1 * 0.08, except: r.id)+ let height = outside ? (iso.facesViewer(n.0, n.1) ? IsoProjection.frontWall : IsoProjection.backWall)+ : IsoProjection.innerWall+ // An inner wall belongs to two rooms: draw it once.+ let key = [a, b].map { "\(($0.0 * 20).rounded()),\(($0.1 * 20).rounded())" }.sorted().joined(separator: "|")+ if !outside, walls[key] != nil { continue }+ walls[key] = Wall(id: key, from: a, to: b, normal: n, height: height,+ depth: iso.depth(mid.0, mid.1) + (outside && !iso.facesViewer(n.0, n.1) ? -0.5 : 0),+ outside: outside)+ }+ }+ return walls.values.sorted { $0.depth < $1.depth }+ }++ private enum Solid: Identifiable {+ case wall(Wall)+ case piece(HomeSnapshot.Furniture, index: Int, depth: Double)++ var id: String {+ switch self {+ case .wall(let w): return "w" + w.id+ case .piece(_, let index, _): return "f\(index)"+ }+ }++ var depth: Double {+ switch self {+ case .wall(let w): return w.depth+ case .piece(_, _, let depth): return depth+ }+ }+ }++ /// Walls and furniture, farthest first, so nearer ones are drawn over them.+ private func solids(_ iso: IsoProjection) -> [Solid] {+ var list = wallList(iso).map(Solid.wall)+ for (i, f) in (home.furniture ?? []).enumerated() where f.type != "rug" {+ list.append(.piece(f, index: i, depth: iso.depth(f.x, f.z)))+ }+ return list.sorted { $0.depth < $1.depth }+ }++ @ViewBuilder private func walls(_ iso: IsoProjection, full: Bool) -> some View {+ ForEach(solids(iso)) { solid in+ switch solid {+ case .wall(let w): wall(w, iso, full: full)+ case .piece(let f, _, _): if full { piece(f, iso) }+ }+ }+ }++ @ViewBuilder private func wall(_ w: Wall, _ iso: IsoProjection, full: Bool) -> some View {+ let base = [iso.point(w.from.0, w.from.1), iso.point(w.to.0, w.to.1)]+ let top = [iso.point(w.to.0, w.to.1, w.height), iso.point(w.from.0, w.from.1, w.height)]+ if full {+ let light = iso.shade(w.normal.0, w.normal.1)+ let front = w.outside && iso.facesViewer(w.normal.0, w.normal.1)+ Polygon(points: base + top)+ .fill(LinearGradient(colors: [Color(white: (front ? 0.40 : 0.66) + 0.2 * light),+ Color(white: (front ? 0.30 : 0.46) + 0.16 * light)],+ startPoint: .top, endPoint: .bottom))+ Path { p in p.move(to: top[0]); p.addLine(to: top[1]) }+ .stroke(Color.white.opacity(0.95), style: StrokeStyle(lineWidth: max(1, iso.scale * 0.08), lineCap: .round))+ } else {+ Path { p in p.move(to: top[0]); p.addLine(to: top[1]) }+ .stroke(Color.white.opacity(0.55), style: StrokeStyle(lineWidth: 1, lineCap: .round))+ }+ }++ private static func furnitureLook(_ type: String) -> (height: Double, color: String) {+ switch type {+ case "sofa", "armchair": return (0.8, "#8b93a7")+ case "coffeeTable", "diningSet", "desk": return (0.74, "#6b4f3a")+ case "tv": return (0.55, "#1b1e26")+ case "sideboard", "dresser", "nightstand": return (0.72, "#5a4434")+ case "island", "kitchen", "vanity": return (0.9, "#e2ded6")+ case "fridge": return (1.7, "#cfd3d8")+ case "bed": return (0.55, "#dfe3ea")+ case "plant": return (1.0, "#3f7a4a")+ case "bathtub", "toilet": return (0.5, "#eef1f4")+ case "wardrobe", "bookshelf": return (1.7, "#5a4434")+ default: return (0.6, "#7a7f8c")+ }+ }++ /// The four corners of a piece's footprint on the plan, turned the way three.js turns it.+ private static func footprint(_ f: HomeSnapshot.Furniture, grow: Double = 0) -> [(Double, Double)] {+ let a = f.rot * .pi / 180, c = cos(a), s = sin(a)+ let hw = f.w / 2 + grow, hd = f.d / 2 + grow+ return [(-hw, -hd), (hw, -hd), (hw, hd), (-hw, hd)].map { (lx, lz) in+ (f.x + lx * c + lz * s, f.z - lx * s + lz * c)+ }+ }++ private func roomLit(at x: Double, _ z: Double) -> HomeSnapshot.Light? {+ guard let room = home.rooms.first(where: { x >= $0.x && x <= $0.x + $0.w && z >= $0.z && z <= $0.z + $0.d }) else { return nil }+ return home.lights(in: room.id).first(where: \.on)+ }++ @ViewBuilder private func piece(_ f: HomeSnapshot.Furniture, _ iso: IsoProjection) -> some View {+ let look = Self.furnitureLook(f.type)+ let h = look.height * IsoProjection.furniture+ let color = Color(hex: f.color ?? look.color)+ let corners = Self.footprint(f, grow: -0.04)+ let lit = roomLit(at: f.x, f.z)+ let dim = lit == nil ? 0.5 : 0.18+ ForEach(0..<4, id: \.self) { i in+ let a = corners[i], b = corners[(i + 1) % 4]+ // The outward normal of this side; only sides that face the viewer are seen.+ let n = (b.1 - a.1, -(b.0 - a.0))+ if iso.facesViewer(n.0, n.1) {+ Polygon(points: [iso.point(a.0, a.1), iso.point(b.0, b.1), iso.point(b.0, b.1, h), iso.point(a.0, a.1, h)])+ .fill(color).overlay(Polygon(points: [iso.point(a.0, a.1), iso.point(b.0, b.1), iso.point(b.0, b.1, h),+ iso.point(a.0, a.1, h)]).fill(Color.black.opacity(min(0.85, dim + 0.3))))+ }+ }+ let top = Polygon(points: corners.map { iso.point($0.0, $0.1, h) })+ top.fill(color)+ .overlay(top.fill(Color.black.opacity(dim)))+ .overlay(top.fill(lit.map { $0.glow.opacity(0.22) } ?? .clear))+ }++ private func acs(_ iso: IsoProjection, full: Bool) -> some View {+ ForEach(home.acs) { ac in+ let p = iso.point(ac.x, ac.z, IsoProjection.backWall * 0.8)+ let size = max(5, iso.scale * 0.55) * (0.9 + 0.1 * boost)+ ZStack {+ if ac.on && full {+ Circle().fill(RadialGradient(colors: [ac.tint.opacity(0.75), .clear], center: .center,+ startRadius: 0, endRadius: size * 1.6))+ .frame(width: size * 3.2, height: size * 3.2)+ .blendMode(.screen)+ }+ Image(systemName: ac.on ? ac.modeSymbol : "air.conditioner.horizontal")+ .font(.system(size: size * 0.95, weight: .bold))+ .foregroundStyle(ac.on ? (full ? Color.white : Color.white) : Color.white.opacity(0.45))+ .frame(width: size * 1.7, height: size * 1.7)+ .background(Circle().fill(ac.on ? ac.tint.opacity(full ? 0.9 : 0.4) : Color.black.opacity(0.35)))+ .overlay(Circle().stroke(Color.white.opacity(0.4), lineWidth: 0.6))+ .widgetAccentable(ac.on)+ }+ .position(p)+ }+ }++ private func lamps(_ iso: IsoProjection, full: Bool) -> some View {+ ForEach(home.lights) { l in+ let p = iso.point(l.x, l.z, 0.12)+ let dot = max(3.5, iso.scale * 0.2) * (0.8 + 0.2 * boost)+ let mark = ZStack {+ if l.on && full {+ Circle().fill(RadialGradient(colors: [Color.white, l.glow.opacity(0.9), l.glow.opacity(0)],+ center: .center, startRadius: 0, endRadius: dot * 2.4))+ .frame(width: dot * 4.8, height: dot * 4.8)+ }+ Circle()+ .fill(l.on ? (full ? Color.white : Color.white) : Color.white.opacity(full ? 0.22 : 0.3))+ .frame(width: dot, height: dot)+ .overlay(Circle().stroke(Color.black.opacity(l.on ? 0 : 0.35), lineWidth: 0.5))+ .widgetAccentable(l.on)+ }+ if interactive {+ Button(intent: ToggleLightIntent(lightID: l.id)) {+ mark.frame(width: max(30, dot * 5), height: max(30, dot * 5)).contentShape(Circle())+ }+ .buttonStyle(.plain)+ .accessibilityLabel("\(l.name), \(l.on ? "on" : "off")")+ .position(p)+ } else {+ mark.position(p)+ }+ }+ }+}diff --git a/widgets/Sources/HouseWidgets.swift b/widgets/Sources/HouseWidgets.swiftnew file mode 100644index 0000000..fc63874--- /dev/null+++ b/widgets/Sources/HouseWidgets.swift@@ -0,0 +1,28 @@+import SwiftUI+import WidgetKit++/// Every widget and control House Control offers, on the iPhone and the Mac.+@main+struct HouseWidgets: WidgetBundle {+ var body: some Widget {+ HomeWidget()+ ScenesWidget()+ LightWidget()+ RoomWidget()+ ClimateWidget()+ #if os(iOS)+ StatusWidget()+ #endif+ controls+ }++ @WidgetBundleBuilder+ private var controls: some Widget {+ if #available(iOS 18.0, macOS 26.0, *) {+ AllLightsControl()+ LightControl()+ SceneControl()+ ClimateControl()+ }+ }+}diff --git a/widgets/Sources/Intents.swift b/widgets/Sources/Intents.swiftnew file mode 100644index 0000000..e65e626--- /dev/null+++ b/widgets/Sources/Intents.swift@@ -0,0 +1,246 @@+import AppIntents+import WidgetKit+import HouseCore++/// The home the widgets show: what the app last wrote, or the demo apartment before it ran.+enum HomeData {+ static var current: HomeSnapshot? { SharedHome()?.snapshot() }+ static var orSample: HomeSnapshot { current ?? sample }++ static let sample: HomeSnapshot = {+ guard let url = Bundle.main.url(forResource: "sample-home", withExtension: "json"),+ let data = try? Data(contentsOf: url),+ let home = try? JSONDecoder().decode(HomeSnapshot.self, from: data) else {+ return HomeSnapshot(name: "Home", plan: "home", rooms: [], lights: [], acs: [], scenes: [])+ }+ return home+ }()+}++// MARK: - Entities (what a configurable widget or control can be pointed at)++struct LightEntity: AppEntity {+ static let typeDisplayRepresentation: TypeDisplayRepresentation = "Light"+ static let defaultQuery = LightQuery()+ var id: String+ var name: String+ var room: String++ var displayRepresentation: DisplayRepresentation {+ DisplayRepresentation(title: "\(name)", subtitle: "\(room)", image: .init(systemName: "lightbulb.fill"))+ }++ init(_ light: HomeSnapshot.Light, in home: HomeSnapshot) {+ id = light.id+ name = light.name+ room = home.room(light.room)?.name ?? light.room+ }+}++struct LightQuery: EntityQuery {+ func entities(for identifiers: [String]) async throws -> [LightEntity] {+ let home = HomeData.orSample+ return identifiers.compactMap { id in home.light(id).map { LightEntity($0, in: home) } }+ }++ func suggestedEntities() async throws -> [LightEntity] {+ let home = HomeData.orSample+ return home.lights.map { LightEntity($0, in: home) }+ }++ func defaultResult() async -> LightEntity? { try? await suggestedEntities().first }+}++struct RoomEntity: AppEntity {+ static let typeDisplayRepresentation: TypeDisplayRepresentation = "Room"+ static let defaultQuery = RoomQuery()+ var id: String+ var name: String++ var displayRepresentation: DisplayRepresentation {+ DisplayRepresentation(title: "\(name)", image: .init(systemName: "square.split.bottomrightquarter"))+ }+}++struct RoomQuery: EntityQuery {+ func entities(for identifiers: [String]) async throws -> [RoomEntity] {+ let home = HomeData.orSample+ return identifiers.compactMap { id in home.room(id).map { RoomEntity(id: $0.id, name: $0.name) } }+ }++ func suggestedEntities() async throws -> [RoomEntity] {+ HomeData.orSample.roomsWithLights.map { RoomEntity(id: $0.id, name: $0.name) }+ }++ func defaultResult() async -> RoomEntity? { try? await suggestedEntities().first }+}++struct ACEntity: AppEntity {+ static let typeDisplayRepresentation: TypeDisplayRepresentation = "Air Conditioner"+ static let defaultQuery = ACQuery()+ var id: String+ var name: String+ var room: String++ var displayRepresentation: DisplayRepresentation {+ DisplayRepresentation(title: "\(name)", subtitle: "\(room)", image: .init(systemName: "air.conditioner.horizontal.fill"))+ }++ init(_ ac: HomeSnapshot.AC, in home: HomeSnapshot) {+ id = ac.id+ name = ac.name+ room = home.room(ac.room)?.name ?? ac.room+ }+}++struct ACQuery: EntityQuery {+ func entities(for identifiers: [String]) async throws -> [ACEntity] {+ let home = HomeData.orSample+ return identifiers.compactMap { id in home.ac(id).map { ACEntity($0, in: home) } }+ }++ func suggestedEntities() async throws -> [ACEntity] {+ let home = HomeData.orSample+ return home.acs.map { ACEntity($0, in: home) }+ }++ func defaultResult() async -> ACEntity? { try? await suggestedEntities().first }+}++struct SceneEntity: AppEntity {+ static let typeDisplayRepresentation: TypeDisplayRepresentation = "Scene"+ static let defaultQuery = SceneQuery()+ var id: String+ var name: String+ var symbol: String++ var displayRepresentation: DisplayRepresentation {+ DisplayRepresentation(title: "\(name)", image: .init(systemName: symbol))+ }++ init(_ scene: HomeSnapshot.Scene) {+ id = scene.id+ name = scene.name+ symbol = scene.symbol+ }+}++struct SceneQuery: EntityQuery {+ func entities(for identifiers: [String]) async throws -> [SceneEntity] {+ let home = HomeData.orSample+ return identifiers.compactMap { id in home.scenes.first { $0.id == id }.map(SceneEntity.init) }+ }++ func suggestedEntities() async throws -> [SceneEntity] { HomeData.orSample.scenes.map(SceneEntity.init) }++ func defaultResult() async -> SceneEntity? { try? await suggestedEntities().first }+}++// MARK: - Widget configuration++struct LightConfiguration: WidgetConfigurationIntent {+ static let title: LocalizedStringResource = "Light"+ static let description = IntentDescription("Choose the lamp this widget switches.")+ @Parameter(title: "Light") var light: LightEntity?+}++struct RoomConfiguration: WidgetConfigurationIntent {+ static let title: LocalizedStringResource = "Room"+ static let description = IntentDescription("Choose the room whose lamps this widget shows.")+ @Parameter(title: "Room") var room: RoomEntity?+}++struct ClimateConfiguration: WidgetConfigurationIntent {+ static let title: LocalizedStringResource = "Air Conditioner"+ static let description = IntentDescription("Choose the air conditioner this widget controls.")+ @Parameter(title: "Air Conditioner") var ac: ACEntity?+}++// MARK: - Actions behind the widgets' buttons++struct ToggleLightIntent: AppIntent {+ static let title: LocalizedStringResource = "Toggle Light"+ static let isDiscoverable = false+ @Parameter(title: "Light") var lightID: String++ init() {}+ init(lightID: String) { self.lightID = lightID }++ func perform() async throws -> some IntentResult {+ await WidgetActions.run(.light(lightID))+ return .result()+ }+}++struct ToggleRoomIntent: AppIntent {+ static let title: LocalizedStringResource = "Toggle Room Lights"+ static let isDiscoverable = false+ @Parameter(title: "Room") var roomID: String+ @Parameter(title: "On") var on: Bool?++ init() {}+ init(roomID: String, on: Bool? = nil) { self.roomID = roomID; self.on = on }++ func perform() async throws -> some IntentResult {+ await WidgetActions.run(.room(roomID, on: on))+ return .result()+ }+}++struct AllLightsIntent: AppIntent {+ static let title: LocalizedStringResource = "Switch All Lights"+ static let isDiscoverable = false+ @Parameter(title: "On") var on: Bool++ init() {}+ init(on: Bool) { self.on = on }++ func perform() async throws -> some IntentResult {+ await WidgetActions.run(.allLights(on: on))+ return .result()+ }+}++struct ApplySceneIntent: AppIntent {+ static let title: LocalizedStringResource = "Apply Scene"+ static let isDiscoverable = false+ @Parameter(title: "Scene") var sceneID: String++ init() {}+ init(sceneID: String) { self.sceneID = sceneID }++ func perform() async throws -> some IntentResult {+ await WidgetActions.run(.scene(sceneID))+ return .result()+ }+}++struct ACPowerIntent: AppIntent {+ static let title: LocalizedStringResource = "Toggle Air Conditioner"+ static let isDiscoverable = false+ @Parameter(title: "Air Conditioner") var acID: String++ init() {}+ init(acID: String) { self.acID = acID }++ func perform() async throws -> some IntentResult {+ await WidgetActions.run(.acPower(acID))+ return .result()+ }+}++struct ACStepIntent: AppIntent {+ static let title: LocalizedStringResource = "Change Temperature"+ static let isDiscoverable = false+ @Parameter(title: "Air Conditioner") var acID: String+ @Parameter(title: "Step") var step: Int++ init() {}+ init(acID: String, step: Int) { self.acID = acID; self.step = step }++ func perform() async throws -> some IntentResult {+ guard let ac = HomeData.current?.ac(acID) else { return .result() }+ await WidgetActions.run(.acTarget(acID, ac.target + Double(step)))+ return .result()+ }+}diff --git a/widgets/Sources/Providers.swift b/widgets/Sources/Providers.swiftnew file mode 100644index 0000000..35b1eba--- /dev/null+++ b/widgets/Sources/Providers.swift@@ -0,0 +1,62 @@+import WidgetKit+import AppIntents+import HouseCore++struct HomeEntry: TimelineEntry {+ let date: Date+ let home: HomeSnapshot+ /// True while the app has not written a home yet: the demo apartment stands in.+ let isSample: Bool+}++/// The app reloads the widgets whenever the home changes; the half-hourly refresh only+/// catches a simulated room temperature creeping towards its set-point.+private let refresh: TimeInterval = 30 * 60++struct HomeProvider: TimelineProvider {+ func placeholder(in context: Context) -> HomeEntry {+ HomeEntry(date: .now, home: HomeData.sample, isSample: true)+ }++ func getSnapshot(in context: Context, completion: @escaping (HomeEntry) -> Void) {+ completion(entry())+ }++ func getTimeline(in context: Context, completion: @escaping (Timeline<HomeEntry>) -> Void) {+ completion(Timeline(entries: [entry()], policy: .after(.now.addingTimeInterval(refresh))))+ }++ private func entry() -> HomeEntry {+ let current = HomeData.current+ return HomeEntry(date: .now, home: current ?? HomeData.sample, isSample: current == nil)+ }+}++struct ConfiguredEntry<Configuration: WidgetConfigurationIntent>: TimelineEntry {+ let date: Date+ let home: HomeSnapshot+ let isSample: Bool+ let configuration: Configuration+}++/// One provider for the widgets that are pointed at a lamp, a room or an AC.+struct ConfiguredProvider<Configuration: WidgetConfigurationIntent>: AppIntentTimelineProvider {+ typealias Entry = ConfiguredEntry<Configuration>++ func placeholder(in context: Context) -> Entry {+ Entry(date: .now, home: HomeData.sample, isSample: true, configuration: Configuration())+ }++ func snapshot(for configuration: Configuration, in context: Context) async -> Entry {+ entry(configuration)+ }++ func timeline(for configuration: Configuration, in context: Context) async -> Timeline<Entry> {+ Timeline(entries: [entry(configuration)], policy: .after(.now.addingTimeInterval(refresh)))+ }++ private func entry(_ configuration: Configuration) -> Entry {+ let current = HomeData.current+ return Entry(date: .now, home: current ?? HomeData.sample, isSample: current == nil, configuration: configuration)+ }+}diff --git a/widgets/Sources/Style.swift b/widgets/Sources/Style.swiftnew file mode 100644index 0000000..e267f15--- /dev/null+++ b/widgets/Sources/Style.swift@@ -0,0 +1,214 @@+import SwiftUI+import WidgetKit+import HouseCore++/// The panel's palette (web/src/style.css), so a widget reads as the same app.+enum Palette {+ static let night = Color(hex: "#0a0e1a")+ static let dusk = Color(hex: "#161d33")+ static let text = Color(hex: "#f3f5fa")+ static let muted = Color(hex: "#dee6f7").opacity(0.6)+ static let faint = Color(hex: "#dee6f7").opacity(0.36)+ static let glass = Color.white.opacity(0.07)+ static let glassHigh = Color.white.opacity(0.12)+ static let line = Color.white.opacity(0.09)+ static let accent = Color(hex: "#3d8bff")+ static let warm = Color(hex: "#ffb46b")+ static let cool = Color(hex: "#56c2ff")+ static let heat = Color(hex: "#ff8a4c")+ static let green = Color(hex: "#4ade80")+}++extension Color {+ init(hex: String) {+ let digits = hex.trimmingCharacters(in: CharacterSet(charactersIn: "#"))+ let value = UInt32(digits, radix: 16) ?? 0xffffff+ self.init(red: Double((value >> 16) & 0xff) / 255, green: Double((value >> 8) & 0xff) / 255,+ blue: Double(value & 0xff) / 255)+ }++ /// The colour of white light at `kelvin` (Tanner Helland's fit), as warm as the 3D view draws it.+ init(kelvin: Double) {+ let t = max(1000, min(40000, kelvin)) / 100+ let r = t <= 66 ? 255 : 329.698727446 * pow(t - 60, -0.1332047592)+ let g = t <= 66 ? 99.4708025861 * log(t) - 161.1195681661 : 288.1221695283 * pow(t - 60, -0.0755148492)+ let b = t >= 66 ? 255 : (t <= 19 ? 0 : 138.5177312231 * log(t - 10) - 305.0447927307)+ func c(_ v: Double) -> Double { max(0, min(255, v)) / 255 }+ self.init(red: c(r), green: c(g), blue: c(b))+ }+}++extension HomeSnapshot.Light {+ /// What the lamp shines in: its colour, or its white temperature (plugs glow warm).+ var glow: Color {+ if let color { return Color(hex: color) }+ return capabilities.contains("temp") ? Color(kelvin: temp) : Palette.warm+ }++ var level: Double { capabilities.contains("brightness") ? brightness : 1 }++ var stateText: String {+ guard on else { return "Off" }+ return capabilities.contains("brightness") ? "\(Int((brightness * 100).rounded()))%" : "On"+ }+}++extension HomeSnapshot.AC {+ var modeSymbol: String {+ switch mode {+ case "heat": return "flame.fill"+ case "dry": return "drop.fill"+ case "fan": return "fan.fill"+ case "auto": return "arrow.triangle.2.circlepath"+ default: return "snowflake"+ }+ }++ var modeName: String { mode.prefix(1).uppercased() + mode.dropFirst() }++ var tint: Color {+ guard on else { return Palette.muted }+ switch mode {+ case "heat": return Palette.heat+ case "fan", "dry": return Color(hex: "#7dd3c0")+ case "auto": return Color(hex: "#a78bfa")+ default: return Palette.cool+ }+ }++ var targetText: String { "\(Int(target))°" }+ var roomText: String? { roomTemp.map { String(format: "%.1f°", $0) } }+}++extension HomeSnapshot.Scene {+ /// A colour that says what the scene does: its brightest colour, else warm or cool white.+ var tint: Color {+ let patches = lights.values+ if let hex = patches.compactMap({ $0["color"]?.string }).first { return Color(hex: hex) }+ let anyOn = patches.contains { $0["on"]?.bool == true }+ if !anyOn { return Color(hex: "#8b9cff") }+ if let t = patches.compactMap({ $0["temp"]?.number }).max() { return t >= 4000 ? Color(hex: "#ffe3a8") : Palette.warm }+ return Palette.warm+ }+}++extension HomeSnapshot {+ /// "6 of 11 lights on", "All lights off".+ var lightsLine: String {+ lightsOn == 0 ? "All lights off" : "\(lightsOn) of \(lights.count) \(lights.count == 1 ? "light" : "lights") on"+ }++ var climateLine: String? {+ guard let ac = acsOn.first else { return nil }+ return "\(ac.modeName) \(ac.targetText)"+ }++ var activeScene: Scene? { scenes.first { $0.id == scene } }++ /// Rooms with lamps, in plan order.+ var roomsWithLights: [Room] { rooms.filter { r in lights.contains { $0.room == r.id } } }++ /// Just one room, with its lamps, ACs and furniture: for a model of that room alone.+ func only(_ id: String) -> HomeSnapshot {+ guard let room = room(id) else { return self }+ var copy = self+ copy.rooms = [room]+ copy.lights = lights.filter { $0.room == id }+ copy.acs = acs.filter { $0.room == id }+ copy.furniture = furniture?.filter { $0.x >= room.x && $0.x <= room.x + room.w && $0.z >= room.z && $0.z <= room.z + room.d }+ return copy+ }+}++/// The night-blue background every widget sits on, with a warm bloom when lamps are on.+struct WidgetBackdrop: View {+ var warmth: Double = 0++ var body: some View {+ ZStack {+ LinearGradient(colors: [Palette.dusk, Palette.night], startPoint: .top, endPoint: .bottom)+ RadialGradient(colors: [Palette.warm.opacity(0.18 * warmth), .clear], center: .init(x: 0.5, y: 0.42),+ startRadius: 0, endRadius: 220)+ }+ }+}++extension View {+ /// The widget's background, which the system removes in StandBy or the tinted home screen.+ func homeBackground(warmth: Double = 0) -> some View {+ containerBackground(for: .widget) { WidgetBackdrop(warmth: warmth) }+ }+}++/// A small caps label above a group ("SCENES", "LIVING").+struct Caption: View {+ let text: String+ init(_ text: String) { self.text = text }++ var body: some View {+ Text(text.uppercased())+ .font(.system(size: 10.5, weight: .bold))+ .kerning(0.9)+ .foregroundStyle(Palette.faint)+ .lineLimit(1)+ }+}++/// The deep links the app understands.+enum DeepLink {+ static func home() -> URL { URL(string: "housecontrol://open")! }+ static func device(_ id: String) -> URL {+ var c = URLComponents()+ c.scheme = "housecontrol"+ c.host = "open"+ c.queryItems = [URLQueryItem(name: "device", value: id)]+ return c.url!+ }+}++// MARK: - Family and rendering mode++private struct StillFamilyKey: EnvironmentKey { static let defaultValue: WidgetFamily? = nil }+private struct StillModeKey: EnvironmentKey { static let defaultValue: WidgetRenderingMode? = nil }++extension EnvironmentValues {+ /// Set by `widgets/Render`, which draws the widgets as still images outside WidgetKit+ /// (the system's own values cannot be set there).+ var stillFamily: WidgetFamily? {+ get { self[StillFamilyKey.self] }+ set { self[StillFamilyKey.self] = newValue }+ }++ var stillRenderingMode: WidgetRenderingMode? {+ get { self[StillModeKey.self] }+ set { self[StillModeKey.self] = newValue }+ }+}++/// The family a widget is drawn for and whether it is in full colour (not the tinted or+/// clear home screen, StandBy at night, or the Lock Screen).+struct WidgetLook: DynamicProperty {+ @Environment(\.widgetFamily) private var widgetFamily+ @Environment(\.widgetRenderingMode) private var widgetRenderingMode+ @Environment(\.stillFamily) private var stillFamily+ @Environment(\.stillRenderingMode) private var stillRenderingMode++ var family: WidgetFamily { stillFamily ?? widgetFamily }++ enum Accessory { case circular, rectangular, inline }++ /// Which Lock Screen shape this is (accessory families exist on the iPhone only).+ var accessory: Accessory? {+ #if os(iOS)+ switch family {+ case .accessoryCircular: return .circular+ case .accessoryRectangular: return .rectangular+ case .accessoryInline: return .inline+ default: return nil+ }+ #else+ return nil+ #endif+ }+ var fullColor: Bool { (stillRenderingMode ?? widgetRenderingMode) == .fullColor }+}diff --git a/widgets/make-sample.mjs b/widgets/make-sample.mjsnew file mode 100644index 0000000..4a56ccf--- /dev/null+++ b/widgets/make-sample.mjs@@ -0,0 +1,23 @@+// Writes Resources/sample-home.json: the demo apartment in its "Cozy" scene, which the+// widgets show until the app has written the real home (the widget gallery, a fresh install).+// node widgets/make-sample.mjs+import { readFileSync, writeFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';++globalThis.window = globalThis;+globalThis.location = { search: '' };+globalThis.localStorage = { getItem: () => null, setItem() {} };++const web = fileURLToPath(new URL('../web/', import.meta.url));+const { normalize } = await import(`${web}src/config.js`);+const { createStore } = await import(`${web}src/store.js`);+const { widgetSnapshot } = await import(`${web}src/widgets.js`);++const config = normalize(JSON.parse(readFileSync(`${web}public/plans/home.json`, 'utf8')));+const store = createStore(config);+store.applyScene('cozy');+store.setAC(config.acs[0].id, { on: true, target: 23 });+for (const ac of Object.values(store.state.acs)) ac.roomTemp = 25.4;+const snapshot = { ...widgetSnapshot(config, store, 'home'), updated: 0 };+writeFileSync(new URL('Resources/sample-home.json', import.meta.url), `${JSON.stringify(snapshot)}\n`);+process.exit(0); // the store's simulation timer would keep node runningdiff --git a/widgets/project.yml b/widgets/project.ymlnew file mode 100644index 0000000..3bf6022--- /dev/null+++ b/widgets/project.yml@@ -0,0 +1,56 @@+# The Mac's widget extension, embedded into HouseControl.app by scripts/build-app.sh+# (the Mac app itself is a Swift package; the iPhone's extension is in ../ios/project.yml).+name: HouseWidgetsMac+options:+ bundleIdPrefix: io.github.0xprobabillity+ deploymentTarget:+ macOS: "14.0"+ createIntermediateGroups: true+configFiles:+ Release: Config/Mac.xcconfig+ Debug: Config/Mac.xcconfig+packages:+ HouseCore:+ path: ../core+targets:+ HouseWidgets:+ type: app-extension+ platform: macOS+ sources:+ - path: Sources+ - path: Resources+ buildPhase: resources+ dependencies:+ - package: HouseCore+ - sdk: WidgetKit.framework+ - sdk: SwiftUI.framework+ info:+ path: Config/Info-macOS.plist+ properties:+ CFBundleDisplayName: House Control+ CFBundleShortVersionString: $(MARKETING_VERSION)+ CFBundleVersion: $(CURRENT_PROJECT_VERSION)+ HouseAppGroup: $(HOUSE_APP_GROUP)+ NSExtension:+ NSExtensionPointIdentifier: com.apple.widgetkit-extension+ entitlements:+ path: Config/macOS.entitlements+ properties:+ com.apple.security.app-sandbox: true+ com.apple.security.application-groups: [$(HOUSE_APP_GROUP)]+ settings:+ base:+ PRODUCT_BUNDLE_IDENTIFIER: io.github.0xprobabillity.HouseControl.Widgets+ PRODUCT_NAME: HouseWidgets+ SWIFT_VERSION: "5.0"+ GENERATE_INFOPLIST_FILE: NO+ CODE_SIGN_STYLE: Manual+ ENABLE_HARDENED_RUNTIME: YES+ SKIP_INSTALL: YES+schemes:+ HouseWidgets:+ build:+ targets:+ HouseWidgets: all+ archive:+ config: Release