Meshtastic-Apple/Meshtastic/Views/Nodes/Helpers/Map/NodeMapSwiftUI.swift

268 lines
8.5 KiB
Swift
Raw Normal View History

2023-09-12 00:02:31 -07:00
//
// NodeMapSwiftUI.swift
// Meshtastic
//
// Copyright(c) Garth Vander Houwen 9/11/23.
//
import SwiftUI
import CoreLocation
import MapKit
struct NodeMapContentSignature: Equatable {
// Used to decide if NodeMapContent needs to be reevaluated.
// Only include fields that are used within NodeMapContent (or approximations like positionCount and lastPositionTime).
let nodeNum: Int64
let positionCount: Int
let lastPositionTime: Date?
let showNodeHistory: Bool
let showRouteLines: Bool
let showConvexHull: Bool
let favorite: Bool
}
private struct NodeMapContentEquatableWrapper<Content: View>: View, Equatable {
// Prevent slow, needless recomputation of NodeMapContent if the NodeMapContentSignature hasn't changed.
let signature: NodeMapContentSignature
@ViewBuilder let content: () -> Content
static func == (lhs: NodeMapContentEquatableWrapper<Content>, rhs: NodeMapContentEquatableWrapper<Content>) -> Bool { lhs.signature == rhs.signature }
var body: some View { content() }
}
2023-09-12 00:02:31 -07:00
struct NodeMapSwiftUI: View {
@Environment(\.managedObjectContext) var context
Transports Interface to Support TCP for all Platforms and Serial on Mac (#1341) * Initial implementation of transports * Initial LogRadio implementation * Fixes for Settings view (caused by debug commenting) * Refinement of the object and actor model * Connect view text and tab updates * Fix mac catalyst and tests * Warning and logging clean-up * In progress commit * Serial Transport and Reconnect draft work * Serial transport and reconnection draft work * Quick fix for BLE - still more work to do * interim commit * More in progress changes * Minor improvements * Pretty good initial implementation * Bump version beyond the app store * Fix for disconnection swipeAction * Tweaks to TCPConnection implementation * Retry for NONCE_ONLY_DB * Revert json string change * Simplified some of the API + "Anti-discovery" * Tweaks for devices leaving the discovery process * Bump version * iOS26 Tweaks * Tweaks and bug fixes * Add link with slash sf symbol * update symbol image on connect view * BLE disconnect handling * Log privacy attributes * Onboarding and minor fixes. * change database to nodes, add emoji to tcp logs * Error handling improvements * More logging emojis * Suppressed unnecessary errors on disconnect * Heartbeat emoji * Add bluetooth symbol * add privacy attributes to [TCP] logs, add custom bluetooth logo * Improve routing logs * Emoji for connect logs * Heartbeat emoji * Add CBCentralManagerScanOptionAllowDuplicatesKey options to central for bluetooth * fix nav errors by switching from observableobject to state * Update connection indicator icon * fix for BLE disconnects * Connection process fixes * More fixes/tweaks to connection process * Strict concurrency * Fix some warnings, remove wifi warning * delete stale keys * interim commit * Update privacy for log, fix wrong space * fix a couple of linting items * Switch to targeted * interim commit * BLE Signal strenth on connect view * Remove BLE RSSI from long press menu * Modem lights * minor spacing tweak * Additional BLE logging and a scanning fix. * Discovery and BLE RSSI improvements * Background suspension * Update isConnected to enable UI during db load * update protobufs * Replace config if statements with switches, Fix unknown module config logging, make dark mode modem circle stroke color white so they are visible * Additional logging cleanup * hast * Set unmessagable to true if the longname has the unmessagable emoji * Connect error handling improvements * Admin popup list icon and activity lights updates * Revert use of .toolbar back to .navigationBarItems * More public logging * Better BLE error handling * Node DB progress meter * minor tweak to activity light interaction timing * Fix comment linting, remove stale keys * Remove stale keys * Easy linting fixes * Two more simple linting fixes * clean up meshtasticapp * More public logging * Replay config * Logging * Fix for unselected node on Settings * Tweak to progress meter based on device idiom * Update protos * Session replay redaction of messages * Serial fix for old devices, and a let statement * Mask text too * Fix typo * BLE poweredOff is now an auto-reconnectable error * Update logging * Fix for peerRemovedPairingInformation * Logging for BLE peripheral:didUpdateValueFor errors. * Fix for inconsistent swipe disconnect behavior * periperal:didUpdateValueFor error handling * Fix for BLEConnection continuation guarding * BLEConnection actor deadlock on disconnect * Heartbeat nonce * Fix for swipe disconnect and task cancellation * Fix for swipe actions not honoring .disabled() * Tell BLETransport when BLEConnection is cancelled * Update navigation logging * Logging updates * Bump version to 2.7.0 * Organize into folders and heartbeat stuff * Minor improvements to manual TCP connection * Auto-connect toggle * Possible BLE bug, still waiting to see in logs * Concurrency tweaks * Concurrency improvements * requestDeviceMetadata fix. fixes remote admin * Minor typo fixes * "All" button for log filters: category and level * More robust continuation handling for BLE * @FetchRequest based ChannelMessageList * Update info.plist and device hardware file * Move auto connect toggle to app settings and debug mode, tint properly with the accent color * Add label to auto connect toggle * Update log for node info received from ourselves over the mesh * Remove unused scrollViewProxy * Update Meshtastic/Views/Onboarding/DeviceOnboarding.swift Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update target for connect view * Properly Set datadog environment * Comment out ble manager * Adjust cyclomatic complexity thresholds in .swiftlint.yml * Linting fixes, delete ble manager * Make session replay debug only --------- Co-authored-by: jake-b <jake-b@users.noreply.github.com> Co-authored-by: jake <jake@jakes-Mac-mini.local> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-08-27 08:09:02 -07:00
@EnvironmentObject var accessoryManager: AccessoryManager
2023-09-18 16:53:02 -07:00
/// Parameters
@ObservedObject var node: NodeInfoEntity
@State var showUserLocation: Bool = false
2023-09-19 17:06:47 -07:00
@State var positions: [PositionEntity] = []
/// Map State User Defaults
@AppStorage("meshMapShowNodeHistory") private var showNodeHistory = false
@AppStorage("meshMapShowRouteLines") private var showRouteLines = false
@AppStorage("enableMapConvexHull") private var showConvexHull = false
2023-10-21 15:33:00 -07:00
@AppStorage("enableMapTraffic") private var showTraffic: Bool = false
@AppStorage("enableMapPointsOfInterest") private var showPointsOfInterest: Bool = false
@AppStorage("mapLayer") private var selectedMapLayer: MapLayer = .hybrid
2023-09-19 17:06:47 -07:00
// Map Configuration
@Namespace var mapScope
@State var mapStyle: MapStyle = MapStyle.hybrid(elevation: .flat, pointsOfInterest: .all, showsTraffic: true)
@State var position = MapCameraPosition.automatic
2024-10-11 18:21:33 -07:00
@State var distance = 10000.0
@State var scene: MKLookAroundScene?
@State var isLookingAround = false
2023-11-17 18:35:31 -08:00
@State var isShowingAltitude = false
@State var isEditingSettings = false
@State var isMeshMap = false
2025-07-22 03:23:43 +00:00
@State var enabledOverlayConfigs: Set<UUID> = Set()
@State private var mapRegion = MKCoordinateRegion.init()
2023-09-20 22:26:21 -07:00
@FetchRequest(sortDescriptors: [NSSortDescriptor(key: "name", ascending: false)],
predicate: NSPredicate(
format: "expire == nil || expire >= %@", Date() as NSDate
), animation: .none)
private var waypoints: FetchedResults<WaypointEntity>
2023-09-12 00:02:31 -07:00
var body: some View {
if node.hasPositions {
2025-07-22 03:23:43 +00:00
mapWithNavigation
} else {
ContentUnavailableView("No Positions", systemImage: "mappin.slash")
}
}
2025-07-22 06:40:43 +00:00
2025-07-22 03:23:43 +00:00
private var mapWithNavigation: some View {
ZStack {
MapReader { _ in
configuredMap
}
}
.navigationBarTitle(String((node.user?.shortName ?? "Unknown".localized) + (" \(node.positions?.count ?? 0) points")), displayMode: .inline)
.navigationBarItems(trailing:
2023-09-14 17:06:38 -07:00
ZStack {
ConnectedDevice(
Transports Interface to Support TCP for all Platforms and Serial on Mac (#1341) * Initial implementation of transports * Initial LogRadio implementation * Fixes for Settings view (caused by debug commenting) * Refinement of the object and actor model * Connect view text and tab updates * Fix mac catalyst and tests * Warning and logging clean-up * In progress commit * Serial Transport and Reconnect draft work * Serial transport and reconnection draft work * Quick fix for BLE - still more work to do * interim commit * More in progress changes * Minor improvements * Pretty good initial implementation * Bump version beyond the app store * Fix for disconnection swipeAction * Tweaks to TCPConnection implementation * Retry for NONCE_ONLY_DB * Revert json string change * Simplified some of the API + "Anti-discovery" * Tweaks for devices leaving the discovery process * Bump version * iOS26 Tweaks * Tweaks and bug fixes * Add link with slash sf symbol * update symbol image on connect view * BLE disconnect handling * Log privacy attributes * Onboarding and minor fixes. * change database to nodes, add emoji to tcp logs * Error handling improvements * More logging emojis * Suppressed unnecessary errors on disconnect * Heartbeat emoji * Add bluetooth symbol * add privacy attributes to [TCP] logs, add custom bluetooth logo * Improve routing logs * Emoji for connect logs * Heartbeat emoji * Add CBCentralManagerScanOptionAllowDuplicatesKey options to central for bluetooth * fix nav errors by switching from observableobject to state * Update connection indicator icon * fix for BLE disconnects * Connection process fixes * More fixes/tweaks to connection process * Strict concurrency * Fix some warnings, remove wifi warning * delete stale keys * interim commit * Update privacy for log, fix wrong space * fix a couple of linting items * Switch to targeted * interim commit * BLE Signal strenth on connect view * Remove BLE RSSI from long press menu * Modem lights * minor spacing tweak * Additional BLE logging and a scanning fix. * Discovery and BLE RSSI improvements * Background suspension * Update isConnected to enable UI during db load * update protobufs * Replace config if statements with switches, Fix unknown module config logging, make dark mode modem circle stroke color white so they are visible * Additional logging cleanup * hast * Set unmessagable to true if the longname has the unmessagable emoji * Connect error handling improvements * Admin popup list icon and activity lights updates * Revert use of .toolbar back to .navigationBarItems * More public logging * Better BLE error handling * Node DB progress meter * minor tweak to activity light interaction timing * Fix comment linting, remove stale keys * Remove stale keys * Easy linting fixes * Two more simple linting fixes * clean up meshtasticapp * More public logging * Replay config * Logging * Fix for unselected node on Settings * Tweak to progress meter based on device idiom * Update protos * Session replay redaction of messages * Serial fix for old devices, and a let statement * Mask text too * Fix typo * BLE poweredOff is now an auto-reconnectable error * Update logging * Fix for peerRemovedPairingInformation * Logging for BLE peripheral:didUpdateValueFor errors. * Fix for inconsistent swipe disconnect behavior * periperal:didUpdateValueFor error handling * Fix for BLEConnection continuation guarding * BLEConnection actor deadlock on disconnect * Heartbeat nonce * Fix for swipe disconnect and task cancellation * Fix for swipe actions not honoring .disabled() * Tell BLETransport when BLEConnection is cancelled * Update navigation logging * Logging updates * Bump version to 2.7.0 * Organize into folders and heartbeat stuff * Minor improvements to manual TCP connection * Auto-connect toggle * Possible BLE bug, still waiting to see in logs * Concurrency tweaks * Concurrency improvements * requestDeviceMetadata fix. fixes remote admin * Minor typo fixes * "All" button for log filters: category and level * More robust continuation handling for BLE * @FetchRequest based ChannelMessageList * Update info.plist and device hardware file * Move auto connect toggle to app settings and debug mode, tint properly with the accent color * Add label to auto connect toggle * Update log for node info received from ourselves over the mesh * Remove unused scrollViewProxy * Update Meshtastic/Views/Onboarding/DeviceOnboarding.swift Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update target for connect view * Properly Set datadog environment * Comment out ble manager * Adjust cyclomatic complexity thresholds in .swiftlint.yml * Linting fixes, delete ble manager * Make session replay debug only --------- Co-authored-by: jake-b <jake-b@users.noreply.github.com> Co-authored-by: jake <jake@jakes-Mac-mini.local> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-08-27 08:09:02 -07:00
deviceConnected: accessoryManager.isConnected,
name: accessoryManager.activeConnection?.device.shortName ?? "?")
2023-09-14 17:06:38 -07:00
})
2025-07-22 03:23:43 +00:00
}
2025-07-22 06:40:43 +00:00
2025-07-22 03:23:43 +00:00
private var configuredMap: some View {
baseMap
.overlay(alignment: .bottom) {
lookAroundView
}
.overlay(alignment: .bottom) {
altitudeView
}
.sheet(isPresented: $isEditingSettings) {
MapSettingsForm(traffic: $showTraffic, pointsOfInterest: $showPointsOfInterest, mapLayer: $selectedMapLayer, meshMap: $isMeshMap, enabledOverlayConfigs: $enabledOverlayConfigs)
}
.onChange(of: selectedMapLayer) { _, newMapLayer in
updateMapStyle(for: newMapLayer)
}
.onChange(of: node) {
handleNodeChange()
}
.onAppear {
handleAppear()
}
.safeAreaInset(edge: .bottom, alignment: .trailing) {
controlButtons
}
.onDisappear {
UIApplication.shared.isIdleTimerDisabled = false
}
}
2025-07-22 06:40:43 +00:00
private var mapContentSignature: NodeMapContentSignature {
let positionCount = node.positions?.count ?? 0
let lastPositionTime = (node.positions?.lastObject as? PositionEntity)?.time
return NodeMapContentSignature(nodeNum: node.num, positionCount: positionCount, lastPositionTime: lastPositionTime, showNodeHistory: showNodeHistory, showRouteLines: showRouteLines, showConvexHull: showConvexHull, favorite: node.favorite)
}
2025-07-22 03:23:43 +00:00
private var baseMap: some View {
NodeMapContentEquatableWrapper(signature: mapContentSignature) {
Map(position: $position, bounds: MapCameraBounds(minimumDistance: 0, maximumDistance: .infinity), scope: mapScope) {
NodeMapContent(node: node)
}
2025-07-22 03:23:43 +00:00
}
.mapScope(mapScope)
.mapStyle(mapStyle)
.mapControls {
MapScaleView(scope: mapScope)
.mapControlVisibility(.visible)
if showUserLocation {
MapUserLocationButton(scope: mapScope)
.mapControlVisibility(.visible)
}
MapPitchToggle(scope: mapScope)
.mapControlVisibility(.visible)
MapCompass(scope: mapScope)
.mapControlVisibility(.visible)
}
.controlSize(.regular)
.transaction { $0.animation = nil }
2025-07-22 03:23:43 +00:00
}
2025-07-22 06:40:43 +00:00
2025-07-22 03:23:43 +00:00
private var lookAroundView: some View {
Group {
if scene != nil && isLookingAround {
LookAroundPreview(initialScene: scene)
.frame(height: UIDevice.current.userInterfaceIdiom == .phone ? 250 : 400)
.clipShape(RoundedRectangle(cornerRadius: 12))
.padding(.horizontal, 20)
}
}
}
2025-07-22 06:40:43 +00:00
2025-07-22 03:23:43 +00:00
private var altitudeView: some View {
Group {
if !isLookingAround && isShowingAltitude {
PositionAltitudeChart(node: node)
.frame(height: UIDevice.current.userInterfaceIdiom == .phone ? 250 : 400)
.clipShape(RoundedRectangle(cornerRadius: 12))
.padding(.horizontal, 20)
}
}
}
2025-07-22 06:40:43 +00:00
2025-07-22 03:23:43 +00:00
private var controlButtons: some View {
HStack {
Button(action: {
withAnimation {
isEditingSettings = !isEditingSettings
}
}) {
Image(systemName: isEditingSettings ? "info.circle.fill" : "info.circle")
.padding(.vertical, 5)
}
.tint(Color(UIColor.secondarySystemBackground))
.foregroundColor(.accentColor)
.buttonStyle(.borderedProminent)
2025-07-22 06:40:43 +00:00
2025-07-22 03:23:43 +00:00
if scene != nil {
Button(action: {
if isShowingAltitude {
isShowingAltitude = false
}
isLookingAround = !isLookingAround
}) {
Image(systemName: isLookingAround ? "binoculars.fill" : "binoculars")
.padding(.vertical, 5)
}
.tint(Color(UIColor.secondarySystemBackground))
.foregroundColor(.accentColor)
.buttonStyle(.borderedProminent)
}
2025-07-22 06:40:43 +00:00
2025-07-22 03:23:43 +00:00
if node.positions?.count ?? 0 > 1 {
Button(action: {
if isLookingAround {
isLookingAround = false
}
isShowingAltitude = !isShowingAltitude
}) {
Image(systemName: isShowingAltitude ? "mountain.2.fill" : "mountain.2")
.padding(.vertical, 5)
}
.tint(Color(UIColor.secondarySystemBackground))
.foregroundColor(.accentColor)
.buttonStyle(.borderedProminent)
}
}
.controlSize(.regular)
.padding(5)
}
2025-07-22 06:40:43 +00:00
2025-07-22 03:23:43 +00:00
private func updateMapStyle(for layer: MapLayer) {
UserDefaults.mapLayer = layer
switch layer {
case .standard:
mapStyle = MapStyle.standard(elevation: .flat, pointsOfInterest: showPointsOfInterest ? .all : .excludingAll, showsTraffic: showTraffic)
case .hybrid:
mapStyle = MapStyle.hybrid(elevation: .flat, pointsOfInterest: showPointsOfInterest ? .all : .excludingAll, showsTraffic: showTraffic)
case .satellite:
mapStyle = MapStyle.imagery(elevation: .flat)
case .offline:
break
}
}
2025-07-22 06:40:43 +00:00
2025-07-22 03:23:43 +00:00
private func handleNodeChange() {
isLookingAround = false
isShowingAltitude = false
let newMostRecent = node.positions?.lastObject as? PositionEntity
if node.positions?.count ?? 0 > 1 {
position = .automatic
} else if let mrCoord = newMostRecent?.coordinate {
position = .camera(MapCamera(centerCoordinate: mrCoord, distance: distance, heading: 0, pitch: 0))
}
if let newMostRecent {
Task {
scene = try? await fetchScene(for: newMostRecent.coordinate)
}
}
}
2025-07-22 06:40:43 +00:00
2025-07-22 03:23:43 +00:00
private func handleAppear() {
UIApplication.shared.isIdleTimerDisabled = true
updateMapStyle(for: selectedMapLayer)
let mostRecent = node.positions?.lastObject as? PositionEntity
if node.positions?.count ?? 0 > 1 {
position = .automatic
} else if let mrCoord = mostRecent?.coordinate {
position = .camera(MapCamera(centerCoordinate: mrCoord, distance: distance, heading: 0, pitch: 0))
}
if scene == nil, let mrCoord = mostRecent?.coordinate {
Task {
scene = try? await fetchScene(for: mrCoord)
}
2023-09-12 00:02:31 -07:00
}
}
2023-10-03 16:37:07 -07:00
/// Get the look around scene
2023-09-14 17:06:38 -07:00
private func fetchScene(for coordinate: CLLocationCoordinate2D) async throws -> MKLookAroundScene? {
let lookAroundScene = MKLookAroundSceneRequest(coordinate: coordinate)
return try await lookAroundScene.scene
2023-09-14 17:06:38 -07:00
}
2023-09-12 00:02:31 -07:00
}