Skip to content

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 the iPhone app

0xProbabilityeafa53a249fe
diff --git a/ios/Config/Base.xcconfig b/ios/Config/Base.xcconfig
new file mode 100644
index 0000000..b1ab8a9
--- /dev/null
+++ b/ios/Config/Base.xcconfig
@@ -0,0 +1,9 @@
+// Version of the iPhone app. CURRENT_PROJECT_VERSION is the build number TestFlight sees.
+MARKETING_VERSION = 0.1.0
+CURRENT_PROJECT_VERSION = 1
+
+CODE_SIGN_STYLE = Automatic
+
+// Your Apple developer team goes into Config/Local.xcconfig (not committed):
+// DEVELOPMENT_TEAM = ABCDE12345
+#include? "Local.xcconfig"
diff --git a/ios/Config/ExportOptions.plist b/ios/Config/ExportOptions.plist
new file mode 100644
index 0000000..8ad567a
--- /dev/null
+++ b/ios/Config/ExportOptions.plist
@@ -0,0 +1,11 @@
+<?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>method</key><string>app-store-connect</string>
+ <key>destination</key><string>export</string>
+ <key>signingStyle</key><string>automatic</string>
+ <key>manageAppVersionAndBuildNumber</key><false/>
+ <key>uploadSymbols</key><true/>
+</dict>
+</plist>
diff --git a/ios/Resources/Assets.xcassets/AccentColor.colorset/Contents.json b/ios/Resources/Assets.xcassets/AccentColor.colorset/Contents.json
new file mode 100644
index 0000000..a77182f
--- /dev/null
+++ b/ios/Resources/Assets.xcassets/AccentColor.colorset/Contents.json
@@ -0,0 +1,7 @@
+{
+ "colors" : [
+ { "idiom" : "universal",
+ "color" : { "color-space" : "srgb", "components" : { "red" : "0.239", "green" : "0.545", "blue" : "1.000", "alpha" : "1.000" } } }
+ ],
+ "info" : { "author" : "xcode", "version" : 1 }
+}
diff --git a/ios/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json b/ios/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json
new file mode 100644
index 0000000..df8b22a
--- /dev/null
+++ b/ios/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json
@@ -0,0 +1,6 @@
+{
+ "images" : [
+ { "filename" : "icon-1024.png", "idiom" : "universal", "platform" : "ios", "size" : "1024x1024" }
+ ],
+ "info" : { "author" : "xcode", "version" : 1 }
+}
diff --git a/ios/Resources/Assets.xcassets/AppIcon.appiconset/icon-1024.png b/ios/Resources/Assets.xcassets/AppIcon.appiconset/icon-1024.png
new file mode 100644
index 0000000..4854409
Binary files /dev/null and b/ios/Resources/Assets.xcassets/AppIcon.appiconset/icon-1024.png differ
diff --git a/ios/Resources/Assets.xcassets/Contents.json b/ios/Resources/Assets.xcassets/Contents.json
new file mode 100644
index 0000000..46cba7d
--- /dev/null
+++ b/ios/Resources/Assets.xcassets/Contents.json
@@ -0,0 +1 @@
+{ "info" : { "author" : "xcode", "version" : 1 } }
diff --git a/ios/Resources/Assets.xcassets/LaunchBackground.colorset/Contents.json b/ios/Resources/Assets.xcassets/LaunchBackground.colorset/Contents.json
new file mode 100644
index 0000000..4e3610f
--- /dev/null
+++ b/ios/Resources/Assets.xcassets/LaunchBackground.colorset/Contents.json
@@ -0,0 +1,7 @@
+{
+ "colors" : [
+ { "idiom" : "universal",
+ "color" : { "color-space" : "srgb", "components" : { "red" : "0.039", "green" : "0.055", "blue" : "0.102", "alpha" : "1.000" } } }
+ ],
+ "info" : { "author" : "xcode", "version" : 1 }
+}
diff --git a/ios/Resources/PrivacyInfo.xcprivacy b/ios/Resources/PrivacyInfo.xcprivacy
new file mode 100644
index 0000000..e87b65d
--- /dev/null
+++ b/ios/Resources/PrivacyInfo.xcprivacy
@@ -0,0 +1,20 @@
+<?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>NSPrivacyTracking</key><false/>
+ <key>NSPrivacyTrackingDomains</key><array/>
+ <key>NSPrivacyCollectedDataTypes</key><array/>
+ <key>NSPrivacyAccessedAPITypes</key>
+ <array>
+ <dict>
+ <key>NSPrivacyAccessedAPIType</key><string>NSPrivacyAccessedAPICategoryUserDefaults</string>
+ <key>NSPrivacyAccessedAPITypeReasons</key><array><string>CA92.1</string></array>
+ </dict>
+ <dict>
+ <key>NSPrivacyAccessedAPIType</key><string>NSPrivacyAccessedAPICategoryFileTimestamp</string>
+ <key>NSPrivacyAccessedAPITypeReasons</key><array><string>C617.1</string></array>
+ </dict>
+ </array>
+</dict>
+</plist>
diff --git a/ios/Sources/AppModel.swift b/ios/Sources/AppModel.swift
new file mode 100644
index 0000000..2550aa1
--- /dev/null
+++ b/ios/Sources/AppModel.swift
@@ -0,0 +1,300 @@
+import SwiftUI
+import HouseCore
+
+/// A short message that slides in under the status bar.
+struct Banner: Equatable, Identifiable {
+ let id = UUID()
+ var symbol: String
+ var text: String
+ var tint: Color = Theme.accent
+}
+
+/// Where the settings sheet opens.
+enum SettingsRoute: Hashable {
+ case pairing
+ case smartLife
+}
+
+/// Everything the screens share: the floor plan, the devices, the link to the Mac.
+@MainActor
+@Observable
+final class AppModel {
+ @ObservationIgnored let plans = PlanStore()
+ @ObservationIgnored let hub: DeviceHub
+ @ObservationIgnored let sync: SyncClient
+ @ObservationIgnored let web: HomeWeb
+ @ObservationIgnored private var pollTimer: Timer?
+ @ObservationIgnored private var bannerTask: Task<Void, Never>?
+ @ObservationIgnored private var pageReady = false
+ @ObservationIgnored private var active = false
+
+ // Floor plan
+ private(set) var activePlan: String
+ private(set) var hasCustomPlan: Bool
+ private(set) var customPlanName: String?
+ private(set) var linkedDevices = 0
+
+ // Mac sync
+ private(set) var syncStatus: SyncClient.Status
+ private(set) var macName: String?
+ private(set) var lastSync: Date?
+
+ // Smart Life
+ private(set) var smartLifeConnected: Bool
+ private(set) var smartLifeAccount: String
+ /// The User Code entered on the Mac, offered here so it need not be typed again.
+ private(set) var suggestedUserCode = ""
+
+ // Presentation
+ var showSettings = false
+ var settingsPath: [SettingsRoute] = []
+ var showWelcome = false
+ private(set) var banner: Banner?
+
+ init() {
+ let environment = ProcessInfo.processInfo.environment
+ // HOUSE_DATA_DIR (SIMCTL_CHILD_HOUSE_DATA_DIR in the simulator) runs the app on a
+ // throw-away folder: nothing goes to the Keychain or the saved panel state.
+ let sandboxed = !(environment["HOUSE_DATA_DIR"] ?? "").isEmpty
+ let directory = plans.directory
+ func secret(_ name: String) -> SecretStore {
+ sandboxed ? FileSecretStore(url: directory.appendingPathComponent("\(name).json"))
+ : KeychainSecretStore(service: "io.github.0xprobabillity.HouseControl", account: name)
+ }
+ hub = DeviceHub(directory: directory, session: secret("smartlife"))
+ sync = SyncClient(store: secret("sync"))
+ web = HomeWeb(persistent: !sandboxed)
+
+ activePlan = plans.activePlan
+ hasCustomPlan = plans.hasCustomPlan
+ customPlanName = plans.customPlanName
+ syncStatus = sync.status
+ macName = sync.pairing?.name
+ smartLifeConnected = hub.isSmartLifeConnected
+ smartLifeAccount = hub.smartLifeAccount
+ lastSync = UserDefaults.standard.object(forKey: "lastSync") as? Date
+
+ hub.onStale = { [weak self] in self?.poll() }
+ reloadLinks()
+
+ sync.deviceName = UIDevice.current.name
+ sync.planRevision = { [plans] in plans.customPlanRevision }
+ sync.onStatus = { [weak self] in
+ guard let self else { return }
+ self.syncStatus = self.sync.status
+ }
+ sync.onState = { [weak self] in self?.received($0) }
+
+ web.onMessage = { [weak self] in self?.handle($0) }
+ web.load { [weak self] in self?.bootPayload() ?? [:] }
+
+ // HOUSE_SCREEN=settings|pairing|smartlife|welcome opens the app there (screenshots, UI checks).
+ switch environment["HOUSE_SCREEN"] {
+ case "settings": showSettings = true
+ case "pairing": showSettings = true; settingsPath = [.pairing]
+ case "smartlife": showSettings = true; settingsPath = [.smartLife]
+ case "welcome": showWelcome = true
+ case "home": break
+ default: showWelcome = !sandboxed && !UserDefaults.standard.bool(forKey: "welcomed")
+ }
+ }
+
+ // MARK: - Life cycle
+
+ /// The app came to the foreground (true) or left it (false).
+ func setActive(_ on: Bool) {
+ guard on != active else { return }
+ active = on
+ if on {
+ sync.start()
+ startPolling()
+ } else {
+ sync.stop()
+ pollTimer?.invalidate()
+ pollTimer = nil
+ }
+ }
+
+ private func startPolling() {
+ pollTimer?.invalidate()
+ pollTimer = nil
+ guard active, pageReady, hub.canPoll else { return }
+ poll()
+ pollTimer = Timer.scheduledTimer(withTimeInterval: 12, repeats: true) { [weak self] _ in
+ MainActor.assumeIsolated { self?.poll() }
+ }
+ }
+
+ private func poll() {
+ Task { @MainActor in
+ guard let update = await hub.poll() else { return }
+ web.call("applyRemote", update)
+ }
+ }
+
+ // MARK: - Web UI
+
+ private func bootPayload() -> [String: Any] {
+ var boot = plans.bootPayload()
+ boot["smartLife"] = hub.smartLifeInfo
+ if let device = ProcessInfo.processInfo.environment["HOUSE_OPEN_DEVICE"] { boot["openDevice"] = device }
+ return boot
+ }
+
+ private func handle(_ message: [String: Any]) {
+ switch message["type"] as? String {
+ case "ready":
+ pageReady = true
+ web.call("shown") // the camera sweep and the lights coming on, once per load
+ startPolling()
+ case "command":
+ hub.command(message) { [weak self] in self?.web.reply(to: message, $0) }
+ case "haptic":
+ Haptics.shared.play(message["kind"] as? String ?? "light")
+ case "openSettings":
+ settingsPath = []
+ showSettings = true
+ default:
+ break
+ }
+ }
+
+ private func reloadLinks() {
+ hub.setLinks(from: plans.activePlan == "custom" ? plans.customPlan() : nil)
+ linkedDevices = hub.linkedDeviceCount
+ }
+
+ /// Re-reads everything that depends on the plan and shows it.
+ private func reloadHome() {
+ activePlan = plans.activePlan
+ hasCustomPlan = plans.hasCustomPlan
+ customPlanName = plans.customPlanName
+ reloadLinks()
+ pageReady = false
+ web.reload()
+ }
+
+ // MARK: - Floor plans
+
+ func selectPlan(_ plan: String) {
+ guard plan != activePlan else { return }
+ plans.select(plan)
+ reloadHome()
+ }
+
+ /// Takes a plan file picked in Files as this phone's home.
+ func importPlan(from url: URL) throws {
+ let scoped = url.startAccessingSecurityScopedResource()
+ defer { if scoped { url.stopAccessingSecurityScopedResource() } }
+ try plans.importPlan(from: url)
+ reloadHome()
+ show(Banner(symbol: "checkmark.circle.fill", text: "Floor plan imported", tint: Theme.green))
+ }
+
+ func removeCustomPlan() {
+ plans.removeCustom()
+ reloadHome()
+ }
+
+ // MARK: - Mac sync
+
+ /// A `housecontrol://pair?…` link, from the camera, the clipboard or another app.
+ @discardableResult
+ func open(_ url: URL) -> Bool {
+ guard let pairing = SyncPairing(link: url.absoluteString) else { return false }
+ pair(pairing)
+ return true
+ }
+
+ func pair(_ pairing: SyncPairing) {
+ sync.pair(pairing)
+ macName = pairing.name
+ UserDefaults.standard.set(true, forKey: "welcomed")
+ Haptics.shared.play("success")
+ if active { sync.start() }
+ }
+
+ func unpair() {
+ sync.unpair()
+ macName = nil
+ lastSync = nil
+ suggestedUserCode = ""
+ UserDefaults.standard.removeObject(forKey: "lastSync")
+ }
+
+ func syncNow() { sync.refresh() }
+
+ private func received(_ state: SyncState) {
+ macName = state.macName
+ lastSync = Date()
+ UserDefaults.standard.set(lastSync, forKey: "lastSync")
+ suggestedUserCode = state.userCode
+ guard let data = state.plan, (try? PlanStore.validate(data)) != nil else { return }
+ // The first plan from the Mac becomes this phone's home; later ones only replace it
+ // (someone who switched to a demo plan stays there).
+ let first = !plans.hasCustomPlan
+ do {
+ try plans.saveCustom(data: data, select: first || plans.activePlan == "custom")
+ } catch {
+ show(Banner(symbol: "exclamationmark.triangle.fill", text: "Could not save the floor plan", tint: Theme.red))
+ return
+ }
+ reloadHome()
+ Haptics.shared.play("success")
+ show(Banner(symbol: "arrow.triangle.2.circlepath",
+ text: first ? "\(plans.customPlanName ?? "Your home") arrived from \(state.macName)"
+ : "Updated from \(state.macName)"))
+ }
+
+ // MARK: - Smart Life
+
+ func beginLogin(userCode: String) async throws -> (token: String, qrContent: String) {
+ try await hub.beginLogin(userCode: userCode)
+ }
+
+ /// True once the login was confirmed in the Smart Life app.
+ func finishLogin(token: String, userCode: String) async -> Bool {
+ guard await hub.finishLogin(token: token, userCode: userCode) else { return false }
+ smartLifeConnected = hub.isSmartLifeConnected
+ smartLifeAccount = hub.smartLifeAccount
+ sync.showQR(nil)
+ Haptics.shared.play("success")
+ startPolling()
+ return true
+ }
+
+ /// Asks the paired Mac to display the login code; false when it is not connected.
+ func showOnMac(_ qrContent: String?) -> Bool { sync.showQR(qrContent) }
+
+ func signOut() {
+ hub.signOut()
+ smartLifeConnected = false
+ smartLifeAccount = ""
+ pollTimer?.invalidate()
+ pollTimer = nil
+ }
+
+ // MARK: - Welcome, banners
+
+ func finishWelcome(pairing: Bool) {
+ UserDefaults.standard.set(true, forKey: "welcomed")
+ showWelcome = false
+ guard pairing else { return }
+ settingsPath = [.pairing]
+ // One sheet has to be gone before the next can come up.
+ Task { @MainActor in
+ try? await Task.sleep(nanoseconds: 450_000_000)
+ showSettings = true
+ }
+ }
+
+ func show(_ new: Banner) {
+ bannerTask?.cancel()
+ withAnimation(.spring(response: 0.45, dampingFraction: 0.82)) { banner = new }
+ bannerTask = Task { @MainActor in
+ try? await Task.sleep(nanoseconds: 3_200_000_000)
+ guard !Task.isCancelled else { return }
+ withAnimation(.easeIn(duration: 0.25)) { banner = nil }
+ }
+ }
+}
diff --git a/ios/Sources/Haptics.swift b/ios/Sources/Haptics.swift
new file mode 100644
index 0000000..76b7dee
--- /dev/null
+++ b/ios/Sources/Haptics.swift
@@ -0,0 +1,30 @@
+import UIKit
+
+/// The taps you feel while using the panel. The web UI names them; this plays them.
+@MainActor
+final class Haptics {
+ static let shared = Haptics()
+
+ private let selection = UISelectionFeedbackGenerator()
+ private let light = UIImpactFeedbackGenerator(style: .light)
+ private let medium = UIImpactFeedbackGenerator(style: .medium)
+ private let heavy = UIImpactFeedbackGenerator(style: .rigid)
+ private let notification = UINotificationFeedbackGenerator()
+ private var lastTick = Date.distantPast
+
+ func play(_ kind: String) {
+ switch kind {
+ case "tick":
+ // A slider dragged quickly would otherwise buzz instead of tick.
+ guard Date().timeIntervalSince(lastTick) > 0.045 else { return }
+ lastTick = Date()
+ selection.selectionChanged()
+ selection.prepare()
+ case "medium": medium.impactOccurred()
+ case "heavy": heavy.impactOccurred()
+ case "success": notification.notificationOccurred(.success)
+ case "error": notification.notificationOccurred(.error)
+ default: light.impactOccurred()
+ }
+ }
+}
diff --git a/ios/Sources/HomeWeb.swift b/ios/Sources/HomeWeb.swift
new file mode 100644
index 0000000..a0e81cd
--- /dev/null
+++ b/ios/Sources/HomeWeb.swift
@@ -0,0 +1,133 @@
+import SwiftUI
+import WebKit
+import OSLog
+import HouseCore
+
+/// The WKWebView that shows the 3D home and its panel, plus the JSON bridge in both
+/// directions. It is the same web UI the Mac app shows in its menu bar popover.
+@MainActor
+final class HomeWeb: NSObject, WKScriptMessageHandler, WKNavigationDelegate {
+ let webView: WKWebView
+ var onMessage: (([String: Any]) -> Void)?
+ private var boot: () -> [String: Any] = { [:] }
+ /// Set by the page's "ready" message; a load that never gets there is retried.
+ private var ready = false
+ private var retries = 0
+ private var watchdog: DispatchWorkItem?
+
+ /// The built web UI inside the app bundle.
+ static var assetRoot: URL {
+ (Bundle.main.resourceURL ?? URL(fileURLWithPath: ".")).appendingPathComponent("dist")
+ }
+
+ init(persistent: Bool) {
+ let config = WKWebViewConfiguration()
+ config.setURLSchemeHandler(AssetSchemeHandler(root: Self.assetRoot), forURLScheme: AssetSchemeHandler.scheme)
+ config.allowsInlineMediaPlayback = true
+ // A run against a throw-away data folder must not touch the saved panel state either.
+ if !persistent { config.websiteDataStore = .nonPersistent() }
+ webView = WKWebView(frame: .zero, configuration: config)
+ super.init()
+ config.userContentController.add(self, name: "house")
+ webView.navigationDelegate = self
+ webView.isOpaque = false
+ webView.backgroundColor = UIColor(Theme.background)
+ webView.scrollView.backgroundColor = UIColor(Theme.background)
+ webView.scrollView.isScrollEnabled = false
+ webView.scrollView.bounces = false
+ webView.scrollView.contentInsetAdjustmentBehavior = .never
+ webView.allowsLinkPreview = false
+ #if DEBUG
+ webView.isInspectable = true
+ #endif
+ }
+
+ func load(boot: @escaping () -> [String: Any]) {
+ self.boot = boot
+ reload()
+ }
+
+ func reload() {
+ let controller = webView.configuration.userContentController
+ controller.removeAllUserScripts()
+ var payload = boot()
+ payload["mode"] = "panel"
+ payload["platform"] = "ios"
+ controller.addUserScript(WKUserScript(source: "window.__HOUSE_BOOT__ = \(WebJSON.literal(payload));",
+ injectionTime: .atDocumentStart, forMainFrameOnly: true))
+ controller.addUserScript(WKUserScript(source: Self.errorReporter, injectionTime: .atDocumentStart, forMainFrameOnly: true))
+ webView.load(URLRequest(url: URL(string: "\(AssetSchemeHandler.indexURL)?mode=panel")!))
+
+ // Right after a cold boot WebKit's processes can be slow enough to drop the first
+ // load; a page that has not reported in is loaded again, a couple of times at most.
+ ready = false
+ watchdog?.cancel()
+ let check = DispatchWorkItem { [weak self] in
+ guard let self, !self.ready, self.retries < 2 else { return }
+ self.retries += 1
+ self.reload()
+ }
+ watchdog = check
+ DispatchQueue.main.asyncAfter(deadline: .now() + 8, execute: check)
+ }
+
+ /// Script errors in the page end up in the device log (Console.app, `log stream`).
+ private static let errorReporter = """
+ (() => {
+ const tell = (text) => window.webkit.messageHandlers.house.postMessage({ type: 'log', text: String(text) });
+ window.addEventListener('error', (e) => tell(`${e.message} (${(e.filename || '').split('/').pop()}:${e.lineno})`), true);
+ window.addEventListener('unhandledrejection', (e) => tell(`unhandled: ${e.reason && e.reason.message || e.reason}`));
+ })();
+ """
+
+ /// Calls `window.house.<function>(…args)` in the page.
+ func call(_ function: String, _ args: Any...) {
+ webView.evaluateJavaScript(WebJSON.call(function, args), completionHandler: nil)
+ }
+
+ func reply(to message: [String: Any], _ result: Any) {
+ guard let id = message["callId"] as? Int else { return }
+ call("reply", id, result)
+ }
+
+ nonisolated func userContentController(_ controller: WKUserContentController, didReceive message: WKScriptMessage) {
+ MainActor.assumeIsolated {
+ guard let body = message.body as? [String: Any] else { return }
+ if body["type"] as? String == "log" {
+ Logger(subsystem: "io.github.0xprobabillity.HouseControl", category: "web").error("\(body["text"] as? String ?? "", privacy: .public)")
+ return
+ }
+ if body["type"] as? String == "ready" {
+ ready = true
+ retries = 0
+ }
+ onMessage?(body)
+ }
+ }
+
+ nonisolated func webView(_ webView: WKWebView, decidePolicyFor action: WKNavigationAction,
+ decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void) {
+ MainActor.assumeIsolated {
+ // The UI never navigates away; anything external opens in Safari.
+ if let url = action.request.url, let scheme = url.scheme, ["http", "https"].contains(scheme),
+ action.navigationType == .linkActivated {
+ UIApplication.shared.open(url)
+ decisionHandler(.cancel)
+ return
+ }
+ decisionHandler(.allow)
+ }
+ }
+
+ /// iOS may discard the page's process while the app is in the background.
+ nonisolated func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
+ MainActor.assumeIsolated { reload() }
+ }
+}
+
+struct HomeWebView: UIViewRepresentable {
+ let web: HomeWeb
+
+ func makeUIView(context: Context) -> WKWebView { web.webView }
+ func updateUIView(_ view: WKWebView, context: Context) {}
+}
diff --git a/ios/Sources/HouseControlApp.swift b/ios/Sources/HouseControlApp.swift
new file mode 100644
index 0000000..3eddda2
--- /dev/null
+++ b/ios/Sources/HouseControlApp.swift
@@ -0,0 +1,17 @@
+import SwiftUI
+
+@main
+struct HouseControlApp: App {
+ @State private var model = AppModel()
+ @Environment(\.scenePhase) private var scenePhase
+
+ var body: some Scene {
+ WindowGroup {
+ RootView()
+ .environment(model)
+ .onChange(of: scenePhase, initial: true) { _, phase in
+ model.setActive(phase == .active)
+ }
+ }
+ }
+}
diff --git a/ios/Sources/PairingView.swift b/ios/Sources/PairingView.swift
new file mode 100644
index 0000000..213899a
--- /dev/null
+++ b/ios/Sources/PairingView.swift
@@ -0,0 +1,231 @@
+import SwiftUI
+import AVFoundation
+import VisionKit
+import HouseCore
+
+/// Pairs this iPhone with House Control on a Mac: scan the code the Mac shows, or paste
+/// the pairing link copied there (the clipboard travels between your devices by itself).
+struct PairingView: View {
+ @Environment(AppModel.self) private var model
+ @Environment(\.dismiss) private var dismiss
+ @State private var camera: CameraState = .unknown
+ @State private var rejected = false
+ @State private var paired: String?
+
+ private enum CameraState { case unknown, ready, denied, unavailable }
+
+ var body: some View {
+ ScrollView {
+ VStack(spacing: 22) {
+ if let paired {
+ success(paired)
+ } else {
+ steps
+ viewfinder
+ if rejected {
+ Label("That is not a House Control pairing code.", systemImage: "exclamationmark.triangle.fill")
+ .font(.system(size: 14, weight: .medium))
+ .foregroundStyle(Theme.red)
+ .transition(.opacity)
+ }
+ paste
+ }
+ }
+ .padding(.horizontal, 18)
+ .padding(.top, 8)
+ .padding(.bottom, 32)
+ .animation(.spring(response: 0.5, dampingFraction: 0.85), value: paired)
+ .animation(.easeOut(duration: 0.2), value: rejected)
+ }
+ .background(Theme.background)
+ .navigationTitle("Pair with Mac")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbarBackground(Theme.background, for: .navigationBar)
+ .task { await prepareCamera() }
+ // The Mac may also hand the link over directly (AirDrop, Handoff, a tap on the link).
+ .onChange(of: model.macName) { _, name in
+ if let name, paired == nil { paired = name }
+ }
+ }
+
+ private var steps: some View {
+ Card(padding: 16) {
+ VStack(alignment: .leading, spacing: 14) {
+ step(1, "On your Mac, right-click the House Control icon in the menu bar.")
+ step(2, "Choose **Pair iPhone…** — a code appears.")
+ step(3, "Point this iPhone at the code. Both devices need to be on the same Wi-Fi.")
+ }
+ }
+ }
+
+ private func step(_ number: Int, _ text: LocalizedStringKey) -> some View {
+ HStack(alignment: .firstTextBaseline, spacing: 12) {
+ Text("\(number)")
+ .font(.system(size: 13, weight: .bold, design: .rounded))
+ .foregroundStyle(Theme.accent)
+ .frame(width: 24, height: 24)
+ .background(Theme.accent.opacity(0.16), in: Circle())
+ Text(text)
+ .font(.system(size: 15))
+ .foregroundStyle(Theme.text)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+
+ @ViewBuilder
+ private var viewfinder: some View {
+ ZStack {
+ RoundedRectangle(cornerRadius: 28, style: .continuous).fill(Color.black.opacity(0.35))
+ switch camera {
+ case .ready:
+ CodeScanner { accept($0) }
+ .clipShape(RoundedRectangle(cornerRadius: 28, style: .continuous))
+ ViewfinderCorners().stroke(.white.opacity(0.9), style: StrokeStyle(lineWidth: 4, lineCap: .round)).padding(46)
+ case .denied:
+ placeholder("camera.fill", "Camera access is off",
+ "Allow the camera for House Control in Settings, or paste the pairing link below.")
+ case .unavailable:
+ placeholder("qrcode.viewfinder", "No camera here",
+ "Use Copy Pairing Link on the Mac and paste it below.")
+ case .unknown:
+ ProgressView().tint(Theme.muted)
+ }
+ }
+ .frame(height: 300)
+ .overlay(RoundedRectangle(cornerRadius: 28, style: .continuous).strokeBorder(Theme.line))
+ }
+
+ private func placeholder(_ symbol: String, _ title: String, _ detail: String) -> some View {
+ VStack(spacing: 10) {
+ Image(systemName: symbol).font(.system(size: 40, weight: .light)).foregroundStyle(Theme.faint)
+ Text(title).font(.system(size: 16, weight: .semibold)).foregroundStyle(Theme.text)
+ Text(detail)
+ .font(.system(size: 14))
+ .foregroundStyle(Theme.muted)
+ .multilineTextAlignment(.center)
+ .padding(.horizontal, 30)
+ }
+ }
+
+ private var paste: some View {
+ VStack(spacing: 10) {
+ // PasteButton reads the clipboard without the "allow paste" prompt.
+ PasteButton(payloadType: String.self) { strings in
+ Task { @MainActor in accept(strings.first ?? "") }
+ }
+ .labelStyle(.titleAndIcon)
+ .buttonBorderShape(.capsule)
+ .tint(Theme.accent)
+ Text("Or press **Copy Pairing Link** on the Mac and paste it here.")
+ .font(.system(size: 13))
+ .foregroundStyle(Theme.faint)
+ .multilineTextAlignment(.center)
+ }
+ .padding(.top, 4)
+ }
+
+ private func success(_ name: String) -> some View {
+ VStack(spacing: 18) {
+ Image(systemName: "checkmark.circle.fill")
+ .font(.system(size: 72, weight: .medium))
+ .foregroundStyle(Theme.green)
+ .symbolEffect(.bounce, value: paired)
+ .padding(.top, 50)
+ Text("Paired with \(name)")
+ .font(.system(size: 24, weight: .bold))
+ .foregroundStyle(Theme.text)
+ .multilineTextAlignment(.center)
+ Text(statusLine)
+ .font(.system(size: 15))
+ .foregroundStyle(Theme.muted)
+ .multilineTextAlignment(.center)
+ .padding(.horizontal, 20)
+ Button("Done") { model.showSettings = false }
+ .buttonStyle(PrimaryButtonStyle())
+ .padding(.top, 14)
+ }
+ .transition(.scale(scale: 0.92).combined(with: .opacity))
+ }
+
+ private var statusLine: String {
+ switch model.syncStatus {
+ case .connected:
+ return model.hasCustomPlan ? "Your floor plan is here and will follow the Mac from now on."
+ : "Connected. Draw your home in the Mac's editor and it appears here."
+ case .failed(let reason): return reason
+ default: return "Looking for the Mac on this Wi-Fi…"
+ }
+ }
+
+ private func accept(_ text: String) {
+ guard paired == nil else { return }
+ guard let pairing = SyncPairing(link: text) else {
+ rejected = true
+ Haptics.shared.play("error")
+ return
+ }
+ rejected = false
+ model.pair(pairing)
+ paired = pairing.name
+ }
+
+ private func prepareCamera() async {
+ guard DataScannerViewController.isSupported else { camera = .unavailable; return }
+ switch AVCaptureDevice.authorizationStatus(for: .video) {
+ case .authorized: camera = .ready
+ case .notDetermined: camera = await AVCaptureDevice.requestAccess(for: .video) ? .ready : .denied
+ default: camera = .denied
+ }
+ }
+}
+
+/// The four corner brackets drawn over the camera picture.
+private struct ViewfinderCorners: Shape {
+ func path(in rect: CGRect) -> Path {
+ let side = min(rect.width, rect.height)
+ let box = CGRect(x: rect.midX - side / 2, y: rect.midY - side / 2, width: side, height: side)
+ let arm = side * 0.16, radius: CGFloat = 18
+ var path = Path()
+ for (corner, dx, dy) in [(CGPoint(x: box.minX, y: box.minY), 1.0, 1.0), (CGPoint(x: box.maxX, y: box.minY), -1.0, 1.0),
+ (CGPoint(x: box.maxX, y: box.maxY), -1.0, -1.0), (CGPoint(x: box.minX, y: box.maxY), 1.0, -1.0)] {
+ path.move(to: CGPoint(x: corner.x, y: corner.y + dy * arm))
+ path.addLine(to: CGPoint(x: corner.x, y: corner.y + dy * radius))
+ path.addQuadCurve(to: CGPoint(x: corner.x + dx * radius, y: corner.y), control: corner)
+ path.addLine(to: CGPoint(x: corner.x + dx * arm, y: corner.y))
+ }
+ return path
+ }
+}
+
+/// VisionKit's live scanner, limited to QR codes.
+private struct CodeScanner: UIViewControllerRepresentable {
+ let onCode: (String) -> Void
+
+ func makeCoordinator() -> Coordinator { Coordinator(onCode: onCode) }
+
+ func makeUIViewController(context: Context) -> DataScannerViewController {
+ let scanner = DataScannerViewController(recognizedDataTypes: [.barcode(symbologies: [.qr])],
+ qualityLevel: .balanced, recognizesMultipleItems: false,
+ isHighFrameRateTrackingEnabled: false, isHighlightingEnabled: true)
+ scanner.delegate = context.coordinator
+ try? scanner.startScanning()
+ return scanner
+ }
+
+ func updateUIViewController(_ scanner: DataScannerViewController, context: Context) {}
+
+ static func dismantleUIViewController(_ scanner: DataScannerViewController, coordinator: Coordinator) {
+ scanner.stopScanning()
+ }
+
+ final class Coordinator: NSObject, DataScannerViewControllerDelegate {
+ let onCode: (String) -> Void
+ init(onCode: @escaping (String) -> Void) { self.onCode = onCode }
+
+ func dataScanner(_ dataScanner: DataScannerViewController, didAdd addedItems: [RecognizedItem], allItems: [RecognizedItem]) {
+ for case .barcode(let code) in addedItems {
+ if let text = code.payloadStringValue { onCode(text) }
+ }
+ }
+ }
+}
diff --git a/ios/Sources/RootView.swift b/ios/Sources/RootView.swift
new file mode 100644
index 0000000..bd4ebbd
--- /dev/null
+++ b/ios/Sources/RootView.swift
@@ -0,0 +1,49 @@
+import SwiftUI
+
+struct RootView: View {
+ @Environment(AppModel.self) private var model
+
+ var body: some View {
+ @Bindable var model = model
+ ZStack(alignment: .top) {
+ Theme.background.ignoresSafeArea()
+ HomeWebView(web: model.web)
+ .ignoresSafeArea()
+ if let banner = model.banner {
+ BannerView(banner: banner)
+ .padding(.top, 6)
+ .transition(.move(edge: .top).combined(with: .opacity))
+ .zIndex(1)
+ }
+ }
+ .sheet(isPresented: $model.showSettings) { SettingsView() }
+ .sheet(isPresented: $model.showWelcome) { WelcomeView() }
+ .onOpenURL { model.open($0) }
+ .preferredColorScheme(.dark)
+ .tint(Theme.accent)
+ }
+}
+
+private struct BannerView: View {
+ let banner: Banner
+
+ var body: some View {
+ HStack(spacing: 10) {
+ Image(systemName: banner.symbol)
+ .font(.system(size: 15, weight: .semibold))
+ .foregroundStyle(banner.tint)
+ Text(banner.text)
+ .font(.system(size: 14.5, weight: .semibold))
+ .foregroundStyle(Theme.text)
+ .lineLimit(2)
+ }
+ .padding(.horizontal, 16)
+ .padding(.vertical, 12)
+ .background(.ultraThinMaterial, in: Capsule())
+ .overlay(Capsule().strokeBorder(Theme.line))
+ .shadow(color: .black.opacity(0.45), radius: 18, y: 8)
+ .padding(.horizontal, 20)
+ .accessibilityElement(children: .combine)
+ .accessibilityAddTraits(.isStaticText)
+ }
+}
diff --git a/ios/Sources/SettingsView.swift b/ios/Sources/SettingsView.swift
new file mode 100644
index 0000000..665c9b8
--- /dev/null
+++ b/ios/Sources/SettingsView.swift
@@ -0,0 +1,283 @@
+import SwiftUI
+import UniformTypeIdentifiers
+import HouseCore
+
+/// Which home is shown, the link to the Mac and the Smart Life account.
+struct SettingsView: View {
+ @Environment(AppModel.self) private var model
+ @Environment(\.dismiss) private var dismiss
+ @State private var importing = false
+ @State private var problem: String?
+ @State private var confirmUnpair = false
+ @State private var confirmSignOut = false
+
+ var body: some View {
+ @Bindable var model = model
+ NavigationStack(path: $model.settingsPath) {
+ ScrollView {
+ VStack(spacing: 30) {
+ homeSection
+ macSection
+ smartLifeSection
+ aboutSection
+ }
+ .padding(.horizontal, 18)
+ .padding(.top, 8)
+ .padding(.bottom, 32)
+ }
+ .background(Theme.background)
+ .navigationTitle("Settings")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbarBackground(Theme.background, for: .navigationBar)
+ .toolbar {
+ ToolbarItem(placement: .confirmationAction) {
+ Button("Done") { dismiss() }.fontWeight(.semibold)
+ }
+ }
+ .navigationDestination(for: SettingsRoute.self) { route in
+ switch route {
+ case .pairing: PairingView()
+ case .smartLife: SmartLifeView()
+ }
+ }
+ }
+ .presentationBackground(Theme.background)
+ .presentationDragIndicator(.visible)
+ .preferredColorScheme(.dark)
+ .fileImporter(isPresented: $importing, allowedContentTypes: [.json]) { result in
+ do { try model.importPlan(from: try result.get()) }
+ catch { problem = error.localizedDescription }
+ }
+ .alert("Could not open this floor plan", isPresented: Binding(get: { problem != nil }, set: { if !$0 { problem = nil } })) {
+ Button("OK", role: .cancel) {}
+ } message: { Text(problem ?? "") }
+ }
+
+ // MARK: - Home
+
+ private var homeSection: some View {
+ VStack(spacing: 10) {
+ SectionTitle("Home")
+ Card {
+ if model.hasCustomPlan {
+ planRow("custom", name: model.customPlanName ?? "My home", detail: customPlanDetail, symbol: "house.fill", tint: Theme.warm)
+ RowDivider()
+ }
+ planRow("home", name: "Apartment", detail: "Demo · 5 rooms, simulated devices", symbol: "building.2.fill", tint: Theme.accent)
+ RowDivider()
+ planRow("studio", name: "Studio", detail: "Demo · 3 rooms, simulated devices", symbol: "square.split.bottomrightquarter.fill", tint: Theme.accent)
+ }
+ Button { importing = true } label: {
+ Label("Import a floor plan file…", systemImage: "square.and.arrow.down")
+ }
+ .buttonStyle(SecondaryButtonStyle())
+ if !model.hasCustomPlan {
+ footnote("Your own home is drawn in House Control on the Mac and arrives here when you pair the two.")
+ }
+ }
+ }
+
+ private var customPlanDetail: String {
+ let devices = model.linkedDevices == 0 ? "No real devices linked"
+ : "\(model.linkedDevices) real device\(model.linkedDevices == 1 ? "" : "s") linked"
+ return model.activePlan == "custom" ? devices : "Your home"
+ }
+
+ private func planRow(_ id: String, name: String, detail: String, symbol: String, tint: Color) -> some View {
+ Button { model.selectPlan(id) } label: {
+ HStack(spacing: 14) {
+ IconBadge(symbol: symbol, tint: tint)
+ VStack(alignment: .leading, spacing: 2) {
+ Text(name).font(.system(size: 16.5, weight: .semibold)).foregroundStyle(Theme.text)
+ Text(detail).font(.system(size: 13.5)).foregroundStyle(Theme.muted)
+ }
+ Spacer(minLength: 8)
+ Image(systemName: model.activePlan == id ? "checkmark.circle.fill" : "circle")
+ .font(.system(size: 22))
+ .foregroundStyle(model.activePlan == id ? Theme.accent : Theme.faint)
+ .contentTransition(.symbolEffect(.replace))
+ }
+ .padding(.horizontal, 14)
+ .frame(minHeight: 66)
+ }
+ .buttonStyle(RowButtonStyle())
+ .accessibilityAddTraits(model.activePlan == id ? .isSelected : [])
+ }
+
+ // MARK: - Mac
+
+ private var macSection: some View {
+ VStack(spacing: 10) {
+ SectionTitle("Mac")
+ if let name = model.macName {
+ Card {
+ HStack(spacing: 14) {
+ IconBadge(symbol: "laptopcomputer", tint: Theme.accent)
+ VStack(alignment: .leading, spacing: 3) {
+ Text(name).font(.system(size: 16.5, weight: .semibold)).foregroundStyle(Theme.text)
+ HStack(spacing: 7) {
+ StatusDot(color: syncColor, pulsing: syncPulsing)
+ Text(syncText).font(.system(size: 13.5)).foregroundStyle(Theme.muted)
+ }
+ }
+ Spacer(minLength: 0)
+ }
+ .padding(.horizontal, 14)
+ .frame(minHeight: 70)
+ if case .failed(let reason) = model.syncStatus {
+ RowDivider()
+ Text(reason)
+ .font(.system(size: 13.5))
+ .foregroundStyle(Theme.red)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(14)
+ }
+ }
+ HStack(spacing: 10) {
+ Button { model.syncNow() } label: { Label("Sync now", systemImage: "arrow.triangle.2.circlepath") }
+ .buttonStyle(SecondaryButtonStyle())
+ Button { confirmUnpair = true } label: { Text("Unpair") }
+ .buttonStyle(SecondaryButtonStyle(tint: Theme.red))
+ .frame(maxWidth: 120)
+ }
+ .confirmationDialog("Unpair from \(name)?", isPresented: $confirmUnpair, titleVisibility: .visible) {
+ Button("Unpair", role: .destructive) { model.unpair() }
+ } message: {
+ Text("The floor plan stays on this iPhone but no longer follows the Mac.")
+ }
+ footnote("Changes you save in the Mac's editor reach this iPhone while both are on the same Wi-Fi.")
+ } else {
+ Card(padding: 16) {
+ HStack(alignment: .top, spacing: 14) {
+ IconBadge(symbol: "laptopcomputer.and.iphone", tint: Theme.accent)
+ VStack(alignment: .leading, spacing: 4) {
+ Text("Bring your home over").font(.system(size: 16.5, weight: .semibold)).foregroundStyle(Theme.text)
+ Text("Pair once and the floor plan you drew on the Mac — rooms, lamps, device links — shows up here and stays up to date.")
+ .font(.system(size: 14))
+ .foregroundStyle(Theme.muted)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+ }
+ NavigationLink(value: SettingsRoute.pairing) {
+ Label("Pair with Mac", systemImage: "qrcode.viewfinder")
+ }
+ .buttonStyle(PrimaryButtonStyle())
+ }
+ }
+ }
+
+ private var syncColor: Color {
+ switch model.syncStatus {
+ case .connected: Theme.green
+ case .failed: Theme.red
+ default: Theme.warm
+ }
+ }
+
+ private var syncPulsing: Bool {
+ switch model.syncStatus {
+ case .searching, .connecting: true
+ default: false
+ }
+ }
+
+ private var syncText: String {
+ switch model.syncStatus {
+ case .connected: return "Connected · up to date"
+ case .connecting: return "Connecting…"
+ case .failed: return "Not syncing"
+ default:
+ guard let last = model.lastSync else { return "Looking for it on this Wi-Fi…" }
+ return "Last synced \(last.formatted(.relative(presentation: .named)))"
+ }
+ }
+
+ // MARK: - Smart Life
+
+ private var smartLifeSection: some View {
+ VStack(spacing: 10) {
+ SectionTitle("Smart Life")
+ if model.smartLifeConnected {
+ Card {
+ HStack(spacing: 14) {
+ IconBadge(symbol: "checkmark.seal.fill", tint: Theme.green)
+ VStack(alignment: .leading, spacing: 3) {
+ Text(model.smartLifeAccount.isEmpty ? "Signed in" : model.smartLifeAccount)
+ .font(.system(size: 16.5, weight: .semibold)).foregroundStyle(Theme.text)
+ .lineLimit(1)
+ Text(model.linkedDevices == 0 ? "No devices linked in this floor plan"
+ : "Controlling \(model.linkedDevices) device\(model.linkedDevices == 1 ? "" : "s")")
+ .font(.system(size: 13.5)).foregroundStyle(Theme.muted)
+ }
+ Spacer(minLength: 0)
+ }
+ .padding(.horizontal, 14)
+ .frame(minHeight: 70)
+ }
+ Button { confirmSignOut = true } label: { Text("Sign out") }
+ .buttonStyle(SecondaryButtonStyle(tint: Theme.red))
+ .confirmationDialog("Sign out of Smart Life?", isPresented: $confirmSignOut, titleVisibility: .visible) {
+ Button("Sign out", role: .destructive) { model.signOut() }
+ } message: {
+ Text("Lights and air conditioners go back to being simulated on this iPhone.")
+ }
+ } else {
+ Card(padding: 16) {
+ HStack(alignment: .top, spacing: 14) {
+ IconBadge(symbol: "lightbulb.2.fill", tint: Theme.warm)
+ VStack(alignment: .leading, spacing: 4) {
+ Text("Devices are simulated").font(.system(size: 16.5, weight: .semibold)).foregroundStyle(Theme.text)
+ Text("Sign in with your Smart Life or Tuya Smart account and the lamps and air conditioners linked in your floor plan become the real ones.")
+ .font(.system(size: 14))
+ .foregroundStyle(Theme.muted)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+ }
+ NavigationLink(value: SettingsRoute.smartLife) {
+ Label("Connect Smart Life", systemImage: "link")
+ }
+ .buttonStyle(SecondaryButtonStyle())
+ }
+ }
+ }
+
+ // MARK: - About
+
+ private var aboutSection: some View {
+ VStack(spacing: 10) {
+ SectionTitle("About")
+ Card {
+ infoRow("Version", value: version)
+ RowDivider().padding(.leading, -52)
+ infoRow("Privacy", value: "No account, no analytics")
+ }
+ footnote("House Control talks to Tuya's servers to reach your devices, and to your own Mac. Nothing else leaves this iPhone.")
+ }
+ }
+
+ private var version: String {
+ let info = Bundle.main.infoDictionary
+ return "\(info?["CFBundleShortVersionString"] as? String ?? "–") (\(info?["CFBundleVersion"] as? String ?? "–"))"
+ }
+
+ private func infoRow(_ title: String, value: String) -> some View {
+ HStack {
+ Text(title).font(.system(size: 16)).foregroundStyle(Theme.text)
+ Spacer()
+ Text(value).font(.system(size: 15)).foregroundStyle(Theme.muted)
+ }
+ .padding(.horizontal, 16)
+ .frame(minHeight: 52)
+ }
+
+ private func footnote(_ text: String) -> some View {
+ Text(text)
+ .font(.system(size: 13))
+ .foregroundStyle(Theme.faint)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(.horizontal, 6)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+}
diff --git a/ios/Sources/SmartLifeView.swift b/ios/Sources/SmartLifeView.swift
new file mode 100644
index 0000000..bf33b8a
--- /dev/null
+++ b/ios/Sources/SmartLifeView.swift
@@ -0,0 +1,234 @@
+import SwiftUI
+import HouseCore
+
+/// Signs this iPhone in to Smart Life. The login is confirmed by scanning a QR code with
+/// the Smart Life app — which lives on this very phone, so the code has to be shown on
+/// another screen: the paired Mac puts it up by itself.
+struct SmartLifeView: View {
+ @Environment(AppModel.self) private var model
+ @State private var userCode = ""
+ @State private var busy = false
+ @State private var problem: String?
+ @State private var login: Login?
+ @State private var onMac = false
+ @FocusState private var typing: Bool
+
+ private struct Login: Equatable {
+ let token: String
+ let content: String
+ }
+
+ var body: some View {
+ ScrollView {
+ VStack(spacing: 22) {
+ if model.smartLifeConnected {
+ connected
+ } else if let login {
+ code(login)
+ } else {
+ entry
+ }
+ }
+ .padding(.horizontal, 18)
+ .padding(.top, 8)
+ .padding(.bottom, 32)
+ .animation(.spring(response: 0.5, dampingFraction: 0.85), value: login)
+ .animation(.spring(response: 0.5, dampingFraction: 0.85), value: model.smartLifeConnected)
+ }
+ .scrollDismissesKeyboard(.interactively)
+ .background(Theme.background)
+ .navigationTitle("Smart Life")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbarBackground(Theme.background, for: .navigationBar)
+ .onAppear { if userCode.isEmpty { userCode = model.suggestedUserCode } }
+ .onChange(of: model.suggestedUserCode) { _, code in if userCode.isEmpty { userCode = code } }
+ .onDisappear { _ = model.showOnMac(nil) }
+ // Ask every two seconds whether the login was confirmed, for as long as the code is up.
+ .task(id: login) {
+ guard let login else { return }
+ for _ in 0..<150 {
+ try? await Task.sleep(nanoseconds: 2_000_000_000)
+ if Task.isCancelled { return }
+ if await model.finishLogin(token: login.token, userCode: userCode) { return }
+ }
+ self.login = nil
+ problem = "The code expired before it was scanned. Show a new one."
+ }
+ }
+
+ // MARK: - Step 1: the User Code
+
+ private var entry: some View {
+ VStack(spacing: 16) {
+ Card(padding: 16) {
+ VStack(alignment: .leading, spacing: 12) {
+ Text("User Code")
+ .font(.system(size: 13, weight: .semibold))
+ .foregroundStyle(Theme.muted)
+ TextField("", text: $userCode, prompt: Text("From the Smart Life app").foregroundStyle(Theme.faint))
+ .font(.system(size: 20, weight: .medium, design: .monospaced))
+ .foregroundStyle(Theme.text)
+ .textInputAutocapitalization(.never)
+ .autocorrectionDisabled()
+ .submitLabel(.go)
+ .focused($typing)
+ .onSubmit { begin() }
+ .padding(.horizontal, 14)
+ .frame(height: 52)
+ .background(Color.black.opacity(0.3), in: RoundedRectangle(cornerRadius: 14, style: .continuous))
+ .overlay(RoundedRectangle(cornerRadius: 14, style: .continuous).strokeBorder(typing ? Theme.accent : Theme.line))
+ if !model.suggestedUserCode.isEmpty, userCode == model.suggestedUserCode {
+ Label("Filled in from your Mac", systemImage: "laptopcomputer")
+ .font(.system(size: 13))
+ .foregroundStyle(Theme.muted)
+ }
+ }
+ }
+ if let problem {
+ Label(problem, systemImage: "exclamationmark.triangle.fill")
+ .font(.system(size: 14, weight: .medium))
+ .foregroundStyle(Theme.red)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(.horizontal, 6)
+ }
+ Button(action: begin) {
+ if busy { ProgressView().tint(.white) } else { Label("Show sign-in code", systemImage: "qrcode") }
+ }
+ .buttonStyle(PrimaryButtonStyle())
+ .disabled(busy || userCode.trimmingCharacters(in: .whitespaces).isEmpty)
+
+ Card(padding: 16) {
+ VStack(alignment: .leading, spacing: 10) {
+ Label("Where is the User Code?", systemImage: "questionmark.circle")
+ .font(.system(size: 15, weight: .semibold))
+ .foregroundStyle(Theme.text)
+ Text("In the Smart Life (or Tuya Smart) app: **Me → Settings → Account and Security**, at the bottom of the list. No Tuya developer account is needed.")
+ .font(.system(size: 14))
+ .foregroundStyle(Theme.muted)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+ }
+ }
+
+ private func begin() {
+ typing = false
+ busy = true
+ problem = nil
+ Task {
+ defer { busy = false }
+ do {
+ let ticket = try await model.beginLogin(userCode: userCode)
+ login = Login(token: ticket.token, content: ticket.qrContent)
+ onMac = model.showOnMac(ticket.qrContent)
+ } catch {
+ problem = error.localizedDescription
+ }
+ }
+ }
+
+ // MARK: - Step 2: the code
+
+ private func code(_ login: Login) -> some View {
+ VStack(spacing: 18) {
+ if onMac, let mac = model.macName {
+ Card(padding: 16) {
+ HStack(alignment: .top, spacing: 14) {
+ IconBadge(symbol: "laptopcomputer", tint: Theme.green)
+ VStack(alignment: .leading, spacing: 4) {
+ Text("The code is on \(mac)").font(.system(size: 16.5, weight: .semibold)).foregroundStyle(Theme.text)
+ Text("Open Smart Life on this iPhone, tap the scanner on its Home tab and point it at the Mac's screen.")
+ .font(.system(size: 14)).foregroundStyle(Theme.muted)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+ }
+ } else {
+ Card(padding: 16) {
+ HStack(alignment: .top, spacing: 14) {
+ IconBadge(symbol: "qrcode.viewfinder", tint: Theme.warm)
+ VStack(alignment: .leading, spacing: 4) {
+ Text("Scan this with Smart Life").font(.system(size: 16.5, weight: .semibold)).foregroundStyle(Theme.text)
+ Text("The Smart Life app on this iPhone has to scan it, so put the code on another screen: share it to a computer or tablet, or pair with your Mac and it appears there by itself.")
+ .font(.system(size: 14)).foregroundStyle(Theme.muted)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+ }
+ }
+
+ if let image = QRCode.image(for: login.content, scale: 12) {
+ Image(decorative: image, scale: 1)
+ .interpolation(.none)
+ .resizable()
+ .scaledToFit()
+ .padding(18)
+ .frame(width: 250, height: 250)
+ .background(.white, in: RoundedRectangle(cornerRadius: 24, style: .continuous))
+ .accessibilityLabel("Smart Life sign-in code")
+ }
+
+ HStack(spacing: 8) {
+ ProgressView().tint(Theme.muted).controlSize(.small)
+ Text("Waiting for you to confirm in Smart Life…")
+ .font(.system(size: 14)).foregroundStyle(Theme.muted)
+ }
+
+ HStack(spacing: 10) {
+ if let png = QRCode.png(for: login.content, scale: 16) {
+ ShareLink(item: QRImage(png: png), preview: SharePreview("Smart Life sign-in code")) {
+ Label("Share code", systemImage: "square.and.arrow.up")
+ }
+ .buttonStyle(SecondaryButtonStyle())
+ }
+ if !onMac, model.macName != nil {
+ Button { onMac = model.showOnMac(login.content) } label: { Label("Show on Mac", systemImage: "laptopcomputer") }
+ .buttonStyle(SecondaryButtonStyle())
+ }
+ }
+ Button("Cancel") {
+ _ = model.showOnMac(nil)
+ self.login = nil
+ }
+ .font(.system(size: 16, weight: .medium))
+ .foregroundStyle(Theme.muted)
+ .padding(.top, 4)
+ }
+ }
+
+ // MARK: - Done
+
+ private var connected: some View {
+ VStack(spacing: 18) {
+ Image(systemName: "checkmark.seal.fill")
+ .font(.system(size: 72, weight: .medium))
+ .foregroundStyle(Theme.green)
+ .symbolEffect(.bounce, value: model.smartLifeConnected)
+ .padding(.top, 50)
+ Text("Smart Life is connected")
+ .font(.system(size: 24, weight: .bold))
+ .foregroundStyle(Theme.text)
+ Text(model.linkedDevices == 0
+ ? "Link lamps and air conditioners to your devices in the Mac's editor — they start working here as soon as the plan syncs."
+ : "\(model.linkedDevices) device\(model.linkedDevices == 1 ? "" : "s") in your floor plan \(model.linkedDevices == 1 ? "is" : "are") now the real thing.")
+ .font(.system(size: 15))
+ .foregroundStyle(Theme.muted)
+ .multilineTextAlignment(.center)
+ .padding(.horizontal, 20)
+ Button("Done") { model.showSettings = false }
+ .buttonStyle(PrimaryButtonStyle())
+ .padding(.top, 14)
+ }
+ .transition(.scale(scale: 0.92).combined(with: .opacity))
+ }
+}
+
+/// The login code as a PNG, for the share sheet.
+private struct QRImage: Transferable {
+ let png: Data
+
+ static var transferRepresentation: some TransferRepresentation {
+ DataRepresentation(exportedContentType: .png) { $0.png }
+ .suggestedFileName("Smart Life sign-in code.png")
+ }
+}
diff --git a/ios/Sources/Theme.swift b/ios/Sources/Theme.swift
new file mode 100644
index 0000000..4ebb5b4
--- /dev/null
+++ b/ios/Sources/Theme.swift
@@ -0,0 +1,129 @@
+import SwiftUI
+
+/// The palette of the 3D panel, so the native screens read as the same app.
+enum Theme {
+ static let background = Color(red: 0.039, green: 0.055, blue: 0.102)
+ static let raised = Color(red: 0.075, green: 0.094, blue: 0.157)
+ static let surface = Color.white.opacity(0.055)
+ static let surfaceHigh = Color.white.opacity(0.1)
+ static let line = Color.white.opacity(0.085)
+ static let text = Color(red: 0.953, green: 0.961, blue: 0.98)
+ static let muted = Color(red: 0.87, green: 0.9, blue: 0.97).opacity(0.6)
+ static let faint = Color(red: 0.87, green: 0.9, blue: 0.97).opacity(0.36)
+ static let accent = Color(red: 0.239, green: 0.545, blue: 1)
+ static let warm = Color(red: 1, green: 0.706, blue: 0.42)
+ static let green = Color(red: 0.29, green: 0.87, blue: 0.5)
+ static let red = Color(red: 1, green: 0.47, blue: 0.43)
+}
+
+/// A rounded glass panel: the container of every settings group.
+struct Card<Content: View>: View {
+ var padding: CGFloat = 0
+ @ViewBuilder var content: Content
+
+ var body: some View {
+ VStack(spacing: 0) { content }
+ .padding(padding)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(Theme.surface, in: RoundedRectangle(cornerRadius: 22, style: .continuous))
+ .overlay(RoundedRectangle(cornerRadius: 22, style: .continuous).strokeBorder(Theme.line))
+ }
+}
+
+struct SectionTitle: View {
+ let text: String
+ init(_ text: String) { self.text = text }
+
+ var body: some View {
+ Text(text.uppercased())
+ .font(.system(size: 12, weight: .bold))
+ .kerning(1.1)
+ .foregroundStyle(Theme.faint)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(.horizontal, 6)
+ .accessibilityAddTraits(.isHeader)
+ }
+}
+
+/// The rounded square with a symbol that starts a row.
+struct IconBadge: View {
+ let symbol: String
+ var tint: Color = Theme.accent
+ var size: CGFloat = 38
+
+ var body: some View {
+ Image(systemName: symbol)
+ .font(.system(size: size * 0.45, weight: .semibold))
+ .foregroundStyle(tint)
+ .frame(width: size, height: size)
+ .background(tint.opacity(0.16), in: RoundedRectangle(cornerRadius: size * 0.32, style: .continuous))
+ .accessibilityHidden(true)
+ }
+}
+
+struct StatusDot: View {
+ let color: Color
+ var pulsing = false
+ @State private var on = false
+
+ var body: some View {
+ Circle()
+ .fill(color)
+ .frame(width: 8, height: 8)
+ .shadow(color: color.opacity(0.9), radius: 4)
+ .opacity(pulsing && on ? 0.35 : 1)
+ .animation(pulsing ? .easeInOut(duration: 0.9).repeatForever(autoreverses: true) : .default, value: on)
+ .onAppear { on = true }
+ .accessibilityHidden(true)
+ }
+}
+
+struct RowDivider: View {
+ var body: some View {
+ Rectangle().fill(Theme.line).frame(height: 1).padding(.leading, 66)
+ }
+}
+
+/// The blue call to action.
+struct PrimaryButtonStyle: ButtonStyle {
+ @Environment(\.isEnabled) private var enabled
+
+ func makeBody(configuration: Configuration) -> some View {
+ configuration.label
+ .font(.system(size: 17, weight: .semibold))
+ .foregroundStyle(.white)
+ .frame(maxWidth: .infinity, minHeight: 54)
+ .background(
+ LinearGradient(colors: [Color(red: 0.353, green: 0.635, blue: 1), Color(red: 0.184, green: 0.482, blue: 0.949)],
+ startPoint: .top, endPoint: .bottom),
+ in: RoundedRectangle(cornerRadius: 18, style: .continuous))
+ .shadow(color: Theme.accent.opacity(enabled ? 0.45 : 0), radius: 14, y: 8)
+ .opacity(enabled ? 1 : 0.4)
+ .scaleEffect(configuration.isPressed ? 0.97 : 1)
+ .animation(.spring(response: 0.3, dampingFraction: 0.7), value: configuration.isPressed)
+ }
+}
+
+struct SecondaryButtonStyle: ButtonStyle {
+ var tint: Color = Theme.text
+
+ func makeBody(configuration: Configuration) -> some View {
+ configuration.label
+ .font(.system(size: 16, weight: .semibold))
+ .foregroundStyle(tint)
+ .frame(maxWidth: .infinity, minHeight: 50)
+ .background(Theme.surfaceHigh, in: RoundedRectangle(cornerRadius: 16, style: .continuous))
+ .overlay(RoundedRectangle(cornerRadius: 16, style: .continuous).strokeBorder(Theme.line))
+ .scaleEffect(configuration.isPressed ? 0.97 : 1)
+ .animation(.spring(response: 0.3, dampingFraction: 0.7), value: configuration.isPressed)
+ }
+}
+
+/// Rows highlight while pressed, like a list cell.
+struct RowButtonStyle: ButtonStyle {
+ func makeBody(configuration: Configuration) -> some View {
+ configuration.label
+ .contentShape(Rectangle())
+ .background(configuration.isPressed ? Theme.surfaceHigh : .clear)
+ }
+}
diff --git a/ios/Sources/WelcomeView.swift b/ios/Sources/WelcomeView.swift
new file mode 100644
index 0000000..3017c18
--- /dev/null
+++ b/ios/Sources/WelcomeView.swift
@@ -0,0 +1,73 @@
+import SwiftUI
+
+/// Shown once, over the demo home that is already running behind it.
+struct WelcomeView: View {
+ @Environment(AppModel.self) private var model
+
+ var body: some View {
+ VStack(spacing: 0) {
+ Image(systemName: "house.fill")
+ .font(.system(size: 34, weight: .semibold))
+ .foregroundStyle(Color(red: 1, green: 0.95, blue: 0.86))
+ .frame(width: 76, height: 76)
+ .background(
+ LinearGradient(colors: [Color(red: 0.36, green: 0.24, blue: 0.52), Color(red: 0.13, green: 0.16, blue: 0.36), Color(red: 0.05, green: 0.07, blue: 0.16)],
+ startPoint: .top, endPoint: .bottom),
+ in: RoundedRectangle(cornerRadius: 20, style: .continuous))
+ .shadow(color: Theme.warm.opacity(0.45), radius: 22)
+ .padding(.top, 44)
+ .accessibilityHidden(true)
+
+ Text("Welcome to House Control")
+ .font(.system(size: 27, weight: .bold))
+ .foregroundStyle(Theme.text)
+ .multilineTextAlignment(.center)
+ .padding(.top, 20)
+ Text("Your home as a live 3D model, in your pocket.")
+ .font(.system(size: 16))
+ .foregroundStyle(Theme.muted)
+ .multilineTextAlignment(.center)
+ .padding(.top, 6)
+
+ VStack(alignment: .leading, spacing: 26) {
+ feature("hand.tap.fill", Theme.warm, "Tap a lamp, drag to dim",
+ "Lights, colours, air conditioners and scenes, right on the floor plan.")
+ feature("laptopcomputer.and.iphone", Theme.accent, "Drawn on your Mac",
+ "Pair once and your own floor plan arrives here and stays in sync.")
+ feature("lightbulb.2.fill", Theme.green, "Smart Life and Tuya devices",
+ "Or none at all: until you sign in, everything is simulated.")
+ }
+ .padding(.horizontal, 6)
+ .frame(maxHeight: .infinity)
+
+ Button { model.finishWelcome(pairing: true) } label: { Label("Pair with my Mac", systemImage: "qrcode.viewfinder") }
+ .buttonStyle(PrimaryButtonStyle())
+ Button("Explore the demo home") { model.finishWelcome(pairing: false) }
+ .font(.system(size: 16, weight: .semibold))
+ .foregroundStyle(Theme.muted)
+ .frame(minHeight: 50)
+ .padding(.top, 4)
+ }
+ .padding(.horizontal, 24)
+ .padding(.bottom, 10)
+ .presentationDetents([.large])
+ .presentationBackground(Theme.background)
+ .presentationDragIndicator(.visible)
+ .preferredColorScheme(.dark)
+ .interactiveDismissDisabled(false)
+ .onDisappear { UserDefaults.standard.set(true, forKey: "welcomed") }
+ }
+
+ private func feature(_ symbol: String, _ tint: Color, _ title: String, _ detail: String) -> some View {
+ HStack(alignment: .top, spacing: 16) {
+ IconBadge(symbol: symbol, tint: tint, size: 44)
+ VStack(alignment: .leading, spacing: 3) {
+ Text(title).font(.system(size: 17, weight: .semibold)).foregroundStyle(Theme.text)
+ Text(detail)
+ .font(.system(size: 14.5))
+ .foregroundStyle(Theme.muted)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+ }
+}
diff --git a/ios/project.yml b/ios/project.yml
new file mode 100644
index 0000000..0a260c4
--- /dev/null
+++ b/ios/project.yml
@@ -0,0 +1,65 @@
+# The Xcode project is generated from this file: `xcodegen generate` (scripts/build-ios.sh does it).
+name: HouseControl
+options:
+ bundleIdPrefix: io.github.0xprobabillity
+ deploymentTarget:
+ iOS: "17.0"
+ createIntermediateGroups: true
+ generateEmptyDirectories: true
+configFiles:
+ Debug: Config/Base.xcconfig
+ Release: Config/Base.xcconfig
+packages:
+ HouseCore:
+ path: ../core
+targets:
+ HouseControl:
+ type: application
+ platform: iOS
+ sources:
+ - path: Sources
+ - path: Resources
+ # The web UI, built by `npm run build` in ../web; lands in the app as the folder "dist".
+ - path: ../web/dist
+ type: folder
+ buildPhase: resources
+ dependencies:
+ - package: HouseCore
+ info:
+ path: Config/Info.plist
+ properties:
+ CFBundleDisplayName: House Control
+ CFBundleShortVersionString: $(MARKETING_VERSION)
+ CFBundleVersion: $(CURRENT_PROJECT_VERSION)
+ LSApplicationCategoryType: public.app-category.lifestyle
+ UILaunchScreen:
+ UIColorName: LaunchBackground
+ UISupportedInterfaceOrientations: [UIInterfaceOrientationPortrait]
+ UIRequiresFullScreen: true
+ UIUserInterfaceStyle: Dark
+ ITSAppUsesNonExemptEncryption: false
+ NSLocalNetworkUsageDescription: House Control looks for your Mac on this Wi-Fi network to receive the floor plan you made there.
+ NSBonjourServices: [_housecontrol._tcp]
+ NSCameraUsageDescription: The camera reads the pairing code shown by House Control on your Mac.
+ CFBundleURLTypes:
+ - CFBundleURLName: io.github.0xprobabillity.HouseControl.pair
+ CFBundleURLSchemes: [housecontrol]
+ settings:
+ base:
+ PRODUCT_BUNDLE_IDENTIFIER: io.github.0xprobabillity.HouseControl
+ PRODUCT_NAME: HouseControl
+ TARGETED_DEVICE_FAMILY: "1"
+ ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon
+ ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME: AccentColor
+ SWIFT_VERSION: "5.0"
+ ENABLE_USER_SCRIPT_SANDBOXING: YES
+ GENERATE_INFOPLIST_FILE: NO
+schemes:
+ HouseControl:
+ build:
+ targets:
+ HouseControl: all
+ run:
+ config: Debug
+ archive:
+ config: Release
diff --git a/scripts/build-ios.sh b/scripts/build-ios.sh
new file mode 100755
index 0000000..bdde5d1
--- /dev/null
+++ b/scripts/build-ios.sh
@@ -0,0 +1,45 @@
+#!/bin/bash
+# Archives the iPhone app for TestFlight / the App Store.
+# ./scripts/build-ios.sh archive + export a signed .ipa into ios/build/export
+# ./scripts/build-ios.sh --upload …and upload it to App Store Connect
+#
+# Needs: Xcode, xcodegen (brew install xcodegen), your team in ios/Config/Local.xcconfig
+# (DEVELOPMENT_TEAM = …) and an App Store Connect API key:
+# ASC_KEY_ID the key's ID; its file AuthKey_<id>.p8 lives in ~/.appstoreconnect/private_keys
+# ASC_ISSUER_ID the issuer ID shown above the key list in App Store Connect
+# The build number is CURRENT_PROJECT_VERSION in ios/Config/Base.xcconfig: raise it for every upload.
+set -euo pipefail
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+: "${ASC_KEY_ID:?Set ASC_KEY_ID to your App Store Connect API key ID}"
+: "${ASC_ISSUER_ID:?Set ASC_ISSUER_ID to your App Store Connect issuer ID}"
+KEY_FILE="${ASC_KEY_FILE:-$HOME/.appstoreconnect/private_keys/AuthKey_$ASC_KEY_ID.p8}"
+[ -f "$KEY_FILE" ] || { echo "No API key file at $KEY_FILE"; exit 1; }
+AUTH=(-allowProvisioningUpdates -authenticationKeyPath "$KEY_FILE"
+ -authenticationKeyID "$ASC_KEY_ID" -authenticationKeyIssuerID "$ASC_ISSUER_ID")
+
+echo "▸ Building web UI"
+cd "$ROOT/web"
+[ -d node_modules ] || npm install
+npm run build --silent
+
+echo "▸ Archiving"
+cd "$ROOT/ios"
+[ -f Config/Local.xcconfig ] || { echo "Create ios/Config/Local.xcconfig with: DEVELOPMENT_TEAM = <your team id>"; exit 1; }
+xcodegen generate --quiet
+rm -rf build/HouseControl.xcarchive build/export
+xcodebuild archive -project HouseControl.xcodeproj -scheme HouseControl -configuration Release \
+ -destination 'generic/platform=iOS' -archivePath build/HouseControl.xcarchive \
+ -derivedDataPath build/DerivedData "${AUTH[@]}" 2>&1 | grep -E "error|ARCHIVE" || true
+[ -d build/HouseControl.xcarchive ] || { echo "Archive failed"; exit 1; }
+
+echo "▸ Exporting"
+xcodebuild -exportArchive -archivePath build/HouseControl.xcarchive -exportPath build/export \
+ -exportOptionsPlist Config/ExportOptions.plist "${AUTH[@]}" 2>&1 | grep -E "error|EXPORT" || true
+[ -f build/export/HouseControl.ipa ] || { echo "Export failed"; exit 1; }
+echo "✓ ios/build/export/HouseControl.ipa"
+
+if [ "${1:-}" = "--upload" ]; then
+ echo "▸ Uploading to App Store Connect"
+ xcrun altool --upload-app -f build/export/HouseControl.ipa -t ios \
+ --apiKey "$ASC_KEY_ID" --apiIssuer "$ASC_ISSUER_ID" 2>&1 | grep -E "UPLOAD|ERROR|error" || true
+fi
diff --git a/scripts/ios-sim.sh b/scripts/ios-sim.sh
new file mode 100755
index 0000000..b6d7e9a
--- /dev/null
+++ b/scripts/ios-sim.sh
@@ -0,0 +1,27 @@
+#!/bin/bash
+# Builds the iPhone app for the simulator and launches it there.
+# ./scripts/ios-sim.sh build + install + launch on the booted simulator
+# HOUSE_SCREEN=settings ./scripts/ios-sim.sh …opening on a given screen (settings, pairing, smartlife, welcome, home)
+# Any HOUSE_* variable set here is passed on to the app.
+set -euo pipefail
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+DEVICE="${DEVICE:-iPhone 17 Pro}"
+
+if [ -z "${SKIP_WEB:-}" ]; then
+ cd "$ROOT/web"
+ [ -d node_modules ] || npm install
+ npm run build --silent
+fi
+
+cd "$ROOT/ios"
+xcodegen generate --quiet
+xcodebuild -project HouseControl.xcodeproj -scheme HouseControl -configuration Debug \
+ -destination "platform=iOS Simulator,name=$DEVICE" -derivedDataPath build/DerivedData \
+ CODE_SIGN_IDENTITY=- build 2>&1 | grep -E "error|warning: |BUILD" | grep -v appintentsmetadataprocessor || true
+APP="build/DerivedData/Build/Products/Debug-iphonesimulator/HouseControl.app"
+[ -d "$APP" ] || { echo "Build failed"; exit 1; }
+
+xcrun simctl bootstatus "$DEVICE" -b >/dev/null
+xcrun simctl install "$DEVICE" "$APP"
+for name in $(compgen -v | grep '^HOUSE_' || true); do export "SIMCTL_CHILD_$name=${!name}"; done
+xcrun simctl launch --terminate-running-process "$DEVICE" io.github.0xprobabillity.HouseControl
diff --git a/scripts/make-icon.swift b/scripts/make-icon.swift
index 911876b..3c8cb9d 100755
--- a/scripts/make-icon.swift
+++ b/scripts/make-icon.swift
@@ -1,24 +1,34 @@
#!/usr/bin/swift
-// Draws the app icon (a lit house on a night-sky tile) and writes macos/AppIcon.icns
-// plus docs/icon.png. Usage: ./scripts/make-icon.swift
+// Draws the app icon (a lit house on a night-sky tile) and writes macos/AppIcon.icns,
+// docs/icon.png and the iPhone app's icon. Usage: ./scripts/make-icon.swift
import AppKit
let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
-func render(_ pixels: Int) -> Data {
+/// `fullBleed` is the iOS form: the artwork fills the square and the system rounds the corners.
+func render(_ pixels: Int, fullBleed: Bool = false) -> Data {
let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: pixels, pixelsHigh: pixels, bitsPerSample: 8,
- samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB,
- bytesPerRow: 0, bitsPerPixel: 0)!
+ samplesPerPixel: fullBleed ? 3 : 4, hasAlpha: !fullBleed, isPlanar: false, colorSpaceName: .deviceRGB,
+ bytesPerRow: 0, bitsPerPixel: fullBleed ? 32 : 0)!
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep)
let ctx = NSGraphicsContext.current!.cgContext
let s = CGFloat(pixels) / 1024
ctx.scaleBy(x: s, y: s)
+ if fullBleed {
+ // The tile is drawn for the macOS grid; scale it up until it covers the canvas.
+ ctx.translateBy(x: 512, y: 512)
+ ctx.scaleBy(x: 1024 / 824, y: 1024 / 824)
+ ctx.translateBy(x: -512, y: -512)
+ }
// macOS icon grid: an 824 pt tile centred on a 1024 pt canvas.
let tile = CGRect(x: 100, y: 100, width: 824, height: 824)
- let shape = CGPath(roundedRect: tile, cornerWidth: 185, cornerHeight: 185, transform: nil)
- ctx.setShadow(offset: CGSize(width: 0, height: -12), blur: 28, color: NSColor.black.withAlphaComponent(0.35).cgColor)
+ let shape = fullBleed ? CGPath(rect: tile, transform: nil)
+ : CGPath(roundedRect: tile, cornerWidth: 185, cornerHeight: 185, transform: nil)
+ if !fullBleed {
+ ctx.setShadow(offset: CGSize(width: 0, height: -12), blur: 28, color: NSColor.black.withAlphaComponent(0.35).cgColor)
+ }
ctx.addPath(shape)
ctx.setFillColor(NSColor.black.cgColor)
ctx.fillPath()
@@ -44,7 +54,7 @@ func render(_ pixels: Int) -> Data {
ctx.restoreGState()
// The house: SF Symbol, tinted warm white.
- let config = NSImage.SymbolConfiguration(pointSize: 430, weight: .semibold)
+ let config = NSImage.SymbolConfiguration(pointSize: fullBleed ? 380 : 430, weight: .semibold)
if let symbol = NSImage(systemSymbolName: "house.fill", accessibilityDescription: nil)?.withSymbolConfiguration(config) {
let size = symbol.size
let box = CGRect(x: 512 - size.width / 2, y: 512 - size.height / 2 - 6, width: size.width, height: size.height)
@@ -74,4 +84,6 @@ iconutil.arguments = ["-c", "icns", iconset.path, "-o", root.appendingPathCompon
try iconutil.run()
iconutil.waitUntilExit()
try render(256).write(to: root.appendingPathComponent("docs/icon.png"))
-print(iconutil.terminationStatus == 0 ? "✓ macos/AppIcon.icns, docs/icon.png" : "✗ iconutil failed")
+try render(1024, fullBleed: true)
+ .write(to: root.appendingPathComponent("ios/Resources/Assets.xcassets/AppIcon.appiconset/icon-1024.png"))
+print(iconutil.terminationStatus == 0 ? "✓ macos/AppIcon.icns, docs/icon.png, iOS AppIcon" : "✗ iconutil failed")