From e1566598c96601ebcf3229aab22fc7a593ee1904 Mon Sep 17 00:00:00 2001 From: Dustin Mierau Date: Fri, 7 Nov 2025 16:16:00 -0800 Subject: Further UI tweraks. Transfers button in toolbar. Better empty states in places. Fix race condition with transactions ids (yikes)! --- .../macOS/Trackers/TrackerBookmarkServerView.swift | 38 +++++++ Hotline/macOS/Trackers/TrackerBookmarkSheet.swift | 119 +++++++++++++++++++++ Hotline/macOS/Trackers/TrackerItemView.swift | 73 +++++++++++++ 3 files changed, 230 insertions(+) create mode 100644 Hotline/macOS/Trackers/TrackerBookmarkServerView.swift create mode 100644 Hotline/macOS/Trackers/TrackerBookmarkSheet.swift create mode 100644 Hotline/macOS/Trackers/TrackerItemView.swift (limited to 'Hotline/macOS/Trackers') diff --git a/Hotline/macOS/Trackers/TrackerBookmarkServerView.swift b/Hotline/macOS/Trackers/TrackerBookmarkServerView.swift new file mode 100644 index 0000000..dc42ea9 --- /dev/null +++ b/Hotline/macOS/Trackers/TrackerBookmarkServerView.swift @@ -0,0 +1,38 @@ +struct TrackerBookmarkServerView: View { + let server: BookmarkServer + + var body: some View { + HStack(alignment: .center, spacing: 6) { + Image("Server") + .resizable() + .scaledToFit() + .frame(width: 16, height: 16, alignment: .center) + Text(self.server.name ?? "Server").lineLimit(1).truncationMode(.tail) + if let serverDescription = self.server.description { + Text(serverDescription) + .foregroundStyle(.secondary) + .lineLimit(1) + .truncationMode(.tail) + } + Spacer(minLength: 0) + if self.server.users > 0 { + Text(String(self.server.users)) + .foregroundStyle(.secondary) + .lineLimit(1) + + Circle() + .fill(.fileComplete) + .frame(width: 7, height: 7) + .keyframeAnimator(initialValue: 1.0, repeating: true) { content, opacity in + content.opacity(opacity) + } keyframes: { _ in + CubicKeyframe(1.0, duration: 2.0) // Stay visible for 1 second + CubicKeyframe(0.6, duration: 0.5) // Fade out quickly + CubicKeyframe(1.0, duration: 0.5) // Fade in quickly + } + .padding(.trailing, 6) + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } +} \ No newline at end of file diff --git a/Hotline/macOS/Trackers/TrackerBookmarkSheet.swift b/Hotline/macOS/Trackers/TrackerBookmarkSheet.swift new file mode 100644 index 0000000..4943016 --- /dev/null +++ b/Hotline/macOS/Trackers/TrackerBookmarkSheet.swift @@ -0,0 +1,119 @@ +struct TrackerBookmarkSheet: View { + @Environment(\.dismiss) private var dismiss + @Environment(\.modelContext) private var modelContext + + @State private var bookmark: Bookmark? = nil + @State private var trackerAddress: String = "" + @State private var trackerName: String = "" + + init() { + + } + + init(_ editingBookmark: Bookmark) { + _bookmark = .init(initialValue: editingBookmark) + _trackerAddress = .init(initialValue: editingBookmark.displayAddress) + _trackerName = .init(initialValue: editingBookmark.name) + } + + var body: some View { + VStack(alignment: .leading) { + Form { + if self.bookmark == nil { + HStack(alignment: .top, spacing: 10) { + GroupedIconView(color: .blue, systemName: "point.3.filled.connected.trianglepath.dotted", padding: 5.0) + .frame(width: 28, height: 28) + + VStack(alignment: .leading) { + Text("Add a Hotline Tracker") + + Text("Enter the address and name of a Hotline Tracker you want to add.") + .foregroundStyle(.secondary) + .font(.subheadline) + } + } + } + else { + HStack(alignment: .top, spacing: 10) { + GroupedIconView(color: .blue, systemName: "point.3.filled.connected.trianglepath.dotted", padding: 5.0) + .frame(width: 28, height: 28) + + VStack(alignment: .leading) { + Text("Edit Hotline Tracker") + + Text("Change the address and name of your Hotline Tracker.") + .foregroundStyle(.secondary) + .font(.subheadline) + } + } + } + + Group { + TextField(text: $trackerAddress) { + Text("Address") + } + TextField(text: $trackerName, prompt: Text("Optional")) { + Text("Name") + } + } +// .textFieldStyle(.roundedBorder) + .controlSize(.large) + } + .formStyle(.grouped) + } + .frame(width: 350) + .fixedSize(horizontal: true, vertical: true) + .toolbar { + ToolbarItem(placement: .confirmationAction) { + Button { + self.saveTracker() + } label: { + if self.bookmark != nil { + Text("Save") + } + else { + Text("Add") + } + } + } + ToolbarItem(placement: .cancellationAction) { + Button("Cancel") { + self.trackerName = "" + self.trackerAddress = "" + + self.dismiss() + } + } + } + } + + private func saveTracker() { + var displayName = trackerName.trimmingCharacters(in: .whitespacesAndNewlines) + let (host, port) = Tracker.parseTrackerAddressAndPort(trackerAddress) + + if displayName.isEmpty { + displayName = host + } + + if !displayName.isEmpty && !host.isEmpty { + if !host.isEmpty { + if self.bookmark != nil { + // We're editing an existing bookmark. + self.bookmark?.name = displayName + self.bookmark?.address = host + self.bookmark?.port = port + } + else { + // We're creating a new bookmark. + let newBookmark = Bookmark(type: .tracker, name: displayName, address: host, port: port) + Bookmark.add(newBookmark, context: modelContext) + } + + self.trackerName = "" + self.trackerAddress = "" + + self.dismiss() + } + } + } +} \ No newline at end of file diff --git a/Hotline/macOS/Trackers/TrackerItemView.swift b/Hotline/macOS/Trackers/TrackerItemView.swift new file mode 100644 index 0000000..59caad5 --- /dev/null +++ b/Hotline/macOS/Trackers/TrackerItemView.swift @@ -0,0 +1,73 @@ +struct TrackerItemView: View { + let bookmark: Bookmark + let isExpanded: Bool + let isLoading: Bool + let count: Int + let onToggleExpanded: () -> Void + @Environment(\.appearsActive) private var appearsActive + + var body: some View { + HStack(alignment: .center, spacing: 6) { + if bookmark.type == .tracker { + Button { + self.onToggleExpanded() + } label: { + Text(Image(systemName: self.isExpanded ? "chevron.down" : "chevron.right")) + .bold() + .font(.system(size: 10)) + .opacity(0.5) + .frame(alignment: .center) + } + .buttonStyle(.plain) + .frame(width: 10) + .padding(.leading, 4) + .padding(.trailing, 2) + } + + switch bookmark.type { + case .tracker: + Image("Tracker") + .resizable() + .scaledToFit() + .frame(width: 16, height: 16, alignment: .center) + Text(bookmark.name).bold().lineLimit(1).truncationMode(.tail) + if isLoading { + ProgressView() + .padding([.leading, .trailing], 2) + .controlSize(.small) + } + Spacer(minLength: 0) + if isExpanded && count > 0 { + HStack(spacing: 4) { + Text(String(count)) + + SpinningGlobeView() + .fontWeight(.semibold) + .frame(width: 12, height: 12) + } + .padding(.horizontal, 6) + .padding(.vertical, 2) + .foregroundStyle(.secondary) +// .background(.quinary) + .clipShape(.capsule) + } + case .server: + Image(systemName: "bookmark.fill") + .resizable() + .scaledToFit() + .foregroundStyle(Color.secondary) + .frame(width: 11, height: 11, alignment: .center) + .opacity(0.75) + .padding(.leading, 3) + .padding(.trailing, 2) + Image("Server") + .resizable() + .scaledToFit() + .frame(width: 16, height: 16, alignment: .center) + Text(bookmark.name).lineLimit(1).truncationMode(.tail) + Spacer(minLength: 0) + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } +} \ No newline at end of file -- cgit From 6afa5551add4541f376867b3d6527df9a0f793f3 Mon Sep 17 00:00:00 2001 From: Dustin Mierau Date: Fri, 7 Nov 2025 16:16:31 -0800 Subject: Further UI tweraks. Transfers button in toolbar. Better empty states in places. Fix race condition with transactions ids (yikes)! --- Hotline.xcodeproj/project.pbxproj | 26 +- Hotline/Hotline/HotlineClientNew.swift | 100 +++-- Hotline/Hotline/HotlineProtocol.swift | 10 +- Hotline/macOS/HotlinePanelView.swift | 12 + Hotline/macOS/News/NewsView.swift | 2 +- Hotline/macOS/Trackers/ServerBookmarkSheet.swift | 70 +++ .../macOS/Trackers/TrackerBookmarkServerView.swift | 4 +- Hotline/macOS/Trackers/TrackerBookmarkSheet.swift | 4 +- Hotline/macOS/Trackers/TrackerItemView.swift | 4 +- Hotline/macOS/Trackers/TrackerView.swift | 480 +++++++++++++++++++++ 10 files changed, 653 insertions(+), 59 deletions(-) create mode 100644 Hotline/macOS/Trackers/ServerBookmarkSheet.swift create mode 100644 Hotline/macOS/Trackers/TrackerView.swift (limited to 'Hotline/macOS/Trackers') diff --git a/Hotline.xcodeproj/project.pbxproj b/Hotline.xcodeproj/project.pbxproj index c63109a..2861aab 100644 --- a/Hotline.xcodeproj/project.pbxproj +++ b/Hotline.xcodeproj/project.pbxproj @@ -33,6 +33,10 @@ DA4F2BF82B16A17200D8ADDC /* HotlineProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA4F2BF72B16A17200D8ADDC /* HotlineProtocol.swift */; }; DA4F2C012B1A558E00D8ADDC /* ChatView.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA4F2C002B1A558E00D8ADDC /* ChatView.swift */; platformFilter = ios; }; DA501BE22EBE9018001714F8 /* GroupedIconView.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA501BE12EBE9018001714F8 /* GroupedIconView.swift */; }; + DA501BE42EBE9517001714F8 /* ServerBookmarkSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA501BE32EBE9517001714F8 /* ServerBookmarkSheet.swift */; }; + DA501BE72EBE9542001714F8 /* TrackerBookmarkSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA501BE62EBE9542001714F8 /* TrackerBookmarkSheet.swift */; }; + DA501BE92EBE9589001714F8 /* TrackerItemView.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA501BE82EBE9589001714F8 /* TrackerItemView.swift */; }; + DA501BEB2EBE95B4001714F8 /* TrackerBookmarkServerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA501BEA2EBE95B4001714F8 /* TrackerBookmarkServerView.swift */; }; DA52689C2EB0738B00DCB941 /* GeneralSettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA52689B2EB0738B00DCB941 /* GeneralSettingsView.swift */; platformFilters = (macos, ); }; DA52689E2EB073A400DCB941 /* IconSettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA52689D2EB073A400DCB941 /* IconSettingsView.swift */; platformFilters = (macos, ); }; DA5268A02EB073BC00DCB941 /* SoundSettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA52689F2EB073BC00DCB941 /* SoundSettingsView.swift */; platformFilters = (macos, ); }; @@ -139,6 +143,10 @@ DA4F2BF72B16A17200D8ADDC /* HotlineProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HotlineProtocol.swift; sourceTree = ""; }; DA4F2C002B1A558E00D8ADDC /* ChatView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatView.swift; sourceTree = ""; }; DA501BE12EBE9018001714F8 /* GroupedIconView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GroupedIconView.swift; sourceTree = ""; }; + DA501BE32EBE9517001714F8 /* ServerBookmarkSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ServerBookmarkSheet.swift; sourceTree = ""; }; + DA501BE62EBE9542001714F8 /* TrackerBookmarkSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TrackerBookmarkSheet.swift; sourceTree = ""; }; + DA501BE82EBE9589001714F8 /* TrackerItemView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TrackerItemView.swift; sourceTree = ""; }; + DA501BEA2EBE95B4001714F8 /* TrackerBookmarkServerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TrackerBookmarkServerView.swift; sourceTree = ""; }; DA52689B2EB0738B00DCB941 /* GeneralSettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GeneralSettingsView.swift; sourceTree = ""; }; DA52689D2EB073A400DCB941 /* IconSettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IconSettingsView.swift; sourceTree = ""; }; DA52689F2EB073BC00DCB941 /* SoundSettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SoundSettingsView.swift; sourceTree = ""; }; @@ -291,6 +299,18 @@ path = Views; sourceTree = ""; }; + DA501BE52EBE9520001714F8 /* Trackers */ = { + isa = PBXGroup; + children = ( + DAE734FA2B2E41F9000C56F6 /* TrackerView.swift */, + DA501BE82EBE9589001714F8 /* TrackerItemView.swift */, + DA501BEA2EBE95B4001714F8 /* TrackerBookmarkServerView.swift */, + DA501BE62EBE9542001714F8 /* TrackerBookmarkSheet.swift */, + DA501BE32EBE9517001714F8 /* ServerBookmarkSheet.swift */, + ); + path = Trackers; + sourceTree = ""; + }; DA52689A2EB0737400DCB941 /* Settings */ = { isa = PBXGroup; children = ( @@ -497,10 +517,10 @@ DA55AC762BE589F700034857 /* AboutView.swift */, DACCE5E22EABE86A008CDD92 /* AppUpdateView.swift */, DAE136B92B9D1147007D8307 /* HotlinePanelView.swift */, - DAE734FA2B2E41F9000C56F6 /* TrackerView.swift */, DAE734F82B2E4185000C56F6 /* ServerView.swift */, DAE735022B30C0BB000C56F6 /* MessageView.swift */, DA5268B42EB6840A00DCB941 /* TransfersView.swift */, + DA501BE52EBE9520001714F8 /* Trackers */, DA5268A82EB081AF00DCB941 /* Chat */, DA5268A62EB0762300DCB941 /* Board */, DA5268A92EB081DE00DCB941 /* News */, @@ -615,6 +635,7 @@ DA7725412B21435B006C5ABB /* ObservableScrollView.swift in Sources */, DAE734FF2B2E6750000C56F6 /* ChatView.swift in Sources */, DA5268B52EB6840A00DCB941 /* TransfersView.swift in Sources */, + DA501BE42EBE9517001714F8 /* ServerBookmarkSheet.swift in Sources */, 11F8288B2BF9428100216BA0 /* AccountManagerView.swift in Sources */, DAC6B2E42EAFE92F004E2CBA /* SpinningGlobeView.swift in Sources */, DADDB28D2B22B5920024040D /* Server.swift in Sources */, @@ -654,11 +675,13 @@ 11A7260A2BE0675A000C1DA7 /* FileDetailsView.swift in Sources */, DA72A0DD2B4CD0BF00A0F48A /* NewsEditorView.swift in Sources */, DA52689C2EB0738B00DCB941 /* GeneralSettingsView.swift in Sources */, + DA501BE92EBE9589001714F8 /* TrackerItemView.swift in Sources */, DA57536C2B36BA1D00FAC277 /* TextDocument.swift in Sources */, DACCE5E12EABE4B4008CDD92 /* AppUpdate.swift in Sources */, DA5268AD2EB12FE200DCB941 /* ServerState.swift in Sources */, DA77253F2B21176D006C5ABB /* NewsView.swift in Sources */, DAC6B2E22EAEE9FE004E2CBA /* NetSocket.swift in Sources */, + DA501BEB2EBE95B4001714F8 /* TrackerBookmarkServerView.swift in Sources */, DA99218E2C51AA5D0058FA6C /* HotlineDataBuilder.swift in Sources */, DA872B132BDDBF78008B1012 /* HotlinePanel.swift in Sources */, DA4B8F3A2EA6FB3C00CBFD53 /* iOSApp.swift in Sources */, @@ -680,6 +703,7 @@ DAC87F072C5010E80060FADF /* HotlineExtensions.swift in Sources */, DAE734FD2B2E65E9000C56F6 /* MessageBoardView.swift in Sources */, DA6980832BFFD06C003E434B /* BookmarkDocument.swift in Sources */, + DA501BE72EBE9542001714F8 /* TrackerBookmarkSheet.swift in Sources */, DAB4D87E2B4C8BCA0048A05C /* FilePreviewTextView.swift in Sources */, DA3429B72EBAB1750010784E /* QuickLookPreviewView.swift in Sources */, DA4F2C012B1A558E00D8ADDC /* ChatView.swift in Sources */, diff --git a/Hotline/Hotline/HotlineClientNew.swift b/Hotline/Hotline/HotlineClientNew.swift index 8642d42..303bd32 100644 --- a/Hotline/Hotline/HotlineClientNew.swift +++ b/Hotline/Hotline/HotlineClientNew.swift @@ -160,6 +160,13 @@ public actor HotlineClientNew { UInt16(0x0001) // Version UInt16(0x0002) // Sub-version }) + + // Transaction IDs + private var nextTransactionID: UInt32 = 1 + private func generateTransactionID() -> UInt32 { + defer { self.nextTransactionID += 1 } + return self.nextTransactionID + } // MARK: - Connection @@ -258,7 +265,7 @@ public actor HotlineClientNew { // MARK: - Login private func performLogin(_ login: HotlineLoginInfo) async throws -> HotlineServerInfo { - var transaction = HotlineTransaction(type: .login) + var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .login) transaction.setFieldEncodedString(type: .userLogin, val: login.login) transaction.setFieldEncodedString(type: .userPassword, val: login.password) transaction.setFieldUInt16(type: .userIconID, val: login.iconID) @@ -494,28 +501,29 @@ public actor HotlineClientNew { // MARK: - Keep-Alive private func startKeepAlive() { - keepAliveTask = Task { [weak self] in + self.keepAliveTask = Task { [weak self] in while !Task.isCancelled { try? await Task.sleep(nanoseconds: 180_000_000_000) // 3 minutes - - guard let self else { return } - - do { - if let version = await self.serverInfo?.version, version >= 185 { - let transaction = HotlineTransaction(type: .connectionKeepAlive) - try await self.socket.send(transaction, endian: .big) - } else { - // Older servers: send getUserNameList as keep-alive - _ = try? await self.getUserList() - } - } catch { - print("HotlineClientNew: Keep-alive failed: \(error)") - } + await self?.sendKeepAlive() + } + } + } + + private func sendKeepAlive() async { + do { + if let version = self.serverInfo?.version, version >= 185 { + let transaction = HotlineTransaction(id: self.generateTransactionID(), type: .connectionKeepAlive) + try await self.socket.send(transaction, endian: .big) + } else { + // Older servers: send getUserNameList as keep-alive + let _ = try? await self.getUserList() } + } catch { + print("HotlineClientNew: Keep-alive failed: \(error)") } } - // MARK: - Public API - Chat + // MARK: - Chat /// Send a chat message to the server /// @@ -524,20 +532,20 @@ public actor HotlineClientNew { /// - encoding: Text encoding (default: UTF-8) /// - announce: Whether this is an announcement (admin only, default: false) public func sendChat(_ message: String, encoding: String.Encoding = .utf8, announce: Bool = false) async throws { - var transaction = HotlineTransaction(type: .sendChat) + var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .sendChat) transaction.setFieldString(type: .data, val: message, encoding: encoding) transaction.setFieldUInt16(type: .chatOptions, val: announce ? 1 : 0) try await socket.send(transaction, endian: .big) } - // MARK: - Public API - Users + // MARK: - Users /// Get the list of users currently connected to the server /// /// - Returns: Array of connected users public func getUserList() async throws -> [HotlineUser] { - let transaction = HotlineTransaction(type: .getUserNameList) + let transaction = HotlineTransaction(id: self.generateTransactionID(), type: .getUserNameList) let reply = try await sendTransaction(transaction) var users: [HotlineUser] = [] @@ -555,7 +563,7 @@ public actor HotlineClientNew { /// - userID: Target user ID /// - encoding: Text encoding (default: UTF-8) public func sendInstantMessage(_ message: String, to userID: UInt16, encoding: String.Encoding = .utf8) async throws { - var transaction = HotlineTransaction(type: .sendInstantMessage) + var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .sendInstantMessage) transaction.setFieldUInt16(type: .userID, val: userID) transaction.setFieldUInt32(type: .options, val: 1) transaction.setFieldString(type: .data, val: message, encoding: encoding) @@ -576,7 +584,7 @@ public actor HotlineClientNew { options: HotlineUserOptions = [], autoresponse: String? = nil ) async throws { - var transaction = HotlineTransaction(type: .setClientUserInfo) + var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .setClientUserInfo) transaction.setFieldString(type: .userName, val: username) transaction.setFieldUInt16(type: .userIconID, val: iconID) transaction.setFieldUInt16(type: .options, val: options.rawValue) @@ -588,13 +596,13 @@ public actor HotlineClientNew { try await socket.send(transaction, endian: .big) } - // MARK: - Public API - Agreement + // MARK: - Agreement /// Send agreement acceptance to the server /// /// Call this after receiving `.agreementRequired` event. public func sendAgree() async throws { - let transaction = HotlineTransaction(type: .agreed) + let transaction = HotlineTransaction(id: self.generateTransactionID(), type: .agreed) try await socket.send(transaction, endian: .big) } @@ -605,7 +613,7 @@ public actor HotlineClientNew { /// - Parameter path: Directory path (empty for root) /// - Returns: Array of files and folders public func getFileList(path: [String] = []) async throws -> [HotlineFile] { - var transaction = HotlineTransaction(type: .getFileNameList) + var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .getFileNameList) if !path.isEmpty { transaction.setFieldPath(type: .filePath, val: path) } @@ -634,7 +642,7 @@ public actor HotlineClientNew { path: [String], preview: Bool = false ) async throws -> (referenceNumber: UInt32, size: Int, fileSize: Int?, waitingCount: Int?) { - var transaction = HotlineTransaction(type: .downloadFile) + var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .downloadFile) transaction.setFieldString(type: .fileName, val: name) transaction.setFieldPath(type: .filePath, val: path) @@ -664,7 +672,7 @@ public actor HotlineClientNew { /// - Parameter path: Category path (empty for root) /// - Returns: Array of news categories public func getNewsCategories(path: [String] = []) async throws -> [HotlineNewsCategory] { - var transaction = HotlineTransaction(type: .getNewsCategoryNameList) + var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .getNewsCategoryNameList) if !path.isEmpty { transaction.setFieldPath(type: .newsPath, val: path) } @@ -686,7 +694,7 @@ public actor HotlineClientNew { /// - Parameter path: Category path /// - Returns: Array of news articles public func getNewsArticles(path: [String] = []) async throws -> [HotlineNewsArticle] { - var transaction = HotlineTransaction(type: .getNewsArticleNameList) + var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .getNewsArticleNameList) if !path.isEmpty { transaction.setFieldPath(type: .newsPath, val: path) } @@ -713,7 +721,7 @@ public actor HotlineClientNew { /// - flavor: Content flavor (default: "text/plain") /// - Returns: Article content as string public func getNewsArticle(id: UInt32, path: [String], flavor: String = "text/plain") async throws -> String? { - var transaction = HotlineTransaction(type: .getNewsArticleData) + var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .getNewsArticleData) transaction.setFieldPath(type: .newsPath, val: path) transaction.setFieldUInt32(type: .newsArticleID, val: id) transaction.setFieldString(type: .newsArticleDataFlavor, val: flavor, encoding: .ascii) @@ -739,7 +747,7 @@ public actor HotlineClientNew { throw HotlineClientError.invalidResponse } - var transaction = HotlineTransaction(type: .postNewsArticle) + var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .postNewsArticle) transaction.setFieldPath(type: .newsPath, val: path) transaction.setFieldUInt32(type: .newsArticleID, val: parentID) transaction.setFieldString(type: .newsArticleTitle, val: title) @@ -756,7 +764,7 @@ public actor HotlineClientNew { /// /// - Returns: Array of message strings public func getMessageBoard() async throws -> [String] { - let transaction = HotlineTransaction(type: .getMessageBoard) + let transaction = HotlineTransaction(id: self.generateTransactionID(), type: .getMessageBoard) let reply = try await sendTransaction(transaction) guard let text = reply.getField(type: .data)?.getString() else { @@ -774,7 +782,7 @@ public actor HotlineClientNew { public func postMessageBoard(_ text: String) async throws { guard !text.isEmpty else { return } - var transaction = HotlineTransaction(type: .oldPostNews) + var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .oldPostNews) transaction.setFieldString(type: .data, val: text, encoding: .macOSRoman) try await socket.send(transaction, endian: .big) @@ -789,7 +797,7 @@ public actor HotlineClientNew { /// - path: Directory path containing the file /// - Returns: File details or nil if not found public func getFileInfo(name: String, path: [String]) async throws -> FileDetails? { - var transaction = HotlineTransaction(type: .getFileInfo) + var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .getFileInfo) transaction.setFieldString(type: .fileName, val: name) transaction.setFieldPath(type: .filePath, val: path) @@ -828,7 +836,7 @@ public actor HotlineClientNew { /// - path: Directory path containing the item /// - Returns: True if deletion succeeded public func deleteFile(name: String, path: [String]) async throws -> Bool { - var transaction = HotlineTransaction(type: .deleteFile) + var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .deleteFile) transaction.setFieldString(type: .fileName, val: name) transaction.setFieldPath(type: .filePath, val: path) @@ -840,13 +848,13 @@ public actor HotlineClientNew { } } - // MARK: - Public API - User Administration + // MARK: - Administration /// Get list of user accounts (requires admin access) /// /// - Returns: Array of user accounts sorted by login public func getAccounts() async throws -> [HotlineAccount] { - let transaction = HotlineTransaction(type: .getAccounts) + let transaction = HotlineTransaction(id: self.generateTransactionID(), type: .getAccounts) let reply = try await sendTransaction(transaction) let accountFields = reply.getFieldList(type: .data) @@ -869,7 +877,7 @@ public actor HotlineClientNew { /// - password: Optional password (nil for no password) /// - access: Access permissions bitmask public func createUser(name: String, login: String, password: String?, access: UInt64) async throws { - var transaction = HotlineTransaction(type: .newUser) + var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .newUser) transaction.setFieldString(type: .userName, val: name) transaction.setFieldEncodedString(type: .userLogin, val: login) @@ -891,7 +899,7 @@ public actor HotlineClientNew { /// - password: Password update - nil to keep current, "" to remove, or new password string /// - access: Access permissions bitmask public func setUser(name: String, login: String, newLogin: String?, password: String?, access: UInt64) async throws { - var transaction = HotlineTransaction(type: .setUser) + var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .setUser) transaction.setFieldString(type: .userName, val: name) transaction.setFieldUInt64(type: .userAccess, val: access) @@ -919,20 +927,20 @@ public actor HotlineClientNew { /// /// - Parameter login: Login username to delete public func deleteUser(login: String) async throws { - var transaction = HotlineTransaction(type: .deleteUser) + var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .deleteUser) transaction.setFieldEncodedString(type: .userLogin, val: login) _ = try await sendTransaction(transaction) } - // MARK: - Public API - Banner Download + // MARK: - Banners /// Request to download the server banner image /// /// - Returns: Tuple of (referenceNumber, transferSize) for the banner download /// - Throws: HotlineClientError if not connected or server doesn't support banners public func downloadBanner() async throws -> (referenceNumber: UInt32, transferSize: Int)? { - let transaction = HotlineTransaction(type: .downloadBanner) + let transaction = HotlineTransaction(id: self.generateTransactionID(), type: .downloadBanner) let reply = try await sendTransaction(transaction) guard @@ -947,7 +955,7 @@ public actor HotlineClientNew { return (referenceNumber, transferSize) } - // MARK: Files + // MARK: - Transfers /// Request to download a file /// @@ -957,7 +965,7 @@ public actor HotlineClientNew { /// - preview: If true, request preview mode (smaller transfer) /// - Returns: Tuple of (referenceNumber, transferSize, fileSize, waitingCount) for the download public func downloadFile(name: String, path: [String], preview: Bool = false) async throws -> (referenceNumber: UInt32, transferSize: Int, fileSize: Int, waitingCount: Int)? { - var transaction = HotlineTransaction(type: .downloadFile) + var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .downloadFile) transaction.setFieldString(type: .fileName, val: name) transaction.setFieldPath(type: .filePath, val: path) @@ -989,7 +997,7 @@ public actor HotlineClientNew { /// - path: Directory path containing the folder /// - Returns: Tuple of (referenceNumber, transferSize, itemCount, waitingCount) for the download public func downloadFolder(name: String, path: [String]) async throws -> (referenceNumber: UInt32, transferSize: Int, itemCount: Int, waitingCount: Int)? { - var transaction = HotlineTransaction(type: .downloadFolder) + var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .downloadFolder) transaction.setFieldString(type: .fileName, val: name) transaction.setFieldPath(type: .filePath, val: path) @@ -1016,7 +1024,7 @@ public actor HotlineClientNew { /// - path: Directory path where the file should be uploaded /// - Returns: Reference number for the upload transfer public func uploadFile(name: String, path: [String]) async throws -> UInt32? { - var transaction = HotlineTransaction(type: .uploadFile) + var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .uploadFile) transaction.setFieldString(type: .fileName, val: name) transaction.setFieldPath(type: .filePath, val: path) @@ -1041,7 +1049,7 @@ public actor HotlineClientNew { public func uploadFolder(name: String, path: [String], fileCount: UInt32, totalSize: UInt32) async throws -> UInt32? { print("HotlineClientNew: uploadFolder request - name='\(name)', path=\(path), fileCount=\(fileCount), totalSize=\(totalSize)") - var transaction = HotlineTransaction(type: .uploadFolder) + var transaction = HotlineTransaction(id: self.generateTransactionID(), type: .uploadFolder) transaction.setFieldString(type: .fileName, val: name) transaction.setFieldPath(type: .filePath, val: path) transaction.setFieldUInt32(type: .transferSize, val: totalSize) diff --git a/Hotline/Hotline/HotlineProtocol.swift b/Hotline/Hotline/HotlineProtocol.swift index 3870261..5fd06dc 100644 --- a/Hotline/Hotline/HotlineProtocol.swift +++ b/Hotline/Hotline/HotlineProtocol.swift @@ -731,12 +731,6 @@ struct HotlineTransactionField { struct HotlineTransaction { static let headerSize = 20 - static var sequenceID: UInt32 = 1 - - static func nextID() -> UInt32 { - HotlineTransaction.sequenceID += 1 - return HotlineTransaction.sequenceID - } var flags: UInt8 = 0 var isReply: UInt8 = 0 @@ -748,9 +742,9 @@ struct HotlineTransaction { var fields: [HotlineTransactionField] = [] - init(type: HotlineTransactionType) { + init(id: UInt32, type: HotlineTransactionType) { self.type = type - self.id = HotlineTransaction.nextID() + self.id = id } init?(from data: [UInt8]) { diff --git a/Hotline/macOS/HotlinePanelView.swift b/Hotline/macOS/HotlinePanelView.swift index 7819c2f..81c24b7 100644 --- a/Hotline/macOS/HotlinePanelView.swift +++ b/Hotline/macOS/HotlinePanelView.swift @@ -119,6 +119,18 @@ struct HotlinePanelView: View { .disabled(self.activeServerState == nil) .help("Accounts") } + + Button { + self.openWindow(id: "transfers") + } + label: { + Image("Section Transfers") + .resizable() + .scaledToFit() + } + .buttonStyle(.plain) + .frame(width: 20, height: 20) + .help("File Transfers") SettingsLink(label: { Image("Section Settings") diff --git a/Hotline/macOS/News/NewsView.swift b/Hotline/macOS/News/NewsView.swift index a07a441..976a985 100644 --- a/Hotline/macOS/News/NewsView.swift +++ b/Hotline/macOS/News/NewsView.swift @@ -138,7 +138,7 @@ struct NewsView: View { ContentUnavailableView { Label("No News", systemImage: "newspaper") } description: { - Text("This server has no newsgroups") + Text("This server has not created any newsgroups yet") } } diff --git a/Hotline/macOS/Trackers/ServerBookmarkSheet.swift b/Hotline/macOS/Trackers/ServerBookmarkSheet.swift new file mode 100644 index 0000000..6ad1657 --- /dev/null +++ b/Hotline/macOS/Trackers/ServerBookmarkSheet.swift @@ -0,0 +1,70 @@ +import SwiftUI + +struct ServerBookmarkSheet: View { + @Environment(\.dismiss) private var dismiss + @Environment(\.modelContext) private var modelContext + + @State private var bookmark: Bookmark + @State private var serverName: String = "" + @State private var serverAddress: String = "" + @State private var serverLogin: String = "" + @State private var serverPassword: String = "" + + init(_ editingBookmark: Bookmark) { + _bookmark = .init(initialValue: editingBookmark) + _serverName = .init(initialValue: editingBookmark.name) + _serverAddress = .init(initialValue: editingBookmark.displayAddress) + _serverLogin = .init(initialValue: editingBookmark.login ?? "") + _serverPassword = .init(initialValue: editingBookmark.password ?? "") + } + + var body: some View { + Form { + Section { + TextField(text: $serverName) { + Text("Name") + } + } + + Section { + TextField(text: $serverAddress) { + Text("Address") + } + TextField(text: $serverLogin, prompt: Text("Optional")) { + Text("Login") + } + SecureField(text: $serverPassword, prompt: Text("Optional")) { + Text("Password") + } + } + } + .formStyle(.grouped) + .frame(width: 350) + .fixedSize(horizontal: true, vertical: true) + .toolbar { + ToolbarItem(placement: .confirmationAction) { + Button("Save") { + let displayName = self.serverName.trimmingCharacters(in: .whitespacesAndNewlines) + let (host, port) = Server.parseServerAddressAndPort(self.serverAddress) + let login = self.serverLogin.trimmingCharacters(in: .whitespacesAndNewlines) + let password = self.serverPassword + + if !displayName.isEmpty && !host.isEmpty { + self.bookmark.name = displayName + self.bookmark.address = host + self.bookmark.port = port + self.bookmark.login = login.isEmpty ? nil : login + self.bookmark.password = password.isEmpty ? nil : password + + self.dismiss() + } + } + } + ToolbarItem(placement: .cancellationAction) { + Button("Cancel") { + self.dismiss() + } + } + } + } +} diff --git a/Hotline/macOS/Trackers/TrackerBookmarkServerView.swift b/Hotline/macOS/Trackers/TrackerBookmarkServerView.swift index dc42ea9..93aea15 100644 --- a/Hotline/macOS/Trackers/TrackerBookmarkServerView.swift +++ b/Hotline/macOS/Trackers/TrackerBookmarkServerView.swift @@ -1,3 +1,5 @@ +import SwiftUI + struct TrackerBookmarkServerView: View { let server: BookmarkServer @@ -35,4 +37,4 @@ struct TrackerBookmarkServerView: View { } .frame(maxWidth: .infinity, maxHeight: .infinity) } -} \ No newline at end of file +} diff --git a/Hotline/macOS/Trackers/TrackerBookmarkSheet.swift b/Hotline/macOS/Trackers/TrackerBookmarkSheet.swift index 4943016..d66a466 100644 --- a/Hotline/macOS/Trackers/TrackerBookmarkSheet.swift +++ b/Hotline/macOS/Trackers/TrackerBookmarkSheet.swift @@ -1,3 +1,5 @@ +import SwiftUI + struct TrackerBookmarkSheet: View { @Environment(\.dismiss) private var dismiss @Environment(\.modelContext) private var modelContext @@ -116,4 +118,4 @@ struct TrackerBookmarkSheet: View { } } } -} \ No newline at end of file +} diff --git a/Hotline/macOS/Trackers/TrackerItemView.swift b/Hotline/macOS/Trackers/TrackerItemView.swift index 59caad5..6e62518 100644 --- a/Hotline/macOS/Trackers/TrackerItemView.swift +++ b/Hotline/macOS/Trackers/TrackerItemView.swift @@ -1,3 +1,5 @@ +import SwiftUI + struct TrackerItemView: View { let bookmark: Bookmark let isExpanded: Bool @@ -70,4 +72,4 @@ struct TrackerItemView: View { } .frame(maxWidth: .infinity, maxHeight: .infinity) } -} \ No newline at end of file +} diff --git a/Hotline/macOS/Trackers/TrackerView.swift b/Hotline/macOS/Trackers/TrackerView.swift new file mode 100644 index 0000000..ddc0a67 --- /dev/null +++ b/Hotline/macOS/Trackers/TrackerView.swift @@ -0,0 +1,480 @@ +import SwiftUI +import SwiftData +import Foundation +import UniformTypeIdentifiers + +enum TrackerSelection: Hashable { + case bookmark(Bookmark) + case bookmarkServer(BookmarkServer) + + var server: Server? { + switch self { + case .bookmark(let b): return b.server + case .bookmarkServer(let t): return t.server + } + } +} + +struct TrackerView: View { + @Environment(\.colorScheme) private var colorScheme + @Environment(\.openWindow) private var openWindow + @Environment(\.controlActiveState) private var controlActiveState + @Environment(\.modelContext) private var modelContext + + @State private var refreshing = false + @State private var trackerSheetPresented: Bool = false + @State private var trackerSheetBookmark: Bookmark? = nil + @State private var serverSheetBookmark: Bookmark? = nil + @State private var attemptedPrepopulate: Bool = false + @State private var fileDropActive = false + @State private var bookmarkExportActive = false + @State private var bookmarkExport: BookmarkDocument? = nil + @State private var expandedTrackers: Set = [] + @State private var trackerServers: [Bookmark: [BookmarkServer]] = [:] + @State private var loadingTrackers: Set = [] + @State private var fetchTasks: [Bookmark: Task] = [:] + @State private var searchText: String = "" + @State private var isSearching = false + + @Query(sort: \Bookmark.order) private var bookmarks: [Bookmark] + @Binding var selection: TrackerSelection? + + private var filteredBookmarks: [Bookmark] { + guard !self.searchText.isEmpty else { + return self.bookmarks + } + + let searchWords = self.searchText.lowercased().split(separator: " ").map(String.init) + + return self.bookmarks.filter { bookmark in + // Always show tracker bookmarks (filter only their servers) + if bookmark.type == .tracker { + return true + } + + // Filter server bookmarks by search text + return self.bookmarkMatchesSearch(bookmark, searchWords: searchWords) + } + } + + private func bookmarkMatchesSearch(_ bookmark: Bookmark, searchWords: [String]) -> Bool { + let searchableText = "\(bookmark.name) \(bookmark.address)".lowercased() + + // All search words must match + return searchWords.allSatisfy { word in + searchableText.contains(word) + } + } + + private func filteredServers(for bookmark: Bookmark) -> [BookmarkServer] { + let servers = self.trackerServers[bookmark] ?? [] + print("TrackerView.filteredServers: Looking up servers for \(bookmark.name), found \(servers.count) servers") + + guard !self.searchText.isEmpty else { + return servers + } + + let searchWords = self.searchText.lowercased().split(separator: " ").map(String.init) + + return servers.filter { server in + let searchableText = "\(server.name ?? "") \(server.address) \(server.description ?? "")".lowercased() + + // All search words must match + return searchWords.allSatisfy { word in + searchableText.contains(word) + } + } + } + + var body: some View { + List(selection: $selection) { + ForEach(filteredBookmarks, id: \.self) { bookmark in + TrackerItemView( + bookmark: bookmark, + isExpanded: self.expandedTrackers.contains(bookmark), + isLoading: self.loadingTrackers.contains(bookmark), + count: self.trackerServers[bookmark]?.count ?? 0 + ) { + self.toggleExpanded(for: bookmark) + } + .tag(TrackerSelection.bookmark(bookmark)) + + if bookmark.type == .tracker && self.expandedTrackers.contains(bookmark) { + ForEach(self.filteredServers(for: bookmark), id: \.self) { trackedServer in + TrackerBookmarkServerView(server: trackedServer) + .moveDisabled(true) + .deleteDisabled(true) + .tag(TrackerSelection.bookmarkServer(trackedServer)) + .padding(.leading, 16 + 8 + 10) + } + } + } + .onMove { movedIndexes, destinationIndex in + Bookmark.move(movedIndexes, to: destinationIndex, context: modelContext) + } + .onDelete { deletedIndexes in + Bookmark.delete(at: deletedIndexes, context: modelContext) + } + } + .onDeleteCommand { + switch self.selection { + case .bookmark(let bookmark): + Bookmark.delete(bookmark, context: modelContext) + default: + break + } + +// if let bookmark = selection, +// bookmark.type != .temporary { +// Bookmark.delete(bookmark, context: modelContext) +// } + } + .environment(\.defaultMinListRowHeight, 34) + .listStyle(.inset) + .alternatingRowBackgrounds(.enabled) + .onChange(of: AppState.shared.cloudKitReady) { + if attemptedPrepopulate { + print("Tracker: Already attempted to prepopulate bookmarks") + return + } + + print("Tracker: Prepopulating bookmarks") + + attemptedPrepopulate = true + + // Make sure default bookmarks are there when empty. + Bookmark.populateDefaults(context: modelContext) + } + .onAppear { +// Bookmark.deleteAll(context: modelContext) + } + .contextMenu(forSelectionType: TrackerSelection.self) { items in + if let item = items.first { + switch item { + case .bookmark(let bookmark): + self.bookmarkContextMenu(bookmark) + case .bookmarkServer(let server): + self.bookmarkServerContextMenu(server) + } + } + } primaryAction: { items in + guard let clickedItem = items.first else { + return + } + + switch clickedItem { + case .bookmark(let bookmark): + if bookmark.type == .server { + if let s = bookmark.server { + openWindow(id: "server", value: s) + } + } + else if bookmark.type == .tracker { + if NSEvent.modifierFlags.contains(.option) { + trackerSheetBookmark = bookmark + } + else { + self.toggleExpanded(for: bookmark) + } + } + + case .bookmarkServer(let bookmarkServer): + openWindow(id: "server", value: bookmarkServer.server) + } + } + .fileExporter(isPresented: $bookmarkExportActive, document: bookmarkExport, contentTypes: [.data], defaultFilename: "\(bookmarkExport?.bookmark.name ?? "Hotline Bookmark").hlbm", onCompletion: { result in + switch result { + case .success(let fileURL): + print("Hotline Bookmark: Successfully exported:", fileURL) + case .failure(let err): + print("Hotline Bookmark: Failed to export:", err) + } + + bookmarkExport = nil + bookmarkExportActive = false + }, onCancellation: {}) + .onKeyPress(.rightArrow) { + switch self.selection { + case .bookmark(let bookmark): + if bookmark.type == .tracker { + self.setExpanded(true, for: bookmark) + return .handled + } + default: + break + } + + return .ignored + } + .onKeyPress(.leftArrow) { + switch self.selection { + case .bookmark(let bookmark): + if bookmark.type == .tracker { + self.setExpanded(false, for: bookmark) + return .handled + } + default: + break + } + + return .ignored + } + .onDrop(of: [UTType.fileURL], isTargeted: $fileDropActive) { providers, dropPoint in + for provider in providers { + let _ = provider.loadDataRepresentation(for: UTType.fileURL) { dataRepresentation, err in + // HOTLINE CREATOR CODE: 1213484099 + // HOTLINE BOOKMARK TYPE CODE: 1213489773 + + if let filePathData = dataRepresentation, + let filePath = String(data: filePathData, encoding: .utf8), + let fileURL = URL(string: filePath) { + + print("Hotline Bookmark: Dropped from ", fileURL.path(percentEncoded: false)) + + DispatchQueue.main.async { + if let newBookmark = Bookmark(fileURL: fileURL) { + print("Hotline Bookmark: Added bookmark.") + Bookmark.add(newBookmark, context: modelContext) + } + else { + print("Hotline Bookmark: Failed to parse.") + } + } + } + } + } + + return true + } + .sheet(item: $trackerSheetBookmark) { item in + TrackerBookmarkSheet(item) + } + .sheet(isPresented: $trackerSheetPresented) { + TrackerBookmarkSheet() + } + .sheet(item: $serverSheetBookmark) { item in + ServerBookmarkSheet(item) + } + .navigationTitle("Servers") + .toolbar { + if #available(macOS 26.0, *) { + ToolbarItem(placement: .navigation) { + self.hotlineLogoImage + } + .sharedBackgroundVisibility(.hidden) + } + else { + ToolbarItem(placement: .navigation) { + self.hotlineLogoImage + } + } + + ToolbarItem(placement: .primaryAction) { + Button { + self.refreshing = true + self.refresh() + self.refreshing = false + } label: { + Label("Refresh", systemImage: "arrow.clockwise") + } + .disabled(refreshing) + .help("Refresh Trackers") + } + + ToolbarItem(placement: .primaryAction) { + Button { + trackerSheetPresented = true + } label: { + Label("Add Tracker", systemImage: "point.3.filled.connected.trianglepath.dotted") + } + .help("Add Tracker") + } + + ToolbarItem(placement: .primaryAction) { + Button { + openWindow(id: "server") + } label: { + Label("Connect to Server", systemImage: "globe.americas.fill") + } + .help("Connect to Server") + } + } + .onOpenURL(perform: { url in + if let s = Server(url: url) { + openWindow(id: "server", value: s) + } + }) + .searchable(text: $searchText, isPresented: $isSearching, placement: .automatic, prompt: "Search") + .background(Button("", action: { isSearching = true }).keyboardShortcut("f").hidden()) + } + + private var hotlineLogoImage: some View { + Image("Hotline") + .resizable() + .renderingMode(.template) + .scaledToFit() + .foregroundColor(Color(hex: 0xE10000)) + .frame(width: 9) + .opacity(controlActiveState == .inactive ? 0.5 : 1.0) + } + + @ViewBuilder + func bookmarkServerContextMenu(_ server: BookmarkServer) -> some View { + Button { + let newBookmark = Bookmark(type: .server, name: server.name ?? server.address, address: server.address, port: server.port, login: nil, password: nil) + Bookmark.add(newBookmark, context: modelContext) + } label: { + Label("Bookmark", systemImage: "bookmark") + } + + Divider() + + Button { + NSPasteboard.general.clearContents() + let displayAddress = (server.port == HotlinePorts.DefaultServerPort) ? server.address : "\(server.address):\(server.port)" + NSPasteboard.general.setString(displayAddress, forType: .string) + } label: { + Label("Copy Address", systemImage: "doc.on.doc") + } + } + + @ViewBuilder + func bookmarkContextMenu(_ bookmark: Bookmark) -> some View { + Button { + NSPasteboard.general.clearContents() + NSPasteboard.general.setString(bookmark.displayAddress, forType: .string) + } label: { + Label("Copy Address", systemImage: "doc.on.doc") + } + + Divider() + + if bookmark.type == .tracker { + Button { + trackerSheetBookmark = bookmark + } label: { + Label("Edit Tracker...", systemImage: "pencil") + } + } + + if bookmark.type == .server { + Button { + serverSheetBookmark = bookmark + } label: { + Label("Edit Bookmark...", systemImage: "pencil") + } + + Button { + bookmarkExport = BookmarkDocument(bookmark: bookmark) + bookmarkExportActive = true + } label: { + Label("Export Bookmark...", systemImage: "square.and.arrow.down") + } + } + + Divider() + + Button { + Bookmark.delete(bookmark, context: modelContext) + } label: { + Label(bookmark.type == .tracker ? "Delete Tracker" : "Delete Bookmark", systemImage: "trash") + } + } + + + func refresh() { + // When a tracker is selected, refresh only that tracker. + if let trackerSelection = self.selection { + switch trackerSelection { + case .bookmark(let bookmark): + if bookmark.type == .tracker { + if self.expandedTrackers.contains(bookmark) { + // Already expanded, cancel old fetch and start new one + self.fetchTasks[bookmark]?.cancel() + let task = Task { + await self.fetchServers(for: bookmark) + } + self.fetchTasks[bookmark] = task + } else { + // Not expanded, expand it (which also fetches) + self.setExpanded(true, for: bookmark) + } + return + } + break + default: + break + } + } + + // Otherwise refresh/expand all trackers. + for bookmark in self.bookmarks { + if bookmark.type == .tracker { + if self.expandedTrackers.contains(bookmark) { + // Already expanded, cancel old fetch and start new one + self.fetchTasks[bookmark]?.cancel() + let task = Task { + await self.fetchServers(for: bookmark) + } + self.fetchTasks[bookmark] = task + } else { + // Not expanded, expand it (which also fetches) + self.setExpanded(true, for: bookmark) + } + } + } + } + + func toggleExpanded(for bookmark: Bookmark) { + guard bookmark.type == .tracker else { return } + self.setExpanded(!self.expandedTrackers.contains(bookmark), for: bookmark) + } + + func setExpanded(_ expanded: Bool, for bookmark: Bookmark) { + guard bookmark.type == .tracker else { return } + + if expanded && !self.expandedTrackers.contains(bookmark) { + self.expandedTrackers.insert(bookmark) + let task = Task { + await self.fetchServers(for: bookmark) + } + self.fetchTasks[bookmark] = task + } else if !expanded && self.expandedTrackers.contains(bookmark) { + // Cancel ongoing fetch and clear data + self.fetchTasks[bookmark]?.cancel() + self.fetchTasks[bookmark] = nil + self.expandedTrackers.remove(bookmark) + self.trackerServers[bookmark] = nil + self.loadingTrackers.remove(bookmark) + } + } + + private func fetchServers(for bookmark: Bookmark) async { + print("TrackerView.fetchServers: Starting fetch for bookmark: \(bookmark.name)") + self.loadingTrackers.insert(bookmark) + let servers = await bookmark.fetchServers() + print("TrackerView.fetchServers: Got \(servers.count) servers from bookmark.fetchServers()") + await MainActor.run { + print("TrackerView.fetchServers: Assigning \(servers.count) servers to trackerServers[\(bookmark.name)]") + self.trackerServers[bookmark] = servers + self.loadingTrackers.remove(bookmark) + self.fetchTasks[bookmark] = nil // Clean up completed task + print("TrackerView.fetchServers: trackerServers now has \(self.trackerServers.count) entries") + print("TrackerView.fetchServers: Verification - trackerServers[\(bookmark.name)] now has \(self.trackerServers[bookmark]?.count ?? -1) servers") + } + } +} + +#if DEBUG +private struct TrackerViewPreview: View { + @State var selection: TrackerSelection? = nil + + var body: some View { + TrackerView(selection: $selection) + } +} + +#Preview { + TrackerViewPreview() +} +#endif -- cgit From 2f332ee497af925db1a2583135e9dfcdaff84794 Mon Sep 17 00:00:00 2001 From: Dustin Mierau Date: Fri, 7 Nov 2025 21:03:53 -0800 Subject: Add Bonjour discovery for Hotline servers on the local network to the Servers window. --- Hotline.xcodeproj/project.pbxproj | 8 + Hotline/Models/Server.swift | 9 + Hotline/State/AppState.swift | 2 + Hotline/State/BonjourState.swift | 256 ++++++++++++++++++++++++++ Hotline/macOS/Trackers/BonjourServerRow.swift | 19 ++ Hotline/macOS/Trackers/TrackerItemView.swift | 2 +- Hotline/macOS/Trackers/TrackerView.swift | 114 +++++++++++- 7 files changed, 406 insertions(+), 4 deletions(-) create mode 100644 Hotline/State/BonjourState.swift create mode 100644 Hotline/macOS/Trackers/BonjourServerRow.swift (limited to 'Hotline/macOS/Trackers') diff --git a/Hotline.xcodeproj/project.pbxproj b/Hotline.xcodeproj/project.pbxproj index cac321c..f94cba2 100644 --- a/Hotline.xcodeproj/project.pbxproj +++ b/Hotline.xcodeproj/project.pbxproj @@ -38,6 +38,8 @@ DA501BE92EBE9589001714F8 /* TrackerItemView.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA501BE82EBE9589001714F8 /* TrackerItemView.swift */; }; DA501BEB2EBE95B4001714F8 /* TrackerBookmarkServerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA501BEA2EBE95B4001714F8 /* TrackerBookmarkServerView.swift */; }; DA501BEE2EBEC42E001714F8 /* Kingfisher in Frameworks */ = {isa = PBXBuildFile; productRef = DA501BED2EBEC42E001714F8 /* Kingfisher */; }; + DA501BF02EBED848001714F8 /* BonjourState.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA501BEF2EBED848001714F8 /* BonjourState.swift */; }; + DA501BF22EBEF415001714F8 /* BonjourServerRow.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA501BF12EBEF415001714F8 /* BonjourServerRow.swift */; }; DA52689C2EB0738B00DCB941 /* GeneralSettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA52689B2EB0738B00DCB941 /* GeneralSettingsView.swift */; platformFilters = (macos, ); }; DA52689E2EB073A400DCB941 /* IconSettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA52689D2EB073A400DCB941 /* IconSettingsView.swift */; platformFilters = (macos, ); }; DA5268A02EB073BC00DCB941 /* SoundSettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA52689F2EB073BC00DCB941 /* SoundSettingsView.swift */; platformFilters = (macos, ); }; @@ -148,6 +150,8 @@ DA501BE62EBE9542001714F8 /* TrackerBookmarkSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TrackerBookmarkSheet.swift; sourceTree = ""; }; DA501BE82EBE9589001714F8 /* TrackerItemView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TrackerItemView.swift; sourceTree = ""; }; DA501BEA2EBE95B4001714F8 /* TrackerBookmarkServerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TrackerBookmarkServerView.swift; sourceTree = ""; }; + DA501BEF2EBED848001714F8 /* BonjourState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BonjourState.swift; sourceTree = ""; }; + DA501BF12EBEF415001714F8 /* BonjourServerRow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BonjourServerRow.swift; sourceTree = ""; }; DA52689B2EB0738B00DCB941 /* GeneralSettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GeneralSettingsView.swift; sourceTree = ""; }; DA52689D2EB073A400DCB941 /* IconSettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IconSettingsView.swift; sourceTree = ""; }; DA52689F2EB073BC00DCB941 /* SoundSettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SoundSettingsView.swift; sourceTree = ""; }; @@ -259,6 +263,7 @@ DACCE5E02EABE4B4008CDD92 /* AppUpdate.swift */, DA3429B42EBA8A450010784E /* FilePreviewState.swift */, DA5268B02EB2708E00DCB941 /* HotlineState.swift */, + DA501BEF2EBED848001714F8 /* BonjourState.swift */, ); path = State; sourceTree = ""; @@ -304,6 +309,7 @@ DA501BE52EBE9520001714F8 /* Trackers */ = { isa = PBXGroup; children = ( + DA501BF12EBEF415001714F8 /* BonjourServerRow.swift */, DAE734FA2B2E41F9000C56F6 /* TrackerView.swift */, DA501BE82EBE9589001714F8 /* TrackerItemView.swift */, DA501BEA2EBE95B4001714F8 /* TrackerBookmarkServerView.swift */, @@ -693,6 +699,7 @@ DA5753682B33E88A00FAC277 /* HotlineTransferClient.swift in Sources */, DAB4D8822B4C8FED0048A05C /* FileIconView.swift in Sources */, DA65499A2BEC280E00EDB697 /* ServerMessageView.swift in Sources */, + DA501BF02EBED848001714F8 /* BonjourState.swift in Sources */, DAAEE66F2B47625600A5BA07 /* FilePreviewImageView.swift in Sources */, DA872B152BDDEE1A008B1012 /* VisualEffectView.swift in Sources */, DA3429AE2EB9C0280010784E /* HotlineFileUploadClientNew.swift in Sources */, @@ -707,6 +714,7 @@ DAC87F072C5010E80060FADF /* HotlineExtensions.swift in Sources */, DAE734FD2B2E65E9000C56F6 /* MessageBoardView.swift in Sources */, DA6980832BFFD06C003E434B /* BookmarkDocument.swift in Sources */, + DA501BF22EBEF415001714F8 /* BonjourServerRow.swift in Sources */, DA501BE72EBE9542001714F8 /* TrackerBookmarkSheet.swift in Sources */, DAB4D87E2B4C8BCA0048A05C /* FilePreviewTextView.swift in Sources */, DA3429B72EBAB1750010784E /* QuickLookPreviewView.swift in Sources */, diff --git a/Hotline/Models/Server.swift b/Hotline/Models/Server.swift index e0fe38b..7d38752 100644 --- a/Hotline/Models/Server.swift +++ b/Hotline/Models/Server.swift @@ -10,6 +10,15 @@ struct Server: Codable { var login: String var password: String + var displayAddress: String { + if self.port == HotlinePorts.DefaultServerPort { + return self.address + } + else { + return "\(self.address):\(String(self.port))" + } + } + init(name: String?, description: String?, address: String, port: Int = HotlinePorts.DefaultServerPort, users: Int = 0, login: String? = nil, password: String? = nil) { self.name = name self.description = description diff --git a/Hotline/State/AppState.swift b/Hotline/State/AppState.swift index 558af2a..3aadf08 100644 --- a/Hotline/State/AppState.swift +++ b/Hotline/State/AppState.swift @@ -11,6 +11,8 @@ final class AppState { private init() { } + + var bonjourState = BonjourState() var activeHotline: HotlineState? = nil var activeServerState: ServerState? = nil diff --git a/Hotline/State/BonjourState.swift b/Hotline/State/BonjourState.swift new file mode 100644 index 0000000..aa7cf44 --- /dev/null +++ b/Hotline/State/BonjourState.swift @@ -0,0 +1,256 @@ +import Foundation +import Network + +@Observable +class BonjourState { + var isExpanded: Bool = false + var isBrowsing: Bool = false + var discoveredServers: [BonjourServer] = [] + + private var browser: NWBrowser? + private var resolutionTasks: [UUID: Task] = [:] + + private actor ConnectionResolverState { + var completed = false + func markComplete() { + self.completed = true + } + } + + struct BonjourServer: Identifiable, Hashable { + let id = UUID() + let serviceName: String + let name: String + let address: String? + let port: UInt16? + let txtRecords: [String: String] + + var displayName: String { + // Use the advertised name, fall back to service name + self.name.isEmpty ? self.serviceName : self.name + } + + var server: Server? { + guard let address = self.address, + let port = self.port else { + return nil + } + return Server(name: self.displayName, description: nil, address: address, port: Int(port)) + } + + var isLoopback: Bool { + guard let address = self.address else { return false } + return address.hasPrefix("127.") || address.hasPrefix("::1") + } + + static func == (lhs: BonjourServer, rhs: BonjourServer) -> Bool { + lhs.address == rhs.address && lhs.port == rhs.port + } + + func hash(into hasher: inout Hasher) { + hasher.combine(self.id) + } + } + + func startBrowsing() { + guard !self.isBrowsing else { + return + } + + self.isBrowsing = true + self.discoveredServers.removeAll() + + let parameters = NWParameters() + parameters.includePeerToPeer = true + + self.browser = NWBrowser(for: .bonjourWithTXTRecord(type: "_hotline._tcp", domain: nil), using: parameters) + + self.browser?.stateUpdateHandler = { [weak self] newState in + Task { @MainActor in + switch newState { + case .ready: + print("BonjourState: Browser ready") + case .failed(let error): + print("BonjourState: Browser failed: \(error)") + self?.stopBrowsing() + case .cancelled: + print("BonjourState: Browser cancelled") + self?.isBrowsing = false + default: + break + } + } + } + + self.browser?.browseResultsChangedHandler = { [weak self] results, changes in + guard let self = self else { + return + } + + Task { @MainActor in + print("BonjourState: Browse results changed, found \(results.count) services") + + // Handle removed services + for change in changes { + if case .removed(let result) = change { + if case .service(let name, _, _, _) = result.endpoint { + self.discoveredServers.removeAll { $0.serviceName == name } + print("BonjourState: Removed service: \(name)") + } + } + } + + // Handle added/updated services + for change in changes { + if case .added(let result) = change, case .service = result.endpoint { + await self.resolveService(result) + } else if case .changed(_, let new, _) = change, case .service = new.endpoint { + await self.resolveService(new) + } + } + } + } + + self.browser?.start(queue: .main) + } + + private func cleanAddress(_ addressString: String) -> String { + // For link-local IPv6 (fe80::), keep zone ID as it's required + if addressString.hasPrefix("fe80:") { + return addressString + } + + // For everything else, strip zone identifier + return addressString.components(separatedBy: "%").first ?? addressString + } + + private func resolveService(_ result: NWBrowser.Result) async { + guard case .service(let name, _, _, _) = result.endpoint else { + return + } + + // Create a connection to resolve the service + let connection = NWConnection(to: result.endpoint, using: .tcp) + let resolver = ConnectionResolverState() + + await withCheckedContinuation { (continuation: CheckedContinuation) in + connection.stateUpdateHandler = { [weak self] state in + Task { @MainActor in + if Task.isCancelled { + await resolver.markComplete() + return + } + + if await resolver.completed { + return + } + + switch state { + case .ready: + await resolver.markComplete() + + // Extract address and port + var address: String? + var port: UInt16? + + guard let path = connection.currentPath, let endpoint = path.remoteEndpoint else { + return + } + + var isLoopback: Bool = false + if path.usesInterfaceType(.loopback) { + isLoopback = true + } + + if case .hostPort(let host, let nwPort) = endpoint { + switch host { + case .ipv4(let ipv4): + address = self?.cleanAddress(ipv4.debugDescription) + case .ipv6(let ipv6): + address = self?.cleanAddress(ipv6.debugDescription) + case .name(let hostname, _): + address = hostname + @unknown default: + break + } + + if isLoopback { + address = "127.0.0.1" + } + port = nwPort.rawValue + } + + // Parse TXT records + var txtRecords: [String: String] = [:] + if case .bonjour(let txtRecord) = result.metadata { + for (key, value) in txtRecord.dictionary { + txtRecords[key] = value + } + } + + let server = BonjourServer( + serviceName: name, + name: name, + address: address, + port: port, + txtRecords: txtRecords + ) + + // Update or add server + if let index = self?.discoveredServers.firstIndex(where: { $0.serviceName == + name }) { + self?.discoveredServers[index] = server + } else { + self?.discoveredServers.append(server) + } + + connection.cancel() + continuation.resume() + + case .failed(let error): + await resolver.markComplete() + + print("BonjourState: Failed to resolve \(name): \(error)") + connection.cancel() + continuation.resume() + + default: + break + } + } + } + + connection.start(queue: .main) + + // Timeout after 5 seconds + Task { + try? await Task.sleep(nanoseconds: 5_000_000_000) + + if await resolver.completed == false { + await resolver.markComplete() + connection.cancel() + continuation.resume() + } + } + } + } + + func stopBrowsing() { + guard self.isBrowsing else { + return + } + + print("BonjourState: Stopping Bonjour browsing") + + // Cancel all resolution tasks + for (_, task) in self.resolutionTasks { + task.cancel() + } + self.resolutionTasks.removeAll() + + self.browser?.cancel() + self.browser = nil + self.isBrowsing = false + self.discoveredServers.removeAll() + } +} diff --git a/Hotline/macOS/Trackers/BonjourServerRow.swift b/Hotline/macOS/Trackers/BonjourServerRow.swift new file mode 100644 index 0000000..d99b23b --- /dev/null +++ b/Hotline/macOS/Trackers/BonjourServerRow.swift @@ -0,0 +1,19 @@ +import SwiftUI + +struct BonjourServerRow: View { + @Environment(\.openWindow) private var openWindow + + let server: BonjourState.BonjourServer + + var body: some View { + HStack(alignment: .center, spacing: 6) { + Image("Server") + .resizable() + .scaledToFit() + .frame(width: 16, height: 16, alignment: .center) + Text(self.server.displayName).lineLimit(1).truncationMode(.tail) + Spacer(minLength: 0) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } +} diff --git a/Hotline/macOS/Trackers/TrackerItemView.swift b/Hotline/macOS/Trackers/TrackerItemView.swift index 6e62518..37093d2 100644 --- a/Hotline/macOS/Trackers/TrackerItemView.swift +++ b/Hotline/macOS/Trackers/TrackerItemView.swift @@ -36,7 +36,7 @@ struct TrackerItemView: View { if isLoading { ProgressView() .padding([.leading, .trailing], 2) - .controlSize(.small) + .controlSize(.mini) } Spacer(minLength: 0) if isExpanded && count > 0 { diff --git a/Hotline/macOS/Trackers/TrackerView.swift b/Hotline/macOS/Trackers/TrackerView.swift index ddc0a67..0eb4a12 100644 --- a/Hotline/macOS/Trackers/TrackerView.swift +++ b/Hotline/macOS/Trackers/TrackerView.swift @@ -6,11 +6,15 @@ import UniformTypeIdentifiers enum TrackerSelection: Hashable { case bookmark(Bookmark) case bookmarkServer(BookmarkServer) + case bonjourGroup + case bonjourServer(BonjourState.BonjourServer) var server: Server? { switch self { - case .bookmark(let b): return b.server - case .bookmarkServer(let t): return t.server + case .bookmark(let b): b.server + case .bookmarkServer(let t): t.server + case .bonjourGroup: nil + case .bonjourServer(let b): b.server } } } @@ -85,6 +89,62 @@ struct TrackerView: View { } } } + + var bonjourRowView: some View { + HStack(alignment: .center, spacing: 6) { + Button { + AppState.shared.bonjourState.isExpanded.toggle() + } label: { + Text(Image(systemName: AppState.shared.bonjourState.isExpanded ? "chevron.down" : "chevron.right")) + .bold() + .font(.system(size: 10)) + .opacity(0.5) + .frame(alignment: .center) + } + .buttonStyle(.plain) + .frame(width: 10) + .padding(.leading, 4) + .padding(.trailing, 2) + + Image(systemName: "bonjour") + .resizable() + .scaledToFit() + .symbolRenderingMode(.multicolor) + .frame(width: 16, height: 16, alignment: .center) + Text("Bonjour").bold().lineLimit(1).truncationMode(.tail) + + if AppState.shared.bonjourState.isBrowsing { + ProgressView() + .controlSize(.mini) + } + + Spacer(minLength: 0) + + if AppState.shared.bonjourState.isExpanded && !AppState.shared.bonjourState.discoveredServers.isEmpty { + HStack(spacing: 4) { + Text(String(AppState.shared.bonjourState.discoveredServers.count)) + + SpinningGlobeView() + .fontWeight(.semibold) + .frame(width: 12, height: 12) + } + .padding(.horizontal, 6) + .padding(.vertical, 2) + .foregroundStyle(.secondary) +// .background(.quinary) + .clipShape(.capsule) + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .onChange(of: AppState.shared.bonjourState.isExpanded) { oldState, newState in + if newState { + AppState.shared.bonjourState.startBrowsing() + } + else { + AppState.shared.bonjourState.stopBrowsing() + } + } + } var body: some View { List(selection: $selection) { @@ -115,6 +175,17 @@ struct TrackerView: View { .onDelete { deletedIndexes in Bookmark.delete(at: deletedIndexes, context: modelContext) } + + self.bonjourRowView + .tag(TrackerSelection.bonjourGroup) + + if AppState.shared.bonjourState.isExpanded { + ForEach(AppState.shared.bonjourState.discoveredServers, id: \.self) { record in + BonjourServerRow(server: record) + .tag(TrackerSelection.bonjourServer(record)) + .padding(.leading, 16 + 8 + 10) + } + } } .onDeleteCommand { switch self.selection { @@ -155,6 +226,10 @@ struct TrackerView: View { self.bookmarkContextMenu(bookmark) case .bookmarkServer(let server): self.bookmarkServerContextMenu(server) + case .bonjourGroup: + EmptyView() + case .bonjourServer(let bonjourServer): + self.bonjourServerContextMenu(bonjourServer) } } } primaryAction: { items in @@ -180,6 +255,15 @@ struct TrackerView: View { case .bookmarkServer(let bookmarkServer): openWindow(id: "server", value: bookmarkServer.server) + + case .bonjourGroup: + AppState.shared.bonjourState.isExpanded.toggle() + + case .bonjourServer(let bonjourServer): + if let server = bonjourServer.server { + openWindow(id: "server", value: server) + } + } } .fileExporter(isPresented: $bookmarkExportActive, document: bookmarkExport, contentTypes: [.data], defaultFilename: "\(bookmarkExport?.bookmark.name ?? "Hotline Bookmark").hlbm", onCompletion: { result in @@ -380,8 +464,32 @@ struct TrackerView: View { Label(bookmark.type == .tracker ? "Delete Tracker" : "Delete Bookmark", systemImage: "trash") } } - + @ViewBuilder + func bonjourServerContextMenu(_ bonjourServer: BonjourState.BonjourServer) -> some View { + Button { + guard let server = bonjourServer.server else { + return + } + let newBookmark = Bookmark(type: .server, name: server.name ?? server.address, address: server.address, port: server.port, login: nil, password: nil) + Bookmark.add(newBookmark, context: modelContext) + } label: { + Label("Bookmark", systemImage: "bookmark") + } + + Divider() + + Button { + guard let server = bonjourServer.server else { + return + } + NSPasteboard.general.clearContents() + NSPasteboard.general.setString(server.displayAddress, forType: .string) + } label: { + Label("Copy Address", systemImage: "doc.on.doc") + } + } + func refresh() { // When a tracker is selected, refresh only that tracker. if let trackerSelection = self.selection { -- cgit From 286c408370681b022deaabd254d499aefec28add Mon Sep 17 00:00:00 2001 From: Dustin Mierau Date: Sat, 8 Nov 2025 12:33:00 -0800 Subject: Some work on making it possible to connect to servers with an IPv6 address. Improve connect form a bit. Add Copy Link to context menu for servers and trackers. --- Hotline.xcodeproj/project.pbxproj | 2 +- Hotline/Library/NetSocket/NetSocket.swift | 19 +++- Hotline/Models/Server.swift | 50 +++++++++- Hotline/State/BonjourState.swift | 22 +++-- Hotline/macOS/ServerView.swift | 151 +++++++++++++++--------------- Hotline/macOS/Trackers/TrackerView.swift | 50 ++++++++-- 6 files changed, 195 insertions(+), 99 deletions(-) (limited to 'Hotline/macOS/Trackers') diff --git a/Hotline.xcodeproj/project.pbxproj b/Hotline.xcodeproj/project.pbxproj index f94cba2..3e600a4 100644 --- a/Hotline.xcodeproj/project.pbxproj +++ b/Hotline.xcodeproj/project.pbxproj @@ -309,12 +309,12 @@ DA501BE52EBE9520001714F8 /* Trackers */ = { isa = PBXGroup; children = ( - DA501BF12EBEF415001714F8 /* BonjourServerRow.swift */, DAE734FA2B2E41F9000C56F6 /* TrackerView.swift */, DA501BE82EBE9589001714F8 /* TrackerItemView.swift */, DA501BEA2EBE95B4001714F8 /* TrackerBookmarkServerView.swift */, DA501BE62EBE9542001714F8 /* TrackerBookmarkSheet.swift */, DA501BE32EBE9517001714F8 /* ServerBookmarkSheet.swift */, + DA501BF12EBEF415001714F8 /* BonjourServerRow.swift */, ); path = Trackers; sourceTree = ""; diff --git a/Hotline/Library/NetSocket/NetSocket.swift b/Hotline/Library/NetSocket/NetSocket.swift index 5c7d185..e66ef3f 100644 --- a/Hotline/Library/NetSocket/NetSocket.swift +++ b/Hotline/Library/NetSocket/NetSocket.swift @@ -173,7 +173,24 @@ public actor NetSocket { guard let nwPort = NWEndpoint.Port(rawValue: port) else { throw NetSocketError.invalidPort } - return try await self.connect(host: .name(host, nil), port: nwPort, tls: tls, config: config) + + // Parse the host string to create the appropriate NWEndpoint.Host + let nwHost: NWEndpoint.Host + + // Try parsing as IPv6 without zone + if let ipv6Addr = IPv6Address(host) { + nwHost = .ipv6(ipv6Addr) + } + // Try parsing as IPv4 + else if let ipv4Addr = IPv4Address(host) { + nwHost = .ipv4(ipv4Addr) + } + // Fall back to treating as hostname + else { + nwHost = .name(host, nil) + } + + return try await self.connect(host: nwHost, port: nwPort, tls: tls, config: config) } // MARK: Close diff --git a/Hotline/Models/Server.swift b/Hotline/Models/Server.swift index 7d38752..3ad3375 100644 --- a/Hotline/Models/Server.swift +++ b/Hotline/Models/Server.swift @@ -15,7 +15,12 @@ struct Server: Codable { return self.address } else { - return "\(self.address):\(String(self.port))" + // Wrap IPv6 addresses in brackets when displaying with port + if self.address.contains(":") { + return "[\(self.address)]:\(String(self.port))" + } else { + return "\(self.address):\(String(self.port))" + } } } @@ -50,10 +55,49 @@ struct Server: Codable { } static func parseServerAddressAndPort(_ address: String) -> (String, Int) { - let url = URL(string: "hotline://\(address)") + let trimmed = address.trimmingCharacters(in: .whitespacesAndNewlines) + + // Check if this looks like an IPv6 address (contains colons but no port delimiter) + // IPv6 addresses can be: + // - fe80::1234 + // - [fe80::1234]:5500 (with port) + // - 2001:db8::1 + // - [2001:db8::1]:6500 (with port) + + // If it starts with [, it's bracketed IPv6 with optional port + if trimmed.hasPrefix("[") { + // Find the closing bracket + if let closeBracketIndex = trimmed.firstIndex(of: "]") { + let hostEndIndex = trimmed.index(after: closeBracketIndex) + let host = String(trimmed[trimmed.index(after: trimmed.startIndex).. 1 { + // This is likely an IPv6 address without a port + // Keep it as-is, including any zone identifier (e.g., %en1 for link-local) + return (trimmed.lowercased(), HotlinePorts.DefaultServerPort) + } + + // Otherwise use URL parsing for IPv4 or hostnames + let url = URL(string: "hotline://\(trimmed)") let port = url?.port ?? HotlinePorts.DefaultServerPort let host = url?.host(percentEncoded: false) ?? "" - return (host.lowercased().trimmingCharacters(in: .whitespacesAndNewlines), port) + return (host.lowercased(), port) } } diff --git a/Hotline/State/BonjourState.swift b/Hotline/State/BonjourState.swift index aa7cf44..b0bb42c 100644 --- a/Hotline/State/BonjourState.swift +++ b/Hotline/State/BonjourState.swift @@ -115,12 +115,13 @@ class BonjourState { } private func cleanAddress(_ addressString: String) -> String { - // For link-local IPv6 (fe80::), keep zone ID as it's required + // For link-local IPv6 addresses (fe80::), we MUST keep the zone identifier + // because it tells the system which network interface to use for routing + // For all other addresses (global IPv6, IPv4), strip the zone identifier if addressString.hasPrefix("fe80:") { return addressString } - - // For everything else, strip zone identifier + return addressString.components(separatedBy: "%").first ?? addressString } @@ -128,7 +129,7 @@ class BonjourState { guard case .service(let name, _, _, _) = result.endpoint else { return } - + // Create a connection to resolve the service let connection = NWConnection(to: result.endpoint, using: .tcp) let resolver = ConnectionResolverState() @@ -148,32 +149,33 @@ class BonjourState { switch state { case .ready: await resolver.markComplete() - + // Extract address and port var address: String? var port: UInt16? - + guard let path = connection.currentPath, let endpoint = path.remoteEndpoint else { return } - + var isLoopback: Bool = false if path.usesInterfaceType(.loopback) { isLoopback = true } - + if case .hostPort(let host, let nwPort) = endpoint { switch host { case .ipv4(let ipv4): address = self?.cleanAddress(ipv4.debugDescription) case .ipv6(let ipv6): - address = self?.cleanAddress(ipv6.debugDescription) + let ipv6String = ipv6.debugDescription + address = self?.cleanAddress(ipv6String) case .name(let hostname, _): address = hostname @unknown default: break } - + if isLoopback { address = "127.0.0.1" } diff --git a/Hotline/macOS/ServerView.swift b/Hotline/macOS/ServerView.swift index a66a071..d2c503f 100644 --- a/Hotline/macOS/ServerView.swift +++ b/Hotline/macOS/ServerView.swift @@ -116,8 +116,13 @@ struct ServerView: View { var body: some View { Group { if model.status == .disconnected { - connectForm - .navigationTitle("Connect to Server") + VStack(alignment: .center) { + Spacer() + self.connectForm + Spacer() + } +// .frame(maxWidth: .infinity, maxHeight: .infinity) + .navigationTitle("Connect to Server") } else if case .failed(let error) = model.status { VStack { @@ -245,79 +250,80 @@ struct ServerView: View { } var connectForm: some View { - VStack(alignment: .center) { - GroupBox { - Form { - Group { - TextField(text: $connectAddress) { - Text("Address:") - } - .focused($focusedField, equals: .address) - - Text("Type the address of the Hotline server you would like to connect to. If you have an account on that server, type your login and password too.") - .font(.caption) - .foregroundStyle(.secondary) - .padding(.bottom, 4) - - TextField(text: $connectLogin, prompt: Text("Optional")) { - Text("Login:") - } - .focused($focusedField, equals: .login) - SecureField(text: $connectPassword, prompt: Text("Optional")) { - Text("Password:") - } - .focused($focusedField, equals: .password) - } - .textFieldStyle(.roundedBorder) - .controlSize(.large) - - HStack { - Button("Save...") { - if !connectAddress.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { - connectNameSheetPresented = true - } - } - .disabled(connectAddress.isEmpty) - .controlSize(.regular) - .buttonStyle(.automatic) - .help("Bookmark server") - - Spacer() - - Button("Cancel") { - dismiss() - } - .controlSize(.regular) - .buttonStyle(.automatic) - .keyboardShortcut(.cancelAction) - - Button("Connect") { - connectToServer() - } - - .controlSize(.regular) - .buttonStyle(.automatic) - .keyboardShortcut(.defaultAction) - } - .padding(.top, 8) - + Form { + HStack(alignment: .top, spacing: 10) { + Image("Server Large") + .resizable() + .scaledToFit() + .frame(width: 28, height: 28) + + VStack(alignment: .leading) { + Text("Connect to Server") + Text("Enter the address of a Hotline server to connect to.") + .foregroundStyle(.secondary) + .font(.subheadline) } - .padding() - .onChange(of: connectAddress) { - let (a, p) = Server.parseServerAddressAndPort(connectAddress) - server.address = a - server.port = p + } + + TextField(text: $connectAddress) { + Text("Address:") + } + .focused($focusedField, equals: .address) + + TextField(text: $connectLogin, prompt: Text("Optional")) { + Text("Login:") + } + .focused($focusedField, equals: .login) + SecureField(text: $connectPassword, prompt: Text("Optional")) { + Text("Password:") + } + .focused($focusedField, equals: .password) + + HStack { + Button("Save...") { + if !connectAddress.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + connectNameSheetPresented = true + } } - .onChange(of: connectLogin) { - server.login = connectLogin.trimmingCharacters(in: .whitespacesAndNewlines) + .disabled(connectAddress.isEmpty) + .controlSize(.regular) + .buttonStyle(.automatic) + .help("Bookmark server") + + Spacer() + + Button("Cancel") { + dismiss() } - .onChange(of: connectPassword) { - server.password = connectPassword + .controlSize(.regular) + .buttonStyle(.automatic) + .keyboardShortcut(.cancelAction) + + Button("Connect") { + connectToServer() } + + .controlSize(.regular) + .buttonStyle(.automatic) + .keyboardShortcut(.defaultAction) } - .onAppear { - focusedField = .address - } + .padding(.top, 8) + } + .formStyle(.grouped) + .fixedSize(horizontal: false, vertical: true) + .onChange(of: connectAddress) { + let (a, p) = Server.parseServerAddressAndPort(connectAddress) + server.address = a + server.port = p + } + .onChange(of: connectLogin) { + server.login = connectLogin.trimmingCharacters(in: .whitespacesAndNewlines) + } + .onChange(of: connectPassword) { + server.password = connectPassword + } + .onAppear { + focusedField = .address } .frame(maxWidth: 380) .padding() @@ -346,8 +352,7 @@ struct ServerView: View { if !name.isEmpty { connectNameSheetPresented = false connectName = "" -// Task.detached { - + let (host, port) = Server.parseServerAddressAndPort(connectAddress) let login: String? = connectLogin.isEmpty ? nil : connectLogin let password: String? = connectPassword.isEmpty ? nil : connectPassword @@ -356,8 +361,6 @@ struct ServerView: View { let newBookmark = Bookmark(type: .server, name: name, address: host, port: port, login: login, password: password) Bookmark.add(newBookmark, context: modelContext) } - -// } } } } diff --git a/Hotline/macOS/Trackers/TrackerView.swift b/Hotline/macOS/Trackers/TrackerView.swift index 0eb4a12..dbbacaa 100644 --- a/Hotline/macOS/Trackers/TrackerView.swift +++ b/Hotline/macOS/Trackers/TrackerView.swift @@ -405,14 +405,13 @@ struct TrackerView: View { @ViewBuilder func bookmarkServerContextMenu(_ server: BookmarkServer) -> some View { Button { - let newBookmark = Bookmark(type: .server, name: server.name ?? server.address, address: server.address, port: server.port, login: nil, password: nil) - Bookmark.add(newBookmark, context: modelContext) + NSPasteboard.general.clearContents() + let displayAddress = (server.port == HotlinePorts.DefaultServerPort) ? server.address : "\(server.address):\(server.port)" + NSPasteboard.general.setString("hotline://\(displayAddress)", forType: .string) } label: { - Label("Bookmark", systemImage: "bookmark") + Label("Copy Link", systemImage: "link") } - Divider() - Button { NSPasteboard.general.clearContents() let displayAddress = (server.port == HotlinePorts.DefaultServerPort) ? server.address : "\(server.address):\(server.port)" @@ -420,10 +419,30 @@ struct TrackerView: View { } label: { Label("Copy Address", systemImage: "doc.on.doc") } + + Divider() + + Button { + let newBookmark = Bookmark(type: .server, name: server.name ?? server.address, address: server.address, port: server.port, login: nil, password: nil) + Bookmark.add(newBookmark, context: modelContext) + } label: { + Label("Bookmark", systemImage: "bookmark") + } } @ViewBuilder func bookmarkContextMenu(_ bookmark: Bookmark) -> some View { + Button { + let linkString: String = switch bookmark.type { + case .tracker: "hotlinetracker://\(bookmark.displayAddress)" + case .server: "hotline://\(bookmark.displayAddress)" + } + NSPasteboard.general.clearContents() + NSPasteboard.general.setString(linkString, forType: .string) + } label: { + Label("Copy Link", systemImage: "link") + } + Button { NSPasteboard.general.clearContents() NSPasteboard.general.setString(bookmark.displayAddress, forType: .string) @@ -471,14 +490,13 @@ struct TrackerView: View { guard let server = bonjourServer.server else { return } - let newBookmark = Bookmark(type: .server, name: server.name ?? server.address, address: server.address, port: server.port, login: nil, password: nil) - Bookmark.add(newBookmark, context: modelContext) + NSPasteboard.general.clearContents() + let displayAddress = (server.port == HotlinePorts.DefaultServerPort) ? server.address : "\(server.address):\(server.port)" + NSPasteboard.general.setString("hotline://\(displayAddress)", forType: .string) } label: { - Label("Bookmark", systemImage: "bookmark") + Label("Copy Link", systemImage: "link") } - Divider() - Button { guard let server = bonjourServer.server else { return @@ -488,6 +506,18 @@ struct TrackerView: View { } label: { Label("Copy Address", systemImage: "doc.on.doc") } + + Divider() + + Button { + guard let server = bonjourServer.server else { + return + } + let newBookmark = Bookmark(type: .server, name: server.name ?? server.address, address: server.address, port: server.port, login: nil, password: nil) + Bookmark.add(newBookmark, context: modelContext) + } label: { + Label("Bookmark", systemImage: "bookmark") + } } func refresh() { -- cgit From 2caf86e633c1a121c8e23d068ac817ed8e80f6a7 Mon Sep 17 00:00:00 2001 From: Dustin Mierau Date: Sat, 8 Nov 2025 19:51:48 -0800 Subject: Moved SoundEffects to Managers. Updated connect form in ServerView. Changed some icons in context menus for bookmarks. --- Hotline.xcodeproj/project.pbxproj | 2 +- Hotline/Library/SoundEffects.swift | 41 ------------------ Hotline/Managers/SoundEffects.swift | 40 +++++++++++++++++ Hotline/macOS/ServerView.swift | 73 +++++++++++++++++--------------- Hotline/macOS/Trackers/TrackerView.swift | 7 ++- 5 files changed, 85 insertions(+), 78 deletions(-) delete mode 100644 Hotline/Library/SoundEffects.swift create mode 100644 Hotline/Managers/SoundEffects.swift (limited to 'Hotline/macOS/Trackers') diff --git a/Hotline.xcodeproj/project.pbxproj b/Hotline.xcodeproj/project.pbxproj index 3e600a4..f91bcf8 100644 --- a/Hotline.xcodeproj/project.pbxproj +++ b/Hotline.xcodeproj/project.pbxproj @@ -441,7 +441,6 @@ children = ( DAB4D8832B4CABEF0048A05C /* Extensions.swift */, DA5268AA2EB11EA300DCB941 /* ColorArt.swift */, - DAE735062B3251B3000C56F6 /* SoundEffects.swift */, DA55AC782BE6A1AD00034857 /* RegularExpressions.swift */, DA6980822BFFD06C003E434B /* BookmarkDocument.swift */, DA501BE02EBE844F001714F8 /* Views */, @@ -494,6 +493,7 @@ DAC6B2DF2EAC6236004E2CBA /* Managers */ = { isa = PBXGroup; children = ( + DAE735062B3251B3000C56F6 /* SoundEffects.swift */, DAC6B2DE2EAC6236004E2CBA /* ChatStore.swift */, ); path = Managers; diff --git a/Hotline/Library/SoundEffects.swift b/Hotline/Library/SoundEffects.swift deleted file mode 100644 index 4964b94..0000000 --- a/Hotline/Library/SoundEffects.swift +++ /dev/null @@ -1,41 +0,0 @@ -import Foundation -import AppKit - -enum SoundEffect: String { - case loggedIn = "logged-in" - case chatMessage = "chat-message" - case transferComplete = "transfer-complete" - case userLogin = "user-login" - case userLogout = "user-logout" - case newNews = "new-news" - case serverMessage = "server-message" - case error = "error" - - static var all: [SoundEffect] = [.loggedIn, .chatMessage, .transferComplete, .userLogin, .userLogout, .newNews, .serverMessage, .error] -} - -@Observable -class SoundEffects { - static let shared = SoundEffects() - - private var preloadedSounds: [SoundEffect: NSSound] = [:] - - private init() { - // Preload sound effects - for effect in SoundEffect.all { - if let soundFileURL = Bundle.main.url(forResource: effect.rawValue, withExtension: "aiff"), - let sound = NSSound(contentsOf: soundFileURL, byReference: true) { - sound.volume = 0.75 - self.preloadedSounds[effect] = sound - } - } - } - - static func play(_ name: SoundEffect) { - Self.shared.play(name) - } - - func play(_ name: SoundEffect) { - self.preloadedSounds[name]?.play() - } -} diff --git a/Hotline/Managers/SoundEffects.swift b/Hotline/Managers/SoundEffects.swift new file mode 100644 index 0000000..85a1c0e --- /dev/null +++ b/Hotline/Managers/SoundEffects.swift @@ -0,0 +1,40 @@ +import Foundation +import AppKit + +enum SoundEffect: String { + case loggedIn = "logged-in" + case chatMessage = "chat-message" + case transferComplete = "transfer-complete" + case userLogin = "user-login" + case userLogout = "user-logout" + case newNews = "new-news" + case serverMessage = "server-message" + case error = "error" + + static var all: [SoundEffect] = [.loggedIn, .chatMessage, .transferComplete, .userLogin, .userLogout, .newNews, .serverMessage, .error] +} + +class SoundEffects { + static let shared = SoundEffects() + + static func play(_ name: SoundEffect) { + Self.shared.play(name) + } + + private var preloadedSounds: [SoundEffect: NSSound] = [:] + + private init() { + // Preload sound effects + for effect in SoundEffect.all { + if let soundFileURL = Bundle.main.url(forResource: effect.rawValue, withExtension: "aiff"), + let sound = NSSound(contentsOf: soundFileURL, byReference: true) { + sound.volume = 0.75 + self.preloadedSounds[effect] = sound + } + } + } + + func play(_ name: SoundEffect) { + self.preloadedSounds[name]?.play() + } +} diff --git a/Hotline/macOS/ServerView.swift b/Hotline/macOS/ServerView.swift index d2c503f..44274ea 100644 --- a/Hotline/macOS/ServerView.swift +++ b/Hotline/macOS/ServerView.swift @@ -121,8 +121,10 @@ struct ServerView: View { self.connectForm Spacer() } -// .frame(maxWidth: .infinity, maxHeight: .infinity) .navigationTitle("Connect to Server") + .onAppear { + self.focusedField = .address + } } else if case .failed(let error) = model.status { VStack { @@ -250,40 +252,47 @@ struct ServerView: View { } var connectForm: some View { - Form { - HStack(alignment: .top, spacing: 10) { - Image("Server Large") - .resizable() - .scaledToFit() - .frame(width: 28, height: 28) + VStack(alignment: .center, spacing: 0) { + Form { + HStack(alignment: .top, spacing: 10) { + Image("Server Large") + .resizable() + .scaledToFit() + .frame(width: 28, height: 28) + + VStack(alignment: .leading) { + Text("Connect to Server") + Text("Enter the address of a Hotline server to connect to.") + .foregroundStyle(.secondary) + .font(.subheadline) + } + } - VStack(alignment: .leading) { - Text("Connect to Server") - Text("Enter the address of a Hotline server to connect to.") - .foregroundStyle(.secondary) - .font(.subheadline) + TextField(text: $connectAddress) { + Text("Address") } + .focused($focusedField, equals: .address) + + TextField(text: $connectLogin, prompt: Text("Optional")) { + Text("Login") + } + .focused($focusedField, equals: .login) + + SecureField(text: $connectPassword, prompt: Text("Optional")) { + Text("Password") + } + .focused($focusedField, equals: .password) } - - TextField(text: $connectAddress) { - Text("Address:") - } - .focused($focusedField, equals: .address) - - TextField(text: $connectLogin, prompt: Text("Optional")) { - Text("Login:") - } - .focused($focusedField, equals: .login) - SecureField(text: $connectPassword, prompt: Text("Optional")) { - Text("Password:") - } - .focused($focusedField, equals: .password) + .formStyle(.grouped) + .fixedSize(horizontal: false, vertical: true) HStack { - Button("Save...") { + Button { if !connectAddress.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { connectNameSheetPresented = true } + } label: { + Image(systemName: "bookmark.fill") } .disabled(connectAddress.isEmpty) .controlSize(.regular) @@ -302,15 +311,12 @@ struct ServerView: View { Button("Connect") { connectToServer() } - .controlSize(.regular) .buttonStyle(.automatic) .keyboardShortcut(.defaultAction) } - .padding(.top, 8) + .padding(.horizontal, 20) } - .formStyle(.grouped) - .fixedSize(horizontal: false, vertical: true) .onChange(of: connectAddress) { let (a, p) = Server.parseServerAddressAndPort(connectAddress) server.address = a @@ -322,14 +328,11 @@ struct ServerView: View { .onChange(of: connectPassword) { server.password = connectPassword } - .onAppear { - focusedField = .address - } .frame(maxWidth: 380) .padding() .sheet(isPresented: $connectNameSheetPresented) { VStack(alignment: .leading) { - Text("Name this server bookmark:") + Text("Save Bookmark") .foregroundStyle(.secondary) .padding(.bottom, 4) TextField("Bookmark Name", text: $connectName) diff --git a/Hotline/macOS/Trackers/TrackerView.swift b/Hotline/macOS/Trackers/TrackerView.swift index dbbacaa..e0ca87d 100644 --- a/Hotline/macOS/Trackers/TrackerView.swift +++ b/Hotline/macOS/Trackers/TrackerView.swift @@ -480,7 +480,12 @@ struct TrackerView: View { Button { Bookmark.delete(bookmark, context: modelContext) } label: { - Label(bookmark.type == .tracker ? "Delete Tracker" : "Delete Bookmark", systemImage: "trash") + if bookmark.type == .tracker { + Label("Delete Tracker", systemImage: "xmark") + } + else { + Label("Delete Bookmark", systemImage: "bookmark.slash") + } } } -- cgit