diff --git a/Meshtastic.xcodeproj/project.pbxproj b/Meshtastic.xcodeproj/project.pbxproj index 0d54f434..14919650 100644 --- a/Meshtastic.xcodeproj/project.pbxproj +++ b/Meshtastic.xcodeproj/project.pbxproj @@ -17,7 +17,7 @@ DD17E5DE277D49D400010EC2 /* storeforward.pb.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD17E5DC277D49D400010EC2 /* storeforward.pb.swift */; }; DD1925B728CDA5A400720036 /* CannedMessagesConfigEnums.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD1925B628CDA5A400720036 /* CannedMessagesConfigEnums.swift */; }; DD1925B928CDA93900720036 /* SerialConfigEnums.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD1925B828CDA93900720036 /* SerialConfigEnums.swift */; }; - DD1BF2F92776FE2E008C8D2F /* MessageList.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD1BF2F82776FE2E008C8D2F /* MessageList.swift */; }; + DD1BF2F92776FE2E008C8D2F /* UserMessageList.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD1BF2F82776FE2E008C8D2F /* UserMessageList.swift */; }; DD2160AF28C5552500C17253 /* MQTTConfig.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD2160AE28C5552500C17253 /* MQTTConfig.swift */; }; DD23A50F26FD1B4400D9B90C /* PeripheralModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD23A50E26FD1B4400D9B90C /* PeripheralModel.swift */; }; DD2553572855B02500E55709 /* LoRaConfig.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD2553562855B02500E55709 /* LoRaConfig.swift */; }; @@ -49,6 +49,7 @@ DD6193792863875F00E59241 /* SerialConfig.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD6193782863875F00E59241 /* SerialConfig.swift */; }; DD73FD1128750779000852D6 /* PositionLog.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD73FD1028750779000852D6 /* PositionLog.swift */; }; DD769E0328D18BF1001A3F05 /* DeviceMetricsLog.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD769E0228D18BF0001A3F05 /* DeviceMetricsLog.swift */; }; + DD798B072915928D005217CD /* ChannelMessageList.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD798B062915928D005217CD /* ChannelMessageList.swift */; }; DD8169F9271F1A6100F4AB02 /* MeshLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD8169F8271F1A6100F4AB02 /* MeshLogger.swift */; }; DD8169FB271F1F3A00F4AB02 /* MeshLog.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD8169FA271F1F3A00F4AB02 /* MeshLog.swift */; }; DD8169FF272476C700F4AB02 /* LogDocument.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD8169FE272476C700F4AB02 /* LogDocument.swift */; }; @@ -129,7 +130,7 @@ DD17E5DC277D49D400010EC2 /* storeforward.pb.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = storeforward.pb.swift; sourceTree = ""; }; DD1925B628CDA5A400720036 /* CannedMessagesConfigEnums.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CannedMessagesConfigEnums.swift; sourceTree = ""; }; DD1925B828CDA93900720036 /* SerialConfigEnums.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SerialConfigEnums.swift; sourceTree = ""; }; - DD1BF2F82776FE2E008C8D2F /* MessageList.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MessageList.swift; sourceTree = ""; }; + DD1BF2F82776FE2E008C8D2F /* UserMessageList.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UserMessageList.swift; sourceTree = ""; }; DD2160AE28C5552500C17253 /* MQTTConfig.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MQTTConfig.swift; sourceTree = ""; }; DD23A50E26FD1B4400D9B90C /* PeripheralModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PeripheralModel.swift; sourceTree = ""; }; DD2553562855B02500E55709 /* LoRaConfig.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LoRaConfig.swift; sourceTree = ""; }; @@ -160,6 +161,7 @@ DD6193782863875F00E59241 /* SerialConfig.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SerialConfig.swift; sourceTree = ""; }; DD73FD1028750779000852D6 /* PositionLog.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PositionLog.swift; sourceTree = ""; }; DD769E0228D18BF0001A3F05 /* DeviceMetricsLog.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeviceMetricsLog.swift; sourceTree = ""; }; + DD798B062915928D005217CD /* ChannelMessageList.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChannelMessageList.swift; sourceTree = ""; }; DD8169F8271F1A6100F4AB02 /* MeshLogger.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeshLogger.swift; sourceTree = ""; }; DD8169FA271F1F3A00F4AB02 /* MeshLog.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeshLog.swift; sourceTree = ""; }; DD8169FE272476C700F4AB02 /* LogDocument.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LogDocument.swift; sourceTree = ""; }; @@ -491,7 +493,8 @@ isa = PBXGroup; children = ( DD882F5C2772E4640005BF05 /* Contacts.swift */, - DD1BF2F82776FE2E008C8D2F /* MessageList.swift */, + DD1BF2F82776FE2E008C8D2F /* UserMessageList.swift */, + DD798B062915928D005217CD /* ChannelMessageList.swift */, ); path = Messages; sourceTree = ""; @@ -700,6 +703,7 @@ DD836AE726F6B38600ABCC23 /* Connect.swift in Sources */, DDAF8C6E26ED19040058C060 /* Extensions.swift in Sources */, DD3501892852FC3B000FC853 /* Settings.swift in Sources */, + DD798B072915928D005217CD /* ChannelMessageList.swift in Sources */, DDA6B2EB28420A7B003E8C16 /* NodeAnnotation.swift in Sources */, DDC2E1A726CEB3400042C5E4 /* LocationHelper.swift in Sources */, DD5394FE276BA0EF00AD86B1 /* PositionEntityExtension.swift in Sources */, @@ -724,7 +728,7 @@ DD6193772862F90F00E59241 /* CannedMessagesConfig.swift in Sources */, DD41582628582E9B009B0E59 /* DeviceConfig.swift in Sources */, DD3CC6B528E33FD100FA9159 /* ShareChannels.swift in Sources */, - DD1BF2F92776FE2E008C8D2F /* MessageList.swift in Sources */, + DD1BF2F92776FE2E008C8D2F /* UserMessageList.swift in Sources */, DD3CC6C228EB9D4900FA9159 /* UpdateCoreData.swift in Sources */, DDB6ABE628B1406100384BA1 /* LoraConfigEnums.swift in Sources */, DDB2CC6E27F3EB47009C5FCC /* telemetry.pb.swift in Sources */, diff --git a/Meshtastic/Helpers/BLEManager.swift b/Meshtastic/Helpers/BLEManager.swift index 0c13dd73..080b3216 100644 --- a/Meshtastic/Helpers/BLEManager.swift +++ b/Meshtastic/Helpers/BLEManager.swift @@ -601,13 +601,16 @@ class BLEManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeriph let fetchedUser = try context?.fetch(fetchBCUserRequest) as! [UserEntity] if fetchedUser.isEmpty { // Save the broadcast user if it does not exist - let bcu: UserEntity = UserEntity(context: context!) - bcu.shortName = "ALL" - bcu.longName = "All - Broadcast" - bcu.hwModel = "UNSET" - bcu.num = Int64(broadcastNodeNum) - bcu.userId = "BROADCASTNODE" - print("💾 Saved the All - Broadcast User") +// let bcu: UserEntity = UserEntity(context: context!) +// bcu.shortName = "ALL" +// bcu.longName = "All - Broadcast" +// bcu.hwModel = "UNSET" +// bcu.num = Int64(broadcastNodeNum) +// bcu.userId = "BROADCASTNODE" +// print("💾 Saved the All - Broadcast User") + } else { + + context!.delete(fetchedUser[0]) } } catch { diff --git a/Meshtastic/Helpers/Extensions.swift b/Meshtastic/Helpers/Extensions.swift index 3ed14763..0c36df3c 100644 --- a/Meshtastic/Helpers/Extensions.swift +++ b/Meshtastic/Helpers/Extensions.swift @@ -68,4 +68,12 @@ extension String { UIGraphicsEndImageContext() return image } + + func camelCaseToWords() -> String { + return unicodeScalars.dropFirst().reduce(String(prefix(1))) { + return CharacterSet.uppercaseLetters.contains($1) + ? $0 + " " + String($1) + : $0 + String($1) + } + } } diff --git a/Meshtastic/Views/Messages/ChannelMessageList.swift b/Meshtastic/Views/Messages/ChannelMessageList.swift new file mode 100644 index 00000000..84a1abb6 --- /dev/null +++ b/Meshtastic/Views/Messages/ChannelMessageList.swift @@ -0,0 +1,342 @@ +// +// UserMessageList.swift +// MeshtasticApple +// +// Created by Garth Vander Houwen on 12/24/21. +// + +import SwiftUI +import CoreData + +struct ChannelMessageList: View { + + @Environment(\.managedObjectContext) var context + @EnvironmentObject var bleManager: BLEManager + @EnvironmentObject var userSettings: UserSettings + + enum Field: Hashable { + case messageText + } + + // Keyboard State + @State var typingMessage: String = "" + @State private var totalBytes = 0 + var maxbytes = 228 + @FocusState var focusedField: Field? + + @ObservedObject var user: UserEntity + @ObservedObject var channel: ChannelEntity + @State var showDeleteMessageAlert = false + @State private var deleteMessageId: Int64 = 0 + @State private var replyMessageId: Int64 = 0 + @State private var sendPositionWithMessage: Bool = false + @State private var refreshId = UUID() + + var body: some View { + NavigationStack { + ScrollViewReader { scrollView in + ScrollView { + LazyVStack { + ForEach( user.messageList ) { (message: MessageEntity) in + if user.num != userSettings.preferredNodeNum { + let currentUser: Bool = (userSettings.preferredNodeNum == message.fromUser?.num ? true : false) + if (user.num == bleManager.broadcastNodeNum || user.num != bleManager.broadcastNodeNum && message.toUser!.num != bleManager.broadcastNodeNum) { + if message.replyID > 0 { + let messageReply = user.messageList.first(where: { $0.messageId == message.replyID }) + HStack { + Text(messageReply?.messagePayload ?? "EMPTY MESSAGE").foregroundColor(.blue).font(.caption2) + .padding(10) + .overlay( + RoundedRectangle(cornerRadius: 18) + .stroke(Color.blue, lineWidth: 0.5) + ) + Image(systemName: "arrowshape.turn.up.left.fill") + .symbolRenderingMode(.hierarchical) + .imageScale(.large).foregroundColor(.blue) + .padding(.trailing) + } + } + HStack (alignment: .top) { + if currentUser { Spacer(minLength:50) } + if !currentUser { + CircleText(text: message.fromUser?.shortName ?? "????", color: currentUser ? .accentColor : Color(.darkGray), circleSize: 44, fontSize: 14) + .padding(.all, 5) + .offset(y: -5) + } + VStack(alignment: currentUser ? .trailing : .leading) { + Text(message.messagePayload ?? "EMPTY MESSAGE") + .padding(10) + .foregroundColor(.white) + .background(currentUser ? Color.blue : Color(.darkGray)) + .cornerRadius(15) + .contextMenu { + VStack{ + Text("Channel: \(message.channel)") + } + Menu("Tapback response") { + ForEach(Tapbacks.allCases) { tb in + Button(action: { + if bleManager.sendMessage(message: tb.emojiString, toUserNum: user.num, isEmoji: true, replyID: message.messageId) { + print("Sent \(tb.emojiString) Tapback") + self.context.refresh(user, mergeChanges: true) + } else { print("\(tb.emojiString) Tapback Failed") } + + }) { + Text(tb.description) + let image = tb.emojiString.image() + Image(uiImage: image!) + } + } + } + Button(action: { + self.replyMessageId = message.messageId + self.focusedField = .messageText + print("I want to reply to \(message.messageId)") + }) { + Text("Reply") + Image(systemName: "arrowshape.turn.up.left.2.fill") + } + Button(action: { + UIPasteboard.general.string = message.messagePayload + }) { + Text("Copy") + Image(systemName: "doc.on.doc") + } + Menu("Message Details") { + VStack { + let messageDate = Date(timeIntervalSince1970: TimeInterval(message.messageTimestamp)) + Text("Date \(messageDate, style: .date) \(messageDate.formattedDate(format: "h:mm:ss a"))").font(.caption2).foregroundColor(.gray) + } + if currentUser && message.receivedACK { + VStack { + Text("Received Ack \(message.receivedACK ? "✔️" : "")") + } + } else if currentUser && message.ackError == 0 { + // Empty Error + Text("Waiting. . .") + } else if currentUser && message.ackError > 0 { + let ackErrorVal = RoutingError(rawValue: Int(message.ackError)) + Text("\(ackErrorVal?.display ?? "No Error" )").fixedSize(horizontal: false, vertical: true) + } + if currentUser { + VStack { + let ackDate = Date(timeIntervalSince1970: TimeInterval(message.ackTimestamp)) + let sixMonthsAgo = Calendar.current.date(byAdding: .month, value: -6, to: Date()) + if ackDate >= sixMonthsAgo! { + Text((ackDate.formattedDate(format: "h:mm:ss a"))).font(.caption2).foregroundColor(.gray) + } else { + Text("Unknown Age").font(.caption2).foregroundColor(.gray) + } + } + } + if message.ackSNR != 0 { + VStack { + Text("Ack SNR \(String(message.ackSNR))") + .font(.caption2) + .foregroundColor(.gray) + } + } + } + Divider() + Button(role: .destructive, action: { + self.showDeleteMessageAlert = true + self.deleteMessageId = message.messageId + print(deleteMessageId) + }) { + Text("Delete") + Image(systemName: "trash") + } + } + + let tapbacks = message.value(forKey: "tapbacks") as! [MessageEntity] + if tapbacks.count > 0 { + VStack (alignment: .trailing) { + HStack { + ForEach( tapbacks ) { (tapback: MessageEntity) in + VStack { + let image = tapback.messagePayload!.image(fontSize: 20) + Image(uiImage: image!).font(.caption) + Text("\(tapback.fromUser?.shortName ?? "????")") + .font(.caption2) + .foregroundColor(.gray) + .fixedSize() + .padding(.bottom, 1) + } + } + } + .padding(10) + .overlay( + RoundedRectangle(cornerRadius: 18) + .stroke(Color.gray, lineWidth: 1) + ) + } + } + HStack { + if currentUser && message.receivedACK { + // Ack Received + Text("Acknowledged").font(.caption2).foregroundColor(.gray) + } else if currentUser && message.ackError == 0 { + // Empty Error + Text("Waiting to be acknowledged. . .").font(.caption2).foregroundColor(.orange) + } else if currentUser && message.ackError > 0 { + let ackErrorVal = RoutingError(rawValue: Int(message.ackError)) + Text("\(ackErrorVal?.display ?? "No Error" )").fixedSize(horizontal: false, vertical: true) + .font(.caption2).foregroundColor(.red) + } + } + } + .padding(.bottom) + .id(user.messageList.firstIndex(of: message)) + if !currentUser { + Spacer(minLength:50) + } + } + .padding([.leading, .trailing]) + .frame(maxWidth: .infinity) + .id(message.messageId) + .alert(isPresented: $showDeleteMessageAlert) { + Alert(title: Text("Are you sure you want to delete this message?"), message: Text("This action is permanent."), primaryButton: .destructive(Text("Delete")) { + print("OK button tapped") + if deleteMessageId > 0 { + let message = user.messageList.first(where: { $0.messageId == deleteMessageId }) + context.delete(message!) + do { + try context.save() + deleteMessageId = 0 + } catch { + print("Failed to delete message \(deleteMessageId)") + } + } + }, secondaryButton: .cancel()) + } + } + } + } + } + } + .padding([.top]) + .scrollDismissesKeyboard(.immediately) + .onAppear(perform: { + self.bleManager.context = context + refreshId = UUID() + if user.messageList.count > 0 { + scrollView.scrollTo(user.messageList.last!.messageId) + } + }) + .onChange(of: user.messageList, perform: { messages in + refreshId = UUID() + if user.messageList.count > 0 { + scrollView.scrollTo(user.messageList.last!.messageId) + } + }) + } + HStack(alignment: .top) { + + ZStack { + let kbType = UIKeyboardType(rawValue: UserDefaults.standard.object(forKey: "keyboardType") as? Int ?? 0) + TextField("Message", text: $typingMessage, axis: .vertical) + .onChange(of: typingMessage, perform: { value in + totalBytes = value.utf8.count + // Only mess with the value if it is too big + if totalBytes > maxbytes { + let firstNBytes = Data(typingMessage.utf8.prefix(maxbytes)) + if let maxBytesString = String(data: firstNBytes, encoding: String.Encoding.utf8) { + // Set the message back to the last place where it was the right size + typingMessage = maxBytesString + } else { + print("not a valid UTF-8 sequence") + } + } + }) + .keyboardType(kbType!) + .toolbar { + ToolbarItemGroup(placement: .keyboard) { + Button("Dismiss Keyboard") { + focusedField = nil + } + .font(.subheadline) + Spacer() + Button { + let userLongName = bleManager.connectedPeripheral != nil ? bleManager.connectedPeripheral.longName : "Unknown" + sendPositionWithMessage = true + if user.num == bleManager.broadcastNodeNum { + + if userSettings.meshtasticUsername.count > 0 { + + typingMessage = "📍 " + userSettings.meshtasticUsername + " has shared their position with the mesh from node " + userLongName + } else { + + typingMessage = "📍 " + userLongName + " has shared their position with the mesh." + } + + } else { + + if userSettings.meshtasticUsername.count > 0 { + + typingMessage = "📍 " + userSettings.meshtasticUsername + " has shared their position with you from node " + userLongName + + } else { + + typingMessage = "📍 " + userLongName + " has shared their position with you." + } + } + } label: { + Image(systemName: "mappin.and.ellipse") + .symbolRenderingMode(.hierarchical) + .imageScale(.large).foregroundColor(.accentColor) + } + + ProgressView("Bytes: \(totalBytes) / \(maxbytes)", value: Double(totalBytes), total: Double(maxbytes)) + .frame(width: 130) + .padding(5) + .font(.subheadline) + .accentColor(.accentColor) + } + } + .padding(.horizontal, 8) + .focused($focusedField, equals: .messageText) + .multilineTextAlignment(.leading) + .frame(minHeight: 50) + + Text(typingMessage).opacity(0).padding(.all, 0) + + } + .overlay(RoundedRectangle(cornerRadius: 20).stroke(.tertiary, lineWidth: 1)) + .padding(.bottom, 15) + Button(action: { + if bleManager.sendMessage(message: typingMessage, toUserNum: user.num, isEmoji: false, replyID: replyMessageId) { + typingMessage = "" + focusedField = nil + replyMessageId = 0 + if sendPositionWithMessage { + if bleManager.sendLocation(destNum: user.num, wantAck: true) { + print("Location Sent") + } + } + } + }) { + Image(systemName: "arrow.up.circle.fill").font(.largeTitle).foregroundColor(.blue) + } + } + .padding(.all, 15) + } + .navigationViewStyle(.stack) + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .principal) { + HStack { + CircleText(text: user.shortName ?? "???", color: .blue, circleSize: 44, fontSize: 14).fixedSize() + Text(user.longName ?? "Unknown").font(.headline) + } + } + ToolbarItem(placement: .navigationBarTrailing) { + ZStack { + ConnectedDevice( + bluetoothOn: bleManager.isSwitchedOn, + deviceConnected: bleManager.connectedPeripheral != nil, + name: (bleManager.connectedPeripheral != nil) ? bleManager.connectedPeripheral.shortName : "????") + } + } + } + } +} diff --git a/Meshtastic/Views/Messages/Contacts.swift b/Meshtastic/Views/Messages/Contacts.swift index 6f126c20..62273ebd 100644 --- a/Meshtastic/Views/Messages/Contacts.swift +++ b/Meshtastic/Views/Messages/Contacts.swift @@ -6,6 +6,7 @@ // import SwiftUI +import CoreData struct Contacts: View { @@ -18,13 +19,7 @@ struct Contacts: View { animation: .default) private var users: FetchedResults - private var prefferedNode: NodeInfoEntity? - - @FetchRequest( - sortDescriptors: [NSSortDescriptor(key: "num", ascending: true)], - animation: .default) - - private var nodes: FetchedResults + @State var node: NodeInfoEntity? = nil @State private var selection: UserEntity? = nil // Nothing selected by default. @@ -33,10 +28,33 @@ struct Contacts: View { NavigationSplitView { List { + Section(header: Text("Channels")) { + // Display Contacts for the rest of the non admin channels + if node != nil { + ForEach(node!.myInfo!.channels?.array as! [ChannelEntity], id: \.self) { (channel: ChannelEntity) in + if channel.name?.lowercased() ?? "" != "admin" && channel.name?.lowercased() ?? "" != "gpio" { + HStack { + VStack(alignment: .leading) { + HStack { + CircleText(text: String(channel.index), color: Color.blue, circleSize: 52, fontSize: 32) + .padding(.trailing, 5) + VStack { + Text(channel.name?.camelCaseToWords() ?? "Channel \(channel.index)").font(.headline) + } + .frame(maxWidth: .infinity, alignment: .leading) + } + } + } + } + } + .padding(.top, 10) + .padding(.bottom, 10) + } + } Section(header: Text("Direct Messages")) { ForEach(users) { (user: UserEntity) in if user.num != bleManager.userSettings?.preferredNodeNum ?? 0 { - NavigationLink(destination: MessageList(user: user)) { + NavigationLink(destination: UserMessageList(user: user)) { let mostRecent = user.num == bleManager.broadcastNodeNum ? user.messageList.last : user.messageList.last(where: { $0.toUser?.num ?? 0 != bleManager.broadcastNodeNum }) let lastMessageTime = Date(timeIntervalSince1970: TimeInterval(Int64((mostRecent?.messageTimestamp ?? 0 )))) let lastMessageDay = Calendar.current.dateComponents([.day], from: lastMessageTime).day ?? 0 @@ -84,12 +102,11 @@ struct Contacts: View { } } } + .padding(.top, 10) + .padding(.bottom, 10) } } } - Section(header: Text("Private Channels")) { - // Display Contacts for the rest of the non admin channels - } } .tint(Color(UIColor.systemGray)) .navigationSplitViewStyle(.automatic) @@ -98,10 +115,33 @@ struct Contacts: View { .navigationBarItems(leading: MeshtasticLogo() ) + .onAppear { + self.bleManager.userSettings = userSettings + self.bleManager.context = context + + if userSettings.preferredNodeNum > 0 { + + let fetchNodeInfoRequest: NSFetchRequest = NSFetchRequest.init(entityName: "NodeInfoEntity") + fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", Int64(userSettings.preferredNodeNum)) + + do { + + let fetchedNode = try context.fetch(fetchNodeInfoRequest) as! [NodeInfoEntity] + // Found a node, check it for a region + if !fetchedNode.isEmpty { + node = fetchedNode[0] + + } + } catch { + + } + } + + } } detail: { if let user = selection { - MessageList(user:user) + UserMessageList(user:user) } else { Text("Select a user") diff --git a/Meshtastic/Views/Messages/MessageList.swift b/Meshtastic/Views/Messages/UserMessageList.swift similarity index 94% rename from Meshtastic/Views/Messages/MessageList.swift rename to Meshtastic/Views/Messages/UserMessageList.swift index b583aa8c..591a698c 100644 --- a/Meshtastic/Views/Messages/MessageList.swift +++ b/Meshtastic/Views/Messages/UserMessageList.swift @@ -8,7 +8,7 @@ import SwiftUI import CoreData -struct MessageList: View { +struct UserMessageList: View { @Environment(\.managedObjectContext) var context @EnvironmentObject var bleManager: BLEManager @@ -75,10 +75,10 @@ struct MessageList: View { Menu("Tapback response") { ForEach(Tapbacks.allCases) { tb in Button(action: { - if bleManager.sendMessage(message: tb.description, toUserNum: user.num, isEmoji: true, replyID: message.messageId) { - print("Sent \(tb.description) Tapback") + if bleManager.sendMessage(message: tb.emojiString, toUserNum: user.num, isEmoji: true, replyID: message.messageId) { + print("Sent \(tb.emojiString) Tapback") self.context.refresh(user, mergeChanges: true) - } else { print("\(tb.description) Tapback Failed") } + } else { print("\(tb.emojiString) Tapback Failed") } }) { Text(tb.description) @@ -90,7 +90,6 @@ struct MessageList: View { Button(action: { self.replyMessageId = message.messageId self.focusedField = .messageText - print("I want to reply to \(message.messageId)") }) { Text("Reply") @@ -108,44 +107,29 @@ struct MessageList: View { Text("Date \(messageDate, style: .date) \(messageDate.formattedDate(format: "h:mm:ss a"))").font(.caption2).foregroundColor(.gray) } if currentUser && message.receivedACK { - VStack { - Text("Received Ack \(message.receivedACK ? "✔️" : "")") } - } else if currentUser && message.ackError == 0 { - // Empty Error Text("Waiting. . .") - } else if currentUser && message.ackError > 0 { - let ackErrorVal = RoutingError(rawValue: Int(message.ackError)) Text("\(ackErrorVal?.display ?? "No Error" )").fixedSize(horizontal: false, vertical: true) } - if currentUser { - VStack { - let ackDate = Date(timeIntervalSince1970: TimeInterval(message.ackTimestamp)) - let sixMonthsAgo = Calendar.current.date(byAdding: .month, value: -6, to: Date()) if ackDate >= sixMonthsAgo! { - Text((ackDate.formattedDate(format: "h:mm:ss a"))).font(.caption2).foregroundColor(.gray) - } else { - Text("Unknown Age").font(.caption2).foregroundColor(.gray) } } } - if message.ackSNR != 0 { VStack { - Text("Ack SNR \(String(message.ackSNR))") .font(.caption2) .foregroundColor(.gray) @@ -165,15 +149,10 @@ struct MessageList: View { let tapbacks = message.value(forKey: "tapbacks") as! [MessageEntity] if tapbacks.count > 0 { - VStack (alignment: .trailing) { - HStack { - ForEach( tapbacks ) { (tapback: MessageEntity) in - VStack { - let image = tapback.messagePayload!.image(fontSize: 20) Image(uiImage: image!).font(.caption) Text("\(tapback.fromUser?.shortName ?? "????")") @@ -227,9 +206,7 @@ struct MessageList: View { print("Failed to delete message \(deleteMessageId)") } } - }, - secondaryButton: .cancel() - ) + }, secondaryButton: .cancel()) } } } @@ -273,14 +250,11 @@ struct MessageList: View { .keyboardType(kbType!) .toolbar { ToolbarItemGroup(placement: .keyboard) { - Button("Dismiss Keyboard") { focusedField = nil } .font(.subheadline) - Spacer() - Button { let userLongName = bleManager.connectedPeripheral != nil ? bleManager.connectedPeripheral.longName : "Unknown" sendPositionWithMessage = true diff --git a/Meshtastic/Views/Nodes/PositionLog.swift b/Meshtastic/Views/Nodes/PositionLog.swift index 87cec4a2..984d22bb 100644 --- a/Meshtastic/Views/Nodes/PositionLog.swift +++ b/Meshtastic/Views/Nodes/PositionLog.swift @@ -24,36 +24,30 @@ struct PositionLog: View { if UIDevice.current.userInterfaceIdiom == .pad || UIDevice.current.userInterfaceIdiom == .mac { //Add a table for mac and ipad - VStack { - Table(node.positions!.reversed() as! [PositionEntity]) { - TableColumn("Seq No") { position in - Text(String(position.seqNo)) - } - //.width(75) - TableColumn("Latitude") { position in - Text(String(format: "%.6f", position.latitude ?? 0)) - } - TableColumn("Longitude") { position in - Text(String(format: "%.6f", position.longitude ?? 0)) - } - TableColumn("Altitude") { position in - Text(String(position.altitude)) - } - //.width(75) - TableColumn("Sats") { position in - Text(String(position.satsInView)) - } - //.width(75) - TableColumn("Speed") { position in - Text(String(position.speed)) - } - //.width(75) - TableColumn("Heading") { position in - Text(String(position.heading)) - } - TableColumn("Time Stamp") { position in - Text(position.time?.formattedDate(format: "MM/dd/yy hh:mm") ?? "Unknown time") - } + Table(node.positions!.reversed() as! [PositionEntity]) { + TableColumn("SeqNo") { position in + Text(String(position.seqNo)) + } + TableColumn("Latitude") { position in + Text(String(format: "%.6f", position.latitude ?? 0)) + } + TableColumn("Longitude") { position in + Text(String(format: "%.6f", position.longitude ?? 0)) + } + TableColumn("Altitude") { position in + Text(String(position.altitude)) + } + TableColumn("Sats") { position in + Text(String(position.satsInView)) + } + TableColumn("Speed") { position in + Text(String(position.speed)) + } + TableColumn("Heading") { position in + Text(String(position.heading)) + } + TableColumn("Time Stamp") { position in + Text(position.time?.formattedDate(format: "MM/dd/yy hh:mm") ?? "Unknown time") } } diff --git a/Meshtastic/Views/Settings/ShareChannels.swift b/Meshtastic/Views/Settings/ShareChannels.swift index 7f88867b..adbf792c 100644 --- a/Meshtastic/Views/Settings/ShareChannels.swift +++ b/Meshtastic/Views/Settings/ShareChannels.swift @@ -55,7 +55,7 @@ struct ShareChannels: View { ScrollView { VStack { if node != nil && node?.myInfo != nil { - Grid(alignment: .top, horizontalSpacing: 2) { + Grid(alignment: .top) { GridRow { Spacer() Text("Include") @@ -78,13 +78,13 @@ struct ShareChannels: View { .toggleStyle(.switch) .labelsHidden() .disabled(channel.role == 1) - Text((channel.name!.isEmpty ? "Primary" : channel.name) ?? "Primary") + Text((channel.name!.isEmpty ? "Primary" : channel.name) ?? "Primary").fixedSize() if channel.psk?.hexDescription.count ?? 0 < 3 { Image(systemName: "lock.slash") - .foregroundColor(.red) + .foregroundColor(.red) } else { Image(systemName: "lock.fill") - .foregroundColor(.green) + .foregroundColor(.green) } } else if channel.index == 1 && channel.role > 0 { Toggle("Channel 1 Included", isOn: $includeChannel1) @@ -94,10 +94,10 @@ struct ShareChannels: View { Text((channel.name!.isEmpty ? "Channel\(channel.index)" : channel.name) ?? "Channel\(channel.index)") if channel.psk?.hexDescription.count ?? 0 < 3 { Image(systemName: "lock.slash") - .foregroundColor(.red) + .foregroundColor(.red) } else { Image(systemName: "lock.fill") - .foregroundColor(.green) + .foregroundColor(.green) } } else if channel.index == 2 && channel.role > 0 { Toggle("Channel 2 Included", isOn: $includeChannel2) @@ -107,10 +107,10 @@ struct ShareChannels: View { Text((channel.name!.isEmpty ? "Channel\(channel.index)" : channel.name) ?? "Channel\(channel.index)") if channel.psk?.hexDescription.count ?? 0 < 3 { Image(systemName: "lock.slash") - .foregroundColor(.red) + .foregroundColor(.red) } else { Image(systemName: "lock.fill") - .foregroundColor(.green) + .foregroundColor(.green) } } else if channel.index == 3 && channel.role > 0 { Toggle("Channel 3 Included", isOn: $includeChannel3) @@ -120,10 +120,10 @@ struct ShareChannels: View { Text((channel.name!.isEmpty ? "Channel\(channel.index)" : channel.name) ?? "Channel\(channel.index)") if channel.psk?.hexDescription.count ?? 0 < 3 { Image(systemName: "lock.slash") - .foregroundColor(.red) + .foregroundColor(.red) } else { Image(systemName: "lock.fill") - .foregroundColor(.green) + .foregroundColor(.green) } } else if channel.index == 4 && channel.role > 0 { Toggle("Channel 4 Included", isOn: $includeChannel4) @@ -133,10 +133,10 @@ struct ShareChannels: View { Text((channel.name!.isEmpty ? "Channel\(channel.index)" : channel.name) ?? "Channel\(channel.index)") if channel.psk?.hexDescription.count ?? 0 < 3 { Image(systemName: "lock.slash") - .foregroundColor(.red) + .foregroundColor(.red) } else { Image(systemName: "lock.fill") - .foregroundColor(.green) + .foregroundColor(.green) } } else if channel.index == 5 && channel.role > 0 { Toggle("Channel 5 Included", isOn: $includeChannel5) @@ -146,10 +146,10 @@ struct ShareChannels: View { Text((channel.name!.isEmpty ? "Channel\(channel.index)" : channel.name) ?? "Channel\(channel.index)") if channel.psk?.hexDescription.count ?? 0 < 3 { Image(systemName: "lock.slash") - .foregroundColor(.red) + .foregroundColor(.red) } else { Image(systemName: "lock.fill") - .foregroundColor(.green) + .foregroundColor(.green) } } else if channel.index == 6 && channel.role > 0 { Toggle("Channel 6 Included", isOn: $includeChannel6) @@ -159,10 +159,10 @@ struct ShareChannels: View { Text((channel.name!.isEmpty ? "Channel\(channel.index)" : channel.name) ?? "Channel\(channel.index)") if channel.psk?.hexDescription.count ?? 0 < 3 { Image(systemName: "lock.slash") - .foregroundColor(.red) + .foregroundColor(.red) } else { Image(systemName: "lock.fill") - .foregroundColor(.green) + .foregroundColor(.green) } } else if channel.index == 7 && channel.role > 0 { Toggle("Channel 7 Included", isOn: $includeChannel7) @@ -172,10 +172,10 @@ struct ShareChannels: View { Text((channel.name!.isEmpty ? "Channel\(channel.index)" : channel.name) ?? "Channel\(channel.index)") if channel.psk?.hexDescription.count ?? 0 < 3 { Image(systemName: "lock.slash") - .foregroundColor(.red) + .foregroundColor(.red) } else { Image(systemName: "lock.fill") - .foregroundColor(.green) + .foregroundColor(.green) } } Spacer() @@ -183,15 +183,15 @@ struct ShareChannels: View { .padding(0) } } - + let qrImage = qrCodeImage.generateQRCode(from: channelsUrl) VStack { if node != nil { ShareLink("Share QR Code & Link", - item: Image(uiImage: qrImage), - subject: Text("Meshtastic Node \(node?.user?.shortName ?? "????") has shared channels with you"), - message: Text(channelsUrl), - preview: SharePreview("Meshtastic Node \(node?.user?.shortName ?? "????") has shared channels with you", + item: Image(uiImage: qrImage), + subject: Text("Meshtastic Node \(node?.user?.shortName ?? "????") has shared channels with you"), + message: Text(channelsUrl), + preview: SharePreview("Meshtastic Node \(node?.user?.shortName ?? "????") has shared channels with you", image: Image(uiImage: qrImage)) ) .buttonStyle(.bordered)