Meshtastic-Apple/Meshtastic/Views/Connect/Connect.swift
Garth Vander Houwen 69c318a9e1
Message list performance fixes into 2.7.6 (#1475)
* Remove extra want config call when adding a contact

* App badge and unnecessary notification fixes (#1455)

* - Fix for app badge not going to zero if a message arrives while you have that chat open
- Fix for push notifications popping up when a message is received while that chat is open

* Fix for cancelling notifications, works now. And scroll to bottom of conversation upon new message

* Fix: Channels help grammer fix (#1452)

* remove outdated TCP not available on Apple devices (#1450)

* Update initial onboarding view

* remove toggle gating for mac

* Update crash reporting opt out in real time

* Update onboarding text

* Use mDNS text records for node name

* TCP IP and port on the connection screen

* Hide app icon chooser on mac

* Infinite loop hang bugfixes and performance improvements for both `UserMessageList` and `ChannelMessageList` (#1465)

* 2.7.5 Working Changes (#1460)

* Remove extra want config call when adding a contact

* App badge and unnecessary notification fixes (#1455)

* - Fix for app badge not going to zero if a message arrives while you have that chat open
- Fix for push notifications popping up when a message is received while that chat is open

* Fix for cancelling notifications, works now. And scroll to bottom of conversation upon new message

* Fix: Channels help grammer fix (#1452)

* remove outdated TCP not available on Apple devices (#1450)

* Update initial onboarding view

* remove toggle gating for mac

* Update crash reporting opt out in real time

* Update onboarding text

---------

Co-authored-by: Gnome Adrift <646322+gnomeadrift@users.noreply.github.com>
Co-authored-by: Zain Kergaye <62440012+ZainKergaye@users.noreply.github.com>
Co-authored-by: NillRudd <102033730+NillRudd@users.noreply.github.com>

* UserEntity: add mostRecentMessage and unreadMessages with early exit when lastMessage is nil, and fetch 1 row (not N) otherwise

* UserList: replace 5 slow calls to user.messageList with new fast calls

* NodeList: always put the connected node at the top of list (if it matches the node filters)

* ChannelEntity: add faster mostRecentPrivateMessage and unreadMessages which fetch 1 row (not N)

* ChannelList: replace 5 calls to channel.allPrivateMessage with new fast calls

* Fix incorrect appState.unreadDirectMessages calculations

* MyInfoEntity: also fix unreadMessages count here to be fast, and use it for appState.unreadChannelMessages

* UserMessageList: use @FetchRequest to prevent the N^2 behavior that was happening in calls to allPrivateMessages

* Refactor ChannelEntityExtension and MyInfoEntityExtension to be more similar to UserEntityExtension

* Remove SwiftUI-infinite-loop-causing `.id(redrawTapbacksTrigger)` in ChannelMessageList and UserMessageList (duplicate row ids)

* MyInfoEntityExtension: exclude emoji tapbacks (which never get marked as read anyway) from unread message count

* Add SaveChannelLinkData so MessageText and MeshtasticApp can use .sheet(item: ...) and avoid infinite loop hang due to Binding rebuild

* ChannelMessageList and UserMessageList: switch to stable messageId for ForEach SwiftUI row identity

* ChannelMessageList and UserMessageList: debouncedScrollToBottom; keyboardWillShowNotification/keyboardDidShowNotification

* ChannelMessageList and UserMessageList: scroll to bottom onFirstAppear

* ChannelMessageList and UserMessageList: block spurious markMessagesAsRead when this View is not active

---------

Co-authored-by: Garth Vander Houwen <garth@meshtastic.com>
Co-authored-by: Gnome Adrift <646322+gnomeadrift@users.noreply.github.com>
Co-authored-by: Zain Kergaye <62440012+ZainKergaye@users.noreply.github.com>
Co-authored-by: NillRudd <102033730+NillRudd@users.noreply.github.com>

* message-list-performance: revert scrolling changes (#1472)

* Revert e0f0b4a0f7 (ChannelMessageList and UserMessageList: scroll to bottom onFirstAppear)

* Revert "ChannelMessageList and UserMessageList: debouncedScrollToBottom; keyboardWillShowNotification/keyboardDidShowNotification"

This reverts commit ee1a7c4415.

---------

Co-authored-by: Gnome Adrift <646322+gnomeadrift@users.noreply.github.com>
Co-authored-by: Zain Kergaye <62440012+ZainKergaye@users.noreply.github.com>
Co-authored-by: NillRudd <102033730+NillRudd@users.noreply.github.com>
Co-authored-by: Jake-B <jake-b@users.noreply.github.com>
Co-authored-by: Mike Robbins <mrobbins@alum.mit.edu>
2025-10-17 18:16:00 -07:00

549 lines
19 KiB
Swift

//
// Connect.swift
// Meshtastic Apple
//
// Copyright(c) Garth Vander Houwen 8/18/21.
//
import SwiftUI
import MapKit
import CoreData
import CoreLocation
import CoreBluetooth
import OSLog
import TipKit
#if canImport(ActivityKit)
import ActivityKit
#endif
struct Connect: View {
@Environment(\.managedObjectContext) var context
@EnvironmentObject var accessoryManager: AccessoryManager
@Environment(\.colorScheme) private var colorScheme
@State var router: Router
@State var node: NodeInfoEntity?
@State var isUnsetRegion = false
@State var invalidFirmwareVersion = false
@State var liveActivityStarted = false
@State var presentingSwitchPreferredPeripheral = false
@State var selectedPeripherialId = ""
var body: some View {
NavigationStack {
VStack(spacing: 0) {
List {
Section {
if let connectedDevice = accessoryManager.activeConnection?.device,
accessoryManager.isConnected || accessoryManager.isConnecting {
TipView(ConnectionTip(), arrowEdge: .bottom)
.tipViewStyle(PersistentTip())
.tipBackground(colorScheme == .dark ? Color(.systemBackground) : Color(.secondarySystemBackground))
.listRowSeparator(.hidden)
VStack(alignment: .leading) {
HStack {
VStack(alignment: .center) {
CircleText(text: node?.user?.shortName?.addingVariationSelectors ?? "?", color: Color(UIColor(hex: UInt32(node?.num ?? 0))), circleSize: 90)
.padding(.trailing, 5)
if node?.latestDeviceMetrics != nil {
BatteryCompact(batteryLevel: node?.latestDeviceMetrics?.batteryLevel ?? 0, font: .caption, iconFont: .callout, color: .accentColor)
.padding(.trailing, 5)
}
}
.padding(.trailing)
VStack(alignment: .leading) {
if node != nil {
HStack {
Text(connectedDevice.longName?.addingVariationSelectors ?? "Unknown".localized).font(.title2)
if connectedDevice.wasRestored {
Circle()
.fill(Color.gray)
.frame(width: 8, height: 8)
}
}
}
Text("Connection Name").font(.callout)+Text(": \(connectedDevice.name.addingVariationSelectors)")
.font(.callout).foregroundColor(Color.gray)
HStack {
if connectedDevice.transportType == .ble {
// baseline aligned looks better for the signal meter
HStack(alignment: .firstTextBaseline) {
TransportIcon(transportType: connectedDevice.transportType)
connectedDevice.getSignalStrength().map { SignalStrengthIndicator(signalStrength: $0, width: 5, height: 20) }
}
} else if connectedDevice.transportType == .tcp {
// Not baseline aligned looks better for the connection string
HStack {
TransportIcon(transportType: connectedDevice.transportType)
Text("\(connectedDevice.connectionDetails ?? connectedDevice.identifier)")
.foregroundColor(.gray)
}
} else {
TransportIcon(transportType: connectedDevice.transportType)
}
Spacer()
}
.padding(0)
if node != nil {
Text("Firmware Version").font(.callout)+Text(": \(node?.metadata?.firmwareVersion ?? "Unknown".localized)")
.font(.callout).foregroundColor(Color.gray)
}
switch accessoryManager.state {
case .subscribed:
Text("Subscribed").font(.callout)
.foregroundColor(.green)
case .retrievingDatabase(let nodeCount):
HStack {
Image(systemName: "square.stack.3d.down.forward")
.symbolRenderingMode(.multicolor)
.symbolEffect(.variableColor.reversing.cumulative, options: .repeat(20).speed(3))
.foregroundColor(.teal)
if let expectedNodeDBSize = accessoryManager.expectedNodeDBSize {
if UIDevice.current.userInterfaceIdiom == .phone {
VStack(alignment: .leading, spacing: 2.0) {
Text("Retrieving nodes").font(.callout)
.foregroundColor(.teal)
ProgressView(value: Double(nodeCount), total: Double(expectedNodeDBSize))
}
} else {
// iPad/Mac with more space, show progress bar AFTER the label
HStack {
Text("Retrieving nodes").font(.callout)
.foregroundColor(.teal)
ProgressView(value: Double(nodeCount), total: Double(expectedNodeDBSize))
}
}
} else {
Text("Retrieving nodes \(nodeCount)").font(.callout)
.foregroundColor(.teal)
}
}
case .communicating:
HStack {
Image(systemName: "square.stack.3d.down.forward")
.symbolRenderingMode(.multicolor)
.symbolEffect(.variableColor.reversing.cumulative, options: .repeat(20).speed(3))
.foregroundColor(.orange)
Text("Communicating").font(.callout)
.foregroundColor(.orange)
}
case .retrying(let attempt):
HStack {
Image(systemName: "square.stack.3d.down.forward")
.symbolRenderingMode(.multicolor)
.symbolEffect(.variableColor.reversing.cumulative, options: .repeat(20).speed(3))
.foregroundColor(.orange)
Text("Retrying (attempt \(attempt))").font(.callout)
.foregroundColor(.orange)
}
default:
EmptyView()
}
}
}
}
.font(.caption)
.foregroundColor(Color.gray)
.padding([.top])
.swipeActions {
if accessoryManager.allowDisconnect {
Button(role: .destructive) {
Task {
try await accessoryManager.disconnect()
}
} label: {
Label("Disconnect", systemImage: "antenna.radiowaves.left.and.right.slash")
}.disabled(!accessoryManager.allowDisconnect)
}
}
.contextMenu {
if node != nil {
Label("\(String(node!.num))", systemImage: "number")
#if !targetEnvironment(macCatalyst)
if accessoryManager.state == .subscribed {
Button {
if !liveActivityStarted {
#if canImport(ActivityKit)
Logger.services.info("Start live activity.")
startNodeActivity()
#endif
} else {
#if canImport(ActivityKit)
Logger.services.info("Stop live activity.")
endActivity()
#endif
}
} label: {
Label("Mesh Live Activity", systemImage: liveActivityStarted ? "stop" : "play")
}
}
#endif
if accessoryManager.allowDisconnect {
Button(role: .destructive) {
if accessoryManager.allowDisconnect {
Task {
try await accessoryManager.disconnect()
}
}
} label: {
Label("Disconnect", systemImage: "antenna.radiowaves.left.and.right.slash")
}
Button(role: .destructive) {
Task {
do {
try await accessoryManager.sendShutdown(fromUser: node!.user!, toUser: node!.user!)
} catch {
Logger.mesh.error("Shutdown Failed: \(error)")
}
}
} label: {
Label("Power Off", systemImage: "power")
}
}
}
}
if isUnsetRegion {
HStack {
NavigationLink {
LoRaConfig(node: node)
} label: {
Label("Set LoRa Region", systemImage: "globe.americas.fill")
.foregroundColor(.red)
.font(.title)
}
}
}
} else {
if accessoryManager.isConnecting {
HStack {
Image(systemName: "antenna.radiowaves.left.and.right")
.resizable()
.symbolRenderingMode(.hierarchical)
.foregroundColor(.orange)
.frame(width: 60, height: 60)
.padding(.trailing)
switch accessoryManager.state {
case .connecting, .communicating:
Text("Connecting . .")
.font(.title2)
.foregroundColor(.orange)
case .retrievingDatabase:
Text("Retreiving nodes . .")
.font(.callout)
.foregroundColor(.orange)
case .retrying(let attempt):
Text("Connection Attempt \(attempt) of 10")
.font(.callout)
.foregroundColor(.orange)
default:
EmptyView()
}
}
.padding()
.swipeActions {
if accessoryManager.allowDisconnect {
Button(role: .destructive) {
Task {
try await accessoryManager.disconnect()
}
} label: {
Label("Disconnect", systemImage: "antenna.radiowaves.left.and.right.slash")
}.disabled(!accessoryManager.allowDisconnect)
}
}
} else {
if let lastError = accessoryManager.lastConnectionError as? Error {
Text(lastError.localizedDescription).font(.callout).foregroundColor(.red)
}
HStack {
Image("custom.link.slash")
.resizable()
.symbolRenderingMode(.hierarchical)
.foregroundColor(.red)
.frame(width: 60, height: 60)
.padding(.trailing)
Text("No device connected").font(.title3)
}
.padding()
}
}
}
.textCase(nil)
if !(accessoryManager.isConnected || accessoryManager .isConnecting) {
Section(header: HStack {
Text("Available Radios").font(.title)
Spacer()
ManualConnectionMenu()
}) {
ForEach(accessoryManager.devices.sorted(by: { $0.name < $1.name })) { device in
HStack {
if UserDefaults.preferredPeripheralId == device.id.uuidString {
Image(systemName: "star.fill")
.imageScale(.large).foregroundColor(.yellow)
.padding(.trailing)
} else {
Image(systemName: "circle.fill")
.imageScale(.large).foregroundColor(.gray)
.padding(.trailing)
}
VStack(alignment: .leading) {
Button(action: {
if UserDefaults.preferredPeripheralId.count > 0 && device.id.uuidString != UserDefaults.preferredPeripheralId {
if accessoryManager.allowDisconnect {
Task { try await accessoryManager.disconnect() }
}
presentingSwitchPreferredPeripheral = true
selectedPeripherialId = device.id.uuidString
} else {
Task {
try? await accessoryManager.connect(to: device)
}
}
}) {
Text(device.name).font(.callout)
}
// Show transport type
HStack {
TransportIcon(transportType: device.transportType)
if device.transportType == .tcp {
// Show IP and Port
Text("\(device.connectionDetails ?? device.identifier)")
.foregroundColor(.gray)
}
}
}
Spacer()
VStack {
device.getSignalStrength().map { SignalStrengthIndicator(signalStrength: $0) }
}
}.padding([.bottom, .top])
}
}
.confirmationDialog("Connecting to a new radio will clear all app data on the phone.", isPresented: $presentingSwitchPreferredPeripheral, titleVisibility: .visible) {
Button("Connect to new radio?", role: .destructive) {
UserDefaults.preferredPeripheralId = selectedPeripherialId
UserDefaults.preferredPeripheralNum = 0
if accessoryManager.allowDisconnect {
Task { try await accessoryManager.disconnect() }
}
clearCoreDataDatabase(context: context, includeRoutes: false)
clearNotifications()
if let radio = accessoryManager.devices.first(where: { $0.id.uuidString == selectedPeripherialId }) {
Task {
try await accessoryManager.connect(to: radio)
}
}
}
}
.textCase(nil)
}
}
.scrollContentBackground(.hidden)
HStack(alignment: .center) {
Spacer()
#if targetEnvironment(macCatalyst)
// TODO: should this be allowDisconnect?
if accessoryManager.allowDisconnect {
Button(role: .destructive, action: {
if accessoryManager.allowDisconnect {
Task {
try await accessoryManager.disconnect()
}
}
}) {
Label("Disconnect", systemImage: "antenna.radiowaves.left.and.right.slash")
}
.buttonStyle(.bordered)
.buttonBorderShape(.capsule)
.controlSize(.large)
.padding()
}
#endif
Spacer()
}
.padding(.bottom, 10)
}
.background(Color(.systemGroupedBackground))
.navigationTitle("Connect")
.navigationBarItems(
leading: MeshtasticLogo(),
trailing: ZStack {
ConnectedDevice(
deviceConnected: accessoryManager.isConnected,
name: accessoryManager.activeConnection?.device.shortName ?? "?",
mqttProxyConnected: accessoryManager.mqttProxyConnected,
mqttTopic: accessoryManager.mqttManager.topic
)
}
)
}
// TODO: REMOVING VERSION STUFF?
// .sheet(isPresented: $invalidFirmwareVersion, onDismiss: didDismissSheet) {
// InvalidVersion(minimumVersion: accessoryManager.minimumVersion, version: accessoryManager.activeConnection?.device.firmwareVersion ?? "?.?.?")
// .presentationDetents([.large])
// .presentationDragIndicator(.automatic)
// }
// .onChange(of: accessoryManager) {
// invalidFirmwareVersion = self.bleManager.invalidVersion
// }
.onChange(of: self.accessoryManager.state) { _, state in
if let deviceNum = accessoryManager.activeDeviceNum, UserDefaults.preferredPeripheralId.count > 0 && state == .subscribed {
let fetchNodeInfoRequest = NodeInfoEntity.fetchRequest()
fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", deviceNum)
do {
node = try context.fetch(fetchNodeInfoRequest).first
if let loRaConfig = node?.loRaConfig, loRaConfig.regionCode == RegionCodes.unset.rawValue {
isUnsetRegion = true
} else {
isUnsetRegion = false
}
} catch {
Logger.data.error("💥 Error fetching node info: \(error.localizedDescription, privacy: .public)")
}
}
}
}
#if !targetEnvironment(macCatalyst)
#if canImport(ActivityKit)
func startNodeActivity() {
liveActivityStarted = true
// 15 Minutes Local Stats Interval
let timerSeconds = 900
let localStats = node?.telemetries?.filtered(using: NSPredicate(format: "metricsType == 4"))
let mostRecent = localStats?.lastObject as? TelemetryEntity
let activityAttributes = MeshActivityAttributes(nodeNum: Int(node?.num ?? 0), name: node?.user?.longName?.addingVariationSelectors ?? "unknown")
let future = Date(timeIntervalSinceNow: Double(timerSeconds))
let initialContentState = MeshActivityAttributes.ContentState(uptimeSeconds: UInt32(mostRecent?.uptimeSeconds ?? 0),
channelUtilization: mostRecent?.channelUtilization ?? 0.0,
airtime: mostRecent?.airUtilTx ?? 0.0,
sentPackets: UInt32(mostRecent?.numPacketsTx ?? 0),
receivedPackets: UInt32(mostRecent?.numPacketsRx ?? 0),
badReceivedPackets: UInt32(mostRecent?.numPacketsRxBad ?? 0),
dupeReceivedPackets: UInt32(mostRecent?.numRxDupe ?? 0),
packetsSentRelay: UInt32(mostRecent?.numTxRelay ?? 0),
packetsCanceledRelay: UInt32(mostRecent?.numTxRelayCanceled ?? 0),
nodesOnline: UInt32(mostRecent?.numOnlineNodes ?? 0),
totalNodes: UInt32(mostRecent?.numTotalNodes ?? 0),
timerRange: Date.now...future)
let activityContent = ActivityContent(state: initialContentState, staleDate: Calendar.current.date(byAdding: .minute, value: 15, to: Date())!)
do {
let myActivity = try Activity<MeshActivityAttributes>.request(attributes: activityAttributes, content: activityContent,
pushType: nil)
Logger.services.info("Requested MyActivity live activity. ID: \(myActivity.id)")
} catch {
Logger.services.error("Error requesting live activity: \(error.localizedDescription, privacy: .public)")
}
}
func endActivity() {
liveActivityStarted = false
Task {
for activity in Activity<MeshActivityAttributes>.activities where activity.attributes.nodeNum == node?.num ?? 0 {
await activity.end(nil, dismissalPolicy: .immediate)
}
}
}
#endif
#endif
func didDismissSheet() {
// bleManager.disconnectPeripheral(reconnect: false)
Task {
try await accessoryManager.disconnect()
}
}
}
struct TransportIcon: View {
var transportType: TransportType
@EnvironmentObject var accessoryManager: AccessoryManager
var body: some View {
let transport = accessoryManager.transportForType(transportType)
return HStack(spacing: 3.0) {
if let icon = transport?.type.icon {
icon
.font(.title2)
.foregroundColor(transport?.type == .ble ? Color.accentColor : Color.primary)
} else {
Image(systemName: "questionmark")
.font(.title2)
}
Text(transport?.type.rawValue ?? "Unknown".localized)
.font(.title3)
}
}
}
struct ManualConnectionMenu: View {
private struct IterableTransport: Identifiable {
let id: UUID
let icon: Image
let title: String
let transport: any Transport
}
private var transports: [IterableTransport]
init() {
self.transports = AccessoryManager.shared.transports.filter { $0.supportsManualConnection}.map { transport in
IterableTransport(id: UUID(), icon: transport.type.icon, title: transport.type.rawValue, transport: transport)
}
}
@State private var selectedTransport: IterableTransport?
@State private var showAlert: Bool = false
@State private var connectionString = ""
var body: some View {
Menu {
ForEach(transports) { transport in
Button {
self.selectedTransport = transport
self.showAlert = true
} label: {
Label(title: { Text(transport.title)}, icon: { transport.icon })
}
}
} label: {
Label("Manual", systemImage: "plus")
}.alert("Manual connection string", isPresented: $showAlert, presenting: selectedTransport) { selectedTransport in
// This continues to be quick and dirty. A better system is needed.
TextField("Enter hostname[:port]", text: $connectionString)
.keyboardType(.URL)
.autocapitalization(.none)
.disableAutocorrection(true)
.onChange(of: connectionString) { _, newValue in
// Filter to only allow valid characters for hostname/IP:port
let allowedCharacters = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-:")
let filtered = String(newValue.unicodeScalars.filter { allowedCharacters.contains($0) })
if filtered != newValue {
connectionString = filtered
}
}
Button("OK", action: {
if !connectionString.isEmpty {
Task {
try await selectedTransport.transport.manuallyConnect(withConnectionString: connectionString)
}
}
})
}
}
}