Compass.swift (7841B)
1 // SPDX-License-Identifier: GPL-2.0-only 2 import Foundation 3 import Observation 4 @preconcurrency import CoreLocation 5 import SwiftUI 6 7 /// Watch compass (magnetometer, magnetic heading) and bearing to follow. 8 @MainActor @Observable 9 final class Compass: NSObject, CLLocationManagerDelegate { 10 /// Magnetic heading in degrees (0 = north), nil until the watch provides one. 11 private(set) var heading: Double? 12 /// Accuracy reported by the watch, in degrees (negative = calibration needed). 13 private(set) var accuracy: Double? 14 /// Bearing to follow, set by the diver. 15 var bearing: Double? 16 17 private let manager = CLLocationManager() 18 private var users = 0 19 20 static var isAvailable: Bool { CLLocationManager.headingAvailable() || isDemo } 21 /// Screenshots (`-demo`): simulated fixed heading, the simulator has no compass. 22 static let isDemo = CommandLine.arguments.contains("-demo") 23 24 override init() { 25 super.init() 26 manager.delegate = self 27 manager.headingFilter = 1 28 if Self.isDemo { 29 heading = 237 30 accuracy = 5 31 bearing = 250 32 } 33 } 34 35 /// Several views may ask for it: it runs as long as at least one is shown. 36 func start() { 37 users += 1 38 if users == 1, Self.isAvailable { manager.startUpdatingHeading() } 39 } 40 41 func stop() { 42 users = max(0, users - 1) 43 if users == 0 { manager.stopUpdatingHeading() } 44 } 45 46 func setBearing() { bearing = heading } 47 func clearBearing() { bearing = nil } 48 49 /// Signed offset to the bearing (negative = turn left), in degrees. 50 var offset: Double? { 51 guard let heading, let bearing else { return nil } 52 var d = (bearing - heading).truncatingRemainder(dividingBy: 360) 53 if d > 180 { d -= 360 } 54 if d < -180 { d += 360 } 55 return d 56 } 57 58 static func cardinal(_ degrees: Double) -> String { 59 let names = [String(localized: "N"), String(localized: "NE"), String(localized: "E"), String(localized: "SE"), 60 String(localized: "S"), String(localized: "SW"), String(localized: "W"), String(localized: "NW")] 61 return names[Int(((degrees + 22.5).truncatingRemainder(dividingBy: 360)) / 45) % 8] 62 } 63 64 nonisolated func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) { 65 let value = newHeading.magneticHeading 66 let accuracy = newHeading.headingAccuracy 67 Task { @MainActor in 68 self.heading = value 69 self.accuracy = accuracy 70 } 71 } 72 73 nonisolated func locationManagerShouldDisplayHeadingCalibration(_ manager: CLLocationManager) -> Bool { true } 74 } 75 76 /// Compass rose that turns with the watch; fixed mark at the top; set bearing in orange. 77 struct CompassView: View { 78 @Environment(Compass.self) private var compass 79 var compact = false 80 81 var body: some View { 82 VStack(spacing: 2) { 83 if !Compass.isAvailable { 84 Label("No compass on this watch", systemImage: "location.slash").font(.footnote) 85 } else if let heading = compass.heading { 86 ZStack { 87 Dial(bearing: compass.bearing).rotationEffect(.degrees(-heading)) 88 // Fixed mark: the direction of the watch. 89 Triangle().fill(.red).frame(width: 12, height: 10).offset(y: compact ? -52 : -66) 90 VStack(spacing: 0) { 91 Text("\(Int(heading.rounded()) % 360)°") 92 .font(.system(size: compact ? 26 : 32, weight: .semibold, design: .rounded)) 93 .monospacedDigit() 94 Text(Compass.cardinal(heading)).font(.footnote).foregroundStyle(.secondary) 95 } 96 } 97 .frame(width: compact ? 120 : 150, height: compact ? 120 : 150) 98 if let offset = compass.offset, let bearing = compass.bearing { 99 HStack(spacing: 4) { 100 Image(systemName: abs(offset) < 5 ? "checkmark" : (offset < 0 ? "arrow.left" : "arrow.right")) 101 Text("bearing \(Int(bearing.rounded()) % 360)° · \(Int(abs(offset).rounded()))°") 102 } 103 .font(.footnote.bold()) 104 .foregroundStyle(abs(offset) < 5 ? .green : .orange) 105 } 106 if let accuracy = compass.accuracy, accuracy < 0 || accuracy > 20 { 107 Text("Low accuracy: draw a figure 8 with your wrist").font(.caption2).foregroundStyle(.orange) 108 } 109 } else { 110 ProgressView() 111 Text("Compass…").font(.footnote).foregroundStyle(.secondary) 112 } 113 } 114 .onAppear { compass.start() } 115 .onDisappear { compass.stop() } 116 } 117 } 118 119 private struct Dial: View { 120 let bearing: Double? 121 122 var body: some View { 123 Canvas { context, size in 124 let c = CGPoint(x: size.width / 2, y: size.height / 2) 125 let r = min(size.width, size.height) / 2 - 2 126 for i in stride(from: 0, to: 360, by: 10) { 127 let a = Angle.degrees(Double(i) - 90).radians 128 let long = i % 90 == 0, mid = i % 30 == 0 129 let inner = r - (long ? 12 : mid ? 8 : 4) 130 var tick = Path() 131 tick.move(to: CGPoint(x: c.x + inner * cos(a), y: c.y + inner * sin(a))) 132 tick.addLine(to: CGPoint(x: c.x + r * cos(a), y: c.y + r * sin(a))) 133 context.stroke(tick, with: .color(i == 0 ? .red : .gray), lineWidth: long ? 2.5 : 1) 134 } 135 for (label, deg) in [(String(localized: "N"), 0.0), (String(localized: "E"), 90.0), 136 (String(localized: "S"), 180.0), (String(localized: "W"), 270.0)] { 137 let a = Angle.degrees(deg - 90).radians 138 let p = CGPoint(x: c.x + (r - 22) * cos(a), y: c.y + (r - 22) * sin(a)) 139 context.draw(Text(label).font(.system(size: 11, weight: .bold)).foregroundColor(deg == 0 ? .red : .white), at: p) 140 } 141 if let bearing { 142 let a = Angle.degrees(bearing - 90).radians 143 let p = CGPoint(x: c.x + (r + 1) * cos(a), y: c.y + (r + 1) * sin(a)) 144 context.fill(Path(ellipseIn: CGRect(x: p.x - 5, y: p.y - 5, width: 10, height: 10)), with: .color(.orange)) 145 } 146 } 147 } 148 } 149 150 private struct Triangle: Shape { 151 func path(in rect: CGRect) -> Path { 152 Path { p in 153 p.move(to: CGPoint(x: rect.midX, y: rect.maxY)) 154 p.addLine(to: CGPoint(x: rect.minX, y: rect.minY)) 155 p.addLine(to: CGPoint(x: rect.maxX, y: rect.minY)) 156 p.closeSubpath() 157 } 158 } 159 } 160 161 /// Compass alone, from the home screen (on land or at the surface the touch screen works: the bearing is set by touch). 162 struct CompassScreen: View { 163 @Environment(Compass.self) private var compass 164 165 var body: some View { 166 ScrollView { 167 VStack(spacing: 6) { 168 CompassView() 169 if compass.heading != nil { 170 if compass.bearing == nil { 171 Button("Set bearing") { compass.setBearing() }.tint(.orange) 172 } else { 173 HStack { 174 Button("New bearing") { compass.setBearing() }.tint(.orange) 175 Button("Clear") { compass.clearBearing() } 176 } 177 } 178 } 179 Text("The bearing set here stays displayed during the dive (compass page, two crown clicks).") 180 .font(.caption2).foregroundStyle(.secondary).multilineTextAlignment(.center) 181 } 182 } 183 .navigationTitle("Compass") 184 } 185 }