Merge current main into conversation notification mute

Keep the current catalog and add only the reviewed mute strings. Import the shared string helper from BitFoundation.
This commit is contained in:
Taksh 2026-11-09 19:08:33 +05:30
commit bebbfc862c
88 changed files with 9123 additions and 1692 deletions

View File

@ -1,4 +1,4 @@
MARKETING_VERSION = 1.7.1
MARKETING_VERSION = 1.8.0
CURRENT_PROJECT_VERSION = 1
IPHONEOS_DEPLOYMENT_TARGET = 16.0

4
Package.resolved generated
View File

@ -5,8 +5,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/21-DOT-DEV/swift-secp256k1",
"state" : {
"revision" : "8c62aba8a3011c9bcea232e5ee007fb0b34a15e2",
"version" : "0.21.1"
"revision" : "bcd6dd8e615ce243eab7097f213c8c4b39305a2e",
"version" : "0.24.0"
}
}
],

View File

@ -19,7 +19,7 @@ let package = Package(
.package(path: "localPackages/Arti"),
.package(path: "localPackages/BitFoundation"),
.package(path: "localPackages/BitLogger"),
.package(url: "https://github.com/21-DOT-DEV/swift-secp256k1", exact: "0.21.1")
.package(url: "https://github.com/21-DOT-DEV/swift-secp256k1", exact: "0.24.0")
],
targets: [
.executableTarget(
@ -38,7 +38,10 @@ let package = Package(
"bitchat.entitlements",
"bitchat-macOS.entitlements",
"LaunchScreen.storyboard",
"ViewModels/Extensions/README.md"
"ViewModels/Extensions/README.md",
// Globe picker geometry, bundled by the Xcode app targets and read
// from Bundle.main; the SwiftPM build only runs tests.
"Resources/Globe"
],
resources: [
.process("Localizable.xcstrings")

View File

@ -935,7 +935,7 @@
repositoryURL = "https://github.com/21-DOT-DEV/swift-secp256k1";
requirement = {
kind = exactVersion;
version = 0.21.1;
version = 0.24.0;
};
};
/* End XCRemoteSwiftPackageReference section */

View File

@ -11,7 +11,6 @@ final class ConversationUIModel: ObservableObject {
@Published private(set) var autocompleteSuggestions: [String] = []
@Published private(set) var selectedAutocompleteIndex = 0
@Published private(set) var currentNickname: String
@Published private(set) var isBatchingPublic = false
@Published private(set) var canSendMediaInCurrentContext = true
@Published private(set) var legacyPrivateMediaConsentRequest: LegacyPrivateMediaConsentRequest?
/// Who is talking live in the public mesh channel right now (floor
@ -23,6 +22,15 @@ final class ConversationUIModel: ObservableObject {
private let conversations: ConversationStore
private var activeChannel: ChannelID
private var cancellables = Set<AnyCancellable>()
/// My geochat sender ID for the location channel on screen, kept with the
/// public key it was built from. `publicKeyHex` hex-encodes on every
/// access, too slow to repeat per row render; keying on the key itself
/// means a geohash switch or a panic wipe (which reseeds every identity)
/// can never leave a stale ID behind. A switch to #mesh, where no row
/// reads it, drops it: a panic wipe always lands there, and the retired
/// key must not stay in memory until a geochat row next renders.
/// (Read access is internal so tests can check that.)
private(set) var ownGeoChatSender: (publicKey: Data, peerID: PeerID)?
init(
chatViewModel: ChatViewModel,
@ -34,7 +42,6 @@ final class ConversationUIModel: ObservableObject {
self.conversations = conversations
self.activeChannel = conversations.activeChannel
self.currentNickname = chatViewModel.nickname
self.isBatchingPublic = chatViewModel.isBatchingPublic
self.showAutocomplete = chatViewModel.showAutocomplete
self.autocompleteSuggestions = chatViewModel.autocompleteSuggestions
self.selectedAutocompleteIndex = chatViewModel.selectedAutocompleteIndex
@ -144,19 +151,50 @@ final class ConversationUIModel: ObservableObject {
}
func mediaAttachment(for message: BitchatMessage) -> BitchatMessage.Media? {
message.mediaAttachment(for: currentNickname)
// The model loads from outgoing/ exactly when the row's sender equals
// the name it is given. Ask with the row's own sender first: text rows,
// most of the timeline, stop here without an identity check per render.
guard let outgoing = message.mediaAttachment(for: message.sender) else { return nil }
if isSentByCurrentUser(message) { return outgoing }
// Not mine by identity: a name the sender can never equal (one
// character longer) loads it from incoming/, so a namesake's file
// resolves there while my send from before a rename stays outgoing.
return message.mediaAttachment(for: message.sender + "\u{0}")
}
func isSelfSender(peerID: PeerID?, displayName: String?) -> Bool {
chatViewModel.isSelfSender(peerID: peerID, displayName: displayName)
}
/// Whether this device wrote the row, by the sender ID it carries (see
/// `BitchatMessage.isOwn`), never by its display name: a namesake, an
/// `anon#xxxx` stranger next to a reader named "anon", and my own rows
/// from before a rename are all told apart correctly.
func isSentByCurrentUser(_ message: BitchatMessage) -> Bool {
message.sender == currentNickname || message.sender.hasPrefix(currentNickname + "#")
message.isOwn(
myPeerID: chatViewModel.meshService.myPeerID,
myGeoChatPeerID: ownGeoChatPeerID()
)
}
func isMediaMessageFromCurrentUser(_ message: BitchatMessage) -> Bool {
message.sender == currentNickname || message.senderPeerID == chatViewModel.meshService.myPeerID
isSentByCurrentUser(message)
}
/// My geochat sender ID in the location channel on screen (nil on #mesh),
/// memoized in `ownGeoChatSender`.
private func ownGeoChatPeerID() -> PeerID? {
// The store's channel, not the mirrored `activeChannel`, which trails
// a switch by a runloop turn.
guard case .location(let channel) = conversations.activeChannel,
let identity = chatViewModel.geohashIdentity(for: channel.geohash)
else { return nil }
if let cached = ownGeoChatSender, cached.publicKey == identity.publicKey {
return cached.peerID
}
let peerID = PeerID(nostr: identity.publicKeyHex)
ownGeoChatSender = (identity.publicKey, peerID)
return peerID
}
/// Whether a private-message row should show the filled verification seal
@ -224,31 +262,35 @@ final class ConversationUIModel: ObservableObject {
}
private func bind() {
// Every message row observes this model, so each republish re-renders
// all of them: forward only real changes, never a re-sent equal value.
chatViewModel.$nickname
.removeDuplicates()
.receive(on: DispatchQueue.main)
.assign(to: &$currentNickname)
chatViewModel.$showAutocomplete
.removeDuplicates()
.receive(on: DispatchQueue.main)
.assign(to: &$showAutocomplete)
chatViewModel.$autocompleteSuggestions
.removeDuplicates()
.receive(on: DispatchQueue.main)
.assign(to: &$autocompleteSuggestions)
chatViewModel.$selectedAutocompleteIndex
.removeDuplicates()
.receive(on: DispatchQueue.main)
.assign(to: &$selectedAutocompleteIndex)
chatViewModel.$isBatchingPublic
.receive(on: DispatchQueue.main)
.assign(to: &$isBatchingPublic)
chatViewModel.$activePublicVoiceTalker
.removeDuplicates()
.receive(on: DispatchQueue.main)
.assign(to: &$activeLiveVoiceTalker)
chatViewModel.$legacyPrivateMediaConsentRequest
.removeDuplicates()
.receive(on: DispatchQueue.main)
.assign(to: &$legacyPrivateMediaConsentRequest)
@ -256,6 +298,9 @@ final class ConversationUIModel: ObservableObject {
.receive(on: DispatchQueue.main)
.sink { [weak self] channel in
self?.activeChannel = channel
if channel == .mesh {
self?.ownGeoChatSender = nil
}
self?.refreshComputedState()
}
.store(in: &cancellables)
@ -278,18 +323,24 @@ final class ConversationUIModel: ObservableObject {
}
private func refreshComputedState() {
let canSendMedia: Bool
if let selectedPeerID = privateConversationModel.selectedPeerID {
// Media transfer is not wired for groups in v1; keep it off so the
// composer can't strand a media placeholder that never sends.
canSendMediaInCurrentContext = !(selectedPeerID.isGeoDM || selectedPeerID.isGeoChat || selectedPeerID.isGroup)
return
canSendMedia = !(selectedPeerID.isGeoDM || selectedPeerID.isGeoChat || selectedPeerID.isGroup)
} else {
switch activeChannel {
case .mesh:
canSendMedia = true
case .location:
canSendMedia = false
}
}
switch activeChannel {
case .mesh:
canSendMediaInCurrentContext = true
case .location:
canSendMediaInCurrentContext = false
// Every write republishes to every message row, and most triggers
// (each peer, favorite or status refresh of the selection) leave the
// value as it was.
if canSendMediaInCurrentContext != canSendMedia {
canSendMediaInCurrentContext = canSendMedia
}
}
}

View File

@ -30,17 +30,22 @@ final class LocationPresenceStore: ObservableObject {
currentGeohash = normalized
}
func setNickname(_ nickname: String, for pubkeyHex: String) {
/// Returns whether the stored nickname changed. Chat events repeat the
/// sender's nickname every time; rewriting an unchanged value would
/// republish the whole table.
@discardableResult
func setNickname(_ nickname: String, for pubkeyHex: String) -> Bool {
guard geoNicknameCapacity > 0 else {
clearGeoNicknames()
return
return false
}
let nickname = nickname.normalizedNickname
let key = pubkeyHex.lowercased()
if geoNicknames[key] != nil {
if let existing = geoNicknames[key] {
guard existing != nickname else { return false }
geoNicknames[key] = nickname
return
return true
}
while geoNicknameOrder.count >= geoNicknameCapacity, let oldest = geoNicknameOrder.first {
@ -50,6 +55,7 @@ final class LocationPresenceStore: ObservableObject {
geoNicknames[key] = nickname
geoNicknameOrder.append(key)
return true
}
func replaceGeoNicknames(_ nicknames: [String: String]) {
@ -83,12 +89,6 @@ final class LocationPresenceStore: ObservableObject {
geoNicknameOrder.removeAll()
}
func retainGeoNicknames(keeping pubkeys: Set<String>) {
let allowed = Set(pubkeys.map { $0.lowercased() })
geoNicknameOrder = geoNicknameOrder.filter { allowed.contains($0) }
geoNicknames = geoNicknames.filter { allowed.contains($0.key) }
}
func markTeleported(_ pubkeyHex: String) {
guard teleportedGeoCapacity > 0 else {
clearTeleportedGeo()
@ -109,6 +109,7 @@ final class LocationPresenceStore: ObservableObject {
func clearTeleported(_ pubkeyHex: String) {
let key = pubkeyHex.lowercased()
guard teleportedGeo.contains(key) else { return }
teleportedGeo.remove(key)
teleportedGeoOrder.removeAll { $0 == key }
}
@ -132,8 +133,11 @@ final class LocationPresenceStore: ObservableObject {
teleportedGeo = Set(ordered)
}
/// Prunes only when someone actually left: every assignment republishes
/// `teleportedGeo`, and its subscribers rebuild the people list.
func retainTeleportedGeo(keeping pubkeys: Set<String>) {
let allowed = Set(pubkeys.map { $0.lowercased() })
guard !teleportedGeo.isSubset(of: allowed) else { return }
teleportedGeoOrder = teleportedGeoOrder.filter { allowed.contains($0) }
teleportedGeo = teleportedGeo.intersection(allowed)
}

View File

@ -58,7 +58,6 @@ struct RecentChatRow: Identifiable, Equatable {
@MainActor
final class PeerListModel: ObservableObject {
@Published private(set) var allPeers: [BitchatPeer] = []
@Published private(set) var meshRows: [MeshPeerRow] = []
@Published private(set) var geohashPeople: [GeohashPersonRow] = []
@Published private(set) var groupRows: [GroupChatRow] = []
@ -66,14 +65,17 @@ final class PeerListModel: ObservableObject {
@Published private(set) var reachableMeshPeerCount = 0
@Published private(set) var connectedMeshPeerCount = 0
@Published private(set) var visibleGeohashPeerCount = 0
@Published private(set) var renderID = ""
private let chatViewModel: ChatViewModel
private let conversations: ConversationStore
private let locationChannelsModel: LocationChannelsModel
private let peerIdentityStore: PeerIdentityStore
private let locationPresenceStore: LocationPresenceStore
/// The mesh roster `refresh()` builds rows from. Not published: no view
/// reads it, and publishing it would re-render on every mesh snapshot.
private var allPeers: [BitchatPeer] = []
private var cancellables = Set<AnyCancellable>()
private var refreshScheduled = false
init(
chatViewModel: ChatViewModel,
@ -132,32 +134,37 @@ final class PeerListModel: ObservableObject {
}
private func bind() {
// No equality guard: `BitchatPeer.==` compares only peer IDs, so a
// rename or a connection, favorite or petname change looks unchanged,
// and blocking someone republishes identical peers. The refresh is
// coalesced, and rows are compared in full before they're written.
chatViewModel.$allPeers
.receive(on: DispatchQueue.main)
.sink { [weak self] peers in
self?.allPeers = peers
self?.refresh()
guard let self else { return }
self.allPeers = peers
self.setNeedsRefresh()
}
.store(in: &cancellables)
chatViewModel.$nickname
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
self?.refresh()
self?.setNeedsRefresh()
}
.store(in: &cancellables)
locationPresenceStore.$teleportedGeo
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
self?.refresh()
self?.setNeedsRefresh()
}
.store(in: &cancellables)
conversations.$unreadConversations
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
self?.refresh()
self?.setNeedsRefresh()
}
.store(in: &cancellables)
@ -168,67 +175,89 @@ final class PeerListModel: ObservableObject {
.receive(on: DispatchQueue.main)
.sink { [weak self] change in
guard case .direct = Self.changedConversationID(change) else { return }
self?.refresh()
self?.setNeedsRefresh()
}
.store(in: &cancellables)
chatViewModel.groupStore.$groups
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
self?.refresh()
self?.setNeedsRefresh()
}
.store(in: &cancellables)
peerIdentityStore.$encryptionStatuses
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
self?.refresh()
self?.setNeedsRefresh()
}
.store(in: &cancellables)
peerIdentityStore.$verifiedFingerprints
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
self?.refresh()
self?.setNeedsRefresh()
}
.store(in: &cancellables)
NotificationCenter.default.publisher(for: Notification.Name("peerStatusUpdated"))
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
self?.refresh()
self?.setNeedsRefresh()
}
.store(in: &cancellables)
chatViewModel.participantTracker.$visiblePeople
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
self?.refresh()
self?.setNeedsRefresh()
}
.store(in: &cancellables)
locationChannelsModel.$selectedChannel
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
self?.refresh()
self?.setNeedsRefresh()
}
.store(in: &cancellables)
locationChannelsModel.$teleported
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
self?.refresh()
self?.setNeedsRefresh()
}
.store(in: &cancellables)
locationChannelsModel.$availableChannels
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
self?.refresh()
self?.setNeedsRefresh()
}
.store(in: &cancellables)
}
/// Rebuilds the rows now. The geohash roster republishes only when
/// membership or names change, so its recency order goes stale while the
/// same people stay active; the people sheet calls this as it opens.
func refreshNow() {
refresh()
}
/// Coalesces bursts of triggers into one rebuild per main-queue turn: a
/// participant event republishes the roster and the teleport set, and a
/// mesh snapshot touches peers, unread and encryption state at once.
private func setNeedsRefresh() {
guard !refreshScheduled else { return }
refreshScheduled = true
DispatchQueue.main.async { [weak self] in
MainActor.assumeIsolated {
guard let self else { return }
self.refreshScheduled = false
self.refresh()
}
}
}
private func refresh() {
let myPeerID = chatViewModel.meshService.myPeerID
let meshRows = allPeers.map { peer in
@ -281,27 +310,15 @@ final class PeerListModel: ObservableObject {
let groupRows = buildGroupRows()
let recentChatRows = buildRecentChatRows(meshRows: meshRows, geohashPeople: geohashPeople)
self.meshRows = meshRows
reachableMeshPeerCount = meshCounts.reachable
connectedMeshPeerCount = meshCounts.connected
self.geohashPeople = geohashPeople
visibleGeohashPeerCount = geohashPeople.count
self.groupRows = groupRows
self.recentChatRows = recentChatRows
renderID = (
meshRows.map {
"\($0.id)-\($0.displayName)-\($0.isConnected)-\($0.isReachable)-\($0.hasUnread)-\($0.isFavorite)-\($0.isBlocked)"
} +
geohashPeople.map {
"geo:\($0.id)-\($0.isTeleported)-\($0.isBlocked)-\($0.displayName)"
} +
groupRows.map {
"group:\($0.id)-\($0.name)-\($0.memberCount)-\($0.hasUnread)"
} +
recentChatRows.map {
"chat:\($0.id)-\($0.displayName)-\($0.hasUnread)"
}
).joined(separator: "|")
// Assign only what changed: every @Published write re-renders every
// view observing this model (root, header, the open sheet).
if self.meshRows != meshRows { self.meshRows = meshRows }
if reachableMeshPeerCount != meshCounts.reachable { reachableMeshPeerCount = meshCounts.reachable }
if connectedMeshPeerCount != meshCounts.connected { connectedMeshPeerCount = meshCounts.connected }
if self.geohashPeople != geohashPeople { self.geohashPeople = geohashPeople }
if visibleGeohashPeerCount != geohashPeople.count { visibleGeohashPeerCount = geohashPeople.count }
if self.groupRows != groupRows { self.groupRows = groupRows }
if self.recentChatRows != recentChatRows { self.recentChatRows = recentChatRows }
}
/// Direct conversations with people absent from the rosters above:

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,38 @@
//
// BitchatMessage+Authorship.swift
// bitchat
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import BitFoundation
extension BitchatMessage {
/// Whether this device wrote the row, judged by the sender ID it carries
/// and never by its display name. Names collide: geochat shows everyone
/// as `nick#<pubkey suffix>`, so a namesake reads `<my nick>#xxxx` and a
/// stranger without a nickname tag reads `anon#xxxx`, while mesh peers,
/// group members and bridged senders can carry my exact name.
///
/// - A `system` row is never mine, although local DM system lines carry
/// my mesh peer ID.
/// - A row without a sender ID (public system lines) is not mine.
/// - A geochat row (`nostr:` + 8 hex) is mine when it carries the ID of my
/// identity for the location channel on screen, `myGeoChatPeerID`.
/// - Every other row I write carries my mesh peer ID, `myPeerID`: mesh
/// public text and its echoes, mesh and geo DMs, group messages, media.
///
/// Each ID is evaluated only for the kind of row that needs it.
func isOwn(
myPeerID: @autoclosure () -> PeerID,
myGeoChatPeerID: @autoclosure () -> PeerID?
) -> Bool {
guard sender != "system", let senderPeerID else { return false }
if senderPeerID.isGeoChat {
return senderPeerID == myGeoChatPeerID()
}
let myPeerID = myPeerID()
return !myPeerID.isEmpty && senderPeerID == myPeerID
}
}

View File

@ -33,11 +33,19 @@ extension BitchatMessage {
}
func mediaAttachment(for nickname: String) -> Media? {
// Files only travel over the mesh radio; geochats, geo DMs and
// bridged messages (internet-relayed from a rendezvous) carry text
// alone. A "[image] " line from such a sender names no file it sent
// us, so it stays a text row.
if let senderPeerID, senderPeerID.isGeoChat || senderPeerID.isGeoDM || senderPeerID.isBridge {
return nil
}
guard let baseDirectory = Cache.shared.filesDir else { return nil }
func url(for category: MimeType.Category) -> URL? {
guard content.hasPrefix(category.messagePrefix),
let filename = String(content.dropFirst(category.messagePrefix.count)).trimmedOrNilIfEmpty
let filename = String(content.dropFirst(category.messagePrefix.count)).trimmedOrNilIfEmpty,
Self.isSafeMediaFilename(filename)
else {
return nil
}
@ -59,4 +67,19 @@ extension BitchatMessage {
}
return nil
}
/// Whether a media filename taken from message text is one plain path
/// component. Anything else ("../outgoing/x.jpg", "a/b", "..") would
/// resolve outside the media directory, so it is rejected, not repaired:
/// sanitizing would still point the row at some other local file.
static func isSafeMediaFilename(_ filename: String) -> Bool {
guard !filename.isEmpty,
filename != ".",
filename != "..",
!filename.unicodeScalars.contains(where: { $0 == "/" || $0 == "\\" })
else {
return false
}
return (filename as NSString).lastPathComponent == filename
}
}

View File

@ -731,7 +731,7 @@ struct NostrProtocol {
}
// Perform ECDH
let sharedSecret = try keyAgreementPrivateKey.sharedSecretFromKeyAgreement(
let sharedSecret = keyAgreementPrivateKey.sharedSecretFromKeyAgreement(
with: keyAgreementPublicKey,
format: .compressed
)

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -12,6 +12,15 @@ import Foundation
final class AutocompleteService {
private typealias Patterns = MessageFormattingEngine.Patterns
/// Whether the text before the cursor ends in an `@` mention token: the
/// only case `getSuggestions` can return anything for, whatever the peers.
/// Lets callers skip assembling the peer list after every keystroke.
static func hasMentionToken(in text: String, cursorPosition: Int) -> Bool {
let textToPosition = String(text.prefix(cursorPosition))
let range = NSRange(location: 0, length: (textToPosition as NSString).length)
return Patterns.mentionAutocomplete.firstMatch(in: textToPosition, options: [], range: range) != nil
}
/// Get autocomplete suggestions for current text
func getSuggestions(for text: String, peers: [String], cursorPosition: Int) -> (suggestions: [String], range: NSRange?) {
let textToPosition = String(text.prefix(cursorPosition))

View File

@ -2488,7 +2488,7 @@ final class BLEService: NSObject {
}
// Signature verification and registry lookups run on messageQueue
// like the live receive path.
self.messageQueue.async {
self.messageQueue.async { [self] in
guard self.isCurrentPanicLifecycleGeneration(generation) else {
return
}

View File

@ -48,6 +48,9 @@ protocol CommandContextProvider: AnyObject {
func getPeerIDForNickname(_ nickname: String) -> PeerID?
func getVisibleGeoParticipants() -> [CommandGeoParticipant]
func nostrPubkeyForDisplayName(_ displayName: String) -> String?
/// A /block or /unblock by name changed which geohash participants are
/// hidden; the roster re-filters instead of waiting for its timer.
func geohashBlockListDidChange()
// MARK: - Chat Actions
func startPrivateChat(with peerID: PeerID)
@ -368,6 +371,7 @@ final class CommandProcessor {
return .success(message: String(format: String(localized: "command.block.already", defaultValue: "%@ is already blocked", comment: "Reply when /block targets an already-blocked nickname"), locale: .current, nickname))
}
identityManager.setNostrBlocked(pub, isBlocked: true)
contextProvider?.geohashBlockListDidChange()
return .success(message: String(format: String(localized: "command.block.done_geo", defaultValue: "blocked %@ in geohash chats", comment: "Confirmation after blocking a geohash participant"), locale: .current, nickname))
}
@ -396,6 +400,7 @@ final class CommandProcessor {
return .success(message: String(format: String(localized: "command.unblock.not_blocked", defaultValue: "%@ is not blocked", comment: "Reply when /unblock targets a nickname that isn't blocked"), locale: .current, nickname))
}
identityManager.setNostrBlocked(pub, isBlocked: false)
contextProvider?.geohashBlockListDidChange()
return .success(message: String(format: String(localized: "command.unblock.done_geo", defaultValue: "unblocked %@ in geohash chats", comment: "Confirmation after unblocking a geohash participant"), locale: .current, nickname))
}
return .error(message: String(format: String(localized: "command.unblock.failed", defaultValue: "cannot unblock %@: not found", comment: "Error when /unblock can't resolve the target"), locale: .current, nickname))

View File

@ -6,6 +6,7 @@
// For more information, see <https://unlicense.org>
//
import BitFoundation
import Foundation
/// Persistent mute preferences for individual conversations (#1594).

View File

@ -43,6 +43,12 @@ final class GeohashParticipantTracker: ObservableObject {
/// Currently visible people for the active geohash
@Published private(set) var visiblePeople: [GeoPerson] = []
/// Bumps whenever the set of ids in `visiblePeople` changes, so derived
/// per-roster state (the sender color palette) is rebuilt only when
/// membership changes — not on every activity timestamp update.
private(set) var visibleMembershipRevision: UInt64 = 0
private var visibleMemberIDs: Set<String> = []
/// The currently active geohash (if any)
private var activeGeohash: String?
@ -65,40 +71,67 @@ final class GeohashParticipantTracker: ObservableObject {
func setActiveGeohash(_ geohash: String?) {
activeGeohash = geohash
if geohash == nil {
visiblePeople = []
publishVisiblePeople([])
} else {
refresh()
}
}
/// Record activity from a participant in the current active geohash
func recordParticipant(pubkeyHex: String) {
guard let gh = activeGeohash else { return }
recordParticipant(pubkeyHex: pubkeyHex, geohash: gh)
/// Record activity from a participant in the current active geohash.
/// Returns `false`, recording nothing, when no geohash is active.
@discardableResult
func recordParticipant(pubkeyHex: String, seenAt: Date = Date()) -> Bool {
guard let gh = activeGeohash else { return false }
return recordParticipant(pubkeyHex: pubkeyHex, geohash: gh, seenAt: seenAt)
}
/// Record activity from a participant in a specific geohash
func recordParticipant(pubkeyHex: String, geohash: String) {
let key = pubkeyHex.lowercased()
var map = participants[geohash] ?? [:]
map[key] = Date()
participants[geohash] = map
// Always notify observers that state has changed so counts in UI update
objectWillChange.send()
/// Record activity from a participant in a specific geohash.
///
/// `seenAt` is when the activity happened, clamped to now: arrival time
/// for live events, the event's own timestamp for history relays replay
/// on subscribe. Replayed history older than the activity window must
/// not make its authors count as present. Returns whether the activity
/// counted, i.e. fell inside the window.
///
/// Runs for every inbound geohash event, so the common case — someone
/// already present sending a heartbeat or message — only moves their
/// timestamp. The roster is republished only when someone becomes
/// visible; departures are picked up by the refresh timer.
@discardableResult
func recordParticipant(pubkeyHex: String, geohash: String, seenAt: Date = Date()) -> Bool {
let now = Date()
let cutoff = now.addingTimeInterval(activityCutoff)
let stamp = min(seenAt, now)
guard stamp >= cutoff else { return false }
// Only refresh visible list if this geohash is currently active
let key = pubkeyHex.lowercased()
let previous = participants[geohash]?[key]
if let previous, previous >= stamp { return true }
participants[geohash, default: [:]][key] = stamp
let wasActive = previous.map { $0 >= cutoff } ?? false
guard !wasActive else { return true }
// Someone newly counts as present here: participant counts for
// this geohash changed (sampled channels included).
objectWillChange.send()
if activeGeohash == geohash {
refresh()
}
return true
}
/// A participant's display name may have changed (a nickname was learned
/// or edited). Republishes the roster if they're currently visible.
func noteDisplayNameChanged(pubkeyHex: String) {
guard visibleMemberIDs.contains(pubkeyHex.lowercased()) else { return }
refresh()
}
/// Remove a participant from all geohashes (used when blocking)
func removeParticipant(pubkeyHex: String) {
let key = pubkeyHex.lowercased()
for (gh, var map) in participants {
map.removeValue(forKey: key)
participants[gh] = map
for geohash in participants.keys {
participants[geohash]?.removeValue(forKey: key)
}
refresh()
}
@ -107,7 +140,22 @@ final class GeohashParticipantTracker: ObservableObject {
func participantCount(for geohash: String) -> Int {
let cutoff = Date().addingTimeInterval(activityCutoff)
let map = participants[geohash] ?? [:]
return map.values.filter { $0 >= cutoff }.count
return map.values.reduce(0) { $1 >= cutoff ? $0 + 1 : $0 }
}
/// Drops entries that aged out of the activity window, in every geohash
/// (sampled ones included) so a long session doesn't keep every pubkey
/// it ever saw.
func pruneExpired(now: Date = Date()) {
let cutoff = now.addingTimeInterval(activityCutoff)
for (geohash, map) in participants {
let active = map.filter { $0.value >= cutoff }
if active.isEmpty {
participants.removeValue(forKey: geohash)
} else if active.count != map.count {
participants[geohash] = active
}
}
}
/// Get the visible people list for the active geohash (read-only query)
@ -125,16 +173,35 @@ final class GeohashParticipantTracker: ObservableObject {
.sorted { $0.lastSeen > $1.lastSeen }
}
/// Refresh the visible people list
/// Refresh the visible people list. Publishes only when what the roster
/// shows changed — who is present or how they're named — so subscribers
/// (the people sheet, the bootstrapper's prune) don't rebuild on
/// activity that only moved timestamps.
func refresh() {
visiblePeople = getVisiblePeople()
let people = getVisiblePeople()
guard Self.rosterKey(people) != Self.rosterKey(visiblePeople) else { return }
publishVisiblePeople(people)
}
/// Start the periodic refresh timer
private static func rosterKey(_ people: [GeoPerson]) -> [String: String] {
Dictionary(people.map { ($0.id, $0.displayName) }, uniquingKeysWith: { first, _ in first })
}
private func publishVisiblePeople(_ people: [GeoPerson]) {
let ids = Set(people.map(\.id))
if ids != visibleMemberIDs {
visibleMemberIDs = ids
visibleMembershipRevision &+= 1
}
visiblePeople = people
}
/// Start the periodic refresh timer: expires people who went quiet.
func startRefreshTimer(interval: TimeInterval = 30.0) {
stopRefreshTimer()
refreshTimer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { [weak self] _ in
Task { @MainActor in
self?.pruneExpired()
self?.refresh()
}
}
@ -149,14 +216,14 @@ final class GeohashParticipantTracker: ObservableObject {
/// Clear all participant data
func clear() {
participants.removeAll()
visiblePeople = []
publishVisiblePeople([])
}
/// Clear participant data for a specific geohash
func clear(geohash: String) {
participants.removeValue(forKey: geohash)
if activeGeohash == geohash {
visiblePeople = []
publishVisiblePeople([])
}
}
}

View File

@ -184,7 +184,7 @@ final class NostrTransport: Transport, @unchecked Sendable {
}
private func refreshReachablePeers() {
Task { @MainActor in
Task { @MainActor [self] in
let favorites = dependencies.loadFavorites()
let reachable = favorites.values
.filter { $0.peerNostrPublicKey != nil }

View File

@ -142,12 +142,20 @@ final class PrivateChatManager: ObservableObject {
// 2. Consolidate from temporary Nostr peer IDs (nostr_* prefixed)
let normalizedNickname = peerNickname.lowercased()
let myPeerID = meshService.myPeerID
var tempPeerIDsToConsolidate: [PeerID] = []
for (storedPeerID, messages) in privateChats {
if storedPeerID.isGeoDM && storedPeerID != peerID {
// Only the peer's own rows say who a thread is with. Mine
// carry my plain nickname (sendGeohashDM), so next to a mesh
// peer who shares it they would match as well: my thread with
// a geohash stranger would fold into the namesake's chat, a
// reply typed there would reach the namesake, and the
// stranger's next reply would open a fresh thread.
let containsMyRows = messages.contains { $0.senderPeerID == myPeerID }
let nicknamesMatch = messages.allSatisfy { $0.sender.lowercased() == normalizedNickname }
if nicknamesMatch && !messages.isEmpty {
if !containsMyRows && nicknamesMatch && !messages.isEmpty {
tempPeerIDsToConsolidate.append(storedPeerID)
}
}
@ -173,7 +181,11 @@ final class PrivateChatManager: ObservableObject {
originalSender: message.originalSender,
isPrivate: message.isPrivate,
recipientNickname: message.recipientNickname,
senderPeerID: peerID,
// Defense in depth: threads holding my rows are
// skipped above, so every row here is the peer's and
// moves to `peerID`. Were one of mine to get through,
// it would keep my ID, as in the stable-key branch.
senderPeerID: message.senderPeerID == meshService.myPeerID ? meshService.myPeerID : peerID,
mentions: message.mentions,
deliveryStatus: message.deliveryStatus
)
@ -198,11 +210,15 @@ final class PrivateChatManager: ObservableObject {
return hasUnreadMessages
}
/// Syncs the read receipt tracking between manager and view model for sent messages
/// Syncs the read receipt tracking between manager and view model for sent
/// messages. "Sent" means carrying my peer ID, never merely my nickname:
/// a namesake's delivered message still gets its READ receipt, and my
/// messages from before a rename still count as mine.
@MainActor
func syncReadReceiptsForSentMessages(peerID: PeerID, nickname: String, externalReceipts: inout Set<String>) {
func syncReadReceiptsForSentMessages(peerID: PeerID, externalReceipts: inout Set<String>) {
guard let myPeerID = meshService?.myPeerID else { return }
for message in messages(for: peerID) {
if message.sender == nickname {
if message.isOwn(myPeerID: myPeerID, myGeoChatPeerID: nil) {
switch message.deliveryStatus {
case .read, .delivered:
externalReceipts.insert(message.id)

View File

@ -0,0 +1,67 @@
//
// GeohashCoverage.swift
// bitchat
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import Foundation
/// Human-readable size of a geohash cell, shared by the location channels sheet and
/// the globe picker.
enum GeohashCoverage {
/// Approximate max cell dimension at the equator, e.g. "~4.9 km" or "~3.0 mi".
static func string(forPrecision len: Int, locale: Locale = .current) -> String {
// Values sourced from common geohash dimension tables.
let maxMeters: Double = {
switch len {
case 2: return 1_250_000
case 3: return 156_000
case 4: return 39_100
case 5: return 4_890
case 6: return 1_220
case 7: return 153
case 8: return 38.2
case 9: return 4.77
case 10: return 1.19
default:
if len <= 1 { return 5_000_000 }
// For >10, scale down conservatively by ~1/4 each char
let over = len - 10
return 1.19 * pow(0.25, Double(over))
}
}()
if usesMetric(locale) {
return "~\(formatDistance(maxMeters / 1000.0)) km"
} else {
return "~\(formatDistance(maxMeters / 1609.344)) mi"
}
}
/// Channel level a geohash of this length belongs to.
static func level(forLength length: Int) -> GeohashChannelLevel {
switch length {
case ...2: return .region
case 3...4: return .province
case 5: return .city
case 6: return .neighborhood
case 7: return .block
default: return .building
}
}
static func usesMetric(_ locale: Locale = .current) -> Bool {
if #available(iOS 16.0, macOS 13.0, *) {
return locale.measurementSystem == .metric
} else {
return locale.usesMetricSystem
}
}
private static func formatDistance(_ value: Double) -> String {
if value >= 100 { return String(format: "%.0f", value.rounded()) }
return String(format: "%.1f", value)
}
}

View File

@ -197,7 +197,13 @@ struct ThemedRootBackground: View {
}
.ignoresSafeArea()
} else {
// Full-bleed like the gradient above. Passed to .background(_:)
// as a view, a backdrop stops at the safe area (a bare Color
// passed as a ShapeStyle would not). In a sheet, the sheet's own
// background (#1C1C1E in dark mode) then shows through the
// home-indicator inset and under the navigation bar.
palette.background
.ignoresSafeArea()
}
}
}

View File

@ -82,6 +82,14 @@ final class ChatComposerCoordinator {
}
func updateAutocomplete(for text: String, cursorPosition: Int) {
// The query can only suggest for an @-token ending at the cursor, so
// skip assembling the candidates (a pass over every mesh peer or
// geohash participant) after each typing pause in plain text.
guard AutocompleteService.hasMentionToken(in: text, cursorPosition: cursorPosition) else {
setAutocompleteState(suggestions: [], range: nil)
return
}
let peerCandidates = autocompleteCandidates()
let (suggestions, range) = context.autocompleteQuery(
for: text,
@ -89,17 +97,7 @@ final class ChatComposerCoordinator {
cursorPosition: cursorPosition
)
if !suggestions.isEmpty {
context.autocompleteSuggestions = suggestions
context.autocompleteRange = range
context.showAutocomplete = true
context.selectedAutocompleteIndex = 0
} else {
context.autocompleteSuggestions = []
context.autocompleteRange = nil
context.showAutocomplete = false
context.selectedAutocompleteIndex = 0
}
setAutocompleteState(suggestions: suggestions, range: suggestions.isEmpty ? nil : range)
}
func completeNickname(_ nickname: String, in text: inout String) -> Int {
@ -143,6 +141,25 @@ final class ChatComposerCoordinator {
}
private extension ChatComposerCoordinator {
/// Shows `suggestions` (hidden when empty) with the highlight reset to the
/// first one. Writes only the properties that change: each write
/// republishes the composer state, which re-renders every message row.
func setAutocompleteState(suggestions: [String], range: NSRange?) {
let isShown = !suggestions.isEmpty
if context.autocompleteSuggestions != suggestions {
context.autocompleteSuggestions = suggestions
}
if context.autocompleteRange != range {
context.autocompleteRange = range
}
if context.showAutocomplete != isShown {
context.showAutocomplete = isShown
}
if context.selectedAutocompleteIndex != 0 {
context.selectedAutocompleteIndex = 0
}
}
func autocompleteCandidates() -> [String] {
switch context.activeChannel {
case .mesh:

View File

@ -9,6 +9,20 @@ final class ChatMessageFormatter {
private unowned let viewModel: ChatViewModel
private let meshPalette = MinimalDistancePalette(config: .mesh)
private let nostrPalette = MinimalDistancePalette(config: .nostr)
/// What the Nostr palette was last built from. Colors are looked up once
/// per people-sheet row and per formatted geochat message, so the palette
/// is rebuilt only when the roster's membership (or our own excluded
/// key) changes rather than recomputing the roster on every lookup.
private var nostrPaletteKey: NostrPaletteKey?
private struct NostrPaletteKey: Equatable {
// periphery:ignore - read only via the synthesized Equatable
// conformance (the rebuild check), which the indexer cannot
// attribute.
let membershipRevision: UInt64
// periphery:ignore - see `membershipRevision`.
let excludedHex: String?
}
init(viewModel: ChatViewModel) {
self.viewModel = viewModel
@ -348,6 +362,10 @@ final class ChatMessageFormatter {
return result
}
/// Prefix of the header's formatted-text cache variants. No full-text
/// variant starts with it, so the two caches can't collide.
static let headerCacheNamespace = "hdr:"
func formatMessageHeader(_ message: BitchatMessage, colorScheme: ColorScheme, theme: AppTheme = .matrix) -> AttributedString {
let design = theme.bodyFontDesign
let isSelf: Bool = {
@ -364,14 +382,23 @@ final class ChatMessageFormatter {
}()
let isDark = colorScheme == .dark
let baseColor: Color = isSelf ? .orange : peerColor(for: message, isDark: isDark)
let isVerifiedSender = !isSelf && isVerifiedSender(of: message)
// Same key ingredients as the full-text cache, in a namespace of its
// own so a header and a full text never answer each other's lookups.
let cacheVariant = Self.headerCacheNamespace + theme.formatCacheVariant + (isVerifiedSender ? "-vf" : "")
if let cachedHeader = message.getCachedFormattedText(isDark: isDark, isSelf: isSelf, variant: cacheVariant) {
return cachedHeader
}
let baseColor: Color = isSelf ? .orange : peerColor(for: message, isDark: isDark)
if message.sender == "system" {
var style = AttributeContainer()
style.foregroundColor = baseColor
style.font = .bitchatSystem(size: 14, weight: .medium, design: design)
return AttributedString(message.sender).mergingAttributes(style)
let header = AttributedString(message.sender).mergingAttributes(style)
message.setCachedFormattedText(header, isDark: isDark, isSelf: isSelf, variant: cacheVariant)
return header
}
var result = AttributedString()
@ -395,6 +422,7 @@ final class ChatMessageFormatter {
appendVerifiedSeal(to: &result, baseColor: baseColor, design: design)
}
result.append(AttributedString("> ").mergingAttributes(senderStyle))
message.setCachedFormattedText(result, isDark: isDark, isSelf: isSelf, variant: cacheVariant)
return result
}
@ -511,20 +539,31 @@ private extension ChatMessageFormatter {
return .orange
}
nostrPalette.ensurePalette(for: currentNostrPaletteSeeds(excluding: myHex))
ensureNostrPalette(excluding: myHex)
if let color = nostrPalette.color(for: pubkeyHexLowercased, isDark: isDark) {
return color
}
return Color(peerSeed: "nostr:" + pubkeyHexLowercased, isDark: isDark)
}
func currentNostrPaletteSeeds(excluding myHex: String?) -> [String: String] {
/// Seeds the palette from the tracker's published roster, and only when
/// its membership changed. Rebuilding it from a fresh roster scan per
/// lookup made every people-sheet render O(N²) in the participant count.
func ensureNostrPalette(excluding myHex: String?) {
let tracker = viewModel.participantTracker
let key = NostrPaletteKey(
membershipRevision: tracker.visibleMembershipRevision,
excludedHex: myHex
)
guard key != nostrPaletteKey else { return }
nostrPaletteKey = key
var seeds: [String: String] = [:]
let excluded = myHex ?? ""
for person in viewModel.visibleGeohashPeople() where person.id != excluded {
for person in tracker.visiblePeople where person.id != excluded {
seeds[person.id] = "nostr:" + person.id
}
return seeds
nostrPalette.ensurePalette(for: seeds)
}
func currentGeohashIdentityHex() -> String? {

View File

@ -870,6 +870,7 @@ final class ChatPrivateConversationCoordinator {
var oldPeerIDsToRemove: [PeerID] = []
var didMigrate = false
let cutoffTime = Date().addingTimeInterval(-TransportConfig.uiMigrationCutoffSeconds)
let myPeerID = context.myPeerID
for (oldPeerID, messages) in context.privateChats where oldPeerID != peerID {
let oldFingerprint = context.storedFingerprint(for: oldPeerID)
@ -895,9 +896,20 @@ final class ChatPrivateConversationCoordinator {
category: .session
)
} else if currentFingerprint == nil || oldFingerprint == nil {
// Which rows are mine goes by sender ID: after a rename my
// older rows carry my previous name, and a stranger who
// takes that name must not read as their author. My
// geo-DM rows name me, not the peer, as their recipient
// (sendGeohashDM), so they say nothing about who a geo-DM
// thread is with: there only the peer's rows count.
// Otherwise a namesake (or someone who took my old name)
// would take the thread, and my next reply, along.
let isGeoDMThread = oldPeerID.isGeoDM
let isRelevantChat = recentMessages.contains { msg in
(msg.sender == senderNickname && msg.sender != context.nickname)
|| (msg.sender == context.nickname && msg.recipientNickname == senderNickname)
if msg.isOwn(myPeerID: myPeerID, myGeoChatPeerID: nil) {
return !isGeoDMThread && msg.recipientNickname == senderNickname
}
return msg.sender == senderNickname
}
if isRelevantChat {

View File

@ -24,10 +24,6 @@ protocol ChatPublicConversationContext: AnyObject {
var currentGeohash: String? { get }
var nickname: String { get }
var myPeerID: PeerID { get }
/// Publishes the public-timeline batching state (UI animation suppression).
/// (Single mutation path for the owner's `isBatchingPublic`; this
/// coordinator never reads it.)
func setPublicBatching(_ isBatching: Bool)
/// Signals that message state changed so observers refresh (e.g. `objectWillChange.send()`).
func notifyUIChanged()
@ -249,14 +245,17 @@ final class ChatPublicConversationCoordinator: PublicMessagePipelineDelegate {
)
}
/// Runs once per participant on every roster rebuild, so keep it to one
/// lowercase copy: `publicKeyHex` is already lowercase.
func displayNameForNostrPubkey(_ pubkeyHex: String) -> String {
let suffix = String(pubkeyHex.suffix(4))
let key = pubkeyHex.lowercased()
if let geohash = context.currentGeohash,
let myGeoIdentity = try? context.deriveNostrIdentity(forGeohash: geohash),
myGeoIdentity.publicKeyHex.lowercased() == pubkeyHex.lowercased() {
myGeoIdentity.publicKeyHex == key {
return context.nickname + "#" + suffix
}
if let nick = context.geoNicknames[pubkeyHex.lowercased()], !nick.isEmpty {
if let nick = context.geoNicknames[key], !nick.isEmpty {
return nick + "#" + suffix
}
return "anon#\(suffix)"
@ -522,7 +521,7 @@ final class ChatPublicConversationCoordinator: PublicMessagePipelineDelegate {
}
let isMentioned = message.mentions?.contains { myTokens.contains($0.normalizedNickname) } ?? false
if isMentioned && message.sender != context.nickname {
if isMentioned && !isOwnMessage(message) {
SecureLogger.info("🔔 Mention from \(message.sender)", category: .session)
context.notifyMention(from: message.sender, message: message.content)
}
@ -547,7 +546,7 @@ final class ChatPublicConversationCoordinator: PublicMessagePipelineDelegate {
let isHugForMe = message.content.contains("🫂") && hugsMe
let isSlapForMe = message.content.contains("🐟") && slapsMe
if isHugForMe && message.sender != context.nickname {
if isHugForMe && !isOwnMessage(message) {
let impactFeedback = UIImpactFeedbackGenerator(style: .medium)
impactFeedback.prepare()
@ -558,7 +557,7 @@ final class ChatPublicConversationCoordinator: PublicMessagePipelineDelegate {
impactFeedback.impactOccurred()
}
}
} else if isSlapForMe && message.sender != context.nickname {
} else if isSlapForMe && !isOwnMessage(message) {
let impactFeedback = UIImpactFeedbackGenerator(style: .heavy)
impactFeedback.prepare()
impactFeedback.impactOccurred()
@ -585,10 +584,6 @@ final class ChatPublicConversationCoordinator: PublicMessagePipelineDelegate {
func pipelinePrewarmMessage(_: PublicMessagePipeline, message: BitchatMessage) {
context.prewarmMessageFormatting(message)
}
func pipelineSetBatchingState(_: PublicMessagePipeline, isBatching: Bool) {
context.setPublicBatching(isBatching)
}
}
private extension ChatPublicConversationCoordinator {
@ -606,4 +601,15 @@ private extension ChatPublicConversationCoordinator {
}
return "name:" + message.sender.lowercased()
}
/// Whether I wrote an inbound message (a gossip replay of my mesh text, or
/// a relay echo of my geochat text), by its sender ID rather than its
/// display name, so a namesake's mention or hug still reaches me.
func isOwnMessage(_ message: BitchatMessage) -> Bool {
message.isOwn(
myPeerID: context.myPeerID,
// The ID my own public rows carry in the active channel.
myGeoChatPeerID: currentPublicSender().peerID
)
}
}

View File

@ -442,8 +442,6 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
// MARK: - Public message batching (UI perf)
let publicMessagePipeline: PublicMessagePipeline
// Single-writer: mutate only via `setPublicBatching(_:)` below.
@Published private(set) var isBatchingPublic: Bool = false
// Backing store for `sentReadReceipts` persistence. `.standard` in
// production; injectable so tests can use a scratch suite that does not
@ -554,7 +552,6 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
func syncReadReceiptsForSentMessages(for peerID: PeerID) {
privateChatManager.syncReadReceiptsForSentMessages(
peerID: peerID,
nickname: nickname,
externalReceipts: &sentReadReceipts
)
}
@ -568,12 +565,6 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
return oldCount - sentReadReceipts.count
}
/// Publishes the public-timeline batching state (UI animation suppression).
@MainActor
func setPublicBatching(_ isBatching: Bool) {
isBatchingPublic = isBatching
}
@MainActor
func setGeoChatSubscriptionID(_ id: String?) {
geoSubscriptionID = id
@ -1355,6 +1346,19 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
return false
}
/// This device's identity in `geohash`'s location channel, through the
/// `cachedGeohashIdentity` slot the message formatter shares (cleared on
/// panic), so per-row callers pay no derivation.
@MainActor
func geohashIdentity(for geohash: String) -> NostrIdentity? {
if let cached = cachedGeohashIdentity, cached.geohash == geohash {
return cached.identity
}
guard let identity = try? idBridge.deriveIdentity(forGeohash: geohash) else { return nil }
cachedGeohashIdentity = (geohash, identity)
return identity
}
// MARK: - Public helpers
/// Return the current, pruned, sorted people list for the active geohash without mutating state.
@ -1609,8 +1613,11 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
// Wipe persisted location state (selected channel, teleport set,
// bookmarks). For an activist-safety wipe, where the user has been is
// exactly the data an adversary inspecting the device wants.
LocationStateManager.shared.panicWipe()
// exactly the data an adversary inspecting the device wants. The app
// runs on `LocationChannelManager.shared` (AppRuntime injects it), so
// this wipes the process-wide state there; a test's own manager keeps
// the wipe from resetting the channel under every other test.
locationManager.panicWipe()
// Reset nickname to anonymous
nickname = "anon\(Int.random(in: 1000...9999))"
@ -1686,6 +1693,8 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
_ = clearGeoSamplingSubs()
cachedGeohashIdentity = nil
nostrKeyMapping.removeAll()
// Every pubkey seen in any geohash this session, with when.
participantTracker.clear()
// Clear read receipt tracking
sentReadReceipts.removeAll()

View File

@ -157,13 +157,19 @@ private extension ChatViewModelBootstrapper {
}
.store(in: &viewModel.cancellables)
// Teleport markers describe people present now, so they follow the
// roster (pruned against it as it is when this runs, not the
// delivered snapshot). Nicknames don't: they name the authors of
// messages on screen, including replayed history from people no
// longer present, so they stay for the channel (cleared on switch,
// bounded by the store's capacity).
viewModel.participantTracker.$visiblePeople
.receive(on: DispatchQueue.main)
.sink { [weak viewModel] people in
Task { @MainActor [weak viewModel] in
let visible = Set(people.map { $0.id })
viewModel?.locationPresenceStore.retainTeleportedGeo(keeping: visible)
viewModel?.locationPresenceStore.retainGeoNicknames(keeping: visible)
.sink { [weak viewModel] _ in
MainActor.assumeIsolated {
guard let viewModel else { return }
let visible = Set(viewModel.participantTracker.visiblePeople.map(\.id))
viewModel.locationPresenceStore.retainTeleportedGeo(keeping: visible)
}
}
.store(in: &viewModel.cancellables)

View File

@ -80,6 +80,11 @@ extension ChatViewModel {
nostrCoordinator.nostrPubkeyForDisplayName(name)
}
@MainActor
func geohashBlockListDidChange() {
participantTracker.refresh()
}
@MainActor
func startGeohashDM(withPubkeyHex hex: String) {
nostrCoordinator.startGeohashDM(withPubkeyHex: hex)

View File

@ -19,7 +19,7 @@ protocol GeoPresenceContext: AnyObject {
func isNostrBlocked(pubkeyHexLowercased: String) -> Bool
func parseMentions(from content: String) -> [String]
func recordGeoParticipant(pubkeyHex: String, geohash: String)
func recordGeoParticipant(pubkeyHex: String, geohash: String, seenAt: Date)
func geoParticipantCount(for geohash: String) -> Int
func markGeoTeleported(_ pubkeyHexLowercased: String)
@ -43,8 +43,8 @@ extension ChatViewModel: GeoPresenceContext {
locationPresenceStore.teleportedGeo.count
}
func recordGeoParticipant(pubkeyHex: String, geohash: String) {
participantTracker.recordParticipant(pubkeyHex: pubkeyHex, geohash: geohash)
func recordGeoParticipant(pubkeyHex: String, geohash: String, seenAt: Date) {
participantTracker.recordParticipant(pubkeyHex: pubkeyHex, geohash: geohash, seenAt: seenAt)
}
func geoParticipantCount(for geohash: String) -> Int {
@ -107,8 +107,21 @@ final class GeoPresenceTracker {
// actor) by NostrRelayManager before delivery.
guard shouldProcessGeoSamplingEvent(event.id) else { return }
let existingCount = context.geoParticipantCount(for: gh)
context.recordGeoParticipant(pubkeyHex: event.pubkey, geohash: gh)
// The open channel is usually one of the sampled cells, and its own
// subscription already records its senders; recording this copy too
// ran the participant bookkeeping twice for every event there.
let isOpenChannel: Bool = {
if case .location(let channel) = context.activeChannel {
return channel.geohash == gh
}
return false
}()
let existingCount = isOpenChannel ? nil : context.geoParticipantCount(for: gh)
if !isOpenChannel {
// Arrival time: sampling replays at most a few minutes of history,
// and live senders with skewed clocks must still count.
context.recordGeoParticipant(pubkeyHex: event.pubkey, geohash: gh, seenAt: Date())
}
guard let content = event.content.trimmedOrNilIfEmpty else { return }
if context.isNostrBlocked(pubkeyHexLowercased: event.pubkey.lowercased()) { return }

View File

@ -47,7 +47,8 @@ protocol GeohashSubscriptionContext: AnyObject {
func startGeoParticipantRefreshTimer()
func stopGeoParticipantRefreshTimer()
func setActiveParticipantGeohash(_ geohash: String?)
func recordGeoParticipant(pubkeyHex: String)
@discardableResult
func recordGeoParticipant(pubkeyHex: String, seenAt: Date) -> Bool
func markGeoTeleported(_ pubkeyHexLowercased: String)
func clearGeoTeleported(_ pubkeyHexLowercased: String)
func clearTeleportedGeo()
@ -118,6 +119,12 @@ final class GeohashSubscriptionManager {
/// Geohashes already told "sent via mesh gateway" this session, so the
/// notice appears once per channel instead of once per message.
private var gatewayNoticeGeohashes = Set<String>()
/// The geochat subscription whose stored history relays may still be
/// replaying; cleared when its EOSE callback runs. Best effort: the relay
/// manager also runs that callback on its fallback timeout (e.g. while
/// Tor is still bootstrapping), and history arriving after it counts as
/// live activity. See `NostrInboundPipeline`'s `isHistoryReplay`.
private var replayingGeoSubscriptionID: String?
init(context: any GeohashSubscriptionContext, inbound: NostrInboundPipeline, presence: GeoPresenceTracker) {
self.context = context
@ -145,14 +152,20 @@ final class GeohashSubscriptionManager {
toGeohash: channel.geohash,
count: TransportConfig.nostrGeoRelayCount
)
NostrRelayManager.shared.subscribe(filter: filter, id: subID, relayUrls: subRelays) { [weak self] event in
replayingGeoSubscriptionID = subID
NostrRelayManager.shared.subscribe(filter: filter, id: subID, relayUrls: subRelays, handler: { [weak self] event in
Task { @MainActor [weak self] in
self?.inbound.subscribeNostrEvent(event)
guard let self else { return }
self.inbound.subscribeNostrEvent(event, isHistoryReplay: self.replayingGeoSubscriptionID == subID)
// Gateway downlink: rebroadcast relay events for the viewed
// channel onto the mesh (no-op unless gateway mode is on).
GatewayService.shared.rebroadcastRelayEvent(event, geohash: channel.geohash)
}
}
}, onEOSE: { [weak self] in
Task { @MainActor [weak self] in
self?.endHistoryReplay(for: subID)
}
})
if let dmSub = context.geoDmSubscriptionID {
NostrRelayManager.shared.unsubscribe(id: dmSub)
@ -219,7 +232,7 @@ final class GeohashSubscriptionManager {
context.setActiveParticipantGeohash(channel.geohash)
if let identity = try? context.deriveNostrIdentity(forGeohash: channel.geohash) {
context.recordGeoParticipant(pubkeyHex: identity.publicKeyHex)
context.recordGeoParticipant(pubkeyHex: identity.publicKeyHex, seenAt: Date())
let key = identity.publicKeyHex.lowercased()
if context.isTeleported && context.isGeohashOutsideRegionalChannels(channel.geohash) {
context.markGeoTeleported(key)
@ -238,14 +251,20 @@ final class GeohashSubscriptionManager {
let ts = Date().addingTimeInterval(-TransportConfig.nostrGeohashInitialLookbackSeconds)
let filter = NostrFilter.geohashEphemeral(channel.geohash, since: ts, limit: TransportConfig.nostrGeohashInitialLimit)
let subRelays = GeoRelayDirectory.shared.closestRelays(toGeohash: channel.geohash, count: 5)
NostrRelayManager.shared.subscribe(filter: filter, id: subID, relayUrls: subRelays) { [weak self] event in
replayingGeoSubscriptionID = subID
NostrRelayManager.shared.subscribe(filter: filter, id: subID, relayUrls: subRelays, handler: { [weak self] event in
Task { @MainActor [weak self] in
self?.inbound.handleNostrEvent(event)
guard let self else { return }
self.inbound.handleNostrEvent(event, isHistoryReplay: self.replayingGeoSubscriptionID == subID)
// Gateway downlink: rebroadcast relay events for the viewed
// channel onto the mesh (no-op unless gateway mode is on).
GatewayService.shared.rebroadcastRelayEvent(event, geohash: channel.geohash)
}
}
}, onEOSE: { [weak self] in
Task { @MainActor [weak self] in
self?.endHistoryReplay(for: subID)
}
})
subscribeToGeoChat(channel)
}
@ -306,7 +325,7 @@ final class GeohashSubscriptionManager {
)
}
context.recordGeoParticipant(pubkeyHex: identity.publicKeyHex)
context.recordGeoParticipant(pubkeyHex: identity.publicKeyHex, seenAt: Date())
context.registerNostrKeyMapping(identity.publicKeyHex, for: PeerID(nostr: identity.publicKeyHex))
SecureLogger.debug(
"GeoTeleport: sent geo message pub=\(identity.publicKeyHex.prefix(8))… teleported=\(geoContext.teleported)",
@ -325,6 +344,12 @@ final class GeohashSubscriptionManager {
context.recordProcessedNostrEvent(event.id)
}
@MainActor
private func endHistoryReplay(for subscriptionID: String) {
guard replayingGeoSubscriptionID == subscriptionID else { return }
replayingGeoSubscriptionID = nil
}
@MainActor
func beginGeohashSampling(for geohashes: [String]) {
guard let context else { return }

View File

@ -29,7 +29,10 @@ protocol NostrInboundPipelineContext: AnyObject {
func setGeoNickname(_ nickname: String, forPubkey pubkeyHex: String)
/// Records the Nostr pubkey behind a (possibly virtual) peer ID.
func registerNostrKeyMapping(_ pubkey: String, for peerID: PeerID)
func recordGeoParticipant(pubkeyHex: String)
/// `seenAt` is the event's own timestamp, so replayed history doesn't
/// count its authors as present. Returns whether the activity counted.
@discardableResult
func recordGeoParticipant(pubkeyHex: String, seenAt: Date) -> Bool
// MARK: Inbound public messages
/// `powBits` is the validated NIP-13 difficulty of the source event
@ -70,11 +73,14 @@ extension ChatViewModel: NostrInboundPipelineContext {
}
func setGeoNickname(_ nickname: String, forPubkey pubkeyHex: String) {
locationPresenceStore.setNickname(nickname, for: pubkeyHex)
if locationPresenceStore.setNickname(nickname, for: pubkeyHex) {
participantTracker.noteDisplayNameChanged(pubkeyHex: pubkeyHex)
}
}
func recordGeoParticipant(pubkeyHex: String) {
participantTracker.recordParticipant(pubkeyHex: pubkeyHex)
@discardableResult
func recordGeoParticipant(pubkeyHex: String, seenAt: Date) -> Bool {
participantTracker.recordParticipant(pubkeyHex: pubkeyHex, seenAt: seenAt)
}
}
@ -115,8 +121,12 @@ final class NostrInboundPipeline {
self.presence = presence
}
/// `isHistoryReplay` marks events relays return from storage before EOSE.
/// Those count as activity at the time they happened, so an hour of
/// replayed history doesn't make its authors look present; live events
/// count when they arrive, which keeps senders with skewed clocks visible.
@MainActor
func subscribeNostrEvent(_ event: NostrEvent) {
func subscribeNostrEvent(_ event: NostrEvent, isHistoryReplay: Bool = false) {
guard let context else { return }
// Cheap rejects (kind, dedup lookup) — duplicates dominate real
// traffic. The signature was already verified (exactly once, off the
@ -146,13 +156,21 @@ final class NostrInboundPipeline {
context.registerNostrKeyMapping(event.pubkey, for: PeerID(nostr_: event.pubkey))
context.registerNostrKeyMapping(event.pubkey, for: PeerID(nostr: event.pubkey))
context.recordGeoParticipant(pubkeyHex: event.pubkey)
let countsAsPresence = context.recordGeoParticipant(
pubkeyHex: event.pubkey,
seenAt: isHistoryReplay ? Date(timeIntervalSince1970: TimeInterval(event.created_at)) : Date()
)
if event.kind == NostrProtocol.EventKind.geohashPresence.rawValue {
return
}
if GeoPresenceTracker.hasTeleportTag(event) {
// Teleport markers describe people present now and are pruned only
// when the roster changes, so a tag on history too old to count must
// not mark its absent author: the marker could still be there when
// they came back. A teleported sender tags every message, so their
// recent ones still mark them.
if countsAsPresence, GeoPresenceTracker.hasTeleportTag(event) {
let key = event.pubkey.lowercased()
let isSelf: Bool = {
if let gh = context.currentGeohash,
@ -193,8 +211,9 @@ final class NostrInboundPipeline {
}
}
/// See `subscribeNostrEvent(_:isHistoryReplay:)` for `isHistoryReplay`.
@MainActor
func handleNostrEvent(_ event: NostrEvent) {
func handleNostrEvent(_ event: NostrEvent, isHistoryReplay: Bool = false) {
guard let context else { return }
// Cheap rejects (kind, dedup lookup) — the signature was already
// verified (exactly once, off the main actor) by NostrRelayManager.
@ -231,25 +250,27 @@ final class NostrInboundPipeline {
return false
}()
if hasTeleportTag, !isSelf {
presence.scheduleMarkPeerTeleported(event.pubkey.lowercased(), logged: true)
}
context.recordGeoParticipant(pubkeyHex: event.pubkey)
if isSelf {
let eventTime = Date(timeIntervalSince1970: TimeInterval(event.created_at))
if Date().timeIntervalSince(eventTime) < 15 {
return
}
let eventTime = Date(timeIntervalSince1970: TimeInterval(event.created_at))
let seenAt = isHistoryReplay ? eventTime : Date()
if isSelf, Date().timeIntervalSince(eventTime) < 15 {
context.recordGeoParticipant(pubkeyHex: event.pubkey, seenAt: seenAt)
return
}
// Learn the nickname before recording the sender, so a newcomer
// enters the roster under their name rather than anon#xxxx.
if let nickTag = event.tags.first(where: { $0.first == "n" }), nickTag.count >= 2 {
context.setGeoNickname(nickTag[1].trimmed, forPubkey: event.pubkey)
}
context.registerNostrKeyMapping(event.pubkey, for: PeerID(nostr_: event.pubkey))
context.registerNostrKeyMapping(event.pubkey, for: PeerID(nostr: event.pubkey))
let countsAsPresence = context.recordGeoParticipant(pubkeyHex: event.pubkey, seenAt: seenAt)
// Only activity that counts marks teleport; see subscribeNostrEvent.
if hasTeleportTag, !isSelf, countsAsPresence {
presence.scheduleMarkPeerTeleported(event.pubkey.lowercased(), logged: true)
}
if event.kind == NostrProtocol.EventKind.geohashPresence.rawValue {
return

View File

@ -22,7 +22,6 @@ protocol PublicMessagePipelineDelegate: AnyObject {
@discardableResult
func pipeline(_: PublicMessagePipeline, commit message: BitchatMessage, to conversationID: ConversationID) -> Bool
func pipelinePrewarmMessage(_: PublicMessagePipeline, message: BitchatMessage)
func pipelineSetBatchingState(_: PublicMessagePipeline, isBatching: Bool)
}
@MainActor
@ -100,8 +99,6 @@ private extension PublicMessagePipeline {
return
}
delegate.pipelineSetBatchingState(self, isBatching: true)
// Content-window dedup against recorded keys and within the batch;
// ID dedup happens in the store at commit time.
var pending: [(message: BitchatMessage, conversationID: ConversationID, contentKey: String)] = []
@ -122,10 +119,7 @@ private extension PublicMessagePipeline {
}
buffer.removeAll(keepingCapacity: true)
guard !pending.isEmpty else {
delegate.pipelineSetBatchingState(self, isBatching: false)
return
}
guard !pending.isEmpty else { return }
pending.sort { $0.message.timestamp < $1.message.timestamp }
@ -140,8 +134,6 @@ private extension PublicMessagePipeline {
delegate.pipelinePrewarmMessage(self, message: item.message)
}
delegate.pipelineSetBatchingState(self, isBatching: false)
if !buffer.isEmpty {
scheduleFlush()
}

View File

@ -9,6 +9,7 @@
// This is free and unencumbered software released into the public domain.
//
import Combine
import SwiftUI
struct MeshEmptyStateView: View {

View File

@ -34,14 +34,12 @@ struct TextMessageView: View {
var body: some View {
VStack(alignment: .leading, spacing: 0) {
// Precompute heavy token scans once per row
let cashuLinks = message.content.extractCashuLinks()
let lightningLinks = message.content.extractLightningLinks()
// Heavy token scans run once per message, not once per render
let scan = message.contentScan
// Baseline alignment keeps the lock and delivery glyphs on the
// first text line; a fixed top padding left the lock's solid body
// hanging below the line's visual center.
HStack(alignment: .firstTextBaseline, spacing: 0) {
let isLong = message.content.isLongForDisplay()
let isExpanded = expandedMessageIDs.contains(message.id)
if message.isPrivate {
Image(systemName: "lock.fill")
@ -70,7 +68,7 @@ struct TextMessageView: View {
}
Text(conversationUIModel.formatMessage(message, colorScheme: colorScheme, theme: theme))
.fixedSize(horizontal: false, vertical: true)
.lineLimit(isLong && !isExpanded ? TransportConfig.uiLongMessageLineLimit : nil)
.lineLimit(scan.isLongForDisplay && !isExpanded ? TransportConfig.uiLongMessageLineLimit : nil)
.frame(maxWidth: .infinity, alignment: .leading)
// Delivery status indicator for private messages. Tappable:
@ -112,7 +110,7 @@ struct TextMessageView: View {
}
// Expand/Collapse for very long messages
if message.content.isLongForDisplay() {
if scan.isLongForDisplay {
let isExpanded = expandedMessageIDs.contains(message.id)
let labelKey = isExpanded ? LocalizedStringKey("content.message.show_less") : LocalizedStringKey("content.message.show_more")
Button(labelKey) {
@ -125,12 +123,12 @@ struct TextMessageView: View {
}
// Render payment chips (Lightning / Cashu) with rounded background
if !lightningLinks.isEmpty || !cashuLinks.isEmpty {
if !scan.lightningLinks.isEmpty || !scan.cashuLinks.isEmpty {
HStack(spacing: 8) {
ForEach(lightningLinks, id: \.self) { link in
ForEach(scan.lightningLinks, id: \.self) { link in
PaymentChipView(paymentType: .lightning(link))
}
ForEach(cashuLinks, id: \.self) { link in
ForEach(scan.cashuLinks, id: \.self) { link in
PaymentChipView(paymentType: .cashu(link))
}
}

View File

@ -291,7 +291,10 @@ struct ContentHeaderView: View {
HStack(spacing: 4) {
Image(systemName: "person.2.fill")
.font(.system(size: headerPeerIconSize, weight: .regular))
Text("\(headerOtherPeersCount)")
// Format style, not Text("\(count)"): same locale digits
// and grouping, and no letterless key for Xcode's
// localization export to add back to the catalog.
Text(headerOtherPeersCount, format: .number)
.font(.system(size: headerPeerCountFontSize, weight: .regular, design: theme.bodyFontDesign))
.accessibilityHidden(true)
}

View File

@ -380,6 +380,9 @@ private struct ContentPeopleListView: View {
showSidebar = true
}
)
// Skip re-rendering the roster when this view
// refreshes for models the list doesn't read.
.equatable()
// Direct conversations survive channel switches; the
// geoDM someone opened from another cell must stay
// reachable here too.
@ -443,7 +446,11 @@ private struct ContentPeopleListView: View {
// the ScrollView centers it — headers and empty states
// floated mid-screen on iPhone.
.frame(maxWidth: .infinity, alignment: .leading)
.id(peerListModel.renderID)
// Keyed by channel only. Rows are keyed by person, so roster
// updates diff in place; a key derived from the rows rebuilds
// the whole list on every heartbeat and resets its stable
// ordering.
.id(ConversationID(channelID: locationChannelsModel.selectedChannel))
}
}
.sheet(isPresented: $showVerifySheet) {

View File

@ -228,7 +228,7 @@ struct ContentView: View {
var body: some View {
mainContent
.onAppear {
.onAppear { [conversationUIModel, voiceRecordingVM] in
conversationUIModel.setCurrentColorScheme(colorScheme)
conversationUIModel.setCurrentTheme(appTheme)
voiceRecordingVM.sessionProvider = { [weak conversationUIModel] in

View File

@ -1,12 +1,21 @@
import SwiftUI
struct GeohashPeopleList: View {
struct GeohashPeopleList: View, Equatable {
@EnvironmentObject private var peerListModel: PeerListModel
@ThemedPalette private var palette
let onTapPerson: () -> Void
@Environment(\.colorScheme) var colorScheme
@State private var orderedIDs: [String] = []
/// The only input is the tap action, which always reveals the DM pane
/// and can't be compared. Treating it as equal lets SwiftUI skip this
/// list when the presenting view re-renders for models the list doesn't
/// read (message batches, chrome, verification); roster changes still
/// arrive through the observed PeerListModel.
nonisolated static func == (lhs: GeohashPeopleList, rhs: GeohashPeopleList) -> Bool {
true
}
private enum Strings {
static let noneNearby: LocalizedStringKey = "geohash_people.none_nearby"
static let youSuffix: LocalizedStringKey = "geohash_people.you_suffix"
@ -34,21 +43,17 @@ struct GeohashPeopleList: View {
} else {
let people = peerListModel.geohashPeople
let currentIDs = people.map(\.id)
let personByID = Dictionary(people.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first })
let displayed = PeopleListOrdering.stableOrder(previous: orderedIDs, current: currentIDs)
.compactMap { personByID[$0] }
// People physically here first, then those who teleported in.
let rows = displayed.filter { !$0.isTeleported } + displayed.filter(\.isTeleported)
let firstID = rows.first?.id
let displayIDs = orderedIDs.filter { currentIDs.contains($0) } + currentIDs.filter { !orderedIDs.contains($0) }
let nonTele = displayIDs.filter { id in
!(people.first(where: { $0.id == id })?.isTeleported ?? false)
}
let tele = displayIDs.filter { id in
people.first(where: { $0.id == id })?.isTeleported ?? false
}
let finalOrder: [String] = nonTele + tele
let firstID = finalOrder.first
let personByID = Dictionary(uniqueKeysWithValues: people.map { ($0.id, $0) })
VStack(alignment: .leading, spacing: 0) {
ForEach(finalOrder.filter { personByID[$0] != nil }, id: \.self) { pid in
let person = personByID[pid]!
// Lazy: a busy room has hundreds of rows, each with a context
// menu and accessibility actions; only the visible ones are built.
LazyVStack(alignment: .leading, spacing: 0) {
ForEach(rows) { person in
HStack(spacing: 4) {
let icon = person.isTeleported ? "face.dashed" : "mappin.and.ellipse"
let assignedColor = peerListModel.colorForGeohashPerson(id: person.id, isDark: colorScheme == .dark)
@ -144,12 +149,17 @@ struct GeohashPeopleList: View {
}
// Seed and update order outside result builder
.onAppear {
orderedIDs = currentIDs
// The roster republishes only when membership or names
// change, so its recency order can be stale. Rebuild once so
// the sheet opens with the most recently active people first.
peerListModel.refreshNow()
orderedIDs = PeopleListOrdering.stableOrder(
previous: [],
current: peerListModel.geohashPeople.map(\.id)
)
}
.onChange(of: currentIDs) { ids in
var newOrder = orderedIDs
newOrder.removeAll { !ids.contains($0) }
for id in ids where !newOrder.contains(id) { newOrder.append(id) }
let newOrder = PeopleListOrdering.stableOrder(previous: orderedIDs, current: ids)
if newOrder != orderedIDs { orderedIDs = newOrder }
}
}

View File

@ -0,0 +1,250 @@
//
// GeohashPickerView.swift
// bitchat
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import SwiftUI
/// Full-screen 3D globe for choosing a geohash channel to teleport to. The cell under
/// the crosshair is the selection; zooming changes precision, and the +/- buttons step
/// precision while framing the cell.
struct GeohashPickerView: View {
let onSelect: (String) -> Void
let onCancel: () -> Void
@StateObject private var state: GlobeState
@State private var world: GlobeWorldData?
@Environment(\.colorScheme) private var colorScheme
@ThemedPalette private var palette
private enum Strings {
static let instruction = String(localized: "geohash_picker.instruction", defaultValue: "drag to spin · pinch to zoom · tap to focus", comment: "Hint at the top of the globe geohash picker explaining its gestures")
static let noSelection = String(localized: "geohash_picker.no_selection", defaultValue: "select location", comment: "Shown in the globe geohash picker before a geohash is under the crosshair")
static let select = String(localized: "geohash_picker.select", defaultValue: "select", comment: "Button in the globe geohash picker that teleports to the geohash under the crosshair")
static let selectHint = String(localized: "geohash_picker.accessibility.select", defaultValue: "select geohash", comment: "Accessibility label for the globe picker's select button")
static let decreasePrecision = String(localized: "geohash_picker.accessibility.decrease_precision", defaultValue: "decrease precision", comment: "Accessibility label for the globe picker button that zooms out to a larger geohash cell")
static let increasePrecision = String(localized: "geohash_picker.accessibility.increase_precision", defaultValue: "increase precision", comment: "Accessibility label for the globe picker button that zooms in to a smaller geohash cell")
}
/// - Parameters:
/// - initialGeohash: cell to fly to; when empty, the coarsest of
/// `nearbyGeohashes` is used, else a wide view of the world.
init(
initialGeohash: String?,
nearbyGeohashes: [String] = [],
onSelect: @escaping (String) -> Void,
onCancel: @escaping () -> Void
) {
self.onSelect = onSelect
self.onCancel = onCancel
let target = Self.initialTarget(initialGeohash: initialGeohash, nearbyGeohashes: nearbyGeohashes)
_state = StateObject(wrappedValue: GlobeState(
targetLat: target.lat,
targetLon: target.lon,
initialPrecision: target.precision,
startZoomedOut: true
))
}
/// Where the intro flies to: the given geohash, else the coarsest nearby channel,
/// else a wide view at precision 2.
static func initialTarget(initialGeohash: String?, nearbyGeohashes: [String]) -> (lat: Double, lon: Double, precision: Int) {
let initial = (initialGeohash ?? "").trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
let focus = Geohash.isValidGeohash(initial)
? initial
: nearbyGeohashes.filter(Geohash.isValidGeohash).min { $0.count < $1.count }
guard let focus else { return (20, 0, 2) }
let center = Geohash.decodeCenter(focus)
return (center.lat, center.lon, min(max(focus.count, 1), GlobeMath.maxPrecision))
}
var body: some View {
ZStack {
palette.background
.ignoresSafeArea()
if let world {
GlobeView(state: state, colors: globeColors, world: world)
.ignoresSafeArea()
}
VStack(spacing: 0) {
topBar
Spacer(minLength: 0)
bottomControls
}
.padding(.horizontal, 16)
.padding(.top, 20)
.padding(.bottom, 20)
}
#if os(macOS)
.frame(minWidth: 560, minHeight: 640)
#endif
.task {
guard world == nil else { return }
world = await Task.detached(priority: .userInitiated) { GlobeWorldData.bundled }.value
}
}
// MARK: - Chrome
private var topBar: some View {
HStack(spacing: 10) {
Text(Strings.instruction)
.bitchatFont(size: 12)
.foregroundColor(palette.primary)
.multilineTextAlignment(.center)
.fixedSize(horizontal: false, vertical: true)
.padding(.horizontal, 14)
.padding(.vertical, 10)
.frame(maxWidth: .infinity)
.geohashPickerPanel()
SheetCloseButton(action: onCancel)
.foregroundColor(palette.primary)
.frame(width: 40, height: 40)
.geohashPickerPanel(cornerRadius: 20)
}
}
private var bottomControls: some View {
VStack(spacing: 10) {
VStack(spacing: 2) {
Text(verbatim: hasSelection ? "#\(state.selectedGeohash)" : Strings.noSelection)
.bitchatFont(size: 14, weight: .medium)
.foregroundColor(palette.primary)
if hasSelection {
Text(verbatim: "\(GeohashCoverage.level(forLength: state.precision).displayName) • \(GeohashCoverage.string(forPrecision: state.precision))")
.bitchatFont(size: 10)
.foregroundColor(palette.secondary)
}
}
.padding(.horizontal, 16)
.padding(.vertical, 8)
.geohashPickerPanel()
.accessibilityElement(children: .combine)
HStack(spacing: 10) {
precisionButton(systemImage: "minus", label: Strings.decreasePrecision) {
state.animatePrecision(state.precision - 1)
}
precisionButton(systemImage: "plus", label: Strings.increasePrecision) {
state.animatePrecision(state.precision + 1)
}
Button {
guard hasSelection else { return }
onSelect(state.selectedGeohash)
} label: {
HStack(spacing: 6) {
Image(systemName: "checkmark")
.font(.bitchatSystem(size: 14, weight: .semibold))
Text(verbatim: Strings.select)
.bitchatFont(size: 12)
}
.foregroundColor(palette.primary)
.pickerCapsule(fill: palette.accentBlue.opacity(0.12))
}
.buttonStyle(.plain)
.disabled(!hasSelection)
.opacity(hasSelection ? 1 : 0.38)
.accessibilityLabel(Strings.selectHint)
}
}
}
private func precisionButton(systemImage: String, label: String, action: @escaping () -> Void) -> some View {
Button(action: action) {
Image(systemName: systemImage)
.font(.bitchatSystem(size: 16, weight: .semibold))
.foregroundColor(palette.locationAccent)
.pickerCapsule(fill: palette.locationAccent.opacity(0.12))
}
.buttonStyle(.plain)
.accessibilityLabel(label)
}
private var hasSelection: Bool { !state.selectedGeohash.isEmpty }
// MARK: - Globe palette
/// Fixed land/ocean tones shared with the Android picker; the accent follows the
/// theme's location color.
private var globeColors: GlobeColors {
let accent = palette.locationAccent
if colorScheme == .dark {
let onSurface = Color(red: 0.961, green: 0.961, blue: 0.961)
let onSurfaceVariant = Color(red: 0.604, green: 0.651, blue: 0.604)
return GlobeColors(
accent: accent,
land: Color(red: 0.086, green: 0.141, blue: 0.106),
coastline: accent.opacity(0.45),
border: onSurfaceVariant.opacity(0.5),
oceanCenter: Color(red: 0.039, green: 0.078, blue: 0.063),
oceanEdge: Color(red: 0.008, green: 0.024, blue: 0.016),
atmosphere: accent,
graticule: onSurface.opacity(0.055),
grid: onSurfaceVariant.opacity(0.6),
label: onSurfaceVariant,
labelHalo: palette.background,
star: onSurface
)
} else {
let onSurface = Color(red: 0.075, green: 0.102, blue: 0.075)
let onSurfaceVariant = Color(red: 0.298, green: 0.341, blue: 0.298)
return GlobeColors(
accent: accent,
land: Color(red: 0.737, green: 0.824, blue: 0.753),
coastline: accent.opacity(0.5),
border: onSurfaceVariant.opacity(0.6),
oceanCenter: Color(red: 0.918, green: 0.949, blue: 0.925),
oceanEdge: Color(red: 0.831, green: 0.886, blue: 0.843),
atmosphere: accent,
graticule: onSurface.opacity(0.08),
grid: onSurfaceVariant.opacity(0.7),
label: onSurfaceVariant,
labelHalo: palette.background,
star: onSurfaceVariant
)
}
}
}
// MARK: - Styling
private struct GeohashPickerPanel: ViewModifier {
@Environment(\.appTheme) private var theme
@ThemedPalette private var palette
let cornerRadius: CGFloat
@ViewBuilder
func body(content: Content) -> some View {
if theme.usesGlassChrome {
content.themedOverlayPanel()
} else {
let shape = RoundedRectangle(cornerRadius: cornerRadius, style: .continuous)
content
.background(shape.fill(palette.background.opacity(0.85)))
.overlay(shape.stroke(palette.divider, lineWidth: 1))
.shadow(color: .black.opacity(0.25), radius: 6, x: 0, y: 2)
}
}
}
private extension View {
/// Floating translucent surface for the picker's hint, readout and close button.
func geohashPickerPanel(cornerRadius: CGFloat = 12) -> some View {
modifier(GeohashPickerPanel(cornerRadius: cornerRadius))
}
/// Pill button body sized like a standard 40pt-tall button.
func pickerCapsule(fill: Color) -> some View {
self
.padding(.horizontal, 24)
.frame(minHeight: 40)
.background(Capsule().fill(fill))
.contentShape(Capsule())
}
}

View File

@ -0,0 +1,285 @@
//
// GlobeGeometry.swift
// bitchat
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import CoreGraphics
import Foundation
/// Polygon/polyline helpers that turn projected geometry into drawable screen paths:
/// splitting at the limb, closing fills along the horizon, and clipping to the viewport.
enum GlobeGeometry {
/// A projected point in disc units (radius 1, screen y down).
struct DiscPoint: Equatable {
let x: Double
let y: Double
let front: Bool
}
/// Core Graphics loses precision with path coordinates far outside the view, which
/// happens at high globe zoom. All geometry is clipped to an expanded viewport rect
/// in screen space before it becomes a path.
struct ClipRect {
let left: Double
let top: Double
let right: Double
let bottom: Double
init(size: CGSize) {
left = -Double(size.width)
top = -Double(size.height)
right = Double(size.width) * 2
bottom = Double(size.height) * 2
}
init(left: Double, top: Double, right: Double, bottom: Double) {
self.left = left
self.top = top
self.right = right
self.bottom = bottom
}
}
private static func limbPoint(behind: DiscPoint, front: DiscPoint) -> CGPoint {
var lo = 0.0
var hi = 1.0
for _ in 0..<14 {
let t = (lo + hi) / 2
let x = behind.x + (front.x - behind.x) * t
let y = behind.y + (front.y - behind.y) * t
if x * x + y * y < 1 { lo = t } else { hi = t }
}
let t = (lo + hi) / 2
return CGPoint(x: behind.x + (front.x - behind.x) * t, y: behind.y + (front.y - behind.y) * t)
}
/// Splits a projected polygon into front-facing runs (disc units). Runs that touch the
/// limb are padded with the horizon intersection point so they can be closed along the
/// horizon. Pass `closed = false` for open polylines (border lines).
static func frontRuns(_ pts: [DiscPoint], closed: Bool = true) -> [[CGPoint]] {
guard let first = pts.first, let last = pts.last else { return [] }
var runs: [[CGPoint]] = []
var run: [CGPoint] = []
var prev: DiscPoint? = closed ? last : nil
for cur in pts {
if cur.front {
if run.isEmpty, let p = prev, !p.front { run.append(limbPoint(behind: p, front: cur)) }
// Antimeridian wrap: consecutive front points can jump across the whole
// disc when a polygon crosses ±180° — break the run instead of drawing
// a chord through the view.
if let tail = run.last {
let dx = cur.x - Double(tail.x)
let dy = cur.y - Double(tail.y)
if dx * dx + dy * dy > 1.2 {
runs.append(run)
run = []
}
}
run.append(CGPoint(x: cur.x, y: cur.y))
} else if !run.isEmpty, let p = prev {
run.append(limbPoint(behind: p, front: cur))
runs.append(run)
run = []
}
prev = cur
}
if !run.isEmpty {
if closed, !runs.isEmpty, first.front, last.front {
runs[0] = run + runs[0]
} else {
// A fully front-facing ring has no limb transition to terminate its run.
// Close it explicitly; cell boundary sampling intentionally omits the
// duplicated final corner.
if closed, runs.isEmpty, first.front, last.front, let head = run.first {
run.append(head)
}
runs.append(run)
}
}
return runs
}
/// Builds a fill polygon (screen units) for a projected ring by clamping back-facing
/// points onto the limb and inserting horizon arc steps between consecutive limb
/// points, so the result approximates (polygon ∩ visible disc) without
/// self-intersecting chords.
static func fillPolygon(_ pts: [DiscPoint], cx: Double, cy: Double, r: Double) -> [CGPoint] {
var out: [CGPoint] = []
out.reserveCapacity(pts.count + 128)
var prevLimbAngle: Double?
var firstLimbAngle: Double?
func addArc(from: Double, to: Double) {
var d = to - from
while d > .pi { d -= 2 * .pi }
while d < -.pi { d += 2 * .pi }
let steps = min(max(Int(abs(d) / 0.04), 1), 64)
for s in 1..<steps {
let a = from + d * Double(s) / Double(steps)
out.append(CGPoint(x: cx + cos(a) * r, y: cy + sin(a) * r))
}
}
for p in pts {
if p.front {
out.append(CGPoint(x: cx + p.x * r, y: cy + p.y * r))
prevLimbAngle = nil
} else {
let len = (p.x * p.x + p.y * p.y).squareRoot()
let lx = len > 1e-6 ? p.x / len : 0
let ly = len > 1e-6 ? p.y / len : -1
let angle = atan2(ly, lx)
if let prev = prevLimbAngle { addArc(from: prev, to: angle) }
if firstLimbAngle == nil { firstLimbAngle = angle }
out.append(CGPoint(x: cx + lx * r, y: cy + ly * r))
prevLimbAngle = angle
}
}
// Wrap-around arc if the ring ends and starts on the limb.
if let lastAngle = prevLimbAngle, let firstAngle = firstLimbAngle, let head = pts.first, !head.front {
addArc(from: lastAngle, to: firstAngle)
}
return out
}
/// Sutherland–Hodgman clip of a polygon to the rect.
static func clipPolygon(_ pts: [CGPoint], to rect: ClipRect) -> [CGPoint] {
func clipEdge(
_ input: [CGPoint],
inside: (CGPoint) -> Bool,
intersect: (CGPoint, CGPoint) -> CGPoint
) -> [CGPoint] {
guard var s = input.last else { return input }
var result: [CGPoint] = []
result.reserveCapacity(input.count + 4)
for e in input {
let eIn = inside(e)
if eIn {
if !inside(s) { result.append(intersect(s, e)) }
result.append(e)
} else if inside(s) {
result.append(intersect(s, e))
}
s = e
}
return result
}
let left = CGFloat(rect.left), right = CGFloat(rect.right)
let top = CGFloat(rect.top), bottom = CGFloat(rect.bottom)
var out = pts
out = clipEdge(out, inside: { $0.x >= left }) { a, b in
CGPoint(x: left, y: a.y + (left - a.x) / (b.x - a.x) * (b.y - a.y))
}
out = clipEdge(out, inside: { $0.x <= right }) { a, b in
CGPoint(x: right, y: a.y + (right - a.x) / (b.x - a.x) * (b.y - a.y))
}
out = clipEdge(out, inside: { $0.y >= top }) { a, b in
CGPoint(x: a.x + (top - a.y) / (b.y - a.y) * (b.x - a.x), y: top)
}
out = clipEdge(out, inside: { $0.y <= bottom }) { a, b in
CGPoint(x: a.x + (bottom - a.y) / (b.y - a.y) * (b.x - a.x), y: bottom)
}
return out
}
/// Liang–Barsky clip of a segment to the rect; returns the clipped endpoints or nil.
static func clipSegment(_ a: CGPoint, _ b: CGPoint, to rect: ClipRect) -> (CGPoint, CGPoint)? {
let x0 = Double(a.x), y0 = Double(a.y)
let dx = Double(b.x) - x0
let dy = Double(b.y) - y0
var u1 = 0.0
var u2 = 1.0
func test(_ p: Double, _ q: Double) -> Bool {
if p == 0 { return q >= 0 }
let r = q / p
if p < 0 {
if r > u2 { return false }
if r > u1 { u1 = r }
} else {
if r < u1 { return false }
if r < u2 { u2 = r }
}
return true
}
guard test(-dx, x0 - rect.left),
test(dx, rect.right - x0),
test(-dy, y0 - rect.top),
test(dy, rect.bottom - y0) else { return nil }
return (
CGPoint(x: x0 + u1 * dx, y: y0 + u1 * dy),
CGPoint(x: x0 + u2 * dx, y: y0 + u2 * dy)
)
}
/// Orthographic projection can choose the wrong side of the horizon closure for very
/// large rings. A single center-point check is ambiguous for a large polygon and
/// caused an occasional whole-disc fill, so compare several visible points with the
/// original geographic ring and invert only when the opposite fill wins clearly.
static func projectedFillNeedsInversion(
polygon: [CGPoint],
ring: GlobeRing,
cx: Double,
cy: Double,
r: Double,
centerLat: Double,
centerLon: Double
) -> Bool {
let samples: [(Double, Double)] = [
(0, 0), (-0.5, 0), (0.5, 0), (0, -0.5), (0, 0.5),
(-0.35, -0.35), (0.35, -0.35), (-0.35, 0.35), (0.35, 0.35)
]
var normalErrors = 0
var invertedErrors = 0
for (nx, ny) in samples {
guard let location = GlobeMath.unproject(x: nx, y: ny, centerLat: centerLat, centerLon: centerLon) else { continue }
let geographicInside = ringContains(ring, lat: location.lat, lon: location.lon)
let projectedInside = polygonContains(polygon, x: cx + nx * r, y: cy + ny * r)
if projectedInside != geographicInside { normalErrors += 1 }
if !projectedInside != geographicInside { invertedErrors += 1 }
}
return invertedErrors < normalErrors
}
/// Even-odd point-in-polygon test in screen space.
static func polygonContains(_ polygon: [CGPoint], x: Double, y: Double) -> Bool {
guard polygon.count >= 3, var previous = polygon.last else { return false }
var inside = false
for current in polygon {
let cy = Double(current.y), py = Double(previous.y)
if (cy > y) != (py > y) {
let intersectionX = (Double(previous.x) - Double(current.x)) * (y - cy) / (py - cy) + Double(current.x)
if x < intersectionX { inside.toggle() }
}
previous = current
}
return inside
}
/// Point-in-ring test in geographic space: counts the ring edges that cross the
/// probe's meridian north of it. Each edge is followed the short way around, so a
/// ring that wraps the antimeridian (Eurasia at Chukotka) has no false crossing at
/// the ±180° seam. Comparing raw relative longitudes there misjudged whole oceans
/// as inside Eurasia, which flipped its fill over the Pacific and Atlantic.
static func ringContains(_ ring: GlobeRing, lat: Double, lon: Double) -> Bool {
guard ring.count >= 3 else { return false }
var inside = false
var previousIndex = ring.count - 1
for index in 0..<ring.count {
let startLat = ring.lats[previousIndex]
let endLat = ring.lats[index]
let start = GlobeMath.normalizeLon(ring.lons[previousIndex] - lon)
// Unbounded on purpose: the end only changes sign relative to the start
// when the edge crosses the probe meridian, never when it crosses ±180°.
let end = start + GlobeMath.normalizeLon(ring.lons[index] - ring.lons[previousIndex])
if (start > 0) != (end > 0) {
let t = start / (start - end)
if startLat + (endLat - startLat) * t > lat { inside.toggle() }
}
previousIndex = index
}
return inside
}
}

View File

@ -0,0 +1,149 @@
//
// GlobeMath.swift
// bitchat
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import Foundation
/// Orthographic globe projection and geohash zoom math for the 3D globe picker.
///
/// The globe is rendered as a disc of radius R centered on screen. Points are
/// projected with an orthographic projection around a view center lat/lon.
enum GlobeMath {
static let minZoom: Double = 1
static let maxZoom: Double = 120_000
static let maxPrecision = 12
struct Projection: Equatable {
/// Disc coordinates in units of globe radius, screen y down.
let x: Double
let y: Double
/// Cosine of the angular distance from the view center; negative on the far side.
let cosC: Double
}
/// Per-point sin/cos of latitude and longitude. Preparing these once removes
/// nearly all trigonometry from animated frames.
struct Terms: Sendable {
let sinLat: Double
let cosLat: Double
let sinLon: Double
let cosLon: Double
init(lat: Double, lon: Double) {
let latRadians = lat * .pi / 180
let lonRadians = lon * .pi / 180
sinLat = sin(latRadians)
cosLat = cos(latRadians)
sinLon = sin(lonRadians)
cosLon = cos(lonRadians)
}
}
/// Frame-local projector for prepared static geometry: center terms are calculated once.
struct PreparedProjector {
private let sinCenterLat: Double
private let cosCenterLat: Double
private let sinCenterLon: Double
private let cosCenterLon: Double
init(centerLat: Double, centerLon: Double) {
let latRadians = centerLat * .pi / 180
let lonRadians = centerLon * .pi / 180
sinCenterLat = sin(latRadians)
cosCenterLat = cos(latRadians)
sinCenterLon = sin(lonRadians)
cosCenterLon = cos(lonRadians)
}
func project(_ terms: Terms) -> Projection {
let sinDeltaLon = terms.sinLon * cosCenterLon - terms.cosLon * sinCenterLon
let cosDeltaLon = terms.cosLon * cosCenterLon + terms.sinLon * sinCenterLon
return Projection(
x: terms.cosLat * sinDeltaLon,
y: -(cosCenterLat * terms.sinLat - sinCenterLat * terms.cosLat * cosDeltaLon),
cosC: sinCenterLat * terms.sinLat + cosCenterLat * terms.cosLat * cosDeltaLon
)
}
}
/// Projects (lat, lon) onto the view disc of a globe centered at (centerLat, centerLon).
/// `cosC` is negative when the point is on the far side of the sphere.
static func projectRaw(lat: Double, lon: Double, centerLat: Double, centerLon: Double) -> Projection {
let phi = lat * .pi / 180
let phi0 = centerLat * .pi / 180
let dLambda = normalizeLon(lon - centerLon) * .pi / 180
let cosC = sin(phi0) * sin(phi) + cos(phi0) * cos(phi) * cos(dLambda)
let x = cos(phi) * sin(dLambda)
let y = -(cos(phi0) * sin(phi) - sin(phi0) * cos(phi) * cos(dLambda))
return Projection(x: x, y: y, cosC: cosC)
}
/// Like `projectRaw` but nil when the point is behind the limb.
static func project(lat: Double, lon: Double, centerLat: Double, centerLon: Double) -> Projection? {
let p = projectRaw(lat: lat, lon: lon, centerLat: centerLat, centerLon: centerLon)
return p.cosC >= 0 ? p : nil
}
/// Inverse projection: disc coordinates (units of radius, screen y down) back to lat/lon.
/// Returns nil if the point lies outside the disc.
static func unproject(x: Double, y: Double, centerLat: Double, centerLon: Double) -> (lat: Double, lon: Double)? {
let rho = (x * x + y * y).squareRoot()
if rho > 1 { return nil }
let c = asin(min(1, max(-1, rho)))
let phi0 = centerLat * .pi / 180
let sinC = sin(c)
let cosC = cos(c)
let lat: Double
let lonOffset: Double
if rho < 1e-9 {
lat = centerLat
lonOffset = 0
} else {
lat = asin(cosC * sin(phi0) + (-y) * sinC * cos(phi0) / rho) * 180 / .pi
lonOffset = atan2(x * sinC, rho * cos(phi0) * cosC - (-y) * sin(phi0) * sinC) * 180 / .pi
}
return (lat, normalizeLon(centerLon + lonOffset))
}
static func normalizeLon(_ lon: Double) -> Double {
var x = lon.truncatingRemainder(dividingBy: 360)
if x > 180 { x -= 360 }
if x < -180 { x += 360 }
return x
}
/// Longitude span of a geohash cell in degrees.
static func cellSpanLon(precision: Int) -> Double {
360 / pow(2, (5 * Double(precision) / 2).rounded(.up))
}
/// Latitude span of a geohash cell in degrees.
static func cellSpanLat(precision: Int) -> Double {
180 / pow(2, (5 * Double(precision) / 2).rounded(.down))
}
/// Picks the geohash precision whose cells render at a comfortable on-screen size
/// for the current zoom: the largest precision whose cell is at least ~22% of the
/// screen's smallest dimension.
static func autoPrecision(globeRadius: Double, screenMin: Double) -> Int {
let target = screenMin * 0.22
var best = 1
for p in 1...maxPrecision {
let span = cellSpanLat(precision: p) * .pi / 180 * globeRadius
if span >= target { best = p } else { break }
}
return min(max(best, 1), maxPrecision)
}
/// Zoom factor (globe radius multiplier over the fit-to-screen base radius) that frames
/// a cell of the given precision nicely: the cell spans ~1/3 of the screen.
static func zoomForPrecision(_ precision: Int, baseRadius: Double, screenMin: Double) -> Double {
let spanRadians = cellSpanLat(precision: precision) * .pi / 180
let targetRadius = (screenMin / 3) / spanRadians
return min(max(targetRadius / baseRadius, minZoom), maxZoom)
}
}

View File

@ -0,0 +1,552 @@
//
// GlobeState.swift
// bitchat
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import Combine
import Foundation
import QuartzCore
#if os(iOS)
import UIKit
#endif
/// How much of the globe a moving frame draws. Detail drops while the globe moves
/// on slow devices and is fully restored once interaction settles. The geohash grid
/// (selected cell and its neighbors) and the city dots are not part of this: both
/// are cheap next to the land geometry, and making them vanish while dragging and
/// pop back on release read as a rendering bug.
enum GlobeMotionDetail: Equatable, Comparable {
case full
case balanced
case fast
struct Frame: Equatable {
let graticuleStepDegrees: Double
let landPointStride: Int
let showBorders: Bool
let showCityLabels: Bool
}
var frame: Frame {
switch self {
case .full:
return Frame(graticuleStepDegrees: 4, landPointStride: 1, showBorders: true,
showCityLabels: true)
case .balanced:
return Frame(graticuleStepDegrees: 8, landPointStride: 2, showBorders: true,
showCityLabels: false)
case .fast:
return Frame(graticuleStepDegrees: 10, landPointStride: 2, showBorders: false,
showCityLabels: false)
}
}
/// Ordered from least to most detailed.
static func < (lhs: GlobeMotionDetail, rhs: GlobeMotionDetail) -> Bool {
lhs.rank < rhs.rank
}
private var rank: Int {
switch self {
case .fast: return 0
case .balanced: return 1
case .full: return 2
}
}
var moreDetailed: GlobeMotionDetail {
switch self {
case .fast: return .balanced
case .balanced, .full: return .full
}
}
/// The level measured frame cadence calls for. Hysteresis alone cannot stop
/// oscillation (shedding detail is what makes frames fast again), so `GlobeState`
/// only ever applies downgrades while the globe is moving.
func next(averageFrameMillis: Double) -> GlobeMotionDetail {
guard averageFrameMillis.isFinite else { return .fast }
switch self {
case .full:
if averageFrameMillis > 34 { return .fast }
if averageFrameMillis > 22 { return .balanced }
return .full
case .balanced:
if averageFrameMillis > 29 { return .fast }
if averageFrameMillis < 18.5 { return .full }
return .balanced
case .fast:
return averageFrameMillis < 22 ? .balanced : .fast
}
}
}
/// Picks the detail level for moving frames. A motion session spans everything from
/// touch-down through any fling or animation until the globe is at rest.
///
/// Within a session detail only ever steps down: shedding layers is what makes
/// frames fast again, so letting measured cadence step back up made neighbor cells,
/// labels and the grid flash on and off while dragging. Between sessions, a smooth
/// one lets the next start a level higher, until any session has had to shed detail.
struct GlobeMotionGovernor {
static let frameSampleCount = 8
static let smoothFrameMillis = 18.5
static let maxSampledFrameMillis = 50.0
private(set) var detail: GlobeMotionDetail = .full
private(set) var isSessionActive = false
private var startDetail: GlobeMotionDetail = .balanced
private var ceilingFound = false
private var sessionDegraded = false
private var windowMillis = 0.0
private var windowCount = 0
private var sessionMillis = 0.0
private var sessionCount = 0
mutating func beginSession() {
guard !isSessionActive else { return }
isSessionActive = true
sessionDegraded = false
windowMillis = 0
windowCount = 0
sessionMillis = 0
sessionCount = 0
detail = startDetail
}
mutating func recordFrame(millis: Double) {
guard isSessionActive else { return }
let frameMillis = min(max(millis, 1), Self.maxSampledFrameMillis)
windowMillis += frameMillis
windowCount += 1
sessionMillis += frameMillis
sessionCount += 1
guard windowCount >= Self.frameSampleCount else { return }
let wanted = detail.next(averageFrameMillis: windowMillis / Double(windowCount))
if wanted < detail {
detail = wanted
sessionDegraded = true
}
windowMillis = 0
windowCount = 0
}
/// Back to full detail at rest; remembers where the next session should start.
mutating func endSession() {
guard isSessionActive else { return }
isSessionActive = false
if sessionDegraded {
ceilingFound = true
startDetail = detail
} else if !ceilingFound,
sessionCount >= Self.frameSampleCount,
sessionMillis / Double(sessionCount) < Self.smoothFrameMillis {
startDetail = detail.moreDetailed
}
detail = .full
}
}
/// Hoisted state for the interactive 3D globe: view center, zoom, geohash precision
/// and the current selection. All mutation funnels through this class so rendering,
/// gestures and buttons stay in sync.
@MainActor
final class GlobeState: ObservableObject {
@Published private(set) var centerLat: Double
@Published private(set) var centerLon: Double
@Published private(set) var zoom: Double
@Published private(set) var precision: Int
@Published private(set) var selectedGeohash = ""
@Published private(set) var isInteracting = false
@Published private(set) var isAnimating = false
/// Detail level for moving frames; `.full` whenever the globe is at rest.
@Published private(set) var motionDetail: GlobeMotionDetail = .full
private(set) var baseRadius: Double = 0
private(set) var screenMin: Double = 0
/// Pending cinematic intro target; consumed once the viewport is known.
private var introTarget: (lat: Double, lon: Double, precision: Int)?
private var motion: Motion?
private var lastTick: CFTimeInterval?
private var governor = GlobeMotionGovernor()
private lazy var clock = GlobeFrameClock { [weak self] timestamp in
self?.tick(timestamp)
}
private enum Motion {
case tween(Tween)
case fling(vx: Double, vy: Double)
}
private struct Tween {
let startLat: Double
let startLon: Double
let endLat: Double
let dLon: Double
let startZoom: Double
let endZoom: Double
let targetPrecision: Int?
let duration: CFTimeInterval
var startTime: CFTimeInterval?
}
private enum Constants {
// Dragging stops close to the projection limit so polar geohash cells remain
// selectable; clamping tighter would make syncSelection() encode the wrong cell.
// Animations may go past it to reach a target (see clampedLat).
static let maxDragLat = 89.0
static let minFlingPerSecond = 35.0
static let maxFlingPerSecond = 1_200.0
static let maxFrameDelta = 1.0 / 30
static let maxFlingRadiusFractionPerFrame = 0.12
static let flingFrictionPerSecond = 4.2
}
/// - Parameter startZoomedOut: begin from a far, offset view and fly into the
/// target once the viewport is laid out.
init(targetLat: Double, targetLon: Double, initialPrecision: Int, startZoomedOut: Bool) {
let precision = min(max(initialPrecision, 1), GlobeMath.maxPrecision)
centerLat = startZoomedOut ? targetLat * 0.4 : targetLat
centerLon = startZoomedOut ? GlobeMath.normalizeLon(targetLon - 70) : targetLon
zoom = GlobeMath.minZoom
self.precision = precision
if startZoomedOut {
introTarget = (targetLat, targetLon, precision)
}
}
var globeRadius: Double { baseRadius * zoom }
var isInMotion: Bool { isInteracting || isAnimating }
/// Detail the next frame should draw.
var frameDetail: GlobeMotionDetail.Frame {
(isInMotion ? motionDetail : .full).frame
}
func setViewport(baseRadius: Double, screenMin: Double, animateIntro: Bool = true) {
guard baseRadius > 0, screenMin > 0 else { return }
let firstLayout = self.baseRadius <= 0
self.baseRadius = baseRadius
self.screenMin = screenMin
if firstLayout, let target = introTarget {
introTarget = nil
let targetZoom = GlobeMath.zoomForPrecision(target.precision, baseRadius: baseRadius, screenMin: screenMin)
if animateIntro {
// Cinematic intro: spin and zoom from the far view into the target location.
animateTo(lat: target.lat, lon: target.lon, zoom: targetZoom, precision: target.precision, duration: 1.4)
} else {
centerLat = target.lat
centerLon = target.lon
zoom = targetZoom
precision = target.precision
}
}
syncSelection()
}
// MARK: - Gestures
func beginInteraction() {
// Mark the touch first so catching a fling continues the same motion session.
isInteracting = true
motionStateChanged()
cancelAnimations()
}
/// Ends a touch; a release velocity (points/second) carries on as an inertial spin
/// within the same motion session.
func endInteraction(flingVelocityX vx: Double = 0, flingVelocityY vy: Double = 0) {
fling(vx: vx, vy: vy)
isInteracting = false
motionStateChanged()
}
/// Direct rotation from drag gestures. Deltas are in screen points.
func rotateBy(dx: Double, dy: Double) {
let r = globeRadius
guard r > 0 else { return }
let degPerPoint = 180 / (Double.pi * r)
centerLon = GlobeMath.normalizeLon(centerLon - dx * degPerPoint)
// A view already past the drag limit (a polar target) may move toward the
// equator but not further out, and never snaps back to the limit.
centerLat = clampedLat(centerLat + dy * degPerPoint, reaching: centerLat)
syncSelection()
}
/// Continuous zoom from pinch gestures; precision follows automatically.
func zoomBy(_ factor: Double) {
guard factor != 1, factor.isFinite, factor > 0 else { return }
zoom = min(max(zoom * factor, GlobeMath.minZoom), GlobeMath.maxZoom)
syncPrecisionFromZoom()
syncSelection()
}
/// Inertial spin after a fling. Velocities are in points/second.
func fling(vx: Double, vy: Double) {
var initialVx = min(max(vx, -Constants.maxFlingPerSecond), Constants.maxFlingPerSecond)
var initialVy = min(max(vy, -Constants.maxFlingPerSecond), Constants.maxFlingPerSecond)
if abs(initialVx) < Constants.minFlingPerSecond { initialVx = 0 }
if abs(initialVy) < Constants.minFlingPerSecond { initialVy = 0 }
guard initialVx != 0 || initialVy != 0 else { return }
start(.fling(vx: initialVx, vy: initialVy))
}
/// Single tap focuses the tapped point; double tap also zooms in.
func focus(lat: Double, lon: Double, zoomIn: Bool) {
if zoomIn {
animateTo(lat: lat, lon: lon, zoom: min(zoom * 1.9, GlobeMath.maxZoom), duration: 0.5)
} else {
animateTo(lat: lat, lon: lon, duration: 0.45)
}
}
// MARK: - Animations
/// Animate the view to a lat/lon, optionally to a zoom and precision.
func animateTo(lat: Double, lon: Double, zoom targetZoom: Double? = nil, precision targetPrecision: Int? = nil, duration: CFTimeInterval = 0.55) {
let endZoom = min(max(targetZoom ?? zoom, GlobeMath.minZoom), GlobeMath.maxZoom)
start(.tween(Tween(
startLat: centerLat,
startLon: centerLon,
endLat: lat,
dLon: GlobeMath.normalizeLon(lon - centerLon),
startZoom: zoom,
endZoom: endZoom,
targetPrecision: targetPrecision,
duration: duration
)))
}
/// Button-driven precision change: adjusts precision and animates zoom to frame it.
func animatePrecision(_ newPrecision: Int) {
let p = min(max(newPrecision, 1), GlobeMath.maxPrecision)
guard p != precision, baseRadius > 0 else { return }
let targetZoom = GlobeMath.zoomForPrecision(p, baseRadius: baseRadius, screenMin: screenMin)
animateTo(lat: centerLat, lon: centerLon, zoom: targetZoom, precision: p, duration: 0.45)
}
func cancelAnimations() {
motion = nil
if isAnimating {
isAnimating = false
motionStateChanged()
}
}
private func start(_ newMotion: Motion) {
motion = newMotion
if !isAnimating {
isAnimating = true
motionStateChanged()
}
clock.start()
}
private func finishMotion() {
motion = nil
isAnimating = false
motionStateChanged()
}
// MARK: - Frame loop
/// One display frame. Internal so tests can drive animations deterministically.
func tick(_ timestamp: CFTimeInterval) {
let previous = lastTick
lastTick = timestamp
let dt = previous.map { min(max(timestamp - $0, 0), Constants.maxFrameDelta) } ?? 0
switch motion {
case .tween(var tween):
let startTime = tween.startTime ?? timestamp
tween.startTime = startTime
let progress = min(max((timestamp - startTime) / tween.duration, 0), 1)
applyTween(tween, t: GlobeEasing.fastOutSlowIn(progress))
if progress >= 1 {
finishMotion()
} else {
motion = .tween(tween)
}
case .fling(var vx, var vy):
let maxStep = globeRadius * Constants.maxFlingRadiusFractionPerFrame
rotateBy(
dx: min(max(vx * dt, -maxStep), maxStep),
dy: min(max(vy * dt, -maxStep), maxStep)
)
let decay = exp(-Constants.flingFrictionPerSecond * dt)
vx *= decay
vy *= decay
if abs(vx) >= Constants.minFlingPerSecond || abs(vy) >= Constants.minFlingPerSecond {
motion = .fling(vx: vx, vy: vy)
} else {
finishMotion()
}
case nil:
break
}
if isInMotion, let previous {
governor.recordFrame(millis: (timestamp - previous) * 1000)
publishMotionDetail()
}
if motion == nil && !isInteracting {
clock.stop()
lastTick = nil
}
}
private func applyTween(_ tween: Tween, t: Double) {
// The target itself is always reachable: a polar cell's center can lie past
// the drag limit, and clamping it would end the animation on another cell.
centerLat = clampedLat(tween.startLat + (tween.endLat - tween.startLat) * t, reaching: tween.endLat)
centerLon = GlobeMath.normalizeLon(tween.startLon + tween.dLon * t)
// Exponential interpolation feels natural for zoom.
zoom = tween.startZoom * pow(tween.endZoom / tween.startZoom, t)
if let target = tween.targetPrecision {
precision = min(max(target, 1), GlobeMath.maxPrecision)
} else {
syncPrecisionFromZoom()
}
syncSelection()
}
/// Starts a motion session when the globe begins moving and ends it once both the
/// touch and any animation are done (see `GlobeMotionGovernor`).
private func motionStateChanged() {
if isInMotion {
guard !governor.isSessionActive else { return }
governor.beginSession()
lastTick = nil
clock.start()
} else {
governor.endSession()
}
publishMotionDetail()
}
private func publishMotionDetail() {
if motionDetail != governor.detail { motionDetail = governor.detail }
}
/// Clamps to the drag limit, widened (up to that pole) on `reach`'s side only.
private func clampedLat(_ lat: Double, reaching reach: Double) -> Double {
let lower = max(min(-Constants.maxDragLat, reach), -90)
let upper = min(max(Constants.maxDragLat, reach), 90)
return min(max(lat, lower), upper)
}
private func syncPrecisionFromZoom() {
guard baseRadius > 0 else { return }
let p = GlobeMath.autoPrecision(globeRadius: globeRadius, screenMin: screenMin)
if p != precision { precision = p }
}
private func syncSelection() {
guard baseRadius > 0 else { return }
let gh = Geohash.encode(latitude: centerLat, longitude: centerLon, precision: precision)
if gh != selectedGeohash { selectedGeohash = gh }
}
}
/// Material's FastOutSlowIn curve, cubic-bezier(0.4, 0.0, 0.2, 1.0), which the
/// Android globe animates with.
enum GlobeEasing {
static func fastOutSlowIn(_ t: Double) -> Double {
cubicBezier(t, x1: 0.4, y1: 0, x2: 0.2, y2: 1)
}
static func cubicBezier(_ t: Double, x1: Double, y1: Double, x2: Double, y2: Double) -> Double {
guard t > 0 else { return 0 }
guard t < 1 else { return 1 }
func sample(_ s: Double, _ a1: Double, _ a2: Double) -> Double {
let inv = 1 - s
return 3 * inv * inv * s * a1 + 3 * inv * s * s * a2 + s * s * s
}
// Solve x(s) = t by bisection; x is monotonic for these control points.
var lo = 0.0
var hi = 1.0
var s = t
for _ in 0..<24 {
let x = sample(s, x1, x2)
if abs(x - t) < 1e-6 { break }
if x < t { lo = s } else { hi = s }
s = (lo + hi) / 2
}
return sample(s, y1, y2)
}
}
/// Per-display-frame callback driving globe animations: CADisplayLink on iOS,
/// a common-mode timer on macOS.
@MainActor
final class GlobeFrameClock {
private let onFrame: (CFTimeInterval) -> Void
#if os(iOS)
private var displayLink: CADisplayLink?
private var proxy: Proxy?
private final class Proxy: NSObject {
weak var clock: GlobeFrameClock?
@objc func step(_ link: CADisplayLink) {
MainActor.assumeIsolated {
clock?.onFrame(link.timestamp)
}
}
}
#else
private var timer: Timer?
#endif
init(onFrame: @escaping (CFTimeInterval) -> Void) {
self.onFrame = onFrame
}
func start() {
#if os(iOS)
guard displayLink == nil else { return }
let proxy = Proxy()
proxy.clock = self
let link = CADisplayLink(target: proxy, selector: #selector(Proxy.step(_:)))
link.preferredFrameRateRange = CAFrameRateRange(minimum: 30, maximum: 120, preferred: 120)
link.add(to: .main, forMode: .common)
self.proxy = proxy
displayLink = link
#else
guard timer == nil else { return }
let timer = Timer(timeInterval: 1.0 / 60, repeats: true) { [weak self] _ in
MainActor.assumeIsolated {
self?.onFrame(CACurrentMediaTime())
}
}
RunLoop.main.add(timer, forMode: .common)
self.timer = timer
#endif
}
func stop() {
#if os(iOS)
displayLink?.invalidate()
displayLink = nil
proxy = nil
#else
timer?.invalidate()
timer = nil
#endif
}
deinit {
#if os(iOS)
displayLink?.invalidate()
#else
timer?.invalidate()
#endif
}
}

View File

@ -0,0 +1,831 @@
//
// GlobeView.swift
// bitchat
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import SwiftUI
#if os(iOS)
import UIKit
#else
import AppKit
#endif
/// Color palette for the globe, derived from the app theme by the caller.
struct GlobeColors: Equatable {
let accent: Color
let land: Color
let coastline: Color
let border: Color
let oceanCenter: Color
let oceanEdge: Color
let atmosphere: Color
let graticule: Color
let grid: Color
let label: Color
let labelHalo: Color
let star: Color
}
/// Interactive orthographic globe: drag to spin (with inertia), pinch to zoom, tap to
/// focus, double tap to zoom in. The selected geohash is always the cell under the
/// crosshair at the screen center.
struct GlobeView: View {
@ObservedObject var state: GlobeState
let colors: GlobeColors
let world: GlobeWorldData
@Environment(\.displayScale) private var displayScale
@Environment(\.appTheme) private var theme
@Environment(\.accessibilityReduceMotion) private var reduceMotion
#if os(iOS)
@State private var selectionFeedback = UISelectionFeedbackGenerator()
#endif
var body: some View {
GeometryReader { proxy in
ZStack {
// Static background lives in its own layer and is not redrawn by globe movement.
GlobeStarfield(color: colors.star)
.equatable()
let renderer = GlobeRenderer(
centerLat: state.centerLat,
centerLon: state.centerLon,
radius: state.globeRadius,
zoom: state.zoom,
selectedGeohash: state.selectedGeohash,
detail: state.frameDetail,
colors: colors,
world: world,
pixel: 1 / max(displayScale, 1),
fontDesign: theme.bodyFontDesign
)
Canvas(rendersAsynchronously: false) { context, size in
renderer.draw(in: &context, size: size)
}
GlobeTouchLayer(state: state)
// Isolated so its pulse does not redraw the globe geometry.
GlobeCrosshair(color: colors.accent, isInMotion: state.isInMotion)
.allowsHitTesting(false)
}
.onAppear { updateViewport(proxy.size) }
.onChange(of: proxy.size) { updateViewport($0) }
}
.onChange(of: state.selectedGeohash) { [previous = state.selectedGeohash] _ in
guard !previous.isEmpty else { return }
#if os(iOS)
selectionFeedback.selectionChanged()
#endif
}
.accessibilityElement()
.accessibilityLabel(Text(verbatim: state.selectedGeohash.isEmpty ? "" : "#\(state.selectedGeohash)"))
.accessibilityAdjustableAction { direction in
switch direction {
case .increment: state.animatePrecision(state.precision + 1)
case .decrement: state.animatePrecision(state.precision - 1)
@unknown default: break
}
}
}
private func updateViewport(_ size: CGSize) {
let minDim = Double(min(size.width, size.height))
state.setViewport(baseRadius: minDim * 0.44, screenMin: minDim, animateIntro: !reduceMotion)
}
}
// MARK: - Background and crosshair
private struct GlobeStarfield: View, Equatable {
let color: Color
private struct Star {
let x: Double
let y: Double
let radius: Double
let alpha: Double
}
private static let stars: [Star] = {
var rng = SeededGenerator(seed: 42)
return (0..<160).map { _ in
Star(
x: rng.nextUnit(),
y: rng.nextUnit(),
radius: 0.6 + rng.nextUnit() * 1.5,
alpha: 0.15 + rng.nextUnit() * 0.55
)
}
}()
var body: some View {
Canvas { context, size in
for star in Self.stars {
let center = CGPoint(x: star.x * size.width, y: star.y * size.height)
let rect = CGRect(x: center.x - star.radius, y: center.y - star.radius, width: star.radius * 2, height: star.radius * 2)
context.fill(Path(ellipseIn: rect), with: .color(color.opacity(star.alpha)))
}
}
.allowsHitTesting(false)
}
/// Deterministic SplitMix64 so the sky is the same every time the picker opens.
private struct SeededGenerator {
var state: UInt64
init(seed: UInt64) { state = seed }
mutating func nextUnit() -> Double {
state &+= 0x9E37_79B9_7F4A_7C15
var z = state
z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9
z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB
z ^= z >> 31
return Double(z >> 11) / Double(1 << 53)
}
}
}
private struct GlobeCrosshair: View {
let color: Color
let isInMotion: Bool
var body: some View {
TimelineView(.animation(minimumInterval: nil, paused: isInMotion)) { timeline in
Canvas { context, size in
let alpha = isInMotion ? 0.9 : Self.pulse(at: timeline.date)
let shading = GraphicsContext.Shading.color(color.opacity(alpha))
let cx = size.width / 2
let cy = size.height / 2
let gap: CGFloat = 5
let len: CGFloat = 9
var path = Path()
path.move(to: CGPoint(x: cx - gap - len, y: cy))
path.addLine(to: CGPoint(x: cx - gap, y: cy))
path.move(to: CGPoint(x: cx + gap, y: cy))
path.addLine(to: CGPoint(x: cx + gap + len, y: cy))
path.move(to: CGPoint(x: cx, y: cy - gap - len))
path.addLine(to: CGPoint(x: cx, y: cy - gap))
path.move(to: CGPoint(x: cx, y: cy + gap))
path.addLine(to: CGPoint(x: cx, y: cy + gap + len))
context.stroke(path, with: shading, lineWidth: 1.6)
context.fill(Path(ellipseIn: CGRect(x: cx - 1.8, y: cy - 1.8, width: 3.6, height: 3.6)), with: shading)
}
}
}
/// 0.45 → 1 → 0.45 over 2.2s, eased like the Android picker's reversing tween.
private static func pulse(at date: Date) -> Double {
let period = 1.1
let phase = date.timeIntervalSinceReferenceDate.truncatingRemainder(dividingBy: period * 2) / period
let t = phase <= 1 ? phase : 2 - phase
return 0.45 + 0.55 * GlobeEasing.fastOutSlowIn(t)
}
}
// MARK: - Renderer
/// Draws one globe frame. Built fresh per frame from a snapshot of `GlobeState`.
private struct GlobeRenderer {
let centerLat: Double
let centerLon: Double
let radius: Double
let zoom: Double
let selectedGeohash: String
let detail: GlobeMotionDetail.Frame
let colors: GlobeColors
let world: GlobeWorldData
/// One device pixel in points; hairline widths are specified in pixels.
let pixel: Double
let fontDesign: Font.Design
private typealias DiscPoint = GlobeGeometry.DiscPoint
func draw(in context: inout GraphicsContext, size: CGSize) {
guard radius > 0, size.width > 0, size.height > 0 else { return }
let cx = Double(size.width) / 2
let cy = Double(size.height) / 2
let r = radius
let center = CGPoint(x: cx, y: cy)
let projector = GlobeMath.PreparedProjector(centerLat: centerLat, centerLon: centerLon)
let clip = GlobeGeometry.ClipRect(size: size)
let screenRect = CGRect(origin: .zero, size: size)
// Once the disc covers the screen, the sphere-wide gradients are constant across
// it (and their huge coordinates would only cost precision), so draw flat fills.
let coverRadius = (cx * cx + cy * cy).squareRoot() + 2
let discCoversScreen = r > coverRadius
let gradientsMatter = r < Double(min(size.width, size.height)) * 10
func disc(_ discRadius: Double) -> Path {
if discRadius > coverRadius { return Path(screenRect) }
return Path(ellipseIn: CGRect(x: cx - discRadius, y: cy - discRadius, width: discRadius * 2, height: discRadius * 2))
}
// Atmosphere glow
if !discCoversScreen {
context.fill(disc(r * 1.22), with: .radialGradient(
Gradient(stops: [
.init(color: colors.atmosphere.opacity(0.30), location: 0),
.init(color: colors.atmosphere.opacity(0.12), location: 0.75),
.init(color: colors.atmosphere.opacity(0), location: 1)
]),
center: center,
startRadius: 0,
endRadius: r * 1.22
))
}
// Ocean sphere
if gradientsMatter {
context.fill(disc(r), with: .radialGradient(
Gradient(stops: [
.init(color: colors.oceanCenter, location: 0),
.init(color: colors.oceanCenter, location: 0.7),
.init(color: colors.oceanEdge, location: 1)
]),
center: CGPoint(x: cx - r * 0.32, y: cy - r * 0.38),
startRadius: 0,
endRadius: r * 1.5
))
} else {
context.fill(Path(screenRect), with: .color(colors.oceanCenter))
}
drawGraticule(in: &context, cx: cx, cy: cy, r: r, clip: clip)
// Fill every landmass first. Coastlines are drawn in a separate final pass so a
// large continent fill can never cover an island outline drawn earlier.
var coastlines = Path()
for ring in world.land {
drawLand(ring, in: &context, projector: projector, cx: cx, cy: cy, r: r, clip: clip, coastlines: &coastlines)
}
context.stroke(coastlines, with: .color(colors.coastline), lineWidth: 1.4 * pixel)
// Country borders are restored when interaction settles.
if detail.showBorders {
var borders = Path()
for line in world.borders {
let pts = line.terms.map { terms -> (DiscPoint, Bool) in
let p = projector.project(terms)
return (DiscPoint(x: p.x, y: p.y, front: p.cosC > 0.005), p.cosC >= 0)
}
guard pts.contains(where: { $0.1 }) else { continue }
appendRuns(GlobeGeometry.frontRuns(pts.map(\.0), closed: false), to: &borders, cx: cx, cy: cy, r: r, clip: clip)
}
context.stroke(borders, with: .color(colors.border), lineWidth: 1.2 * pixel)
}
// Sphere shading: dark limb + night side for 3D depth
if gradientsMatter {
context.fill(disc(r + 1), with: .radialGradient(
Gradient(stops: [
.init(color: .black.opacity(0), location: 0),
.init(color: .black.opacity(0), location: 0.62),
.init(color: .black.opacity(0.34), location: 0.88),
.init(color: .black.opacity(0.72), location: 1)
]),
center: CGPoint(x: cx - r * 0.25, y: cy - r * 0.3),
startRadius: 0,
endRadius: r * 1.35
))
context.fill(disc(r + 1), with: .linearGradient(
Gradient(stops: [
.init(color: .black.opacity(0), location: 0),
.init(color: .black.opacity(0), location: 0.55),
.init(color: .black.opacity(0.42), location: 1)
]),
startPoint: CGPoint(x: cx - r * 0.7, y: cy - r * 0.7),
endPoint: CGPoint(x: cx + r * 0.75, y: cy + r * 0.8)
))
}
// Dots follow the zoom at every detail level; only their labels wait for rest.
drawCities(in: &context, projector: projector, cx: cx, cy: cy, r: r, size: size)
// The grid is drawn at every detail level, including while dragging.
if !selectedGeohash.isEmpty {
let cells = visibleCells
drawGeohashGrid(cells, in: &context, cx: cx, cy: cy, r: r, clip: clip)
drawGeohashLabels(cells, in: &context, cx: cx, cy: cy, r: r)
}
}
private var visibleCells: [String] {
var cells = [selectedGeohash]
for neighbor in Geohash.neighbors(of: selectedGeohash) where !cells.contains(neighbor) {
cells.append(neighbor)
}
return cells
}
private func screen(_ p: CGPoint, cx: Double, cy: Double, r: Double) -> CGPoint {
CGPoint(x: cx + Double(p.x) * r, y: cy + Double(p.y) * r)
}
private func appendRuns(_ runs: [[CGPoint]], to path: inout Path, cx: Double, cy: Double, r: Double, clip: GlobeGeometry.ClipRect) {
for run in runs where run.count >= 2 {
for k in 1..<run.count {
guard let segment = GlobeGeometry.clipSegment(
screen(run[k - 1], cx: cx, cy: cy, r: r),
screen(run[k], cx: cx, cy: cy, r: r),
to: clip
) else { continue }
path.move(to: segment.0)
path.addLine(to: segment.1)
}
}
}
private func drawGraticule(in context: inout GraphicsContext, cx: Double, cy: Double, r: Double, clip: GlobeGeometry.ClipRect) {
let step = detail.graticuleStepDegrees
var path = Path()
func trace(_ points: [(lat: Double, lon: Double)]) {
var prev: GlobeMath.Projection?
for point in points {
if let p = GlobeMath.project(lat: point.lat, lon: point.lon, centerLat: centerLat, centerLon: centerLon), p.cosC > 0.02 {
if let pp = prev, let segment = GlobeGeometry.clipSegment(
CGPoint(x: cx + pp.x * r, y: cy + pp.y * r),
CGPoint(x: cx + p.x * r, y: cy + p.y * r),
to: clip
) {
path.move(to: segment.0)
path.addLine(to: segment.1)
}
prev = p
} else {
prev = nil
}
}
}
// Latitude lines
for lat in stride(from: -75.0, through: 75.0, by: 15) {
trace(stride(from: -180.0, through: 180.0, by: step).map { (lat, $0) })
}
// Longitude lines
for lon in stride(from: -180.0, to: 180.0, by: 15) {
trace(stride(from: -90.0, through: 90.0, by: step).map { ($0, lon) })
}
context.stroke(path, with: .color(colors.graticule), lineWidth: pixel)
}
private func drawLand(
_ ring: GlobeRing,
in context: inout GraphicsContext,
projector: GlobeMath.PreparedProjector,
cx: Double, cy: Double, r: Double,
clip: GlobeGeometry.ClipRect,
coastlines: inout Path
) {
let pointStride = ring.count >= 64 ? detail.landPointStride : 1
let n = (ring.count - 1) / pointStride + 1
guard n >= 3 else { return }
var anyFront = false
var anyBack = false
var pts: [DiscPoint] = []
pts.reserveCapacity(n)
for i in 0..<n {
let p = projector.project(ring.terms[min(i * pointStride, ring.count - 1)])
if p.cosC >= 0 { anyFront = true } else { anyBack = true }
pts.append(DiscPoint(x: p.x, y: p.y, front: p.cosC > 0.005))
}
guard anyFront else { return }
appendRuns(GlobeGeometry.frontRuns(pts), to: &coastlines, cx: cx, cy: cy, r: r, clip: clip)
let polygon = GlobeGeometry.fillPolygon(pts, cx: cx, cy: cy, r: r)
let invert = anyBack && GlobeGeometry.projectedFillNeedsInversion(
polygon: polygon, ring: ring, cx: cx, cy: cy, r: r, centerLat: centerLat, centerLon: centerLon
)
fill(pts, polygon: polygon, color: colors.land, in: &context, cx: cx, cy: cy, r: r, clip: clip, invert: invert)
}
private func fill(
_ pts: [DiscPoint],
polygon: [CGPoint]? = nil,
color: Color,
in context: inout GraphicsContext,
cx: Double, cy: Double, r: Double,
clip: GlobeGeometry.ClipRect,
invert: Bool = false
) {
guard pts.contains(where: \.front) else { return }
let poly = polygon ?? GlobeGeometry.fillPolygon(pts, cx: cx, cy: cy, r: r)
guard poly.count >= 3 else { return }
let clipped = GlobeGeometry.clipPolygon(poly, to: clip)
guard clipped.count >= 3 else { return }
var path = Path()
if invert {
// Even-odd filling with the globe disc flips the one ring whose horizon
// closure the projection put on the wrong side.
let clipBounds = CGRect(x: clip.left, y: clip.top, width: clip.right - clip.left, height: clip.bottom - clip.top)
let discRect = CGRect(x: cx - r, y: cy - r, width: r * 2, height: r * 2)
if discRect.contains(clipBounds) {
path.addRect(clipBounds)
} else {
path.addEllipse(in: discRect)
}
}
path.addLines(clipped)
path.closeSubpath()
context.fill(path, with: .color(color), style: FillStyle(eoFill: invert))
}
private func drawCities(
in context: inout GraphicsContext,
projector: GlobeMath.PreparedProjector,
cx: Double, cy: Double, r: Double,
size: CGSize
) {
let maxRank: Int
if zoom < 2 {
maxRank = 1
} else if zoom < 8 {
maxRank = 3
} else if zoom < 40 {
maxRank = 4
} else {
maxRank = 10
}
let width = Double(size.width)
let height = Double(size.height)
for city in world.cities where city.rank <= maxRank {
let p = projector.project(city.terms)
guard p.cosC >= 0.03 else { continue }
let sx = cx + p.x * r
let sy = cy + p.y * r
guard sx >= -50, sx <= width + 50, sy >= -50, sy <= height + 50 else { continue }
let alpha = min(max(p.cosC, 0.25), 1)
let important = city.capital || city.megacity
let dotRadius = important ? 2.6 : 1.8
let dotColor = city.capital ? colors.accent.opacity(alpha) : colors.label.opacity(alpha * 0.85)
context.fill(
Path(ellipseIn: CGRect(x: sx - dotRadius, y: sy - dotRadius, width: dotRadius * 2, height: dotRadius * 2)),
with: .color(dotColor)
)
if detail.showCityLabels && (zoom >= 6 || (important && zoom >= 2.5)) {
drawLabel(
city.name,
at: CGPoint(x: sx + dotRadius + 3, y: sy),
anchor: .leading,
size: 10,
weight: .medium,
color: colors.label.opacity(200 / 255 * alpha),
halo: colors.labelHalo.opacity(140 / 255 * alpha),
in: &context
)
}
}
}
private func drawGeohashGrid(_ cells: [String], in context: inout GraphicsContext, cx: Double, cy: Double, r: Double, clip: GlobeGeometry.ClipRect) {
for cell in cells {
let isSelected = cell == selectedGeohash
let b = Geohash.decodeBounds(cell)
let spanLat = b.latMax - b.latMin
let spanLon = b.lonMax - b.lonMin
let steps = min(max(Int((spanLat / 1.5).rounded(.up)), 4), 48)
// Sample the cell boundary: N edge l->r, E edge t->b, S edge r->l, W edge b->t
var pts: [DiscPoint] = []
pts.reserveCapacity(steps * 4 + 4)
func add(_ lat: Double, _ rawLon: Double) {
// Keep the boundary continuous across the antimeridian relative to the view.
var lon = rawLon
while lon - centerLon > 180 { lon -= 360 }
while lon - centerLon < -180 { lon += 360 }
let p = GlobeMath.projectRaw(lat: lat, lon: lon, centerLat: centerLat, centerLon: centerLon)
pts.append(DiscPoint(x: p.x, y: p.y, front: p.cosC >= 0.005))
}
for s in 0...steps { add(b.latMax, b.lonMin + spanLon * Double(s) / Double(steps)) }
for s in 1...steps { add(b.latMax - spanLat * Double(s) / Double(steps), b.lonMax) }
for s in 1...steps { add(b.latMin, b.lonMax - spanLon * Double(s) / Double(steps)) }
for s in 1..<steps { add(b.latMin + spanLat * Double(s) / Double(steps), b.lonMin) }
guard pts.contains(where: \.front) else { continue }
var outline = Path()
appendRuns(GlobeGeometry.frontRuns(pts), to: &outline, cx: cx, cy: cy, r: r, clip: clip)
if isSelected {
fill(pts, color: colors.accent.opacity(0.20), in: &context, cx: cx, cy: cy, r: r, clip: clip)
context.stroke(outline, with: .color(colors.accent.opacity(0.35)), lineWidth: 7 * pixel)
context.stroke(outline, with: .color(colors.accent), lineWidth: 3.2 * pixel)
} else {
fill(pts, color: colors.grid.opacity(0.05), in: &context, cx: cx, cy: cy, r: r, clip: clip)
context.stroke(outline, with: .color(colors.grid), lineWidth: 1.6 * pixel)
}
}
}
private func drawGeohashLabels(_ cells: [String], in context: inout GraphicsContext, cx: Double, cy: Double, r: Double) {
for cell in cells {
let isSelected = cell == selectedGeohash
let c = Geohash.decodeCenter(cell)
guard let p = GlobeMath.project(lat: c.lat, lon: c.lon, centerLat: centerLat, centerLon: centerLon),
p.cosC >= 0.08 else { continue }
drawLabel(
cell,
at: CGPoint(x: cx + p.x * r, y: cy + p.y * r),
anchor: .center,
size: isSelected ? 12.5 : 10,
weight: isSelected ? .semibold : .medium,
color: isSelected ? colors.accent : colors.label.opacity(160 / 255 * min(max(p.cosC, 0.4), 1)),
halo: colors.labelHalo.opacity(isSelected ? 200 / 255 : 120 / 255),
in: &context
)
}
}
/// Text with a thin halo in the background color so labels stay legible over land,
/// grid lines and the limb shading.
private func drawLabel(
_ string: String,
at point: CGPoint,
anchor: UnitPoint,
size: CGFloat,
weight: Font.Weight,
color: Color,
halo: Color,
in context: inout GraphicsContext
) {
var resolved = context.resolve(
Text(verbatim: string).font(.system(size: size, weight: weight, design: fontDesign))
)
resolved.shading = .color(halo)
let w = size * 0.09
for (dx, dy) in [(-w, 0), (w, 0), (0, -w), (0, w), (-w, -w), (w, -w), (-w, w), (w, w)] {
context.draw(resolved, at: CGPoint(x: point.x + dx, y: point.y + dy), anchor: anchor)
}
resolved.shading = .color(color)
context.draw(resolved, at: point, anchor: anchor)
}
}
// MARK: - Touch handling
/// Gesture surface over the globe. A single raw-touch handler (rather than stacked
/// recognizers) mirrors the Android picker: centroid pan rotates, pinch zooms in the
/// same gesture, a quick tap focuses immediately and a second tap zooms in.
#if os(iOS)
private struct GlobeTouchLayer: UIViewRepresentable {
let state: GlobeState
func makeUIView(context: Context) -> GlobeTouchSurface {
let view = GlobeTouchSurface()
view.state = state
return view
}
func updateUIView(_ view: GlobeTouchSurface, context: Context) {
view.state = state
}
}
private final class GlobeTouchSurface: UIView {
weak var state: GlobeState?
private static let touchSlop: CGFloat = 8
private var touches: Set<UITouch> = []
private var downTime: TimeInterval = 0
private var downPosition: CGPoint = .zero
private var moved: CGVector = .zero
private var dragStarted = false
private var hadMultipleTouches = false
private var lastCentroid: CGPoint?
private var lastSpan: CGFloat?
private var samples: [(time: TimeInterval, position: CGPoint)] = []
private var lastTapTime: TimeInterval = 0
private var lastTapPosition: CGPoint = .zero
override init(frame: CGRect) {
super.init(frame: frame)
isMultipleTouchEnabled = true
backgroundColor = .clear
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func touchesBegan(_ began: Set<UITouch>, with event: UIEvent?) {
if touches.isEmpty, let first = began.first {
state?.beginInteraction()
downTime = first.timestamp
downPosition = first.location(in: self)
moved = .zero
dragStarted = false
hadMultipleTouches = false
samples = [(first.timestamp, downPosition)]
}
touches.formUnion(began)
if touches.count > 1 {
hadMultipleTouches = true
samples.removeAll()
}
resetBaseline()
}
override func touchesMoved(_ movedTouches: Set<UITouch>, with event: UIEvent?) {
guard let state, let previousCentroid = lastCentroid else { return }
let centroid = currentCentroid()
let pan = CGVector(dx: centroid.x - previousCentroid.x, dy: centroid.y - previousCentroid.y)
if pan != .zero {
moved.dx += pan.dx
moved.dy += pan.dy
if !dragStarted && hypot(moved.dx, moved.dy) >= Self.touchSlop {
dragStarted = true
}
if dragStarted { state.rotateBy(dx: Double(pan.dx), dy: Double(pan.dy)) }
}
if touches.count > 1, let previousSpan = lastSpan, previousSpan > 0 {
let span = currentSpan(around: centroid)
if span > 0 { state.zoomBy(Double(span / previousSpan)) }
lastSpan = span
}
lastCentroid = centroid
if !hadMultipleTouches, touches.count == 1, let touch = touches.first {
samples.append((touch.timestamp, touch.location(in: self)))
if samples.count > 20 { samples.removeFirst(samples.count - 20) }
}
}
override func touchesEnded(_ ended: Set<UITouch>, with event: UIEvent?) {
if !hadMultipleTouches, touches.count == 1, let touch = ended.first {
samples.append((touch.timestamp, touch.location(in: self)))
}
finish(ended, upTime: ended.first?.timestamp ?? downTime, cancelled: false)
}
override func touchesCancelled(_ cancelled: Set<UITouch>, with event: UIEvent?) {
finish(cancelled, upTime: cancelled.first?.timestamp ?? downTime, cancelled: true)
}
private func finish(_ lifted: Set<UITouch>, upTime: TimeInterval, cancelled: Bool) {
touches.subtract(lifted)
guard touches.isEmpty else {
resetBaseline()
return
}
lastCentroid = nil
lastSpan = nil
guard let state else { return }
guard !cancelled else {
state.endInteraction()
return
}
let isTap = !hadMultipleTouches
&& !dragStarted
&& upTime - downTime < 0.4
&& hypot(moved.dx, moved.dy) < Self.touchSlop
let r = state.globeRadius
let tapLocation = r > 0 ? GlobeMath.unproject(
x: Double((downPosition.x - bounds.midX) / r),
y: Double((downPosition.y - bounds.midY) / r),
centerLat: state.centerLat,
centerLon: state.centerLon
) : nil
if isTap, let location = tapLocation {
let isDouble = upTime - lastTapTime < 0.35
&& hypot(downPosition.x - lastTapPosition.x, downPosition.y - lastTapPosition.y) < Self.touchSlop * 4
lastTapTime = upTime
lastTapPosition = downPosition
state.focus(lat: location.lat, lon: location.lon, zoomIn: isDouble)
state.endInteraction()
} else if dragStarted && !hadMultipleTouches {
let velocity = releaseVelocity(at: upTime)
state.endInteraction(flingVelocityX: Double(velocity.dx), flingVelocityY: Double(velocity.dy))
} else {
state.endInteraction()
}
}
/// Average velocity over the last 100ms of movement; zero when the finger rested
/// before lifting.
private func releaseVelocity(at upTime: TimeInterval) -> CGVector {
guard let last = samples.last, upTime - last.time < 0.04 else { return .zero }
let window = samples.filter { last.time - $0.time <= 0.1 }
guard let first = window.first, last.time - first.time > 0.005 else { return .zero }
let dt = CGFloat(last.time - first.time)
return CGVector(dx: (last.position.x - first.position.x) / dt, dy: (last.position.y - first.position.y) / dt)
}
private func resetBaseline() {
let centroid = currentCentroid()
lastCentroid = centroid
lastSpan = touches.count > 1 ? currentSpan(around: centroid) : nil
}
private func currentCentroid() -> CGPoint {
guard !touches.isEmpty else { return .zero }
var x: CGFloat = 0
var y: CGFloat = 0
for touch in touches {
let p = touch.location(in: self)
x += p.x
y += p.y
}
return CGPoint(x: x / CGFloat(touches.count), y: y / CGFloat(touches.count))
}
private func currentSpan(around centroid: CGPoint) -> CGFloat {
guard !touches.isEmpty else { return 0 }
let total = touches.reduce(CGFloat(0)) { sum, touch in
let p = touch.location(in: self)
return sum + hypot(p.x - centroid.x, p.y - centroid.y)
}
return total / CGFloat(touches.count)
}
}
#else
private struct GlobeTouchLayer: NSViewRepresentable {
let state: GlobeState
func makeNSView(context: Context) -> GlobeTouchSurface {
let view = GlobeTouchSurface()
view.state = state
return view
}
func updateNSView(_ view: GlobeTouchSurface, context: Context) {
view.state = state
}
}
/// macOS: click-drag spins, trackpad pinch or scroll zooms, click focuses,
/// double click zooms in.
private final class GlobeTouchSurface: NSView {
weak var state: GlobeState?
private var lastDrag: CGPoint?
private var dragDistance: CGFloat = 0
private var samples: [(time: TimeInterval, position: CGPoint)] = []
override var isFlipped: Bool { true }
override var acceptsFirstResponder: Bool { true }
override func mouseDown(with event: NSEvent) {
state?.beginInteraction()
let p = convert(event.locationInWindow, from: nil)
lastDrag = p
dragDistance = 0
samples = [(event.timestamp, p)]
}
override func mouseDragged(with event: NSEvent) {
let p = convert(event.locationInWindow, from: nil)
if let last = lastDrag {
dragDistance += hypot(p.x - last.x, p.y - last.y)
state?.rotateBy(dx: Double(p.x - last.x), dy: Double(p.y - last.y))
}
lastDrag = p
samples.append((event.timestamp, p))
if samples.count > 20 { samples.removeFirst(samples.count - 20) }
}
override func mouseUp(with event: NSEvent) {
guard let state else { return }
lastDrag = nil
let p = convert(event.locationInWindow, from: nil)
let r = state.globeRadius
if dragDistance < 4 {
if r > 0, let location = GlobeMath.unproject(
x: Double((p.x - bounds.midX) / r),
y: Double((p.y - bounds.midY) / r),
centerLat: state.centerLat,
centerLon: state.centerLon
) {
state.focus(lat: location.lat, lon: location.lon, zoomIn: event.clickCount >= 2)
}
state.endInteraction()
} else if let last = samples.last, event.timestamp - last.time < 0.04,
let first = samples.first(where: { last.time - $0.time <= 0.1 }),
last.time - first.time > 0.005 {
let dt = CGFloat(last.time - first.time)
state.endInteraction(
flingVelocityX: Double((last.position.x - first.position.x) / dt),
flingVelocityY: Double((last.position.y - first.position.y) / dt)
)
} else {
state.endInteraction()
}
}
override func magnify(with event: NSEvent) {
state?.cancelAnimations()
state?.zoomBy(Double(1 + event.magnification))
}
override func scrollWheel(with event: NSEvent) {
state?.cancelAnimations()
state?.zoomBy(Double(exp(event.scrollingDeltaY * (event.hasPreciseScrollingDeltas ? 0.01 : 0.1))))
}
}
#endif

View File

@ -0,0 +1,139 @@
//
// GlobeWorldData.swift
// bitchat
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import Foundation
/// A polygon ring or polyline on the globe, with projection terms prepared once.
struct GlobeRing: Sendable {
let lats: [Double]
let lons: [Double]
let terms: [GlobeMath.Terms]
var count: Int { lats.count }
init(lats: [Double], lons: [Double]) {
self.lats = lats
self.lons = lons
self.terms = zip(lats, lons).map { GlobeMath.Terms(lat: $0, lon: $1) }
}
}
struct GlobeCity: Sendable {
let name: String
let rank: Int
let capital: Bool
let megacity: Bool
/// The position, kept only as the projection terms the renderer reads.
let terms: GlobeMath.Terms
init(name: String, lat: Double, lon: Double, rank: Int, capital: Bool, megacity: Bool) {
self.name = name
self.rank = rank
self.capital = capital
self.megacity = megacity
self.terms = GlobeMath.Terms(lat: lat, lon: lon)
}
}
/// The bundled Natural Earth geometry (public domain) the globe draws: 110m land
/// polygons, admin-0 boundary lines and 50m populated places. The files are the
/// same ones the Android picker ships.
struct GlobeWorldData: Sendable {
let land: [GlobeRing]
let borders: [GlobeRing]
let cities: [GlobeCity]
/// Parsed on first access; callers load it off the main thread.
static let bundled = GlobeWorldData(bundle: .main)
init(land: [GlobeRing], borders: [GlobeRing], cities: [GlobeCity]) {
self.land = land
self.borders = borders
self.cities = cities
}
private init(bundle: Bundle) {
func data(_ name: String) -> Data? {
bundle.url(forResource: name, withExtension: "geojson").flatMap { try? Data(contentsOf: $0) }
}
self.init(
land: data("world_land").map(Self.parseLand) ?? [],
borders: data("world_borders").map(Self.parseBorders) ?? [],
cities: data("world_cities").map(Self.parseCities) ?? []
)
}
/// Polygon and MultiPolygon geometries; every ring (outer and holes) becomes one entry.
static func parseLand(_ data: Data) -> [GlobeRing] {
var rings: [GlobeRing] = []
for geometry in geometries(data) {
switch geometry["type"] as? String {
case "Polygon":
appendRings(geometry["coordinates"], minimumPoints: 3, to: &rings)
case "MultiPolygon":
for polygon in geometry["coordinates"] as? [Any] ?? [] {
appendRings(polygon, minimumPoints: 3, to: &rings)
}
default:
continue
}
}
return rings
}
/// LineString and MultiLineString geometries.
static func parseBorders(_ data: Data) -> [GlobeRing] {
var lines: [GlobeRing] = []
for geometry in geometries(data) {
switch geometry["type"] as? String {
case "LineString":
appendRings([geometry["coordinates"] as Any], minimumPoints: 2, to: &lines)
case "MultiLineString":
appendRings(geometry["coordinates"], minimumPoints: 2, to: &lines)
default:
continue
}
}
return lines
}
/// `{"cities": [{"n": name, "r": rank, "cap": 0|1, "mega": 0|1, "lat": .., "lon": ..}]}`
static func parseCities(_ data: Data) -> [GlobeCity] {
guard let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let entries = root["cities"] as? [[String: Any]] else { return [] }
return entries.compactMap { entry in
guard let name = entry["n"] as? String,
let lat = (entry["lat"] as? NSNumber)?.doubleValue,
let lon = (entry["lon"] as? NSNumber)?.doubleValue,
let rank = (entry["r"] as? NSNumber)?.intValue else { return nil }
return GlobeCity(
name: name,
lat: lat,
lon: lon,
rank: rank,
capital: (entry["cap"] as? NSNumber)?.intValue == 1,
megacity: (entry["mega"] as? NSNumber)?.intValue == 1
)
}
}
private static func geometries(_ data: Data) -> [[String: Any]] {
guard let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return [] }
return root["geometries"] as? [[String: Any]] ?? []
}
/// GeoJSON positions are [lon, lat].
private static func appendRings(_ ringsJSON: Any?, minimumPoints: Int, to out: inout [GlobeRing]) {
for ring in ringsJSON as? [Any] ?? [] {
guard let points = ring as? [[NSNumber]], points.count >= minimumPoints else { continue }
let valid = points.filter { $0.count >= 2 }
guard valid.count >= minimumPoints else { continue }
out.append(GlobeRing(lats: valid.map { $0[1].doubleValue }, lons: valid.map { $0[0].doubleValue }))
}
}
}

View File

@ -30,7 +30,7 @@ struct GroupChatList: View {
ForEach(groups) { group in
HStack(spacing: 4) {
Text("#\(group.name)")
hashtagText(for: group)
.bitchatFont(size: 14)
.foregroundColor(palette.primary)
.lineLimit(1)
@ -69,6 +69,19 @@ struct GroupChatList: View {
}
}
/// "#name", not localized: there is nothing to translate, and a
/// letterless "#%@" catalog key breaks string catalog symbol generation
/// (SwiftPM's default build system). It renders as the localized lookup
/// did: the name is isolated (the lookup isolates names containing
/// right-to-left text; isolating every name renders the same), so the
/// "#" stays on the same side of RTL names, and the text is tagged with
/// the app language, as text from a localization table is.
private func hashtagText(for group: GroupChatRow) -> Text {
var hashtag = AttributedString("#\u{2068}\(group.name)\u{2069}")
hashtag.languageIdentifier = Bundle.main.preferredLocalizations.first ?? "en"
return Text(hashtag)
}
private func accessibilityDescription(for group: GroupChatRow) -> String {
var parts: [String] = [
group.name,

View File

@ -16,6 +16,9 @@ struct LocationChannelsSheet: View {
@State private var pendingShareGeohash: String?
@State private var showSharePrecisionWarning = false
@State private var activeSharePayload: ChannelSharePayload?
@State private var showGlobePicker = false
/// Geohash chosen on the globe; applied once the picker has dismissed.
@State private var pickedGeohash: String?
private enum Strings {
static let title: LocalizedStringKey = "location_channels.title"
@ -55,6 +58,7 @@ struct LocationChannelsSheet: View {
static let sharePrecisionTitle = String(localized: "channel.share.precision_warning.title", defaultValue: "share a precise location channel?", comment: "Title of the confirmation before sharing a neighborhood-or-finer geohash invite")
static let sharePrecisionMessage = String(localized: "channel.share.precision_warning.message", defaultValue: "this channel covers a small area. an invite sent over sms or imessage is visible to the carrier and both handsets — it discloses interest in that place, not only that someone uses bitchat.", comment: "Body of the confirmation before sharing a fine-precision geohash invite")
static let shareAnyway = String(localized: "channel.share.precision_warning.confirm", defaultValue: "share anyway", comment: "Confirms sharing a fine-precision location channel after the OpSec warning")
static let openMap = String(localized: "location_channels.accessibility.open_map", defaultValue: "open map", comment: "Accessibility label for the button that opens the globe geohash picker")
static func meshTitle(_ count: Int) -> String {
let label = String(localized: "location_channels.mesh_label", comment: "Label for the mesh channel row")
@ -220,6 +224,47 @@ struct LocationChannelsSheet: View {
.sheet(item: $activeSharePayload) { payload in
ShareActivityView(text: payload.text)
}
#if os(iOS)
.fullScreenCover(isPresented: $showGlobePicker, onDismiss: applyPickedGeohash) {
globePicker
}
#else
.sheet(isPresented: $showGlobePicker, onDismiss: applyPickedGeohash) {
globePicker
}
#endif
}
/// Opens on the typed geohash, else the current location channel; the picker
/// itself falls back to the coarsest nearby channel.
private var globePicker: some View {
let typed = customGeohash.trimmed.lowercased().replacingOccurrences(of: "#", with: "")
let initial: String
if !typed.isEmpty {
initial = typed
} else if case .location(let channel) = locationChannelsModel.selectedChannel {
initial = channel.geohash
} else {
initial = ""
}
return GeohashPickerView(
initialGeohash: initial,
nearbyGeohashes: locationChannelsModel.availableChannels.map(\.geohash),
onSelect: { geohash in
pickedGeohash = geohash
showGlobePicker = false
},
onCancel: { showGlobePicker = false }
)
}
private func applyPickedGeohash() {
guard let geohash = pickedGeohash else { return }
pickedGeohash = nil
guard validateGeohash(geohash) else { return }
customError = nil
locationChannelsModel.teleport(to: geohash)
isPresented = false
}
private func requestShare(forGeohash geohash: String) {
@ -239,7 +284,17 @@ struct LocationChannelsSheet: View {
SheetCloseButton { isPresented = false }
}
/// Participant counts mean "active in the last five minutes": they change
/// as people arrive and as quiet ones age out, neither of which publishes
/// anything this sheet observes, so re-read them every few seconds while
/// the sheet is open.
private var channelList: some View {
TimelineView(.periodic(from: .now, by: 5)) { _ in
channelListContent
}
}
private var channelListContent: some View {
ScrollView {
LazyVStack(spacing: 0) {
channelRow(title: Strings.meshTitle(peerListModel.reachableMeshPeerCount), subtitlePrefix: Strings.subtitlePrefix(geohash: "bluetooth", coverage: bluetoothRangeString()), isSelected: isMeshSelected, titleColor: standardBlue, titleBold: peerListModel.reachableMeshPeerCount > 0) {
@ -374,6 +429,15 @@ struct LocationChannelsSheet: View {
.lowercased()
.replacingOccurrences(of: "#", with: "")
let isValid = validateGeohash(normalized)
Button(action: { showGlobePicker = true }) {
Image(systemName: "map")
.font(.bitchatSystem(size: 16))
.foregroundColor(palette.secondary)
.frame(width: 36, height: 36)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.accessibilityLabel(Strings.openMap)
Button(action: {
let gh = normalized
guard isValid else { customError = Strings.invalidGeohash; return }
@ -617,59 +681,12 @@ extension LocationChannelsSheet {
// MARK: - Coverage helpers
extension LocationChannelsSheet {
private func coverageString(forPrecision len: Int) -> String {
// Approximate max cell dimension at equator for a given geohash length.
// Values sourced from common geohash dimension tables.
let maxMeters: Double = {
switch len {
case 2: return 1_250_000
case 3: return 156_000
case 4: return 39_100
case 5: return 4_890
case 6: return 1_220
case 7: return 153
case 8: return 38.2
case 9: return 4.77
case 10: return 1.19
default:
if len <= 1 { return 5_000_000 }
// For >10, scale down conservatively by ~1/4 each char
let over = len - 10
return 1.19 * pow(0.25, Double(over))
}
}()
let usesMetric: Bool = {
if #available(iOS 16.0, macOS 13.0, *) {
return Locale.current.measurementSystem == .metric
} else {
return Locale.current.usesMetricSystem
}
}()
if usesMetric {
let km = maxMeters / 1000.0
return "~\(formatDistance(km)) km"
} else {
let miles = maxMeters / 1609.344
return "~\(formatDistance(miles)) mi"
}
}
private func formatDistance(_ value: Double) -> String {
if value >= 100 { return String(format: "%.0f", value.rounded()) }
if value >= 10 { return String(format: "%.1f", value) }
return String(format: "%.1f", value)
GeohashCoverage.string(forPrecision: len)
}
private func bluetoothRangeString() -> String {
let usesMetric: Bool = {
if #available(iOS 16.0, macOS 13.0, *) {
return Locale.current.measurementSystem == .metric
} else {
return Locale.current.usesMetricSystem
}
}()
// Approximate Bluetooth LE range for typical mobile devices; environment dependent
return usesMetric ? "~10–50 m" : "~30–160 ft"
GeohashCoverage.usesMetric() ? "~10–50 m" : "~30–160 ft"
}
private func locationName(for level: GeohashChannelLevel) -> String? {

View File

@ -39,10 +39,9 @@ struct MeshPeerList: View {
var body: some View {
let currentIDs = peerListModel.meshRows.map(\.id)
let displayIDs = orderedIDs.filter { currentIDs.contains($0) } + currentIDs.filter { !orderedIDs.contains($0) }
let peers: [MeshPeerRow] = displayIDs.compactMap { id in
peerListModel.meshRows.first(where: { $0.id == id })
}
let rowByID = Dictionary(peerListModel.meshRows.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first })
let peers: [MeshPeerRow] = PeopleListOrdering.stableOrder(previous: orderedIDs, current: currentIDs)
.compactMap { rowByID[$0] }
if peerListModel.meshRows.isEmpty {
// Match the section's row rhythm (same size, indent, and vertical
@ -55,8 +54,7 @@ struct MeshPeerList: View {
.padding(.vertical, 4)
} else {
VStack(alignment: .leading, spacing: 0) {
ForEach(0..<peers.count, id: \.self) { idx in
let peer = peers[idx]
ForEach(peers) { peer in
let isMe = peer.isMe
HStack(spacing: 4) {
let assigned = peerListModel.colorForMeshPeer(id: peer.peerID, isDark: colorScheme == .dark)
@ -243,9 +241,7 @@ struct MeshPeerList: View {
orderedIDs = currentIDs
}
.onChange(of: currentIDs) { ids in
var newOrder = orderedIDs
newOrder.removeAll { !ids.contains($0) }
for id in ids where !newOrder.contains(id) { newOrder.append(id) }
let newOrder = PeopleListOrdering.stableOrder(previous: orderedIDs, current: ids)
if newOrder != orderedIDs { orderedIDs = newOrder }
}
}

View File

@ -0,0 +1,236 @@
//
// MessageListScrollPolicy.swift
// bitchat
//
// The pure rules behind MessageListView's scroll position: how many messages
// arrived since the list last looked, how wide the window must be to keep a
// scrolled-up reader's rows in place, and when the top row may expand the
// window. Kept free of SwiftUI so the rules are unit-testable.
//
import BitFoundation
import Foundation
enum MessageListScrollPolicy {
/// What the list saw at its last look at a timeline.
struct TimelineMark: Equatable {
/// Conversation the mark belongs to; a mark never carries across.
let contextKey: String
/// Newest message at the time (nil: the timeline was empty), and its
/// timestamp to fall back on if that message is gone by the next look.
let newestMessageID: String?
let newestTimestamp: Date?
/// First message of the window at the time, and the window size it
/// was taken at: a window resized since then voids it.
let windowFirstMessageID: String?
let windowCount: Int
/// Messages in the timeline at the time.
let count: Int
}
/// Messages that landed after a mark's newest message.
struct Appended: Equatable {
/// Every such message: rows the window has to make room for.
var total = 0
/// Those the jump-to-latest pill counts.
var unseen = 0
}
/// What the list does about a change to the timeline it shows.
enum TimelineReaction: Equatable {
/// A timeline the list was not showing: land at its newest message.
case land
/// Scroll to the newest row.
case follow
/// Keep a scrolled-up reader's rows in place and count what's new.
case keepPosition
/// Leave the scroll alone: the rendered rows did not change.
case hold
}
/// The reaction to a timeline change. `mark` is the mark taken in this
/// timeline's context, if any; `appendedCount` what `appended(since:in:)`
/// counted after it; `windowCount` the window size the list renders.
static func reaction(
mark: TimelineMark?,
messages: [BitchatMessage],
newestIsOwn: Bool,
appendedCount: Int,
windowCount: Int,
isAtBottom: Bool
) -> TimelineReaction {
// No mark here: the list arrives from another timeline (a channel or
// DM switch), whatever the old timeline's row callbacks did to
// isAtBottom on the way out.
guard let mark else { return .land }
// Emptied (e.g. /clear): nothing to scroll to.
guard !messages.isEmpty else { return .hold }
// A new message of mine takes the reader to it from anywhere. New
// means appended since the mark (the newest message is then the last
// one counted): an older message of mine that a removal left newest
// (a retracted bridge alias, a dropped empty voice burst) is not.
if newestIsOwn && appendedCount > 0 {
return .follow
}
if !isAtBottom {
return .keepPosition
}
// At the bottom, follow any change that can move the rendered rows: a
// late message landing among the visible rows pushes the newest one
// off screen. Only provably unchanged rows skip the scroll, which
// would be a no-op, and a no-op scrollTo stays queued until the next
// layout pass: the reader's next drag, which it snaps back down.
let isWindowUnchanged = isRenderedWindowUnchanged(
since: mark,
appendedCount: appendedCount,
windowCount: windowCount,
in: messages
)
return isWindowUnchanged ? .hold : .follow
}
/// Whether the window rendered at the bottom (the last `windowCount`
/// messages) holds exactly the rows it held at `mark`: nothing appended,
/// the same message count, a full window starting at the same message.
/// True for a late message landing above the window at the store cap
/// (it evicts the oldest message, also above the window).
static func isRenderedWindowUnchanged(
since mark: TimelineMark,
appendedCount: Int,
windowCount: Int,
in messages: [BitchatMessage]
) -> Bool {
appendedCount == 0
&& mark.count == messages.count
&& mark.windowCount == windowCount
&& messages.count >= windowCount
&& mark.windowFirstMessageID == messages.suffix(windowCount).first?.id
}
/// Whether a row ID (`"<context>|<message id>"`) belongs to the timeline
/// of `contextKey`. Row callbacks lag a switch, so the list checks them
/// against the context it has landed in.
static func isRow(_ rowID: String, inContext contextKey: String) -> Bool {
rowID.hasPrefix(contextKey + "|")
}
/// Whether the retry of a scroll to the bottom has anything to do: not
/// once the newest row is the one confirmed on screen, where the
/// scrollTo would be a no-op that stays queued until the reader's next
/// drag.
static func needsScroll(toNewestRowID newestRowID: String?, bottomRowID: String?) -> Bool {
guard let newestRowID else { return false }
return newestRowID != bottomRowID
}
/// Messages the unseen counters may book as "new": rows that render as
/// human messages. System lines render as narration and whitespace-only
/// content never renders at all, so neither belongs in the pill count.
static func isUnseenEligible(_ message: BitchatMessage) -> Bool {
message.sender != "system" && !message.content.trimmed.isEmpty
}
/// Messages after `mark`'s newest one. Located by ID, not by count: at
/// the store cap every append evicts the oldest message, so the count
/// stops moving. If that message is gone (evicted by a burst larger than
/// the cap, or removed), everything newer than its timestamp counts.
static func appended(since mark: TimelineMark, in messages: [BitchatMessage]) -> Appended {
let start: Int
if let newestID = mark.newestMessageID, let newestTimestamp = mark.newestTimestamp {
if let index = messages.lastIndex(where: { $0.id == newestID }) {
start = index + 1
} else {
// The timeline is timestamp-ordered.
start = (messages.lastIndex(where: { $0.timestamp <= newestTimestamp }) ?? -1) + 1
}
} else {
start = 0
}
var appended = Appended()
for message in messages[start...] {
appended.total += 1
if isUnseenEligible(message) {
appended.unseen += 1
}
}
return appended
}
/// Window size that keeps a scrolled-up reader's rows in place. The
/// window is a suffix of the timeline, so every message landing below its
/// first row (appended, or a late one inserted mid-timeline) would push
/// that row out of the top and shift everything on screen up a row.
/// While `mark` still describes the window, its first message stays
/// first; otherwise the window grows by `appendedCount`. Never shrinks,
/// never grows past the timeline.
static func windowCountKeepingFirstRow(
current: Int,
mark: TimelineMark?,
appendedCount: Int,
in messages: [BitchatMessage]
) -> Int {
let needed: Int
if let mark,
mark.windowCount == current,
let firstID = mark.windowFirstMessageID,
let index = messages.lastIndex(where: { $0.id == firstID }) {
needed = messages.count - index
} else {
needed = current + appendedCount
}
return max(current, min(messages.count, needed))
}
/// Whether the window's first row coming on screen may grow the window.
/// Not while an earlier expansion's position restore is still queued: the
/// rows it inserted put a new first row on screen at once, and expanding
/// again cascades straight to the oldest message. And not before the list
/// has settled at the bottom of this context: the initial scroll down to
/// the newest row starts with the top rows on screen.
static func canExpandWindow(
isRestoringExpansion: Bool,
bottomSettledContextKey: String?,
contextKey: String
) -> Bool {
!isRestoringExpansion && bottomSettledContextKey == contextKey
}
/// Whether a throttled follow-scroll should still run when its timer
/// fires. The timer is held back while a drag is tracking, so by then the
/// reader may have scrolled away from the bottom or switched timelines.
static func shouldRunDeferredFollowScroll(
isAtBottom: Bool,
scheduledContextKey: String,
currentContextKey: String
) -> Bool {
isAtBottom && scheduledContextKey == currentContextKey
}
}
extension MessageListScrollPolicy.TimelineMark {
/// Marks `messages` as seen, with the window taken at `windowCount`.
init(contextKey: String, messages: [BitchatMessage], windowCount: Int) {
self.init(
contextKey: contextKey,
newestMessageID: messages.last?.id,
newestTimestamp: messages.last?.timestamp,
windowFirstMessageID: messages.suffix(windowCount).first?.id,
windowCount: windowCount,
count: messages.count
)
}
/// The same mark with the window re-taken at `windowCount` (after the
/// window was resized without anything new being seen).
func withWindowCount(_ windowCount: Int, in messages: [BitchatMessage]) -> Self {
Self(
contextKey: contextKey,
newestMessageID: newestMessageID,
newestTimestamp: newestTimestamp,
windowFirstMessageID: messages.suffix(windowCount).first?.id,
windowCount: windowCount,
count: count
)
}
}

View File

@ -14,6 +14,34 @@ private struct MessageDisplayItem: Identifiable {
let message: BitchatMessage
}
/// What the list's change detection keys on. The count alone stops moving
/// once the store's cap evicts the oldest message on every append, so the IDs
/// at both ends ride along, and the context key makes a switch to another
/// timeline one change even between two empty ones. The DM peer rides along
/// because the deprecated `onChange(of:perform:)` runs the closure from the
/// previous render, whose `privatePeer` is still the old one right after a
/// DM switch.
private struct TimelineSignature: Equatable {
let privatePeer: PeerID?
let contextKey: String
// periphery:ignore - read only via the synthesized Equatable
// conformance (onChange's comparison), which the indexer cannot
// attribute.
let count: Int
// periphery:ignore - see `count`.
let firstMessageID: String?
// periphery:ignore - see `count`.
let lastMessageID: String?
init(privatePeer: PeerID?, contextKey: String, messages: [BitchatMessage]) {
self.privatePeer = privatePeer
self.contextKey = contextKey
count = messages.count
firstMessageID = messages.first?.id
lastMessageID = messages.last?.id
}
}
struct MessageListView: View {
@EnvironmentObject private var publicChatModel: PublicChatModel
@EnvironmentObject private var privateInboxModel: PrivateInboxModel
@ -43,11 +71,24 @@ struct MessageListView: View {
@State private var lastScrollTime: Date = .distantPast
@State private var scrollThrottleTimer: Timer?
@State private var unseenCount = 0
@State private var lastSeenMessageCount = 0
/// Context key the unseen counters were baselined against. Channel
/// switches swap the timeline wholesale, so a count delta is only a
/// "new messages" signal while the context is unchanged.
@State private var unseenBaselineKey = ""
/// The timeline as of the last change this list observed: its newest
/// message (the next change counts what landed after it) and the
/// window's first row (kept in place while the reader is scrolled up).
/// Marks are per context: channel switches swap the timeline wholesale,
/// so a difference only means "new messages" within one context. Its
/// context is the one the list has landed in; row callbacks from any
/// other timeline are ignored.
@State private var timelineMark: MessageListScrollPolicy.TimelineMark?
/// Row whose appearance last put the list at the bottom, cleared when it
/// leaves the screen. Its leaving means the reader scrolled up, even while
/// a newer row that landed below it has not appeared yet.
@State private var bottomRowID: String?
/// Set while an expansion's position-restoring scroll is still queued.
@State private var isRestoringExpansion = false
/// Context whose newest row has appeared since the list appeared or
/// landed in it, i.e. whose scroll to the bottom has landed. Window
/// expansion waits for it.
@State private var bottomSettledContextKey: String?
/// Whether this instance holds the nearby-notes counter active (mesh
/// public timeline only); balanced against activate/deactivate.
@State private var holdsNotesCounter = false
@ -55,28 +96,31 @@ struct MessageListView: View {
@ThemedPalette private var palette
var body: some View {
let currentWindowCount: Int = {
if let peer = privatePeer {
return windowCountPrivate[peer] ?? TransportConfig.uiWindowInitialCountPrivate
}
return windowCountPublic
}()
let currentWindowCount = windowCount(for: privatePeer)
let messages = conversationMessages(for: privatePeer)
let windowedMessages = Array(messages.suffix(currentWindowCount))
let contextKey: String = {
if let peer = privatePeer {
"dm:\(peer)"
} else {
locationChannelsModel.selectedChannel.contextKey
}
}()
let contextKey = timelineContextKey(for: privatePeer)
// While the reader is scrolled up, messages landing below the
// window's first row widen the window in this same render instead of
// pushing that row out of the top, which would shift what they are
// reading (onTimelineChange then records the wider window).
let renderedWindowCount = isAtBottom
? currentWindowCount
: MessageListScrollPolicy.windowCountKeepingFirstRow(
current: currentWindowCount,
mark: contextMark(for: contextKey),
appendedCount: 0,
in: messages
)
let windowedMessages = Array(messages.suffix(renderedWindowCount))
let messageItems: [MessageDisplayItem] = windowedMessages.compactMap { message in
guard !message.content.trimmed.isEmpty else { return nil }
return MessageDisplayItem(id: "\(contextKey)|\(message.id)", message: message)
}
// Top edge of the rendered window (whitespace-only messages get no
// row, so they could never report reaching it).
let firstRowID = messageItems.first?.id
VStack(spacing: 0) {
// Notes pinned to this place stay visible while chatting — a
@ -97,11 +141,25 @@ struct MessageListView: View {
let message = item.message
messageRow(for: message)
.onAppear {
if message.id == windowedMessages.last?.id {
// Callbacks lag a timeline switch: the new
// rows appear before the old ones disappear,
// each with its own render's view of which row
// was last. Only rows of the timeline the list
// has landed in may move its state, checked
// against live state rather than the render's.
guard isLandedRow(item.id) else { return }
if item.id == newestRowID(for: privatePeer) {
isAtBottom = true
unseenCount = 0
if bottomRowID != item.id {
bottomRowID = item.id
}
if bottomSettledContextKey != contextKey {
bottomSettledContextKey = contextKey
}
returnWindowToInitialSize(for: privatePeer, contextKey: contextKey, messages: messages)
}
if message.id == windowedMessages.first?.id,
if item.id == firstRowID,
messages.count > windowedMessages.count {
expandWindow(
ifNeededFor: message,
@ -112,8 +170,16 @@ struct MessageListView: View {
}
}
.onDisappear {
if message.id == windowedMessages.last?.id {
// A row of the landed timeline shares this
// closure's peer, so newestRowID is live here.
guard isLandedRow(item.id) else { return }
if item.id == newestRowID(for: privatePeer) || item.id == bottomRowID {
isAtBottom = false
bottomRowID = nil
// Leaving the bottom drops a follow-scroll
// still waiting on the throttle: it would
// yank the reader back down.
cancelFollowScroll()
}
}
.contentShape(Rectangle())
@ -170,7 +236,6 @@ struct MessageListView: View {
.background(message.isArchivedEcho ? palette.secondary.opacity(0.08) : Color.clear)
}
}
.transaction { tx in if conversationUIModel.isBatchingPublic { tx.disablesAnimations = true } }
.padding(.vertical, 2)
// Only carried history on screen: the ambient layer (radar,
@ -203,19 +268,18 @@ struct MessageListView: View {
Button("common.cancel", role: .cancel) {}
}
.onAppear {
scrollToBottom(on: proxy)
// Runs before the rows' onAppear: lands the list (and sets the
// mark the row callbacks are checked against) before any row
// reports in. Expansion waits until the scroll below has
// brought the newest row on screen.
bottomSettledContextKey = nil
scrollToBottom(on: proxy, privatePeer: privatePeer)
}
.onChange(of: privatePeer) { _ in
scrollToBottom(on: proxy)
}
.onChange(of: publicChatModel.messages.count) { _ in
onMessagesChange(proxy: proxy)
}
.onChange(of: privateMessageCount(for: privatePeer)) { _ in
onPrivateChatsChange(proxy: proxy)
}
.onChange(of: locationChannelsModel.selectedChannel) { newChannel in
onSelectedChannelChange(newChannel, proxy: proxy)
// The one change handler: a channel or DM switch changes the
// signature too, so landing in the new timeline happens here,
// ahead of that update's row callbacks.
.onChange(of: TimelineSignature(privatePeer: privatePeer, contextKey: contextKey, messages: messages)) { signature in
onTimelineChange(signature, proxy: proxy)
}
.confirmationDialog(
selectedMessageSender.map { "@\($0)" } ?? String(localized: "content.actions.title", comment: "Fallback title for the message action sheet"),
@ -271,7 +335,7 @@ struct MessageListView: View {
}
}
.onDisappear {
scrollThrottleTimer?.invalidate()
cancelFollowScroll()
}
}
}
@ -306,11 +370,61 @@ private extension MessageListView {
}
}
var currentContextKey: String {
/// Context key of the timeline shown for `privatePeer` (the DM, or the
/// public channel); also the prefix of its row IDs. The public key comes
/// from the channel PublicChatModel publishes together with its messages:
/// the selected channel switches one render or more before the timeline
/// does, and keying the old messages with the new channel re-keys (and
/// re-appears) every row.
func timelineContextKey(for privatePeer: PeerID?) -> String {
if let peer = privatePeer {
return "dm:\(peer)"
}
return locationChannelsModel.selectedChannel.contextKey
return publicChatModel.activeChannel.contextKey
}
func windowCount(for privatePeer: PeerID?) -> Int {
if let peer = privatePeer {
return windowCountPrivate[peer] ?? TransportConfig.uiWindowInitialCountPrivate
}
return windowCountPublic
}
func setWindowCount(_ count: Int, for privatePeer: PeerID?) {
if let peer = privatePeer {
windowCountPrivate[peer] = count
} else {
windowCountPublic = count
}
}
/// Returns the window to its initial size once the reader is back at the
/// bottom (the newest row has appeared): whatever it grew by while they
/// were scrolled up, or expanded into history, need not stay rendered,
/// and dropping rows above the bottom moves nothing on screen. Never in
/// the same update as a scroll: rows changing above the viewport make
/// SwiftUI hold its position, and a pending scrollTo never lands.
func returnWindowToInitialSize(for privatePeer: PeerID?, contextKey: String, messages: [BitchatMessage]) {
let initialCount = privatePeer == nil
? TransportConfig.uiWindowInitialCountPublic
: TransportConfig.uiWindowInitialCountPrivate
guard windowCount(for: privatePeer) > initialCount else { return }
setWindowCount(initialCount, for: privatePeer)
timelineMark = contextMark(for: contextKey)?.withWindowCount(initialCount, in: messages)
}
/// The timeline mark, if it was taken in `contextKey`.
func contextMark(for contextKey: String) -> MessageListScrollPolicy.TimelineMark? {
guard let timelineMark, timelineMark.contextKey == contextKey else { return nil }
return timelineMark
}
/// Whether a row belongs to the timeline the list has landed in (the
/// mark's context: the change handler lands a switch before the rows of
/// that update report in).
func isLandedRow(_ rowID: String) -> Bool {
guard let landedContextKey = timelineMark?.contextKey else { return false }
return MessageListScrollPolicy.isRow(rowID, inContext: landedContextKey)
}
/// Tappable strip above the mesh timeline while notes are pinned at this
@ -412,30 +526,6 @@ private extension MessageListView {
.fixedSize(horizontal: false, vertical: true)
}
/// Messages the unseen counters may book as "new": rows that render as
/// human messages. System lines render as narration and whitespace-only
/// content never renders at all, so neither belongs in the pill count.
func unseenEligibleCount(in messages: [BitchatMessage]) -> Int {
messages.filter { $0.sender != "system" && !$0.content.trimmed.isEmpty }.count
}
/// Updates the unseen-count baseline for the current context and returns
/// how many messages were appended since the last observation. A context
/// change (timeline swapped wholesale) re-baselines and reports zero, so
/// cross-channel count differences are never booked as "new" messages.
func rebaselinedAppendedCount(newCount: Int) -> Int {
let key = currentContextKey
if unseenBaselineKey != key {
unseenBaselineKey = key
unseenCount = 0
lastSeenMessageCount = newCount
return 0
}
let appended = max(0, newCount - lastSeenMessageCount)
lastSeenMessageCount = newCount
return appended
}
/// A failed private text message of our own can be resent through the
/// normal send path (the context menu removes the failed original and
/// re-submits its content).
@ -467,7 +557,7 @@ private extension MessageListView {
/// message via the existing scrollToBottom helper.
func jumpToLatestPill(proxy: ScrollViewProxy) -> some View {
Button {
scrollToBottom(on: proxy)
scrollToBottom(on: proxy, privatePeer: privatePeer)
} label: {
HStack(spacing: 4) {
Image(systemName: "arrow.down")
@ -533,32 +623,28 @@ private extension MessageListView {
allMessages: [BitchatMessage],
privatePeer: PeerID?,
proxy: ScrollViewProxy) {
let step = TransportConfig.uiWindowStepCount
let contextKey: String = {
if let peer = privatePeer {
"dm:\(peer)"
} else {
locationChannelsModel.selectedChannel.contextKey
}
}()
let preserveID = "\(contextKey)|\(message.id)"
let contextKey = timelineContextKey(for: privatePeer)
guard MessageListScrollPolicy.canExpandWindow(
isRestoringExpansion: isRestoringExpansion,
bottomSettledContextKey: bottomSettledContextKey,
contextKey: contextKey
) else { return }
if let peer = privatePeer {
let current = windowCountPrivate[peer] ?? TransportConfig.uiWindowInitialCountPrivate
let newCount = min(allMessages.count, current + step)
guard newCount != current else { return }
windowCountPrivate[peer] = newCount
DispatchQueue.main.async {
proxy.scrollTo(preserveID, anchor: .top)
}
} else {
let current = windowCountPublic
let newCount = min(allMessages.count, current + step)
guard newCount != current else { return }
windowCountPublic = newCount
DispatchQueue.main.async {
proxy.scrollTo(preserveID, anchor: .top)
}
let current = windowCount(for: privatePeer)
let newCount = min(allMessages.count, current + TransportConfig.uiWindowStepCount)
guard newCount != current else { return }
setWindowCount(newCount, for: privatePeer)
// The window's first row moved up with it: re-take the mark's window
// so a scrolled-up reader keeps holding the new first row.
timelineMark = contextMark(for: contextKey)?.withWindowCount(newCount, in: allMessages)
// Until the restore below lands, the rows just inserted above leave a
// new first row on screen; it must not expand the window again.
let preserveID = "\(contextKey)|\(message.id)"
isRestoringExpansion = true
DispatchQueue.main.async {
proxy.scrollTo(preserveID, anchor: .top)
isRestoringExpansion = false
}
}
@ -593,155 +679,161 @@ private extension MessageListView {
}
}
func scrollToBottom(on proxy: ScrollViewProxy) {
func scrollToBottom(on proxy: ScrollViewProxy, privatePeer: PeerID?) {
// A follow-scroll still pending (possibly for a timeline being left)
// has nothing left to do.
cancelFollowScroll()
isAtBottom = true
unseenCount = 0
lastSeenMessageCount = unseenEligibleCount(in: conversationMessages(for: privatePeer))
unseenBaselineKey = currentContextKey
if let targetPeerID {
proxy.scrollTo(targetPeerID, anchor: .bottom)
timelineMark = MessageListScrollPolicy.TimelineMark(
contextKey: timelineContextKey(for: privatePeer),
messages: conversationMessages(for: privatePeer),
windowCount: windowCount(for: privatePeer)
)
if let target = newestRowID(for: privatePeer) {
proxy.scrollTo(target, anchor: .bottom)
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
if let secondTarget = self.targetPeerID {
// Retry only a scroll that has not landed. Once the newest row is
// on screen the retry would be a no-op, and a no-op scrollTo stays
// queued until the next layout pass: the reader's next drag.
if let secondTarget = self.newestRowID(for: privatePeer),
MessageListScrollPolicy.needsScroll(toNewestRowID: secondTarget, bottomRowID: bottomRowID) {
proxy.scrollTo(secondTarget, anchor: .bottom)
}
}
}
var targetPeerID: String? {
if let peer = privatePeer,
let last = privateInboxModel.messages(for: peer).last?.id {
return "dm:\(peer)|\(last)"
}
if let last = publicChatModel.messages.last?.id {
return "\(locationChannelsModel.selectedChannel.contextKey)|\(last)"
}
return nil
/// Lands the list at the newest message of a timeline it was not showing
/// (a channel or DM switch): nothing about the old timeline's bottom
/// carries over.
func land(on proxy: ScrollViewProxy, privatePeer: PeerID?) {
bottomRowID = nil
bottomSettledContextKey = nil
scrollToBottom(on: proxy, privatePeer: privatePeer)
}
func onMessagesChange(proxy: ScrollViewProxy) {
guard privatePeer == nil else { return }
let messages = publicChatModel.messages
let appendedCount = rebaselinedAppendedCount(newCount: unseenEligibleCount(in: messages))
guard let lastMsg = messages.last else {
// Timeline emptied (e.g. /clear): nothing below to jump to.
unseenCount = 0
/// Row ID of the newest message that has a row (whitespace-only
/// messages render none).
func newestRowID(for privatePeer: PeerID?) -> String? {
guard let newest = conversationMessages(for: privatePeer).last(where: { !$0.content.trimmed.isEmpty }) else {
return nil
}
return "\(timelineContextKey(for: privatePeer))|\(newest.id)"
}
/// Handles any change to the shown timeline: an append, a late message
/// inserted mid-timeline, an eviction at the cap, a removal, or a
/// different timeline altogether (a channel or DM switch).
func onTimelineChange(_ signature: TimelineSignature, proxy: ScrollViewProxy) {
// The deprecated onChange runs the previous render's closure, so the
// timeline comes from the new value rather than `self.privatePeer`.
let privatePeer = signature.privatePeer
let contextKey = signature.contextKey
let messages = conversationMessages(for: privatePeer)
// No mark in this context means the timeline was swapped wholesale:
// nothing is booked as "new", the list lands instead.
let mark = contextMark(for: contextKey)
let appended = mark.map { MessageListScrollPolicy.appended(since: $0, in: messages) }
?? MessageListScrollPolicy.Appended()
let currentWindowCount = windowCount(for: privatePeer)
let reaction = MessageListScrollPolicy.reaction(
mark: mark,
messages: messages,
newestIsOwn: messages.last.map { conversationUIModel.isSentByCurrentUser($0) } ?? false,
appendedCount: appended.total,
windowCount: currentWindowCount,
isAtBottom: isAtBottom
)
if reaction == .land {
land(on: proxy, privatePeer: privatePeer)
return
}
// If the newest message is from me, always scroll to bottom
let isFromSelf = conversationUIModel.isSentByCurrentUser(lastMsg)
if !isFromSelf && !isAtBottom { // Only autoscroll when user is at/near bottom
unseenCount += appendedCount
return
} else { // Ensure we consider ourselves at bottom for subsequent messages
// Record the window this render kept: for a scrolled-up reader,
// widened over what landed below its first row instead of dropping
// that row (grown by the appended count if the mark lost track of
// it). A follow keeps it too: rows changing above the viewport in the
// same update as the scroll make SwiftUI hold its position instead.
let keptWindowCount = isAtBottom
? currentWindowCount
: MessageListScrollPolicy.windowCountKeepingFirstRow(
current: currentWindowCount,
mark: mark,
appendedCount: appended.total,
in: messages
)
if keptWindowCount != currentWindowCount {
setWindowCount(keptWindowCount, for: privatePeer)
}
timelineMark = MessageListScrollPolicy.TimelineMark(contextKey: contextKey, messages: messages, windowCount: keptWindowCount)
switch reaction {
case .keepPosition:
unseenCount += appended.unseen
case .follow:
// Ensure we consider ourselves at bottom for subsequent messages
isAtBottom = true
unseenCount = 0
}
func scrollIfNeeded(date: Date) {
lastScrollTime = date
let contextKey = locationChannelsModel.selectedChannel.contextKey
if let target = messages.last.map({ "\(contextKey)|\($0.id)" }) {
proxy.scrollTo(target, anchor: .bottom)
followToBottom(privatePeer: privatePeer, proxy: proxy)
case .hold:
if messages.isEmpty {
// Timeline emptied (e.g. /clear): nothing below to jump to.
unseenCount = 0
}
case .land:
break
}
}
// Throttle scroll animations to prevent excessive UI updates
/// Scrolls to the newest row, at most once per throttle interval. A
/// throttled scroll decides when its timer fires: the timer is held back
/// while a drag is tracking, so by then the reader may have scrolled
/// away or switched timelines, and newer rows may have landed.
func followToBottom(privatePeer: PeerID?, proxy: ScrollViewProxy) {
let now = Date()
if now.timeIntervalSince(lastScrollTime) > TransportConfig.uiScrollThrottleSeconds {
// Immediate scroll if enough time has passed
scrollIfNeeded(date: now)
} else {
// Schedule a delayed scroll
scrollThrottleTimer?.invalidate()
scrollThrottleTimer = Timer.scheduledTimer(withTimeInterval: TransportConfig.uiScrollThrottleSeconds, repeats: false) { _ in
Task { @MainActor in
scrollIfNeeded(date: Date())
}
scrollToNewestRow(privatePeer: privatePeer, proxy: proxy, at: now)
return
}
// Schedule a delayed scroll
let scheduledContextKey = timelineContextKey(for: privatePeer)
scrollThrottleTimer?.invalidate()
scrollThrottleTimer = Timer.scheduledTimer(withTimeInterval: TransportConfig.uiScrollThrottleSeconds, repeats: false) { _ in
Task { @MainActor in
guard MessageListScrollPolicy.shouldRunDeferredFollowScroll(
isAtBottom: isAtBottom,
scheduledContextKey: scheduledContextKey,
currentContextKey: timelineContextKey(for: privatePeer)
) else { return }
scrollToNewestRow(privatePeer: privatePeer, proxy: proxy, at: Date())
}
}
}
func onPrivateChatsChange(proxy: ScrollViewProxy) {
guard let peerID = privatePeer else { return }
let messages = privateInboxModel.messages(for: peerID)
let appendedCount = rebaselinedAppendedCount(newCount: unseenEligibleCount(in: messages))
guard let lastMsg = messages.last else {
// Timeline emptied (e.g. /clear): nothing below to jump to.
unseenCount = 0
return
}
// If the newest private message is from me, always scroll
let isFromSelf = conversationUIModel.isSentByCurrentUser(lastMsg)
if !isFromSelf && !isAtBottom { // Only autoscroll when user is at/near bottom
unseenCount += appendedCount
return
} else {
isAtBottom = true
unseenCount = 0
}
func scrollIfNeeded(date: Date) {
lastScrollTime = date
let contextKey = "dm:\(peerID)"
if let target = messages.last.map({ "\(contextKey)|\($0.id)" }) {
proxy.scrollTo(target, anchor: .bottom)
}
}
// Same throttling for private chats
let now = Date()
if now.timeIntervalSince(lastScrollTime) > TransportConfig.uiScrollThrottleSeconds {
scrollIfNeeded(date: now)
} else {
scrollThrottleTimer?.invalidate()
scrollThrottleTimer = Timer.scheduledTimer(withTimeInterval: TransportConfig.uiScrollThrottleSeconds, repeats: false) { _ in
Task { @MainActor in
scrollIfNeeded(date: Date())
}
}
}
}
func onSelectedChannelChange(_ channel: ChannelID, proxy: ScrollViewProxy) {
// When switching to a new geohash channel, scroll to the bottom
guard privatePeer == nil else { return }
// Invalidate the unseen baseline: the timeline is about to swap (or
// already has — the ordering of this onChange vs the count onChange
// is not guaranteed), so the next count observation re-baselines
// instead of booking the cross-channel difference as "new".
unseenCount = 0
unseenBaselineKey = ""
// Entering any public channel shows its latest messages: a channel
// switch swaps the timeline wholesale, so the prior scroll offset is
// meaningless. Landing at the bottom keeps isAtBottom honest (no
// stale jump-to-latest pill) and matches standard chat behavior.
isAtBottom = true
windowCountPublic = TransportConfig.uiWindowInitialCountPublic
let contextKey: String
switch channel {
case .mesh:
contextKey = "mesh"
case .location(let ch):
contextKey = "geo:\(ch.geohash)"
}
if let target = publicChatModel.messages.last?.id.map({ "\(contextKey)|\($0)" }) {
func scrollToNewestRow(privatePeer: PeerID?, proxy: ScrollViewProxy, at date: Date) {
lastScrollTime = date
if let target = newestRowID(for: privatePeer) {
proxy.scrollTo(target, anchor: .bottom)
}
}
/// Drops a follow-scroll still waiting on the throttle.
func cancelFollowScroll() {
guard let timer = scrollThrottleTimer else { return }
timer.invalidate()
scrollThrottleTimer = nil
}
func conversationMessages(for privatePeer: PeerID?) -> [BitchatMessage] {
if let privatePeer {
return privateInboxModel.messages(for: privatePeer)
}
return publicChatModel.messages
}
func privateMessageCount(for privatePeer: PeerID?) -> Int {
conversationMessages(for: privatePeer).count
}
}
private extension ChannelID {

View File

@ -3,8 +3,27 @@
// Shared text parsing helpers for message rendering.
//
import BitFoundation
import Foundation
extension BitchatMessage {
/// The row's payment chips and collapse decision, scanned on first use
/// and cached on the message: a row re-renders far more often than its
/// immutable `content` could change.
var contentScan: ContentScan {
if let cached = getCachedContentScan() {
return cached
}
let scan = ContentScan(
cashuLinks: content.extractCashuLinks(),
lightningLinks: content.extractLightningLinks(),
isLongForDisplay: content.isLongForDisplay()
)
setCachedContentScan(scan)
return scan
}
}
extension String {
// Detect if there is an extremely long token (no whitespace/newlines) that could break layout
func hasVeryLongToken(threshold: Int) -> Bool {

View File

@ -0,0 +1,32 @@
//
// PeopleListOrdering.swift
// bitchat
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
/// Row ordering for the people sheet's rosters.
///
/// Rows stay where they are while the sheet is open: ids already on screen
/// keep their relative order (minus anyone who left) and newcomers append in
/// the producer's order. Without this, recency-sorted rosters reshuffle on
/// every heartbeat and rows move out from under a tap.
enum PeopleListOrdering {
/// Linear in the roster size; duplicate ids in `current` collapse to
/// their first occurrence so `ForEach` identities stay unique.
static func stableOrder(previous: [String], current: [String]) -> [String] {
let currentIDs = Set(current)
var ordered: [String] = []
ordered.reserveCapacity(current.count)
var placed = Set<String>()
placed.reserveCapacity(current.count)
for id in previous where currentIDs.contains(id) && placed.insert(id).inserted {
ordered.append(id)
}
for id in current where placed.insert(id).inserted {
ordered.append(id)
}
return ordered
}
}

View File

@ -182,9 +182,6 @@ struct AppArchitectureTests {
#expect(store.geoNicknames == ["bbbbbb": "bob", "cccccc": "carol"])
store.retainGeoNicknames(keeping: Set(["CCCCCC"]))
#expect(store.geoNicknames == ["cccccc": "carol"])
store.setCurrentGeohash("u4pruz")
#expect(store.geoNicknames.isEmpty)
}
@ -714,6 +711,44 @@ struct AppArchitectureTests {
#expect(transport.sentMessages.last?.content == "hello mesh")
}
@Test("ConversationUIModel republishes only changed composer state")
@MainActor
func conversationUIModelSkipsUnchangedComposerState() async {
let viewModel = makeArchitectureViewModel()
let locationChannelsModel = LocationChannelsModel(manager: makeArchitectureLocationManager())
let privateConversationModel = PrivateConversationModel(
chatViewModel: viewModel,
conversations: viewModel.conversations,
locationChannelsModel: locationChannelsModel
)
let uiModel = ConversationUIModel(
chatViewModel: viewModel,
privateConversationModel: privateConversationModel,
conversations: viewModel.conversations
)
// Bindings deliver on the main queue in FIFO order: once this change
// lands, every initial value delivered before it has landed too.
viewModel.selectedAutocompleteIndex = 1
await waitUntil { uiModel.selectedAutocompleteIndex == 1 }
var publishCount = 0
let cancellable = uiModel.objectWillChange.sink { publishCount += 1 }
defer { cancellable.cancel() }
// Re-sent equal values (what every typing pause used to produce) ...
viewModel.showAutocomplete = viewModel.showAutocomplete
viewModel.autocompleteSuggestions = viewModel.autocompleteSuggestions
viewModel.selectedAutocompleteIndex = 1
viewModel.activePublicVoiceTalker = viewModel.activePublicVoiceTalker
// ... are dropped: only the real change queued behind them publishes.
viewModel.selectedAutocompleteIndex = 2
await waitUntil { uiModel.selectedAutocompleteIndex == 2 }
#expect(uiModel.selectedAutocompleteIndex == 2)
#expect(publishCount == 1)
}
@Test("VerificationModel bridges selected conversation and fingerprint actions")
@MainActor
func verificationModelBridgesSelectedConversationAndFingerprintActions() async {

View File

@ -0,0 +1,90 @@
//
// BitchatMessageMediaTests.swift
// bitchatTests
//
// Which messages render as local media rows, and which file such a row
// loads. The filename comes from (possibly remote) message text, so it must
// never resolve outside the media directory it names.
//
import BitFoundation
import Foundation
import Testing
@testable import bitchat
struct BitchatMessageMediaTests {
private static let meshPeerID = PeerID(str: "0011223344556677")
private static let nostrPubkey = String(repeating: "ab", count: 32)
private func message(_ content: String, sender: String = "alice", senderPeerID: PeerID? = meshPeerID) -> BitchatMessage {
BitchatMessage(sender: sender, content: content, timestamp: Date(), isRelay: false, senderPeerID: senderPeerID)
}
@Test
func meshMediaResolvesInsideItsCategoryDirectory() {
guard case .image(let imageURL)? = message("[image] img_1.jpg").mediaAttachment(for: "me"),
case .voice(let voiceURL)? = message("[voice] note 1.m4a").mediaAttachment(for: "me"),
case .image(let ownImageURL)? = message("[image] img_2.jpg", sender: "me").mediaAttachment(for: "me")
else {
Issue.record("Expected mesh media messages to resolve to media rows")
return
}
#expect(imageURL.lastPathComponent == "img_1.jpg")
#expect(imageURL.deletingLastPathComponent().path.hasSuffix("/files/images/incoming"))
#expect(voiceURL.lastPathComponent == "note 1.m4a")
#expect(voiceURL.deletingLastPathComponent().path.hasSuffix("/files/voicenotes/incoming"))
#expect(ownImageURL.deletingLastPathComponent().path.hasSuffix("/files/images/outgoing"))
}
@Test
func nostrSendersNeverGetMediaRows() {
// Geochats, geo DMs and bridged messages carry no files, so a
// media-looking line from a Nostr sender must stay text instead of
// loading some local file.
let geoChatSender = PeerID(nostr: Self.nostrPubkey)
let geoDMSender = PeerID(nostr_: Self.nostrPubkey)
let bridgedSender = PeerID(bridge: Self.nostrPubkey)
#expect(geoChatSender.isGeoChat)
#expect(geoDMSender.isGeoDM)
#expect(bridgedSender.isBridge)
for content in ["[image] img_1.jpg", "[voice] note.m4a"] {
#expect(message(content, senderPeerID: geoChatSender).mediaAttachment(for: "me") == nil)
#expect(message(content, senderPeerID: geoDMSender).mediaAttachment(for: "me") == nil)
#expect(message(content, senderPeerID: bridgedSender).mediaAttachment(for: "me") == nil)
#expect(message(content, sender: "me", senderPeerID: geoChatSender).mediaAttachment(for: "me") == nil)
}
// A message without a sender ID keeps the mesh behavior.
#expect(message("[image] img_1.jpg", senderPeerID: nil).mediaAttachment(for: "me") != nil)
}
@Test
func filenamesThatAreNotOnePlainComponentAreRejected() {
let unsafeNames = [
"../outgoing/x.jpg",
"../../Library/secret.jpg",
"a/b.jpg",
"/etc/hosts",
"x.jpg/",
"..",
".",
"a\\b.jpg",
"..\\outgoing\\x.jpg"
]
for name in unsafeNames {
#expect(!BitchatMessage.isSafeMediaFilename(name), "\(name)")
#expect(message("[image] \(name)").mediaAttachment(for: "me") == nil, "\(name)")
#expect(message("[voice] \(name)").mediaAttachment(for: "me") == nil, "\(name)")
}
#expect(!BitchatMessage.isSafeMediaFilename(""))
#expect(message("[image] ").mediaAttachment(for: "me") == nil)
}
@Test
func plainFilenamesAreAccepted() {
for name in ["img_20260101_120000.jpg", "note 1.m4a", "photo...jpg", "...", "émoji-😀.png"] {
#expect(BitchatMessage.isSafeMediaFilename(name), "\(name)")
}
}
}

View File

@ -22,11 +22,13 @@ import BitFoundation
/// `ChatComposerCoordinator` is testable without a `ChatViewModel`.
@MainActor
private final class MockChatComposerContext: ChatComposerContext {
// Autocomplete UI state
var autocompleteSuggestions: [String] = []
var autocompleteRange: NSRange?
var showAutocomplete = false
var selectedAutocompleteIndex = -1
// Autocomplete UI state. Every write is counted: each one republishes the
// composer state (and re-renders the message rows) in the real owner.
var autocompleteSuggestions: [String] = [] { didSet { autocompleteStateWrites += 1 } }
var autocompleteRange: NSRange? { didSet { autocompleteStateWrites += 1 } }
var showAutocomplete = false { didSet { autocompleteStateWrites += 1 } }
var selectedAutocompleteIndex = -1 { didSet { autocompleteStateWrites += 1 } }
private(set) var autocompleteStateWrites = 0
var queryResult: (suggestions: [String], range: NSRange?) = ([], nil)
private(set) var queriedPeerCandidates: [[String]] = []
private(set) var appliedSuggestions: [(suggestion: String, text: String, range: NSRange)] = []
@ -158,6 +160,57 @@ struct ChatComposerCoordinatorContextTests {
#expect(geoContext.queriedPeerCandidates == [["carol#dddd"]])
}
@Test @MainActor
func updateAutocomplete_withoutMentionTokenAtCursor_skipsCandidateQuery() {
let context = MockChatComposerContext()
let coordinator = ChatComposerCoordinator(context: context)
context.meshNicknamesByPeerID = [PeerID(str: "1111111111111111"): "alice"]
context.queryResult = (["@alice"], NSRange(location: 3, length: 3))
// Plain text, and a mention that no longer ends at the cursor: the
// query could not suggest anything, so it never runs.
coordinator.updateAutocomplete(for: "plain text", cursorPosition: 10)
coordinator.updateAutocomplete(for: "hi @al there", cursorPosition: 12)
#expect(context.queriedPeerCandidates.isEmpty)
#expect(context.autocompleteSuggestions.isEmpty)
#expect(!context.showAutocomplete)
// The same text with the cursor right after the token queries.
coordinator.updateAutocomplete(for: "hi @al there", cursorPosition: 6)
#expect(context.queriedPeerCandidates == [["alice"]])
#expect(context.autocompleteSuggestions == ["@alice"])
#expect(context.showAutocomplete)
}
@Test @MainActor
func updateAutocomplete_rewritesNothingWhenStateIsUnchanged() {
let context = MockChatComposerContext()
let coordinator = ChatComposerCoordinator(context: context)
context.meshNicknamesByPeerID = [PeerID(str: "1111111111111111"): "alice"]
// The first clear only has to reset the highlight index.
coordinator.updateAutocomplete(for: "hello", cursorPosition: 5)
#expect(context.autocompleteStateWrites == 1)
#expect(context.selectedAutocompleteIndex == 0)
// Typing pauses in plain text then leave the state untouched.
coordinator.updateAutocomplete(for: "hello there", cursorPosition: 11)
#expect(context.autocompleteStateWrites == 1)
// Showing suggestions writes; re-querying the same result does not.
context.queryResult = (["@alice"], NSRange(location: 0, length: 2))
coordinator.updateAutocomplete(for: "@a", cursorPosition: 2)
let writesAfterShowing = context.autocompleteStateWrites
#expect(writesAfterShowing == 4)
coordinator.updateAutocomplete(for: "@a", cursorPosition: 2)
#expect(context.autocompleteStateWrites == writesAfterShowing)
// A moved highlight is still reset to the first suggestion.
context.selectedAutocompleteIndex = 2
coordinator.updateAutocomplete(for: "@a", cursorPosition: 2)
#expect(context.selectedAutocompleteIndex == 0)
}
@Test @MainActor
func completeNickname_appliesSuggestionResetsStateAndReturnsCursor() {
let context = MockChatComposerContext()

View File

@ -0,0 +1,99 @@
//
// ChatMessageFormatterTests.swift
// bitchatTests
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import Foundation
import SwiftUI
import Testing
@testable import bitchat
/// Counts full roster scans: `GeohashParticipantTracker.getVisiblePeople()`
/// asks its context whether each participant is blocked exactly once.
@MainActor
private final class RosterScanCountingContext: GeohashParticipantContext {
private weak var base: ChatViewModel?
private(set) var isBlockedCalls = 0
init(base: ChatViewModel) {
self.base = base
}
func displayNameForPubkey(_ pubkeyHex: String) -> String {
base?.displayNameForPubkey(pubkeyHex) ?? "anon#\(pubkeyHex.suffix(4))"
}
func isBlocked(_ pubkeyHexLowercased: String) -> Bool {
isBlockedCalls += 1
return base?.isBlocked(pubkeyHexLowercased) ?? false
}
}
@MainActor
struct ChatMessageFormatterTests {
private let geohash = "u4pruyd"
/// One people-sheet render asks for a color per row. Each lookup used to
/// rebuild the palette from a fresh roster scan, making the sheet O(N²):
/// 60 rows cost 3,600 block checks before a single row was laid out.
@Test func geohashColorLookupsDoNotRescanTheRoster() {
let viewModel = makeViewModel()
let pubkeys = seedParticipants(60, in: viewModel)
let counter = RosterScanCountingContext(base: viewModel)
viewModel.participantTracker.configure(context: counter)
defer { viewModel.participantTracker.configure(context: viewModel) }
let first = pubkeys.map { viewModel.colorForNostrPubkey($0, isDark: true) }
let second = pubkeys.map { viewModel.colorForNostrPubkey($0, isDark: true) }
#expect(counter.isBlockedCalls == 0)
#expect(first == second)
}
/// The palette follows roster membership: a newcomer gets a palette slot
/// (not the hash fallback) and people already on screen keep theirs.
@Test func paletteTracksMembershipChangesWithoutRecoloringExistingRows() {
let viewModel = makeViewModel()
let pubkeys = seedParticipants(10, in: viewModel)
let before = pubkeys.map { viewModel.colorForNostrPubkey($0, isDark: true) }
let newcomer = String(format: "%064x", 0xfeed)
viewModel.participantTracker.recordParticipant(pubkeyHex: newcomer, geohash: geohash)
// Palette colors use the configured saturation, which the hash
// fallback can never produce exactly, so inequality proves a slot.
#expect(viewModel.colorForNostrPubkey(newcomer, isDark: true) != Color(peerSeed: "nostr:" + newcomer, isDark: true))
#expect(pubkeys.map { viewModel.colorForNostrPubkey($0, isDark: true) } == before)
}
// MARK: - Helpers
private func makeViewModel() -> ChatViewModel {
let keychain = MockKeychain()
// A private location manager: the shared one is switched by other
// suites running in parallel, and a switch resets the roster.
let locationSuite = "ChatMessageFormatterTests.\(UUID().uuidString)"
let locationStorage = UserDefaults(suiteName: locationSuite) ?? .standard
locationStorage.removePersistentDomain(forName: locationSuite)
return ChatViewModel(
keychain: keychain,
idBridge: NostrIdentityBridge(keychain: MockKeychainHelper()),
identityManager: MockIdentityManager(keychain),
transport: MockTransport(),
locationManager: LocationChannelManager(storage: locationStorage)
)
}
private func seedParticipants(_ count: Int, in viewModel: ChatViewModel) -> [String] {
let tracker = viewModel.participantTracker
tracker.setActiveGeohash(geohash)
let pubkeys = (1...count).map { String(format: "%064x", $0) }
for pubkey in pubkeys {
tracker.recordParticipant(pubkeyHex: pubkey, geohash: geohash)
}
return pubkeys
}
}

View File

@ -152,7 +152,10 @@ private final class MockChatNostrContext: ChatNostrContext {
private(set) var refreshTimerStopCount = 0
private(set) var activeParticipantGeohashes: [String?] = []
private(set) var recordedParticipants: [String] = []
private(set) var recordedParticipantTimes: [Date] = []
private(set) var recordedSampledParticipants: [(pubkeyHex: String, geohash: String)] = []
/// "nickname:<pubkey>" / "record:<pubkey>" in call order.
private(set) var presenceCallLog: [String] = []
private(set) var clearTeleportedGeoCount = 0
private(set) var clearGeoNicknamesCount = 0
var visiblePeople: [GeoPerson] = []
@ -160,9 +163,15 @@ private final class MockChatNostrContext: ChatNostrContext {
func startGeoParticipantRefreshTimer() { refreshTimerStartCount += 1 }
func stopGeoParticipantRefreshTimer() { refreshTimerStopCount += 1 }
func setActiveParticipantGeohash(_ geohash: String?) { activeParticipantGeohashes.append(geohash) }
func recordGeoParticipant(pubkeyHex: String) { recordedParticipants.append(pubkeyHex) }
func recordGeoParticipant(pubkeyHex: String, seenAt: Date) -> Bool {
recordedParticipants.append(pubkeyHex)
recordedParticipantTimes.append(seenAt)
presenceCallLog.append("record:\(pubkeyHex)")
// Like the tracker: activity older than the window doesn't count.
return seenAt >= Date().addingTimeInterval(-TransportConfig.uiRecentCutoffFiveMinutesSeconds)
}
func recordGeoParticipant(pubkeyHex: String, geohash: String) {
func recordGeoParticipant(pubkeyHex: String, geohash: String, seenAt: Date) {
recordedSampledParticipants.append((pubkeyHex, geohash))
}
@ -170,7 +179,10 @@ private final class MockChatNostrContext: ChatNostrContext {
recordedSampledParticipants.filter { $0.geohash == geohash }.count
}
func setGeoNickname(_ nickname: String, forPubkey pubkeyHex: String) { geoNicknames[pubkeyHex.lowercased()] = nickname }
func setGeoNickname(_ nickname: String, forPubkey pubkeyHex: String) {
geoNicknames[pubkeyHex.lowercased()] = nickname
presenceCallLog.append("nickname:\(pubkeyHex)")
}
func markGeoTeleported(_ pubkeyHexLowercased: String) { teleportedKeys.insert(pubkeyHexLowercased) }
func clearGeoTeleported(_ pubkeyHexLowercased: String) { teleportedKeys.remove(pubkeyHexLowercased) }
@ -239,6 +251,18 @@ private func drainMainQueue() async {
}
}
/// A signed geohash message carrying the teleport tag, sent at `sentAt`
/// (the `NostrProtocol` builder always stamps now).
private func teleportedGeohashEvent(from sender: NostrIdentity, sentAt: Date) throws -> NostrEvent {
try NostrEvent(
pubkey: sender.publicKeyHex,
createdAt: sentAt,
kind: .ephemeralEvent,
tags: [["g", "u4pruyd"], ["t", "teleport"]],
content: "from earlier"
).sign(with: sender.schnorrSigningKey())
}
// MARK: - Coordinator Tests Against Mock Context
/// Exercises `ChatNostrCoordinator` against `MockChatNostrContext` with no
@ -334,6 +358,104 @@ struct ChatNostrCoordinatorContextTests {
#expect(context.handledPublicMessages.isEmpty)
}
/// A newcomer's nickname is known before they're recorded, so they enter
/// the roster under their name. Live events count as activity when they
/// arrive (keeping senders with skewed clocks visible).
@Test @MainActor
func handleNostrEvent_learnsTheNicknameBeforeRecordingTheSender() async throws {
let context = MockChatNostrContext()
let coordinator = ChatNostrCoordinator(context: context)
let sender = try NostrIdentity.generate()
let event = try NostrProtocol.createEphemeralGeohashEvent(
content: "hello",
geohash: "u4pruyd",
senderIdentity: sender,
nickname: "alice"
)
let beforeArrival = Date()
coordinator.inbound.handleNostrEvent(event)
await drainMainQueue()
#expect(context.presenceCallLog == ["nickname:\(event.pubkey)", "record:\(event.pubkey)"])
#expect(context.recordedParticipantTimes.first.map { $0 >= beforeArrival } == true)
}
/// Stored history relays replay before EOSE counts as activity at the
/// time it happened, so joining doesn't mark an hour of authors present.
@Test @MainActor
func handleNostrEvent_stampsReplayedHistoryWithTheEventTime() async throws {
let context = MockChatNostrContext()
let coordinator = ChatNostrCoordinator(context: context)
let sender = try NostrIdentity.generate()
let event = try NostrProtocol.createEphemeralGeohashEvent(
content: "from earlier",
geohash: "u4pruyd",
senderIdentity: sender
)
coordinator.inbound.handleNostrEvent(event, isHistoryReplay: true)
await drainMainQueue()
#expect(context.recordedParticipantTimes == [Date(timeIntervalSince1970: TimeInterval(event.created_at))])
}
/// A teleport tag on replayed history too old to count as presence must
/// not mark its author, on either inbound path: markers are pruned only
/// as the roster changes, so one set for someone absent would still be
/// there when they came back. Recent history still marks.
@Test @MainActor
func replayedTeleportTag_marksOnlyAuthorsWhoseActivityStillCounts() async throws {
let context = MockChatNostrContext()
let coordinator = ChatNostrCoordinator(context: context)
let longGone = try NostrIdentity.generate()
let alsoLongGone = try NostrIdentity.generate()
let stillHere = try NostrIdentity.generate()
// Ten minutes old: past the five-minute activity window.
let expired = try teleportedGeohashEvent(from: longGone, sentAt: Date().addingTimeInterval(-600))
let expiredOnResubscribe = try teleportedGeohashEvent(from: alsoLongGone, sentAt: Date().addingTimeInterval(-600))
let recent = try teleportedGeohashEvent(from: stillHere, sentAt: Date().addingTimeInterval(-60))
coordinator.inbound.handleNostrEvent(expired, isHistoryReplay: true)
coordinator.inbound.subscribeNostrEvent(expiredOnResubscribe, isHistoryReplay: true)
coordinator.inbound.handleNostrEvent(recent, isHistoryReplay: true)
await drainMainQueue()
#expect(context.teleportedKeys == [stillHere.publicKeyHex.lowercased()])
}
/// The open channel is usually also a sampled cell. Its own subscription
/// records senders, so the sampled copy must not record them again
/// (that ran the roster bookkeeping twice per event); other sampled
/// cells still count.
@Test @MainActor
func presenceSampling_skipsTheOpenChannelButCountsOtherCells() async throws {
let context = MockChatNostrContext()
let coordinator = ChatNostrCoordinator(context: context)
context.activeChannel = .location(GeohashChannel(level: .neighborhood, geohash: "u4pruy"))
let sender = try NostrIdentity.generate()
let inOpenChannel = try NostrProtocol.createEphemeralGeohashEvent(
content: "here",
geohash: "u4pruy",
senderIdentity: sender
)
let elsewhere = try NostrProtocol.createEphemeralGeohashEvent(
content: "there",
geohash: "u4pruz",
senderIdentity: sender
)
coordinator.presence.subscribeNostrEvent(inOpenChannel, gh: "u4pruy")
coordinator.presence.subscribeNostrEvent(elsewhere, gh: "u4pruz")
await drainMainQueue()
#expect(context.recordedSampledParticipants.map(\.geohash) == ["u4pruz"])
}
@Test @MainActor
func handleGiftWrap_routesEmbeddedPrivateMessageAndDeduplicates() async throws {
let context = MockChatNostrContext()

View File

@ -208,6 +208,8 @@ struct ChatOutgoingCoordinatorContextTests {
let echo = context.appendedPublicMessages[0].message
#expect(context.appendedPublicMessages[0].conversationID == .geohash("u4pruydq"))
#expect(echo.sender == "me#2222")
// The echo is told apart as mine by this ID, not by its name.
#expect(echo.senderPeerID == PeerID(nostr: MockChatOutgoingContext.dummyIdentity.publicKeyHex))
#expect(context.recordedActivityKeys == ["geo:u4pruydq"])
#expect(context.sentGeohashContexts.count == 1)
let geoContext = context.sentGeohashContexts[0]

View File

@ -811,6 +811,246 @@ struct ChatPrivateConversationCoordinatorContextTests {
#expect(context.notifyUIChangedCount == 1)
}
@Test @MainActor
func migratePrivateChats_leavesMyGeoDMThreadOutOfANamesakesChat() async {
// My reply to a geohash stranger names me as its recipient
// (sendGeohashDM), so by nickname it reads as written to any mesh
// peer called "alice". That namesake's first DM must not take the
// thread along, or my next reply there would go to them.
let context = MockChatPrivateConversationContext()
context.nickname = "alice"
let coordinator = ChatPrivateConversationCoordinator(context: context)
let geoThread = PeerID(nostr_: String(repeating: "42", count: 32))
let namesakePeerID = PeerID(str: "8899aabbccddeeff")
context.privateChats[geoThread] = [
makeIncomingMessage(
id: "stranger-1",
sender: "carol#4242",
timestamp: Date().addingTimeInterval(-120),
senderPeerID: geoThread,
recipientNickname: "alice"
),
BitchatMessage(
id: "my-reply",
sender: "alice",
content: "hi carol",
timestamp: Date().addingTimeInterval(-60),
isRelay: false,
isPrivate: true,
recipientNickname: "alice",
senderPeerID: context.myPeerID,
deliveryStatus: .sent
)
]
context.selectedPrivateChatPeer = geoThread
coordinator.handlePrivateMessage(
makeIncomingMessage(id: "namesake-1", sender: "alice", senderPeerID: namesakePeerID, recipientNickname: "alice")
)
#expect(context.privateChats[geoThread]?.map(\.id) == ["stranger-1", "my-reply"])
#expect(context.privateChats[namesakePeerID]?.map(\.id) == ["namesake-1"])
#expect(context.migratedChats.isEmpty)
// The open thread is still the stranger's, and the namesake's message
// waits unread rather than being read receipted from my thread.
#expect(context.selectedPrivateChatPeer == geoThread)
#expect(context.meshReadReceipts.isEmpty)
#expect(context.unreadPrivateMessages == [namesakePeerID])
}
@Test @MainActor
func migratePrivateChats_leavesMyThreadAloneWhenAStrangerTakesMyOldName() async {
// I was "alice" and am now "alicia". My reply to bob still carries the
// old name, but it is mine by its sender ID, so a stranger who now
// calls themselves "alice" is not its author and must not take the
// thread (and with it my next reply) along.
let context = MockChatPrivateConversationContext()
context.nickname = "alicia"
let coordinator = ChatPrivateConversationCoordinator(context: context)
let bobThread = PeerID(str: "1122334455667788")
let strangerPeerID = PeerID(str: "8899aabbccddeeff")
context.privateChats[bobThread] = [
makeIncomingMessage(
id: "bob-1",
sender: "bob",
timestamp: Date().addingTimeInterval(-120),
senderPeerID: bobThread,
recipientNickname: "alice"
),
BitchatMessage(
id: "my-old-reply",
sender: "alice",
content: "hi bob",
timestamp: Date().addingTimeInterval(-60),
isRelay: false,
isPrivate: true,
recipientNickname: "bob",
senderPeerID: context.myPeerID,
deliveryStatus: .sent
)
]
context.selectedPrivateChatPeer = bobThread
coordinator.handlePrivateMessage(
makeIncomingMessage(id: "stranger-1", sender: "alice", senderPeerID: strangerPeerID, recipientNickname: "alicia")
)
#expect(context.privateChats[bobThread]?.map(\.id) == ["bob-1", "my-old-reply"])
#expect(context.privateChats[strangerPeerID]?.map(\.id) == ["stranger-1"])
#expect(context.migratedChats.isEmpty)
#expect(context.selectedPrivateChatPeer == bobThread)
}
@Test @MainActor
func migratePrivateChats_leavesMyGeoDMThreadAloneWhenAStrangerTakesMyOldName() async {
// My geo-DM replies name me as their recipient, under the name I had
// then. After a rename, a stranger who takes that old name must not
// match them and take the thread along.
let context = MockChatPrivateConversationContext()
context.nickname = "alicia"
let coordinator = ChatPrivateConversationCoordinator(context: context)
let geoThread = PeerID(nostr_: String(repeating: "45", count: 32))
let strangerPeerID = PeerID(str: "8899aabbccddeeff")
context.privateChats[geoThread] = [
makeIncomingMessage(
id: "carol-1",
sender: "carol#4545",
timestamp: Date().addingTimeInterval(-120),
senderPeerID: geoThread,
recipientNickname: "alice"
),
BitchatMessage(
id: "my-old-reply",
sender: "alice",
content: "hi carol",
timestamp: Date().addingTimeInterval(-60),
isRelay: false,
isPrivate: true,
recipientNickname: "alice",
senderPeerID: context.myPeerID,
deliveryStatus: .sent
)
]
context.selectedPrivateChatPeer = geoThread
coordinator.handlePrivateMessage(
makeIncomingMessage(id: "stranger-1", sender: "alice", senderPeerID: strangerPeerID, recipientNickname: "alicia")
)
#expect(context.privateChats[geoThread]?.map(\.id) == ["carol-1", "my-old-reply"])
#expect(context.privateChats[strangerPeerID]?.map(\.id) == ["stranger-1"])
#expect(context.migratedChats.isEmpty)
#expect(context.selectedPrivateChatPeer == geoThread)
}
@Test @MainActor
func migratePrivateChats_stillMovesAGeoDMThreadWithMyRepliesByThePeersRows() async {
// My replies are no evidence in a geo-DM thread, but they don't veto
// it either: the peer's own rows still take it to their mesh chat.
// (Received geo-DM rows carry a geo name today, so this pins the rule
// rather than a path that occurs.)
let context = MockChatPrivateConversationContext()
context.nickname = "alice"
let coordinator = ChatPrivateConversationCoordinator(context: context)
let theirThread = PeerID(nostr_: String(repeating: "44", count: 32))
let bobPeerID = PeerID(str: "8899aabbccddeeff")
context.privateChats[theirThread] = [
makeIncomingMessage(
id: "bob-earlier",
sender: "bob",
timestamp: Date().addingTimeInterval(-120),
senderPeerID: theirThread,
recipientNickname: "alice"
),
BitchatMessage(
id: "my-reply",
sender: "alice",
content: "hi bob",
timestamp: Date().addingTimeInterval(-60),
isRelay: false,
isPrivate: true,
recipientNickname: "alice",
senderPeerID: context.myPeerID,
deliveryStatus: .sent
)
]
coordinator.handlePrivateMessage(
makeIncomingMessage(id: "bob-1", sender: "bob", senderPeerID: bobPeerID, recipientNickname: "alice")
)
#expect(context.privateChats[theirThread] == nil)
#expect(context.privateChats[bobPeerID]?.map(\.id) == ["bob-earlier", "my-reply", "bob-1"])
#expect(context.migratedChats.map(\.from) == [theirThread])
}
@Test @MainActor
func migratePrivateChats_stillMovesAGeoDMThreadWithoutMyRowsByNickname() async {
// The skip is for threads holding my rows: a geo-DM thread of the
// peer's own rows still follows them to their mesh chat by name.
let context = MockChatPrivateConversationContext()
context.nickname = "alice"
let coordinator = ChatPrivateConversationCoordinator(context: context)
let theirThread = PeerID(nostr_: String(repeating: "43", count: 32))
let bobPeerID = PeerID(str: "8899aabbccddeeff")
context.privateChats[theirThread] = [
makeIncomingMessage(
id: "bob-earlier",
sender: "bob",
timestamp: Date().addingTimeInterval(-60),
senderPeerID: theirThread,
recipientNickname: "alice"
)
]
coordinator.handlePrivateMessage(
makeIncomingMessage(id: "bob-1", sender: "bob", senderPeerID: bobPeerID, recipientNickname: "alice")
)
#expect(context.privateChats[theirThread] == nil)
#expect(context.privateChats[bobPeerID]?.map(\.id) == ["bob-earlier", "bob-1"])
#expect(context.migratedChats.map(\.from) == [theirThread])
}
@Test @MainActor
func migratePrivateChats_stillMovesMyMeshThreadByNickname() async {
// Only geo-DM rows name me as their recipient. My mesh rows name the
// peer, so my thread with bob under his previous peer ID follows him
// to the new one.
let context = MockChatPrivateConversationContext()
context.nickname = "alice"
let coordinator = ChatPrivateConversationCoordinator(context: context)
let previousPeerID = PeerID(str: "1122334455667788")
let bobPeerID = PeerID(str: "8899aabbccddeeff")
context.privateChats[previousPeerID] = [
makeIncomingMessage(
id: "bob-earlier",
sender: "bob",
timestamp: Date().addingTimeInterval(-120),
senderPeerID: previousPeerID,
recipientNickname: "alice"
),
BitchatMessage(
id: "my-reply",
sender: "alice",
content: "hi bob",
timestamp: Date().addingTimeInterval(-60),
isRelay: false,
isPrivate: true,
recipientNickname: "bob",
senderPeerID: context.myPeerID,
deliveryStatus: .sent
)
]
coordinator.handlePrivateMessage(
makeIncomingMessage(id: "bob-1", sender: "bob", senderPeerID: bobPeerID, recipientNickname: "alice")
)
#expect(context.privateChats[previousPeerID] == nil)
#expect(context.privateChats[bobPeerID]?.map(\.id) == ["bob-earlier", "my-reply", "bob-1"])
}
@Test @MainActor
func handlePrivateMessage_postsNotificationOnlyWhenNotViewingChat() async {
let context = MockChatPrivateConversationContext()

View File

@ -30,13 +30,8 @@ private final class MockChatPublicConversationContext: ChatPublicConversationCon
var currentGeohash: String?
var nickname = "me"
var myPeerID = PeerID(str: "0011223344556677")
private(set) var isBatchingPublic = false
private(set) var notifyUIChangedCount = 0
func setPublicBatching(_ isBatching: Bool) {
isBatchingPublic = isBatching
}
func notifyUIChanged() {
notifyUIChangedCount += 1
}
@ -541,9 +536,6 @@ struct ChatPublicConversationCoordinatorContextTests {
coordinator.pipelinePrewarmMessage(pipeline, message: message)
#expect(context.prewarmedMessageIDs == ["pipeline-msg"])
coordinator.pipelineSetBatchingState(pipeline, isBatching: true)
#expect(context.isBatchingPublic)
}
@Test @MainActor
@ -606,7 +598,8 @@ struct ChatPublicConversationCoordinatorContextTests {
)
#expect(context.mentionNotifications.count == 1)
// My own message mentioning myself does not notify.
// My own message mentioning myself (a gossip replay of my mesh text,
// stamped with my peer ID) does not notify.
coordinator.checkForMentions(
BitchatMessage(
id: "mention-3",
@ -614,10 +607,65 @@ struct ChatPublicConversationCoordinatorContextTests {
content: "talking about @me",
timestamp: Date(),
isRelay: false,
senderPeerID: context.myPeerID,
mentions: ["me"]
)
)
#expect(context.mentionNotifications.count == 1)
}
@Test @MainActor
func checkForMentions_tellsMyOwnMessagesFromNamesakesBySenderID() async {
let context = MockChatPublicConversationContext()
let coordinator = ChatPublicConversationCoordinator(context: context)
let myGeoHex = MockChatPublicConversationContext.dummyIdentity.publicKeyHex
let namesakeHex = String(repeating: "ef", count: 32)
// A namesake shown by my bare nickname (multi-hop mesh, or the
// signed-name fallback) mentioning me still notifies.
coordinator.checkForMentions(
BitchatMessage(
id: "namesake-mesh",
sender: "me",
content: "hi @me",
timestamp: Date(),
isRelay: false,
senderPeerID: PeerID(str: "8899aabbccddeeff"),
mentions: ["me"]
)
)
#expect(context.mentionNotifications.map(\.message) == ["hi @me"])
// In a location channel, a relay echo of my own geochat message
// (NostrInboundPipeline.subscribeNostrEvent) stays quiet...
context.activeChannel = .location(GeohashChannel(level: .city, geohash: "u4pruy"))
context.currentGeohash = "u4pruy"
coordinator.checkForMentions(
BitchatMessage(
id: "own-geo-echo",
sender: "me#\(myGeoHex.suffix(4))",
content: "note to @me",
timestamp: Date(),
isRelay: false,
senderPeerID: PeerID(nostr: myGeoHex),
mentions: ["me"]
)
)
#expect(context.mentionNotifications.map(\.message) == ["hi @me"])
// ...while a geochat namesake mentioning me notifies.
coordinator.checkForMentions(
BitchatMessage(
id: "namesake-geo",
sender: "me#\(namesakeHex.suffix(4))",
content: "yo @me",
timestamp: Date(),
isRelay: false,
senderPeerID: PeerID(nostr: namesakeHex),
mentions: ["me"]
)
)
#expect(context.mentionNotifications.map(\.message) == ["hi @me", "yo @me"])
}
}

View File

@ -0,0 +1,102 @@
//
// ChatViewModelBootstrapperTests.swift
// bitchatTests
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import Foundation
import Testing
@testable import bitchat
@MainActor
struct ChatViewModelBootstrapperTests {
/// Nicknames name the authors of messages on screen, including replayed
/// history from people no longer present. Roster publishes prune presence
/// state (teleport markers) but must keep those names resolvable for
/// /msg, /block, autocomplete and DM headers.
@Test func rosterPublishesKeepNicknamesOfAuthorsWhoAreNotPresent() async {
let viewModel = makeViewModel()
// The initial (mesh) channel arrives asynchronously and resets the
// tracker; let startup settle first.
await drainMainQueue()
let geohash = "u4pruyd"
viewModel.currentGeohash = geohash
viewModel.participantTracker.setActiveGeohash(geohash)
let author = String(repeating: "a", count: 64)
// A replayed message from ten minutes ago: named, but not present.
viewModel.setGeoNickname("troll", forPubkey: author)
viewModel.participantTracker.recordParticipant(pubkeyHex: author, seenAt: Date().addingTimeInterval(-600))
// Someone else arrives, so the roster publishes and the prune runs.
viewModel.participantTracker.recordParticipant(pubkeyHex: String(repeating: "b", count: 64))
await drainMainQueue()
#expect(viewModel.geoNicknames[author] == "troll")
}
/// Teleport markers follow the roster, which prunes them only as it
/// changes. A teleport tag replayed from before the activity window must
/// not mark its absent author: the marker would wait for them, and when
/// they came back, no longer teleported, they'd still be badged.
@Test func expiredReplayedTeleportTagDoesNotFollowItsAuthorBackIn() async throws {
let viewModel = makeViewModel()
await drainMainQueue()
let geohash = "u4pruyd"
viewModel.currentGeohash = geohash
viewModel.participantTracker.setActiveGeohash(geohash)
let sender = try NostrIdentity.generate()
// Replayed on join: a message they sent teleported, ten minutes ago.
let replayed = try NostrEvent(
pubkey: sender.publicKeyHex,
createdAt: Date().addingTimeInterval(-600),
kind: .ephemeralEvent,
tags: [["g", geohash], ["t", "teleport"]],
content: "from earlier"
).sign(with: sender.schnorrSigningKey())
viewModel.nostrCoordinator.inbound.handleNostrEvent(replayed, isHistoryReplay: true)
await drainMainQueue()
// They come back, live and local.
let live = try NostrProtocol.createEphemeralGeohashEvent(
content: "back",
geohash: geohash,
senderIdentity: sender
)
viewModel.nostrCoordinator.inbound.handleNostrEvent(live)
await drainMainQueue()
let key = sender.publicKeyHex.lowercased()
#expect(viewModel.participantTracker.visiblePeople.map(\.id) == [key])
#expect(!viewModel.teleportedGeo.contains(key))
}
/// A private location manager: the shared one is switched by other
/// suites running in parallel, and a switch clears nicknames and
/// teleport markers.
private func makeViewModel() -> ChatViewModel {
let keychain = MockKeychain()
let locationSuite = "ChatViewModelBootstrapperTests.\(UUID().uuidString)"
let locationStorage = UserDefaults(suiteName: locationSuite) ?? .standard
locationStorage.removePersistentDomain(forName: locationSuite)
return ChatViewModel(
keychain: keychain,
idBridge: NostrIdentityBridge(keychain: MockKeychainHelper()),
identityManager: MockIdentityManager(keychain),
transport: MockTransport(),
locationManager: LocationChannelManager(storage: locationStorage)
)
}
private func drainMainQueue() async {
for _ in 0..<4 {
await withCheckedContinuation { continuation in
DispatchQueue.main.async { continuation.resume() }
}
}
}
}

View File

@ -823,8 +823,8 @@ struct ChatViewModelGeoDMTests {
/// Contracts for the owner-side intent ops that are the sole mutation paths
/// for `ChatViewModel`'s shared coordinator state (`nostrKeyMapping`,
/// `sentReadReceipts`, `sentGeoDeliveryAcks`, `isBatchingPublic`, the geo
/// subscription IDs, and the selected private chat hand-off).
/// `sentReadReceipts`, `sentGeoDeliveryAcks`, the geo subscription IDs, and
/// the selected private chat hand-off).
struct ChatViewModelIntentOperationTests {
@Test @MainActor
@ -890,17 +890,6 @@ struct ChatViewModelIntentOperationTests {
#expect(viewModel.nostrKeyMapping[PeerID(nostr_: otherHex)] == otherHex)
}
@Test @MainActor
func setPublicBatching_publishesBatchingState() async {
let (viewModel, _) = makeTestableViewModel()
#expect(!viewModel.isBatchingPublic)
viewModel.setPublicBatching(true)
#expect(viewModel.isBatchingPublic)
viewModel.setPublicBatching(false)
#expect(!viewModel.isBatchingPublic)
}
@Test @MainActor
func geoSubscriptionIntentOps_setClearAndDrainSubscriptions() async {
let (viewModel, _) = makeTestableViewModel()

View File

@ -19,7 +19,8 @@ private func makeTestableViewModel(
keychain injectedKeychain: MockKeychain? = nil,
panicMediaWipe: (() throws -> Void)? = nil,
panicRecoveryOperations: PanicRecoveryOperations? = nil,
panicNetworkLifecycle: PanicNetworkLifecycle = .noop
panicNetworkLifecycle: PanicNetworkLifecycle = .noop,
locationManager: LocationChannelManager = .shared
) -> (viewModel: ChatViewModel, transport: MockTransport) {
let keychain = injectedKeychain ?? MockKeychain()
let keychainHelper = MockKeychainHelper()
@ -32,6 +33,7 @@ private func makeTestableViewModel(
idBridge: idBridge,
identityManager: identityManager,
transport: transport,
locationManager: locationManager,
panicMediaWipe: panicMediaWipe,
panicRecoveryOperations: panicRecoveryOperations,
panicNetworkLifecycle: panicNetworkLifecycle
@ -691,6 +693,37 @@ struct ChatViewModelFormattingTests {
#expect(String(header.characters) == "<@Alice#a1b2> ")
}
@Test @MainActor
func formatMessageHeader_isCachedApartFromTheFullText() async {
let (viewModel, _) = makeTestableViewModel()
let message = BitchatMessage(
id: "fmt-3",
sender: "Alice#a1b2",
content: "hello",
timestamp: Date(),
isRelay: false,
senderPeerID: PeerID(str: "00000000000000b3")
)
// The full text is cached first under the same scheme, theme and
// sender flags; the header lookup must not pick it up.
let fullText = viewModel.formatMessageAsText(message, colorScheme: .dark, theme: .matrix)
let header = viewModel.formatMessageHeader(message, colorScheme: .dark, theme: .matrix)
#expect(String(header.characters) == "<@Alice#a1b2> ")
#expect(String(fullText.characters).hasPrefix("<@Alice#a1b2> hello"))
#expect(
message.getCachedFormattedText(
isDark: true,
isSelf: false,
variant: ChatMessageFormatter.headerCacheNamespace
) == header
)
// Later lookups are answered from each one's own cache entry.
#expect(viewModel.formatMessageHeader(message, colorScheme: .dark, theme: .matrix) == header)
#expect(viewModel.formatMessageAsText(message, colorScheme: .dark, theme: .matrix) == fullText)
}
}
// MARK: - Verification Tests
@ -1068,6 +1101,46 @@ struct ChatViewModelPrivateChatTests {
// At minimum, it should not crash
#expect(Bool(true)) // If we get here without crash, the test passes
}
@Test @MainActor
func syncReadReceiptsForSentMessages_judgesMineBySenderIDNotNickname() async {
let (viewModel, transport) = makeTestableViewModel()
viewModel.nickname = "alice"
let peerID = PeerID(str: "0011223344556677")
viewModel.seedPrivateChat([
// A namesake's file, delivered to me (BLEFileTransferHandler.incomingMessage):
// it still needs my READ receipt.
BitchatMessage(
id: "namesake-delivered",
sender: "alice",
content: "[image] theirs.jpg",
timestamp: Date(),
isRelay: false,
isPrivate: true,
recipientNickname: "alice",
senderPeerID: peerID,
deliveryStatus: .delivered(to: "alice", at: Date())
),
// My own message from before a rename, already read.
BitchatMessage(
id: "mine-before-rename",
sender: "al",
content: "hi",
timestamp: Date(),
isRelay: false,
isPrivate: true,
recipientNickname: "bob",
senderPeerID: transport.myPeerID,
deliveryStatus: .read(by: "bob", at: Date())
)
], for: peerID)
viewModel.syncReadReceiptsForSentMessages(for: peerID)
#expect(!viewModel.hasSentReadReceipt("namesake-delivered"))
#expect(!viewModel.privateChatManager.sentReadReceipts.contains("namesake-delivered"))
#expect(viewModel.hasSentReadReceipt("mine-before-rename"))
}
}
// MARK: - Private Chat Selection Tests
@ -2302,6 +2375,29 @@ struct ChatViewModelPanicTests {
#expect(viewModel.geoNicknames.isEmpty)
#expect(viewModel.teleportedGeo.isEmpty)
}
@Test @MainActor
func panicClearAllData_wipesTheLocationStateOfItsOwnManager() throws {
// Where the device has been, persisted the way the location manager
// writes it: a teleport and a bookmark.
let suiteName = "ChatViewModelPanicTests.\(UUID().uuidString)"
let storage = try #require(UserDefaults(suiteName: suiteName))
defer { storage.removePersistentDomain(forName: suiteName) }
storage.set(try JSONEncoder().encode(["u4pruy"]), forKey: "locationChannel.teleportedSet")
storage.set(try JSONEncoder().encode(["u4pruy"]), forKey: "locationChannel.bookmarks")
let locationManager = LocationChannelManager(storage: storage)
#expect(locationManager.bookmarks == ["u4pruy"])
let (viewModel, _) = makeTestableViewModel(locationManager: locationManager)
viewModel.panicClearAllData()
// The wipe lands on the manager the view model runs on: `.shared` in
// the app, this test's own here, which leaves the process-wide one to
// the tests that select channels on it.
#expect(locationManager.bookmarks.isEmpty)
#expect(storage.object(forKey: "locationChannel.teleportedSet") == nil)
#expect(storage.object(forKey: "locationChannel.bookmarks") == nil)
}
}
// MARK: - Service Lifecycle Tests

View File

@ -292,6 +292,8 @@ struct CommandProcessorTests {
Issue.record("Expected success result")
}
#expect(identityManager.isNostrBlocked(pubkeyHexLowercased: String(repeating: "d", count: 64)))
// The roster re-filters now rather than on its next timer tick.
#expect(context.geohashBlockListChangeCount == 1)
let unblockResult = await withSelectedChannel(.mesh, context: context) {
processor.process("/unblock @carol")
@ -303,6 +305,7 @@ struct CommandProcessorTests {
Issue.record("Expected success result")
}
#expect(!identityManager.isNostrBlocked(pubkeyHexLowercased: String(repeating: "d", count: 64)))
#expect(context.geohashBlockListChangeCount == 2)
}
/// /fav must go through toggleFavorite (which persists by the real noise
@ -608,6 +611,7 @@ private final class MockCommandContextProvider: CommandContextProvider {
private(set) var commandOutputDestinations: [CommandOutputDestination] = []
private(set) var toggledFavorites: [PeerID] = []
private(set) var favoriteNotifications: [(peerID: PeerID, isFavorite: Bool)] = []
private(set) var geohashBlockListChangeCount = 0
init(nickname: String = "tester", idBridge: NostrIdentityBridge = NostrIdentityBridge(keychain: MockKeychain())) {
self.nickname = nickname
@ -626,6 +630,10 @@ private final class MockCommandContextProvider: CommandContextProvider {
displayNameToNostrPubkey[displayName]
}
func geohashBlockListDidChange() {
geohashBlockListChangeCount += 1
}
func startPrivateChat(with peerID: PeerID) {
startedPrivateChats.append(peerID)
}

View File

@ -0,0 +1,470 @@
//
// ConversationUIModelTests.swift
// bitchatTests
//
// "Is this row mine?" drives the message list: the context-menu actions,
// the jump to the bottom on my own send, DM delivery status, the verified
// seal and which media directory a row loads from. The answer must come from
// the sender ID a row carries, never from its display name, which namesakes
// share by design (geochat shows everyone as nick#<pubkey suffix>).
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import BitFoundation
import Foundation
import Testing
@testable import bitchat
/// A chat stack with a known mesh peer ID and an isolated location manager,
/// so no other test's channel selection leaks in.
@MainActor
private func makeChatViewModel(nickname: String) -> (viewModel: ChatViewModel, transport: MockTransport) {
let keychain = MockKeychain()
let transport = MockTransport()
transport.myPeerID = ConversationUIModelTests.myPeerID
let suiteName = "ConversationUIModelTests.\(UUID().uuidString)"
let storage = UserDefaults(suiteName: suiteName) ?? .standard
storage.removePersistentDomain(forName: suiteName)
let viewModel = ChatViewModel(
keychain: keychain,
idBridge: NostrIdentityBridge(keychain: MockKeychainHelper()),
identityManager: MockIdentityManager(keychain),
transport: transport,
locationManager: LocationChannelManager(storage: storage)
)
viewModel.nickname = nickname
return (viewModel, transport)
}
/// The UI model mirrors the nickname a runloop turn late, so a test that
/// renames builds a fresh one; that keeps the rename test meaningful against
/// a helper that compares names.
@MainActor
private func makeUIModel(for viewModel: ChatViewModel) -> ConversationUIModel {
let privateConversationModel = PrivateConversationModel(
chatViewModel: viewModel,
conversations: viewModel.conversations,
locationChannelsModel: LocationChannelsModel(manager: viewModel.locationManager)
)
return ConversationUIModel(
chatViewModel: viewModel,
privateConversationModel: privateConversationModel,
conversations: viewModel.conversations
)
}
private func row(
_ sender: String,
_ senderPeerID: PeerID?,
content: String = "hi",
isPrivate: Bool = false,
deliveryStatus: DeliveryStatus? = nil,
isBridged: Bool = false
) -> BitchatMessage {
BitchatMessage(
sender: sender,
content: content,
timestamp: Date(),
isRelay: false,
isPrivate: isPrivate,
senderPeerID: senderPeerID,
deliveryStatus: deliveryStatus,
isBridged: isBridged
)
}
/// `hex` with its first `count` characters changed. Changing the first 8
/// gives a different geochat sender ID (`nostr:` + 8 hex) while the last 4,
/// the display suffix, stay the same.
private func altered(_ hex: String, first count: Int) -> String {
String(hex.prefix(count).map { $0 == "0" ? "1" : "0" }) + hex.dropFirst(count)
}
struct ConversationUIModelTests {
static let myPeerID = PeerID(str: "a1b2c3d4e5f60718")
static let peerID = PeerID(str: "0f1e2d3c4b5a6978")
static let geohash = "u4pruy"
static let locationChannel = ChannelID.location(GeohashChannel(level: .city, geohash: geohash))
@MainActor
private static func show(geohash: String, in viewModel: ChatViewModel) {
viewModel.activeChannel = .location(GeohashChannel(level: .city, geohash: geohash))
}
/// Switches channels the way the channel picker does: through the
/// location manager, which the view model follows a few hops later.
/// Tests that await must switch this way, since the view model re-applies
/// the manager's selection on a later turn and would undo a direct
/// `activeChannel` write. Returns once the UI model has mirrored the
/// switch (media is off in location channels), so no channel update
/// queued before it can still reach the memo.
@MainActor
private static func switchAndSettle(to channel: ChannelID, in viewModel: ChatViewModel, uiModel: ConversationUIModel) async -> Bool {
viewModel.locationManager.select(channel)
let mediaAllowed = channel == .mesh
return await TestHelpers.waitUntil({
viewModel.activeChannel == channel && uiModel.canSendMediaInCurrentContext == mediaAllowed
}, timeout: TestConstants.settleTimeout)
}
@MainActor
private static func myGeoHex(_ viewModel: ChatViewModel, geohash: String = ConversationUIModelTests.geohash) throws -> String {
try viewModel.idBridge.deriveIdentity(forGeohash: geohash).publicKeyHex
}
@Test @MainActor
func geochatNamesakesAreNotMine() throws {
let (viewModel, _) = makeChatViewModel(nickname: "alice")
let uiModel = makeUIModel(for: viewModel)
Self.show(geohash: Self.geohash, in: viewModel)
let myHex = try Self.myGeoHex(viewModel)
let theirHex = altered(myHex, first: 64)
let twinHex = altered(myHex, first: 8)
// My own row, as ChatOutgoingCoordinator.sendGeohashPublicMessage stamps it.
#expect(uiModel.isSentByCurrentUser(row("alice#\(myHex.suffix(4))", PeerID(nostr: myHex))))
// Another "alice": same name, different key.
#expect(!uiModel.isSentByCurrentUser(row("alice#\(theirHex.suffix(4))", PeerID(nostr: theirHex))))
// Even a display string identical to mine, down to the 4-hex suffix.
#expect(!uiModel.isSentByCurrentUser(row("alice#\(myHex.suffix(4))", PeerID(nostr: twinHex))))
}
@Test @MainActor
func anonReaderDoesNotOwnAnonymousStrangers() throws {
let (viewModel, _) = makeChatViewModel(nickname: "anon")
let uiModel = makeUIModel(for: viewModel)
Self.show(geohash: Self.geohash, in: viewModel)
let myHex = try Self.myGeoHex(viewModel)
let strangerHex = altered(myHex, first: 64)
let strangerName = "anon#\(strangerHex.suffix(4))"
// Geochat and sampled senders without an n tag
// (displayNameForNostrPubkey, GeoPresenceTracker.cooldownPerGeohash).
#expect(!uiModel.isSentByCurrentUser(row(strangerName, PeerID(nostr: strangerHex))))
// A bridged sender without one (BridgeService.classify).
#expect(!uiModel.isSentByCurrentUser(row(strangerName, PeerID(bridge: strangerHex), isBridged: true)))
// A geo DM from an unnamed stranger, delivered to me.
#expect(!uiModel.isSentByCurrentUser(row(
strangerName,
PeerID(nostr_: strangerHex),
isPrivate: true,
deliveryStatus: .delivered(to: "anon", at: Date())
)))
// My own geochat row is still mine.
#expect(uiModel.isSentByCurrentUser(row("anon#\(myHex.suffix(4))", PeerID(nostr: myHex))))
}
@Test @MainActor
func meshAndGroupNamesakesAreNotMine() {
let (viewModel, _) = makeChatViewModel(nickname: "alice")
let uiModel = makeUIModel(for: viewModel)
let namesakeRows = [
// Public text, suffixed while the namesake is connected
// (BLEPeerSenderDisplayName.collisionResolvedName)...
row("alice#\(Self.peerID.id.prefix(4))", Self.peerID),
// ...and by its bare signed name otherwise
// (BLEService.signedSenderDisplayName).
row("alice", Self.peerID),
// A DM; received DMs keep the default .sending status.
row("alice", Self.peerID, isPrivate: true),
// A courier-opened DM, keyed by the sender's full Noise key.
row("alice", PeerID(hexData: Data((0..<32).map(UInt8.init))), isPrivate: true),
// A group member with my name (ChatGroupCoordinator.handleGroupMessagePayload).
row("alice", PeerID(str: "f00dfacecafebeef"), isPrivate: true)
]
for message in namesakeRows {
#expect(!uiModel.isSentByCurrentUser(message), "\(message.sender) from \(message.senderPeerID?.id ?? "nil")")
}
}
@Test @MainActor
func ownRowsOnEveryPathStayMineAcrossARename() throws {
let (viewModel, _) = makeChatViewModel(nickname: "alice")
let myHex = try Self.myGeoHex(viewModel)
let me = Self.myPeerID
// Each row as its construction site stamps it.
let ownRows = [
// Mesh text and the wave (ChatOutgoingCoordinator.sendMeshPublicMessage).
row("alice", me, content: "mesh text"),
// Gossip self-replay and the archived echo restored at launch
// (ChatTransportEventCoordinator.handlePublicMessage,
// ChatViewModelBootstrapper.loadArchivedEchoes).
BitchatMessage(id: "echo-0011", sender: "alice", content: "archived echo", timestamp: Date(), isRelay: false, senderPeerID: me),
// Mesh DM (ChatPrivateConversationCoordinator.sendPrivateMessage).
row("alice", me, content: "mesh dm", isPrivate: true, deliveryStatus: .delivered(to: "bob", at: Date())),
// Geo DM: plain nickname, mesh ID (ChatPrivateConversationCoordinator.sendGeohashDM).
row("alice", me, content: "geo dm", isPrivate: true, deliveryStatus: .sent),
// Group message (ChatGroupCoordinator.sendGroupMessage).
row("alice", me, content: "group message", isPrivate: true, deliveryStatus: .sent),
// Voice note (ChatMediaTransferCoordinator.enqueueMediaMessage).
row("alice", me, content: "[voice] note.m4a", isPrivate: true, deliveryStatus: .sending),
// Geochat text and its relay echo
// (ChatOutgoingCoordinator.sendGeohashPublicMessage, NostrInboundPipeline).
row("alice#\(myHex.suffix(4))", PeerID(nostr: myHex), content: "geochat text")
]
let uiModel = makeUIModel(for: viewModel)
Self.show(geohash: Self.geohash, in: viewModel)
for message in ownRows {
#expect(uiModel.isSentByCurrentUser(message), "\(message.content) from \(message.senderPeerID?.id ?? "nil")")
}
// A rename changes no sender ID: everything I sent stays mine.
viewModel.nickname = "alicia"
let renamedUIModel = makeUIModel(for: viewModel)
for message in ownRows {
#expect(renamedUIModel.isSentByCurrentUser(message), "\(message.content) from \(message.senderPeerID?.id ?? "nil")")
}
}
@Test @MainActor
func systemLinesAndRowsWithoutASenderIDAreNeverMine() throws {
let (viewModel, _) = makeChatViewModel(nickname: "alice")
let uiModel = makeUIModel(for: viewModel)
Self.show(geohash: Self.geohash, in: viewModel)
let myHex = try Self.myGeoHex(viewModel)
// DM command output and the screenshot notice carry my mesh ID
// (ChatViewModel.addLocalPrivateSystemMessage,
// ChatLifecycleCoordinator.appendPrivateScreenshotNotice); counting
// them as mine would pull a scrolled-up reader down.
#expect(!uiModel.isSentByCurrentUser(row("system", Self.myPeerID, isPrivate: true)))
// A converted emote keeps its author's ID
// (ChatPrivateConversationCoordinator.processActionMessage).
#expect(!uiModel.isSentByCurrentUser(row("system", PeerID(nostr: myHex))))
// Public system lines carry no sender ID...
#expect(!uiModel.isSentByCurrentUser(row("system", nil)))
// ...and a name alone never makes a row mine.
#expect(!uiModel.isSentByCurrentUser(row("alice", nil)))
}
@Test @MainActor
func mediaRowsLoadFromTheDirectionTheirSenderIDNames() throws {
let (viewModel, _) = makeChatViewModel(nickname: "alice")
let uiModel = makeUIModel(for: viewModel)
let namesakeImage = row(
"alice",
Self.peerID,
content: "[image] theirs.jpg",
isPrivate: true,
deliveryStatus: .delivered(to: "alice", at: Date())
)
// Sent before I renamed myself from "al" to "alice".
let myImage = row("al", Self.myPeerID, content: "[image] mine.jpg", isPrivate: true, deliveryStatus: .sent)
// A namesake's image is received media: blurred, deletable, no Cancel.
#expect(!uiModel.isMediaMessageFromCurrentUser(namesakeImage))
guard case .image(let theirURL)? = uiModel.mediaAttachment(for: namesakeImage) else {
Issue.record("Expected the namesake's image to resolve to an image row")
return
}
#expect(theirURL.deletingLastPathComponent().path.hasSuffix("/images/incoming"))
#expect(uiModel.isMediaMessageFromCurrentUser(myImage))
guard case .image(let myURL)? = uiModel.mediaAttachment(for: myImage) else {
Issue.record("Expected my image to resolve to an image row")
return
}
#expect(myURL.deletingLastPathComponent().path.hasSuffix("/images/outgoing"))
}
@Test @MainActor
func verifiedNamesakeKeepsTheSealOnTheirDMs() {
let (viewModel, transport) = makeChatViewModel(nickname: "alice")
let uiModel = makeUIModel(for: viewModel)
transport.peerFingerprints[Self.peerID] = "namesake-fingerprint"
viewModel.peerIdentityStore.setVerified("namesake-fingerprint", verified: true)
// The seal is what tells a verified "alice" from an impersonator.
#expect(uiModel.showsVerifiedSeal(for: row("alice", Self.peerID, isPrivate: true)))
#expect(!uiModel.showsVerifiedSeal(for: row("alice", Self.myPeerID, isPrivate: true)))
}
@Test @MainActor
func geochatOwnershipFollowsTheChannelOnScreen() throws {
let (viewModel, _) = makeChatViewModel(nickname: "alice")
let uiModel = makeUIModel(for: viewModel)
let hexA = try Self.myGeoHex(viewModel, geohash: "u4pruy")
let hexB = try Self.myGeoHex(viewModel, geohash: "9q8yy")
let fromA = row("alice#\(hexA.suffix(4))", PeerID(nostr: hexA))
let fromB = row("alice#\(hexB.suffix(4))", PeerID(nostr: hexB))
Self.show(geohash: "u4pruy", in: viewModel)
#expect(uiModel.isSentByCurrentUser(fromA))
#expect(!uiModel.isSentByCurrentUser(fromB))
// Read from the store right after the switch, with no runloop turn.
// A row of my geohash-A identity shown in B renders as a stranger
// (ChatMessageFormatter.formatMessageAsText) and is treated as one.
Self.show(geohash: "9q8yy", in: viewModel)
#expect(uiModel.isSentByCurrentUser(fromB))
#expect(!uiModel.isSentByCurrentUser(fromA))
viewModel.activeChannel = .mesh
#expect(!uiModel.isSentByCurrentUser(fromA))
#expect(!uiModel.isSentByCurrentUser(fromB))
}
@Test @MainActor
func switchingToMeshDropsMyMemoizedGeochatSender() async throws {
let (viewModel, _) = makeChatViewModel(nickname: "alice")
let uiModel = makeUIModel(for: viewModel)
#expect(await Self.switchAndSettle(to: Self.locationChannel, in: viewModel, uiModel: uiModel))
let myHex = try Self.myGeoHex(viewModel)
#expect(uiModel.isSentByCurrentUser(row("alice#\(myHex.suffix(4))", PeerID(nostr: myHex))))
#expect(uiModel.ownGeoChatSender?.peerID == PeerID(nostr: myHex))
// No row on #mesh reads it, so it goes with the switch rather than
// whenever a geochat row next renders.
#expect(await Self.switchAndSettle(to: .mesh, in: viewModel, uiModel: uiModel))
#expect(uiModel.ownGeoChatSender == nil)
}
@Test @MainActor
func panicWipeRetiresTheOldGeochatIdentity() async throws {
let (viewModel, _) = makeChatViewModel(nickname: "alice")
let uiModel = makeUIModel(for: viewModel)
#expect(await Self.switchAndSettle(to: Self.locationChannel, in: viewModel, uiModel: uiModel))
let oldHex = try Self.myGeoHex(viewModel)
let beforeWipe = row("alice#\(oldHex.suffix(4))", PeerID(nostr: oldHex))
#expect(uiModel.isSentByCurrentUser(beforeWipe))
#expect(uiModel.ownGeoChatSender != nil)
// The wipe reseeds every geohash identity and returns to the mesh,
// which takes the retired key out of the memo too.
viewModel.panicClearAllData()
#expect(await TestHelpers.waitUntil({ uiModel.ownGeoChatSender == nil }, timeout: TestConstants.settleTimeout))
Self.show(geohash: Self.geohash, in: viewModel)
let newHex = try Self.myGeoHex(viewModel)
#expect(newHex != oldHex)
#expect(uiModel.isSentByCurrentUser(row("\(viewModel.nickname)#\(newHex.suffix(4))", PeerID(nostr: newHex))))
#expect(!uiModel.isSentByCurrentUser(beforeWipe))
}
// MARK: - Rows from the real send paths
// With no nickname fallback, a send path that forgets to stamp the sender
// ID turns my own row into a stranger's. Each test below sends the way the
// composer does, through the UI model's `sendMessage(_:)` and
// `sendVoiceNote(at:)`, and asks the UI model about the row that send
// produced.
@MainActor
private static func publicRow(_ content: String, in channel: ChannelID, of viewModel: ChatViewModel) -> BitchatMessage? {
viewModel.conversations.conversationsByID[ConversationID(channelID: channel)]?.messages.first { $0.content == content }
}
@MainActor
private static func privateRow(_ content: String, with peerID: PeerID, of viewModel: ChatViewModel) -> BitchatMessage? {
viewModel.privateChats[peerID]?.first { $0.content == content }
}
/// A voice note to send. Any bytes do: the voice-note path checks only
/// the file's size.
private static func makeVoiceNote() throws -> URL {
let url = FileManager.default.temporaryDirectory
.appendingPathComponent("voice-\(UUID().uuidString).m4a")
try Data("voice payload".utf8).write(to: url, options: .atomic)
return url
}
@Test @MainActor
func myMeshPublicSendIsMine() throws {
let (viewModel, transport) = makeChatViewModel(nickname: "alice")
let uiModel = makeUIModel(for: viewModel)
uiModel.sendMessage("hello mesh")
#expect(transport.sentMessages.map(\.content) == ["hello mesh"])
let sent = try #require(Self.publicRow("hello mesh", in: .mesh, of: viewModel))
#expect(uiModel.isSentByCurrentUser(sent))
}
@Test @MainActor
func myMeshDMIsMine() throws {
let (viewModel, transport) = makeChatViewModel(nickname: "alice")
let uiModel = makeUIModel(for: viewModel)
transport.connectedPeers.insert(Self.peerID)
transport.peerNicknames[Self.peerID] = "bob"
viewModel.startPrivateChat(with: Self.peerID)
uiModel.sendMessage("hi bob")
#expect(transport.sentPrivateMessages.map(\.content) == ["hi bob"])
let sent = try #require(Self.privateRow("hi bob", with: Self.peerID, of: viewModel))
#expect(uiModel.isSentByCurrentUser(sent))
}
@Test @MainActor
func myGeoDMIsMine() async throws {
let (viewModel, _) = makeChatViewModel(nickname: "alice")
let uiModel = makeUIModel(for: viewModel)
#expect(await Self.switchAndSettle(to: Self.locationChannel, in: viewModel, uiModel: uiModel))
let stranger = try NostrIdentity.generate()
let conversation = PeerID(nostr_: stranger.publicKeyHex)
viewModel.registerNostrKeyMapping(stranger.publicKeyHex, for: conversation)
viewModel.startPrivateChat(with: conversation)
uiModel.sendMessage("hi stranger")
let sent = try #require(Self.privateRow("hi stranger", with: conversation, of: viewModel))
// Handed to the Nostr transport, not failed on the way there.
#expect(sent.deliveryStatus == .sent)
#expect(uiModel.isSentByCurrentUser(sent))
}
@Test @MainActor
func myGeochatPublicSendIsMine() async throws {
let (viewModel, _) = makeChatViewModel(nickname: "alice")
let uiModel = makeUIModel(for: viewModel)
#expect(await Self.switchAndSettle(to: Self.locationChannel, in: viewModel, uiModel: uiModel))
let myHex = try Self.myGeoHex(viewModel)
uiModel.sendMessage("hello geohash")
// The echo lands once its NIP-13 nonce is mined off the main actor.
#expect(await TestHelpers.waitUntil(
{ Self.publicRow("hello geohash", in: Self.locationChannel, of: viewModel) != nil },
timeout: TestConstants.settleTimeout
))
let sent = try #require(Self.publicRow("hello geohash", in: Self.locationChannel, of: viewModel))
#expect(sent.senderPeerID == PeerID(nostr: myHex))
#expect(uiModel.isSentByCurrentUser(sent))
}
@Test @MainActor
func myVoiceNoteOnMeshIsMine() async throws {
let (viewModel, transport) = makeChatViewModel(nickname: "alice")
let uiModel = makeUIModel(for: viewModel)
let note = try Self.makeVoiceNote()
defer { try? FileManager.default.removeItem(at: note) }
uiModel.sendVoiceNote(at: note)
// The row is enqueued at once; wait out the detached preparation so
// the send has finished before the test does.
#expect(await TestHelpers.waitUntil({ transport.sentBroadcastFiles.count == 1 }, timeout: TestConstants.settleTimeout))
let sent = try #require(Self.publicRow("[voice] \(note.lastPathComponent)", in: .mesh, of: viewModel))
#expect(uiModel.isSentByCurrentUser(sent))
}
@Test @MainActor
func myVoiceNoteInADMIsMine() async throws {
let (viewModel, transport) = makeChatViewModel(nickname: "alice")
let uiModel = makeUIModel(for: viewModel)
transport.connectedPeers.insert(Self.peerID)
transport.peerNicknames[Self.peerID] = "bob"
let note = try Self.makeVoiceNote()
defer { try? FileManager.default.removeItem(at: note) }
viewModel.startPrivateChat(with: Self.peerID)
uiModel.sendVoiceNote(at: note)
#expect(await TestHelpers.waitUntil({ transport.sentPrivateFiles.count == 1 }, timeout: TestConstants.settleTimeout))
let sent = try #require(Self.privateRow("[voice] \(note.lastPathComponent)", with: Self.peerID, of: viewModel))
#expect(uiModel.isSentByCurrentUser(sent))
}
}

View File

@ -6,6 +6,7 @@
// This is free and unencumbered software released into the public domain.
//
import Combine
import Testing
import Foundation
@testable import bitchat
@ -272,6 +273,189 @@ struct GeohashParticipantTrackerTests {
#expect(tracker.visiblePeople.count == 1)
}
// MARK: - Membership Revision Tests
@Test func membershipRevision_bumpsWhenSomeoneJoins() async {
let tracker = GeohashParticipantTracker()
let context = MockParticipantContext()
tracker.configure(context: context)
tracker.setActiveGeohash("abc123")
let before = tracker.visibleMembershipRevision
tracker.recordParticipant(pubkeyHex: "pubkey1")
#expect(tracker.visibleMembershipRevision != before)
}
@Test func membershipRevision_staysPutOnRepeatActivity() async {
let tracker = GeohashParticipantTracker()
let context = MockParticipantContext()
tracker.configure(context: context)
tracker.setActiveGeohash("abc123")
tracker.recordParticipant(pubkeyHex: "pubkey1")
tracker.recordParticipant(pubkeyHex: "pubkey2")
let before = tracker.visibleMembershipRevision
// Heartbeats from people already present only move timestamps.
tracker.recordParticipant(pubkeyHex: "pubkey1")
tracker.recordParticipant(pubkeyHex: "pubkey2")
tracker.refresh()
#expect(tracker.visibleMembershipRevision == before)
}
@Test func membershipRevision_bumpsWhenSomeoneLeaves() async {
let tracker = GeohashParticipantTracker()
let context = MockParticipantContext()
tracker.configure(context: context)
tracker.setActiveGeohash("abc123")
tracker.recordParticipant(pubkeyHex: "pubkey1")
tracker.recordParticipant(pubkeyHex: "pubkey2")
let afterJoins = tracker.visibleMembershipRevision
tracker.removeParticipant(pubkeyHex: "pubkey1")
#expect(tracker.visibleMembershipRevision != afterJoins)
let afterRemoval = tracker.visibleMembershipRevision
tracker.setActiveGeohash(nil)
#expect(tracker.visibleMembershipRevision != afterRemoval)
}
// MARK: - Activity Semantics
@Test func recordParticipant_ignoresActivityOlderThanTheWindow() async {
let tracker = GeohashParticipantTracker()
let context = MockParticipantContext()
tracker.configure(context: context)
tracker.setActiveGeohash("abc123")
var changes = 0
let cancellable = tracker.objectWillChange.sink { _ in changes += 1 }
// Replayed history from ten minutes ago doesn't make its author present
// (nor announce a count change or rebuild the roster).
tracker.recordParticipant(pubkeyHex: "pubkey1", seenAt: Date().addingTimeInterval(-600))
#expect(tracker.participantCount(for: "abc123") == 0)
#expect(tracker.visiblePeople.isEmpty)
#expect(changes == 0)
_ = cancellable
}
/// The inbound pipeline marks a teleport tag only when the activity
/// carrying it counted. Activity that makes no one present must report
/// false, or its tag leaves a marker the roster never prunes; activity
/// from someone already present must report true, or their live teleport
/// tags would stop marking them.
@Test func recordParticipant_reportsWhetherTheActivityCounted() async {
let tracker = GeohashParticipantTracker()
let context = MockParticipantContext()
tracker.configure(context: context)
let now = Date()
// No channel open: nothing is recorded.
#expect(!tracker.recordParticipant(pubkeyHex: "pubkey1"))
tracker.setActiveGeohash("abc123")
#expect(!tracker.recordParticipant(pubkeyHex: "pubkey1", seenAt: now.addingTimeInterval(-600)))
// Arriving, then a heartbeat from someone already present.
#expect(tracker.recordParticipant(pubkeyHex: "pubkey1", seenAt: now.addingTimeInterval(-60)))
#expect(tracker.recordParticipant(pubkeyHex: "pubkey1"))
// A late copy of earlier activity that is still inside the window.
#expect(tracker.recordParticipant(pubkeyHex: "pubkey1", seenAt: now.addingTimeInterval(-200)))
#expect(tracker.participantCount(for: "abc123") == 1)
}
@Test func recordParticipant_neverMovesActivityBackwards() async {
let tracker = GeohashParticipantTracker()
let context = MockParticipantContext()
tracker.configure(context: context)
tracker.setActiveGeohash("abc123")
let now = Date()
tracker.recordParticipant(pubkeyHex: "older", seenAt: now.addingTimeInterval(-120))
tracker.recordParticipant(pubkeyHex: "newer", seenAt: now.addingTimeInterval(-60))
// A late copy of an earlier event from "newer" must not demote them.
tracker.recordParticipant(pubkeyHex: "newer", seenAt: now.addingTimeInterval(-200))
#expect(tracker.getVisiblePeople().map(\.id) == ["newer", "older"])
}
@Test func recordParticipant_clampsFutureTimestampsToNow() async {
let tracker = GeohashParticipantTracker()
let context = MockParticipantContext()
tracker.configure(context: context)
tracker.setActiveGeohash("abc123")
tracker.recordParticipant(pubkeyHex: "skewed", seenAt: Date().addingTimeInterval(3600))
#expect(tracker.getVisiblePeople().first.map { $0.lastSeen <= Date() } == true)
}
@Test func repeatActivity_doesNotRepublishTheRoster() async {
let tracker = GeohashParticipantTracker()
let context = MockParticipantContext()
tracker.configure(context: context)
tracker.setActiveGeohash("abc123")
tracker.recordParticipant(pubkeyHex: "pubkey1")
tracker.recordParticipant(pubkeyHex: "pubkey2")
var publishes = 0
let cancellable = tracker.$visiblePeople.dropFirst().sink { _ in publishes += 1 }
// Heartbeats and messages from people already present.
tracker.recordParticipant(pubkeyHex: "pubkey1")
tracker.recordParticipant(pubkeyHex: "pubkey2")
tracker.refresh()
#expect(publishes == 0)
_ = cancellable
}
@Test func displayNameChange_republishesTheRoster() async {
let tracker = GeohashParticipantTracker()
let context = MockParticipantContext()
tracker.configure(context: context)
tracker.setActiveGeohash("abc123")
tracker.recordParticipant(pubkeyHex: "pubkey1")
#expect(tracker.visiblePeople.first?.displayName.hasPrefix("anon#") == true)
context.nicknameMap["pubkey1"] = "alice"
tracker.noteDisplayNameChanged(pubkeyHex: "pubkey1")
#expect(tracker.visiblePeople.first?.displayName.hasPrefix("alice#") == true)
}
@Test func pruneExpired_dropsEntriesThatAgedOut() async {
let tracker = GeohashParticipantTracker()
let context = MockParticipantContext()
tracker.configure(context: context)
let now = Date()
tracker.recordParticipant(pubkeyHex: "quiet", geohash: "geo1", seenAt: now.addingTimeInterval(-200))
tracker.recordParticipant(pubkeyHex: "chatty", geohash: "geo1", seenAt: now)
tracker.recordParticipant(pubkeyHex: "gone", geohash: "geo2", seenAt: now.addingTimeInterval(-200))
// Two minutes on, "quiet" and "gone" are past the five-minute window.
tracker.pruneExpired(now: now.addingTimeInterval(120))
#expect(tracker.participantCount(for: "geo1") == 1)
#expect(tracker.participantCount(for: "geo2") == 0)
}
@Test func objectWillChange_firesOnlyWhenSomeoneNewlyCounts() async {
let tracker = GeohashParticipantTracker()
let context = MockParticipantContext()
tracker.configure(context: context)
var changes = 0
let cancellable = tracker.objectWillChange.sink { _ in changes += 1 }
tracker.recordParticipant(pubkeyHex: "pubkey1", geohash: "geo1")
let afterJoin = changes
tracker.recordParticipant(pubkeyHex: "pubkey1", geohash: "geo1")
#expect(afterJoin >= 1)
#expect(changes == afterJoin)
_ = cancellable
}
// MARK: - GeoPerson Tests
@Test func geoPerson_identifiable() async {

View File

@ -0,0 +1,485 @@
import CoreGraphics
import Foundation
import Testing
@testable import bitchat
struct GlobeMathTests {
@Test func preparedProjectorMatchesReferenceProjection() {
let centers: [(Double, Double)] = [(0, 0), (45.25, 12.5), (-72, 179.5)]
let points: [(Double, Double)] = [(0, 0), (51.5074, -0.1278), (-33.8688, 151.2093), (89, -179.9)]
for (centerLat, centerLon) in centers {
let projector = GlobeMath.PreparedProjector(centerLat: centerLat, centerLon: centerLon)
for (lat, lon) in points {
let actual = projector.project(GlobeMath.Terms(lat: lat, lon: lon))
let expected = GlobeMath.projectRaw(lat: lat, lon: lon, centerLat: centerLat, centerLon: centerLon)
#expect(abs(expected.x - actual.x) < 1e-9)
#expect(abs(expected.y - actual.y) < 1e-9)
#expect(abs(expected.cosC - actual.cosC) < 1e-9)
}
}
}
@Test func unprojectInvertsProjection() throws {
let p = GlobeMath.projectRaw(lat: 48.2, lon: 16.4, centerLat: 40, centerLon: 10)
let location = try #require(GlobeMath.unproject(x: p.x, y: p.y, centerLat: 40, centerLon: 10))
#expect(abs(location.lat - 48.2) < 1e-9)
#expect(abs(location.lon - 16.4) < 1e-9)
#expect(GlobeMath.unproject(x: 0.9, y: 0.9, centerLat: 0, centerLon: 0) == nil)
}
@Test func zoomForPrecisionStaysWithinInteractiveBounds() {
for precision in 1...GlobeMath.maxPrecision {
let zoom = GlobeMath.zoomForPrecision(precision, baseRadius: 400, screenMin: 900)
#expect(zoom >= GlobeMath.minZoom)
#expect(zoom <= GlobeMath.maxZoom)
}
}
/// The +/- buttons frame a precision; the pinch-driven precision must agree, or the
/// first pinch after a button tap would jump to another cell size.
@Test func autoPrecisionAgreesWithFramedPrecision() {
let base = 400.0, screen = 900.0
for precision in 2...GlobeMath.maxPrecision {
let zoom = GlobeMath.zoomForPrecision(precision, baseRadius: base, screenMin: screen)
guard zoom > GlobeMath.minZoom, zoom < GlobeMath.maxZoom else { continue }
#expect(GlobeMath.autoPrecision(globeRadius: base * zoom, screenMin: screen) == precision)
}
}
@Test func cellSpansMatchGeohashBounds() {
for precision in 1...8 {
let b = Geohash.decodeBounds(Geohash.encode(latitude: 10, longitude: 10, precision: precision))
#expect(abs((b.latMax - b.latMin) - GlobeMath.cellSpanLat(precision: precision)) < 1e-9)
#expect(abs((b.lonMax - b.lonMin) - GlobeMath.cellSpanLon(precision: precision)) < 1e-9)
}
}
}
struct GlobeGeometryTests {
private let square = [
GlobeGeometry.DiscPoint(x: -0.5, y: -0.5, front: true),
GlobeGeometry.DiscPoint(x: 0.5, y: -0.5, front: true),
GlobeGeometry.DiscPoint(x: 0.5, y: 0.5, front: true),
GlobeGeometry.DiscPoint(x: -0.5, y: 0.5, front: true)
]
@Test func closedFullyVisibleRingConnectsLastPointToFirst() throws {
let runs = GlobeGeometry.frontRuns(square, closed: true)
let run = try #require(runs.first)
#expect(runs.count == 1)
#expect(run.count == square.count + 1)
#expect(run.first == run.last)
}
@Test func openFullyVisibleLineDoesNotConnectLastPointToFirst() throws {
let runs = GlobeGeometry.frontRuns(square, closed: false)
let run = try #require(runs.first)
#expect(runs.count == 1)
#expect(run.count == square.count)
#expect(run.first != run.last)
}
@Test func ringCrossingTheLimbSplitsIntoFrontRuns() {
let pts = [
GlobeGeometry.DiscPoint(x: -0.5, y: 0, front: true),
GlobeGeometry.DiscPoint(x: 0, y: 0, front: true),
GlobeGeometry.DiscPoint(x: 0.5, y: 0, front: false),
GlobeGeometry.DiscPoint(x: 0.2, y: 0.2, front: true)
]
let runs = GlobeGeometry.frontRuns(pts, closed: false)
#expect(runs.count == 2)
#expect(runs.allSatisfy { $0.count >= 2 })
}
@Test func polygonContainsDistinguishesInsideAndOutsidePoints() {
let polygon = [CGPoint(x: -10, y: -10), CGPoint(x: 10, y: -10), CGPoint(x: 10, y: 10), CGPoint(x: -10, y: 10)]
#expect(GlobeGeometry.polygonContains(polygon, x: 0, y: 0))
#expect(!GlobeGeometry.polygonContains(polygon, x: 20, y: 0))
}
@Test func ringContainsDistinguishesInsideAndOutsideCoordinates() {
let ring = GlobeRing(lats: [-10, -10, 10, 10], lons: [-10, 10, 10, -10])
#expect(GlobeGeometry.ringContains(ring, lat: 0, lon: 0))
#expect(!GlobeGeometry.ringContains(ring, lat: 20, lon: 0))
}
@Test func ringContainsHandlesTheAntimeridian() {
let ring = GlobeRing(lats: [-10, -10, 10, 10], lons: [170, -170, -170, 170])
#expect(GlobeGeometry.ringContains(ring, lat: 0, lon: 180))
#expect(GlobeGeometry.ringContains(ring, lat: 0, lon: -175))
#expect(!GlobeGeometry.ringContains(ring, lat: 20, lon: 180))
#expect(!GlobeGeometry.ringContains(ring, lat: 0, lon: 0))
}
@Test func clipSegmentClampsToRect() throws {
let rect = GlobeGeometry.ClipRect(left: 0, top: 0, right: 10, bottom: 10)
let clipped = try #require(GlobeGeometry.clipSegment(CGPoint(x: -10, y: 5), CGPoint(x: 20, y: 5), to: rect))
#expect(clipped.0 == CGPoint(x: 0, y: 5))
#expect(clipped.1 == CGPoint(x: 10, y: 5))
#expect(GlobeGeometry.clipSegment(CGPoint(x: -10, y: -5), CGPoint(x: 20, y: -5), to: rect) == nil)
}
@Test func clipPolygonKeepsOnlyTheVisiblePart() {
let rect = GlobeGeometry.ClipRect(left: 0, top: 0, right: 10, bottom: 10)
let clipped = GlobeGeometry.clipPolygon(
[CGPoint(x: -5, y: -5), CGPoint(x: 15, y: -5), CGPoint(x: 15, y: 15), CGPoint(x: -5, y: 15)],
to: rect
)
#expect(clipped.count == 4)
#expect(clipped.allSatisfy { $0.x >= 0 && $0.x <= 10 && $0.y >= 0 && $0.y <= 10 })
}
@Test func smallVisibleRingIsNotInverted() {
let ring = GlobeRing(lats: [-10, -10, 10, 10], lons: [-10, 10, 10, -10])
let projector = GlobeMath.PreparedProjector(centerLat: 0, centerLon: 0)
let pts = ring.terms.map { terms -> GlobeGeometry.DiscPoint in
let p = projector.project(terms)
return GlobeGeometry.DiscPoint(x: p.x, y: p.y, front: p.cosC > 0.005)
}
let polygon = GlobeGeometry.fillPolygon(pts, cx: 100, cy: 100, r: 100)
#expect(!GlobeGeometry.projectedFillNeedsInversion(
polygon: polygon, ring: ring, cx: 100, cy: 100, r: 100, centerLat: 0, centerLon: 0
))
}
}
struct GlobeMotionDetailTests {
@Test func fullDetailPreservesAllGlobeFeatures() {
let detail = GlobeMotionDetail.full.frame
#expect(detail.landPointStride == 1)
#expect(detail.showBorders)
#expect(detail.showCityLabels)
}
@Test func balancedDetailPreservesOrientationAndSelection() {
let detail = GlobeMotionDetail.balanced.frame
#expect(detail.landPointStride == 2)
#expect(detail.showBorders)
#expect(!detail.showCityLabels)
}
@Test func fastDetailUsesMinimumMovingFrameWork() {
let detail = GlobeMotionDetail.fast.frame
#expect(detail.landPointStride == 2)
#expect(!detail.showBorders)
#expect(!detail.showCityLabels)
}
@Test func adaptiveDetailDegradesOnSlowFramesAndRecoversWithHysteresis() {
#expect(GlobeMotionDetail.full.next(averageFrameMillis: 24) == .balanced)
#expect(GlobeMotionDetail.balanced.next(averageFrameMillis: 32) == .fast)
#expect(GlobeMotionDetail.fast.next(averageFrameMillis: 17) == .balanced)
#expect(GlobeMotionDetail.balanced.next(averageFrameMillis: 17) == .full)
#expect(GlobeMotionDetail.balanced.next(averageFrameMillis: 20) == .balanced)
#expect(GlobeMotionDetail.full.next(averageFrameMillis: .nan) == .fast)
}
private func record(_ governor: inout GlobeMotionGovernor, frames: Int, millis: Double) -> [GlobeMotionDetail] {
(0..<frames).map { _ in
governor.recordFrame(millis: millis)
return governor.detail
}
}
/// Regression: dropping detail makes frames fast, and stepping back up mid-drag
/// made the grid, neighbor cells and labels flash on and off.
@Test func detailNeverStepsBackUpDuringOneMotion() {
var governor = GlobeMotionGovernor()
#expect(governor.detail == .full)
governor.beginSession()
#expect(governor.detail == .balanced)
var seen = record(&governor, frames: 8, millis: 33)
seen += record(&governor, frames: 64, millis: 8)
seen += record(&governor, frames: 8, millis: 33)
seen += record(&governor, frames: 64, millis: 8)
#expect(seen.contains(.fast))
// Monotonic: once a level is dropped it never returns within the session.
#expect(zip(seen, seen.dropFirst()).allSatisfy { $1 <= $0 })
governor.endSession()
#expect(governor.detail == .full)
}
@Test func smoothSessionsStartTheNextOneHigherUntilOneDegrades() {
var governor = GlobeMotionGovernor()
governor.beginSession()
_ = record(&governor, frames: 16, millis: 8)
governor.endSession()
governor.beginSession()
#expect(governor.detail == .full)
_ = record(&governor, frames: 8, millis: 26)
#expect(governor.detail == .balanced)
governor.endSession()
// Having failed once, later smooth sessions stop retrying the upgrade, so
// detail doesn't alternate from one gesture to the next.
for _ in 0..<3 {
governor.beginSession()
#expect(governor.detail == .balanced)
_ = record(&governor, frames: 16, millis: 8)
governor.endSession()
}
}
@Test func easingRunsFromZeroToOneMonotonically() {
#expect(GlobeEasing.fastOutSlowIn(0) == 0)
#expect(GlobeEasing.fastOutSlowIn(1) == 1)
var previous = 0.0
for step in 1...20 {
let value = GlobeEasing.fastOutSlowIn(Double(step) / 20)
#expect(value >= previous)
previous = value
}
#expect(GlobeEasing.fastOutSlowIn(0.5) > 0.7)
}
}
@MainActor
struct GlobeStateTests {
@Test func selectionFollowsTheViewCenterOnceLaidOut() {
let state = GlobeState(targetLat: 48.2, targetLon: 16.4, initialPrecision: 4, startZoomedOut: false)
#expect(state.selectedGeohash.isEmpty)
state.setViewport(baseRadius: 170, screenMin: 390)
#expect(state.selectedGeohash == Geohash.encode(latitude: 48.2, longitude: 16.4, precision: 4))
}
@Test func introWithoutAnimationJumpsStraightToTheTarget() {
let state = GlobeState(targetLat: 37.77, targetLon: -122.42, initialPrecision: 5, startZoomedOut: true)
state.setViewport(baseRadius: 170, screenMin: 390, animateIntro: false)
#expect(state.precision == 5)
#expect(state.selectedGeohash == Geohash.encode(latitude: 37.77, longitude: -122.42, precision: 5))
#expect(!state.isAnimating)
}
@Test func pinchingInRaisesPrecisionAndRotationClampsNearThePoles() {
let state = GlobeState(targetLat: 0, targetLon: 0, initialPrecision: 1, startZoomedOut: false)
state.setViewport(baseRadius: 170, screenMin: 390)
let before = state.precision
state.zoomBy(64)
#expect(state.precision > before)
state.rotateBy(dx: 0, dy: 1_000_000)
#expect(state.centerLat <= 89)
#expect(state.selectedGeohash.count == state.precision)
}
@Test func zoomStaysWithinBounds() {
let state = GlobeState(targetLat: 0, targetLon: 0, initialPrecision: 2, startZoomedOut: false)
state.setViewport(baseRadius: 170, screenMin: 390)
state.zoomBy(0.0001)
#expect(state.zoom == GlobeMath.minZoom)
state.zoomBy(1e12)
#expect(state.zoom == GlobeMath.maxZoom)
// Pinching tops out around block-sized cells; finer precision is button-only.
#expect(state.precision == GlobeMath.autoPrecision(globeRadius: state.globeRadius, screenMin: 390))
#expect(state.precision >= 7)
}
@Test func interactionCancelsAnimationsAndRestoresFullDetail() {
let state = GlobeState(targetLat: 0, targetLon: 0, initialPrecision: 2, startZoomedOut: false)
state.setViewport(baseRadius: 170, screenMin: 390)
state.animatePrecision(4)
#expect(state.isAnimating)
#expect(state.motionDetail == .balanced)
state.beginInteraction()
#expect(!state.isAnimating)
#expect(state.isInteracting)
state.endInteraction()
#expect(!state.isInMotion)
#expect(state.motionDetail == .full)
#expect(state.frameDetail == GlobeMotionDetail.full.frame)
}
@Test func releasingIntoAFlingKeepsTheSameMotionSession() {
let state = GlobeState(targetLat: 0, targetLon: 0, initialPrecision: 2, startZoomedOut: false)
state.setViewport(baseRadius: 170, screenMin: 390)
state.beginInteraction()
#expect(state.motionDetail == .balanced)
state.endInteraction(flingVelocityX: 800, flingVelocityY: 0)
#expect(!state.isInteracting)
#expect(state.isAnimating)
#expect(state.motionDetail == .balanced)
state.beginInteraction()
#expect(!state.isAnimating)
#expect(state.motionDetail == .balanced)
state.endInteraction()
#expect(state.motionDetail == .full)
}
/// Review regression (PR #1807): `zzzz`'s center is 89.91°, past the ±89° drag
/// limit. The animated intro used to clamp there and select `zzzf`, while the
/// Reduce Motion path kept `zzzz`.
@Test func polarIntroLandsOnTheRequestedCellWithAndWithoutAnimation() {
let target = GeohashPickerView.initialTarget(initialGeohash: "zzzz", nearbyGeohashes: [])
#expect(target.lat > 89)
let animated = GlobeState(targetLat: target.lat, targetLon: target.lon, initialPrecision: target.precision, startZoomedOut: true)
animated.setViewport(baseRadius: 170, screenMin: 390, animateIntro: true)
#expect(animated.isAnimating)
animated.tick(100)
animated.tick(110)
#expect(!animated.isAnimating)
#expect(animated.selectedGeohash == "zzzz")
let still = GlobeState(targetLat: target.lat, targetLon: target.lon, initialPrecision: target.precision, startZoomedOut: true)
still.setViewport(baseRadius: 170, screenMin: 390, animateIntro: false)
#expect(still.selectedGeohash == "zzzz")
#expect(still.centerLat == animated.centerLat)
}
@Test func draggingFromAPolarTargetNeverSnapsBackToTheDragLimit() {
let center = Geohash.decodeCenter("zzzz")
let state = GlobeState(targetLat: center.lat, targetLon: center.lon, initialPrecision: 4, startZoomedOut: false)
state.setViewport(baseRadius: 170, screenMin: 390)
let start = state.centerLat
state.rotateBy(dx: 0, dy: 50)
#expect(state.centerLat == start)
state.rotateBy(dx: 0, dy: -0.01)
#expect(state.centerLat < start)
#expect(state.centerLat > 89)
state.rotateBy(dx: 0, dy: -1_000_000)
#expect(state.centerLat == -89)
}
@Test func slowFlingsAreIgnored() {
let state = GlobeState(targetLat: 0, targetLon: 0, initialPrecision: 2, startZoomedOut: false)
state.setViewport(baseRadius: 170, screenMin: 390)
state.fling(vx: 10, vy: -10)
#expect(!state.isAnimating)
state.fling(vx: 800, vy: 0)
#expect(state.isAnimating)
state.cancelAnimations()
}
}
struct GlobeWorldDataTests {
private static let landURL = URL(fileURLWithPath: #filePath)
.deletingLastPathComponent()
.deletingLastPathComponent()
.appendingPathComponent("bitchat/Resources/Globe/world_land.geojson")
/// Regression: Eurasia wraps the antimeridian at Chukotka, and the old relative-
/// longitude test counted the ±180° seam as a crossing, so open ocean read as
/// inside Eurasia and its fill was flipped over the Pacific and Atlantic.
@Test func bundledLandClassifiesOceansAndContinents() throws {
let land = GlobeWorldData.parseLand(try Data(contentsOf: Self.landURL))
#expect(land.count > 100)
func isLand(_ lat: Double, _ lon: Double) -> Bool {
land.contains { GlobeGeometry.ringContains($0, lat: lat, lon: lon) }
}
for (lat, lon) in [(0.0, -150.0), (32.3, -64.8), (40.0, -50.0), (-30.0, 80.0), (10.0, -30.0), (60.0, -85.0)] {
#expect(!isLand(lat, lon), "ocean at \(lat),\(lon) read as land")
}
for (lat, lon) in [(55.75, 37.62), (64.7, 177.5), (39.9, 116.4), (39.0, -98.0), (-15.8, -47.9), (0.0, 20.0)] {
#expect(isLand(lat, lon), "land at \(lat),\(lon) read as ocean")
}
}
/// No visible ocean pixel may be painted by a land fill, from any vantage point.
@Test func landFillsLeaveVisibleOceanUncovered() throws {
let land = GlobeWorldData.parseLand(try Data(contentsOf: Self.landURL))
let size = CGSize(width: 402, height: 874)
let cx = 201.0, cy = 437.0
let clip = GlobeGeometry.ClipRect(size: size)
let oceans: [(Double, Double)] = [(32.3, -64.8), (40, -50), (30, -20), (0, -150), (-30, 80)]
for centerLat in stride(from: -60.0, through: 60, by: 30) {
for centerLon in stride(from: -180.0, to: 180, by: 30) {
for zoom in [1.0, 3, 8] {
let r = 0.44 * 402 * zoom
let projector = GlobeMath.PreparedProjector(centerLat: centerLat, centerLon: centerLon)
for ocean in oceans {
guard let p = GlobeMath.project(lat: ocean.0, lon: ocean.1, centerLat: centerLat, centerLon: centerLon),
(p.x * p.x + p.y * p.y).squareRoot() < 0.98 else { continue }
let point = CGPoint(x: cx + p.x * r, y: cy + p.y * r)
guard CGRect(origin: .zero, size: size).contains(point) else { continue }
for ring in land {
let projected = ring.terms.map { projector.project($0) }
guard projected.contains(where: { $0.cosC >= 0 }) else { continue }
let pts = projected.map { GlobeGeometry.DiscPoint(x: $0.x, y: $0.y, front: $0.cosC > 0.005) }
let polygon = GlobeGeometry.fillPolygon(pts, cx: cx, cy: cy, r: r)
let invert = projected.contains(where: { $0.cosC < 0 }) && GlobeGeometry.projectedFillNeedsInversion(
polygon: polygon, ring: ring, cx: cx, cy: cy, r: r, centerLat: centerLat, centerLon: centerLon
)
let clipped = GlobeGeometry.clipPolygon(polygon, to: clip)
guard clipped.count >= 3 else { continue }
let path = CGMutablePath()
if invert { path.addEllipse(in: CGRect(x: cx - r, y: cy - r, width: 2 * r, height: 2 * r)) }
path.addLines(between: clipped)
path.closeSubpath()
#expect(
!path.contains(point, using: invert ? .evenOdd : .winding),
"ocean \(ocean) painted as land viewing \(centerLat),\(centerLon) at zoom \(zoom)"
)
}
}
}
}
}
}
@Test func parsesPolygonsMultiPolygonsAndLines() {
let land = Data("""
{"type":"GeometryCollection","geometries":[
{"type":"Polygon","coordinates":[[[0,0],[10,0],[10,10],[0,0]]]},
{"type":"MultiPolygon","coordinates":[[[[20,20],[30,20],[30,30],[20,20]]],[[[1,1],[2,2]]]]}
]}
""".utf8)
let rings = GlobeWorldData.parseLand(land)
#expect(rings.count == 2)
// GeoJSON positions are [lon, lat].
#expect(rings[0].lons == [0, 10, 10, 0])
#expect(rings[0].lats == [0, 0, 10, 0])
#expect(rings[0].terms.count == rings[0].count)
let borders = Data("""
{"type":"GeometryCollection","geometries":[
{"type":"LineString","coordinates":[[0,0],[1,1]]},
{"type":"MultiLineString","coordinates":[[[2,2],[3,3],[4,4]],[[5,5]]]}
]}
""".utf8)
let lines = GlobeWorldData.parseBorders(borders)
#expect(lines.map(\.count) == [2, 3])
}
@Test func parsesCities() {
let cities = GlobeWorldData.parseCities(Data("""
{"cities":[{"n":"Vienna","r":1,"cap":1,"mega":0,"pop":1,"lon":16.37,"lat":48.2},{"n":"broken"}]}
""".utf8))
#expect(cities.count == 1)
#expect(cities[0].name == "Vienna")
#expect(cities[0].capital)
#expect(!cities[0].megacity)
#expect(abs(cities[0].terms.sinLat - sin(48.2 * .pi / 180)) < 1e-12)
#expect(abs(cities[0].terms.sinLon - sin(16.37 * .pi / 180)) < 1e-12)
}
}
@MainActor
struct GeohashPickerTargetTests {
@Test func prefersTheGivenGeohash() {
let target = GeohashPickerView.initialTarget(initialGeohash: "u2edk", nearbyGeohashes: ["u2"])
let center = Geohash.decodeCenter("u2edk")
#expect(target.lat == center.lat)
#expect(target.lon == center.lon)
#expect(target.precision == 5)
}
@Test func fallsBackToTheCoarsestNearbyChannel() {
let target = GeohashPickerView.initialTarget(initialGeohash: "", nearbyGeohashes: ["u2edk", "u2e", "u2edk7q"])
#expect(target.precision == 3)
#expect(target.lat == Geohash.decodeCenter("u2e").lat)
}
@Test func defaultsToAWideWorldView() {
let target = GeohashPickerView.initialTarget(initialGeohash: nil, nearbyGeohashes: [])
#expect(target.lat == 20)
#expect(target.lon == 0)
#expect(target.precision == 2)
}
@Test func coverageMatchesTheChannelLevels() {
#expect(GeohashCoverage.level(forLength: 1) == .region)
#expect(GeohashCoverage.level(forLength: 4) == .province)
#expect(GeohashCoverage.level(forLength: 5) == .city)
#expect(GeohashCoverage.level(forLength: 12) == .building)
#expect(GeohashCoverage.string(forPrecision: 5, locale: Locale(identifier: "de_DE")) == "~4.9 km")
#expect(GeohashCoverage.string(forPrecision: 2, locale: Locale(identifier: "en_US")) == "~777 mi")
}
}

View File

@ -16,11 +16,15 @@ struct LocalizationCoverageTests {
var allLocales: Set<String> { coverage.values.reduce(into: []) { $0.formUnion($1) } }
}
private static func loadCatalog(_ relativePath: String) throws -> Catalog {
let url = repoRoot.appendingPathComponent(relativePath)
let data = try Data(contentsOf: url)
/// The catalog's `strings` table: key -> entry.
private static func loadStrings(_ relativePath: String) throws -> [String: Any] {
let data = try Data(contentsOf: repoRoot.appendingPathComponent(relativePath))
let root = try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any])
let strings = try #require(root["strings"] as? [String: Any])
return try #require(root["strings"] as? [String: Any])
}
private static func loadCatalog(_ relativePath: String) throws -> Catalog {
let strings = try loadStrings(relativePath)
var coverage: [String: Set<String>] = [:]
for (key, value) in strings {
@ -70,6 +74,59 @@ struct LocalizationCoverageTests {
#expect(missing.isEmpty, "share extension is missing locales: \(missing.joined(separator: ", "))")
}
/// SwiftPM's default build system on Swift 6.4+ (swiftbuild) generates a
/// Swift symbol for every manually managed catalog key, and fails the
/// whole build on a key it cannot name ("%@", "#%@", "%lld/%lld"). CI may
/// still run the native build system, which never generates symbols, so
/// check the rule here rather than wait for the runner image to move.
/// This covers nameability only: the tool also fails on two manual keys
/// that generate the same symbol ("1" and "_1") and on skipped positional
/// arguments ("%1$@ %3$@"), which this does not check.
@Test func everyManualKeyCanDeriveAGeneratedSymbol() throws {
for path in [Self.mainCatalogPath, Self.shareExtensionCatalogPath] {
let unnameable = try Self.loadStrings(path).compactMap { key, value -> String? in
guard (value as? [String: Any])?["extractionState"] as? String == "manual" else { return nil }
return Self.canDeriveSymbol(from: key) ? nil : key
}.sorted()
#expect(
unnameable.isEmpty,
"""
manual keys in \(path) that string catalog symbol generation \
cannot name, which breaks `swift build`: \(unnameable). Use \
Text(verbatim:) at the call site, or give the key a name.
"""
)
}
}
/// Mirrors `xcstringstool generate-symbols`: printf-style format specifiers
/// split the key into words, and a character (grapheme cluster) can only
/// be part of the symbol name if every scalar in it can be part of a Swift
/// identifier. This approximates that, erring towards rejection, with
/// letters, numbers, marks, `_`, `$`, the joiners ZWJ and ZWNJ, and emoji
/// outside the Basic Multilingual Plane. So 🔒, 👋🏽 and 🧑‍🎄 count, but BMP
/// emoji (✅ ⚡ ❤️) and sequences built on one (🏃‍♂️ ✌🏽) do not.
private static func canDeriveSymbol(from key: String) -> Bool {
let words = key.replacingOccurrences(
of: #"%(\d+\$)?[-+0]*\d*(\.\d+)?(hh|h|ll|l|q|L|z|t|j)?[@dDiuUxXoOfFeEgGcCsSpaA]|%%"#,
with: " ",
options: .regularExpression
)
return words.contains { character in
character.unicodeScalars.allSatisfy { scalar in
switch scalar.properties.generalCategory {
case .uppercaseLetter, .lowercaseLetter, .titlecaseLetter, .modifierLetter, .otherLetter,
.decimalNumber, .letterNumber, .otherNumber,
.nonspacingMark, .spacingMark, .enclosingMark:
return true
default:
return scalar == "_" || scalar == "$" || scalar == "\u{200C}" || scalar == "\u{200D}"
|| (scalar.value >= 0x10000 && scalar.properties.isEmoji)
}
}
}
}
/// The catalog tests above validate the CATALOG; this one validates the
/// CODE. A `String(localized:)` whose key is absent from the catalog its
/// target actually ships compiles and runs fine — it just silently ships

View File

@ -0,0 +1,44 @@
//
// LocationPresenceStoreTests.swift
// bitchatTests
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import Combine
import Testing
@testable import bitchat
@MainActor
struct LocationPresenceStoreTests {
@Test func setNickname_reportsWhetherTheNameChanged() {
let store = LocationPresenceStore()
#expect(store.setNickname("alice", for: "AA") == true)
// Chat events repeat the sender's nickname every time.
#expect(store.setNickname("alice", for: "aa") == false)
#expect(store.setNickname("alicia", for: "aa") == true)
#expect(store.geoNicknames["aa"] == "alicia")
}
/// Every write republishes, and the people list rebuilds on these
/// publishers, so pruning that removes nothing must not write.
@Test func pruningThatRemovesNothingDoesNotRepublish() {
let store = LocationPresenceStore()
store.markTeleported("aa")
store.setNickname("alice", for: "aa")
var changes = 0
let cancellable = store.objectWillChange.sink { _ in changes += 1 }
store.retainTeleportedGeo(keeping: ["aa", "bb"])
store.clearTeleported("cc")
#expect(changes == 0)
store.retainTeleportedGeo(keeping: ["bb"])
#expect(changes == 1)
#expect(store.teleportedGeo.isEmpty)
_ = cancellable
}
}

View File

@ -332,6 +332,40 @@ struct MessageFormattingEngineTests {
#expect(content.isLongForDisplay())
}
@Test func contentScan_matchesTheStringScansAndIsCachedOnTheMessage() {
let cashu = "cashuA" + String(repeating: "a", count: 40)
let invoice = "lnbc1" + String(repeating: "q", count: 60)
let long = String(repeating: "a", count: TransportConfig.uiLongMessageLengthThreshold + 1)
let contents = [
"plain words",
"pay \(cashu) or lightning:\(invoice) or \(invoice)",
"\(long) \(cashu)",
"same \(cashu) twice \(cashu)"
]
for content in contents {
let message = BitchatMessage(sender: "alice", content: content, timestamp: Date(), isRelay: false)
#expect(message.getCachedContentScan() == nil)
let scan = message.contentScan
#expect(scan.cashuLinks == content.extractCashuLinks())
#expect(scan.lightningLinks == content.extractLightningLinks())
#expect(scan.isLongForDisplay == content.isLongForDisplay())
#expect(message.getCachedContentScan() == scan)
}
}
@Test func contentScan_servesTheCachedScanWithoutRescanning() {
let cashu = "cashuA" + String(repeating: "a", count: 40)
let message = BitchatMessage(sender: "alice", content: "pay \(cashu)", timestamp: Date(), isRelay: false)
// A sentinel no scan of this content could produce.
let sentinel = BitchatMessage.ContentScan(cashuLinks: [], lightningLinks: ["lightning:sentinel"], isLongForDisplay: true)
message.setCachedContentScan(sentinel)
#expect(message.contentScan == sentinel)
}
@MainActor
@Test func formatMessage_longCashuMessageFallsBackToPlainContentPath() {
let context = MockMessageFormattingContext(nickname: "carol")

View File

@ -0,0 +1,400 @@
//
// MessageListScrollPolicyTests.swift
// bitchatTests
//
// The pure rules behind MessageListView's scroll position: appended-message
// counting (including at the store cap, where the count stops moving), the
// window size that keeps a scrolled-up reader's first row in place, the
// reaction to a timeline change (land, follow, keep position, hold), which
// row callbacks count, and the gates on expansion and follow-scrolls.
//
import BitFoundation
import Foundation
import Testing
@testable import bitchat
private typealias Policy = MessageListScrollPolicy
private let baseDate = Date(timeIntervalSince1970: 1_700_000_000)
private func message(_ index: Int, sender: String = "alice", content: String? = nil, at timestamp: Double? = nil) -> BitchatMessage {
BitchatMessage(
id: "m\(index)",
sender: sender,
content: content ?? "message \(index)",
timestamp: baseDate.addingTimeInterval(timestamp ?? Double(index)),
isRelay: false
)
}
private func timeline(_ range: Range<Int>) -> [BitchatMessage] {
range.map { message($0) }
}
/// Inserts a late message (older timestamp) just before `index`.
private func inserting(_ late: BitchatMessage, before index: Int, in messages: [BitchatMessage]) -> [BitchatMessage] {
var copy = messages
copy.insert(late, at: index)
return copy
}
struct MessageListScrollPolicyTests {
// MARK: - Timeline marks
@Test
func timelineMark_recordsTheNewestMessageAndTheWindowsFirstRow() {
let messages = timeline(0..<10)
let mark = Policy.TimelineMark(contextKey: "mesh", messages: messages, windowCount: 4)
#expect(mark.newestMessageID == "m9")
#expect(mark.newestTimestamp == messages[9].timestamp)
#expect(mark.windowFirstMessageID == "m6")
#expect(mark.windowCount == 4)
// A window wider than the timeline starts at its oldest message.
#expect(Policy.TimelineMark(contextKey: "mesh", messages: messages, windowCount: 300).windowFirstMessageID == "m0")
// An empty timeline marks nothing.
let empty = Policy.TimelineMark(contextKey: "mesh", messages: [], windowCount: 300)
#expect(empty.newestMessageID == nil)
#expect(empty.windowFirstMessageID == nil)
}
@Test
func timelineMark_withWindowCountRetakesOnlyTheWindow() {
let messages = timeline(0..<10)
let mark = Policy.TimelineMark(contextKey: "geo:u4pruy", messages: Array(messages.prefix(8)), windowCount: 4)
let expanded = mark.withWindowCount(7, in: messages)
#expect(expanded.contextKey == "geo:u4pruy")
// What was seen stays as it was; the window is re-taken.
#expect(expanded.newestMessageID == "m7")
#expect(expanded.windowFirstMessageID == "m3")
#expect(expanded.windowCount == 7)
}
// MARK: - Appended messages
@Test
func appended_countsOnlyMessagesAfterTheMarkedNewest() {
let mark = Policy.TimelineMark(contextKey: "mesh", messages: timeline(0..<6), windowCount: 300)
var messages = timeline(0..<9)
messages.append(message(9, sender: "system"))
messages.append(message(10, content: " "))
let appended = Policy.appended(since: mark, in: messages)
// m6, m7, m8, a system line and a whitespace-only message landed; the
// pill counts only the three human messages.
#expect(appended == Policy.Appended(total: 5, unseen: 3))
}
@Test
func appended_countsEverythingWhenTheTimelineWasEmpty() {
let mark = Policy.TimelineMark(contextKey: "mesh", messages: [], windowCount: 300)
#expect(Policy.appended(since: mark, in: timeline(0..<3)) == Policy.Appended(total: 3, unseen: 3))
#expect(Policy.appended(since: mark, in: []) == Policy.Appended())
}
@Test
func appended_keepsCountingAtTheStoreCap() {
// At the cap every append evicts the oldest message: the count never
// moves, but the appended messages are still found after the newest.
let capped = timeline(0..<10)
let mark = Policy.TimelineMark(contextKey: "mesh", messages: capped, windowCount: 300)
let afterThreeAppends = timeline(3..<13)
#expect(afterThreeAppends.count == capped.count)
#expect(Policy.appended(since: mark, in: afterThreeAppends) == Policy.Appended(total: 3, unseen: 3))
}
@Test
func appended_doesNotCountLateMessagesLandingAboveTheNewest() {
let messages = timeline(0..<10)
let mark = Policy.TimelineMark(contextKey: "mesh", messages: messages, windowCount: 300)
let late = message(100, at: 7.5)
let withLate = inserting(late, before: 8, in: messages)
#expect(Policy.appended(since: mark, in: withLate) == Policy.Appended())
}
@Test
func appended_fallsBackToTimestampsWhenTheNewestIsGone() {
let mark = Policy.TimelineMark(contextKey: "mesh", messages: timeline(0..<10), windowCount: 300)
// The newest seen message was removed (e.g. a block purge); two
// newer ones landed since.
let removedNewest = timeline(0..<9) + timeline(10..<12)
#expect(Policy.appended(since: mark, in: removedNewest) == Policy.Appended(total: 2, unseen: 2))
// A burst larger than the cap evicted it: everything left is newer.
let evictedNewest = timeline(20..<30)
#expect(Policy.appended(since: mark, in: evictedNewest) == Policy.Appended(total: 10, unseen: 10))
}
// MARK: - Window growth
@Test
func windowCountKeepingFirstRow_growsOverMessagesAppendedBelowIt() {
let messages = timeline(0..<20)
let mark = Policy.TimelineMark(contextKey: "mesh", messages: messages, windowCount: 10)
let grown = Policy.windowCountKeepingFirstRow(
current: 10,
mark: mark,
appendedCount: 0,
in: messages + timeline(20..<23)
)
#expect(grown == 13)
#expect((messages + timeline(20..<23)).suffix(grown).first?.id == "m10")
}
@Test
func windowCountKeepingFirstRow_absorbsLateMessagesInsertedBelowIt() {
let messages = timeline(0..<20)
let mark = Policy.TimelineMark(contextKey: "mesh", messages: messages, windowCount: 10)
// Below the first row: the window grows to keep it.
let lateInside = inserting(message(100, at: 15.5), before: 16, in: messages)
#expect(Policy.windowCountKeepingFirstRow(current: 10, mark: mark, appendedCount: 0, in: lateInside) == 11)
// Above the first row: the suffix already keeps it.
let lateAbove = inserting(message(101, at: 4.5), before: 5, in: messages)
#expect(Policy.windowCountKeepingFirstRow(current: 10, mark: mark, appendedCount: 0, in: lateAbove) == 10)
}
@Test
func windowCountKeepingFirstRow_keepsTheFirstRowAtTheStoreCap() {
let capped = timeline(0..<20)
let mark = Policy.TimelineMark(contextKey: "mesh", messages: capped, windowCount: 10)
// Two appends, two head evictions: same count, first row two places up.
let afterTwoAppends = timeline(2..<22)
let grown = Policy.windowCountKeepingFirstRow(current: 10, mark: mark, appendedCount: 2, in: afterTwoAppends)
#expect(grown == 12)
#expect(afterTwoAppends.suffix(grown).first?.id == "m10")
}
@Test
func windowCountKeepingFirstRow_growsByTheAppendedCountWithoutAUsableMark() {
let messages = timeline(0..<30)
// No mark (fresh context): grow by what was appended.
#expect(Policy.windowCountKeepingFirstRow(current: 10, mark: nil, appendedCount: 3, in: messages) == 13)
// A mark taken at another window size (the window was expanded since).
let stale = Policy.TimelineMark(contextKey: "mesh", messages: timeline(0..<27), windowCount: 8)
#expect(Policy.windowCountKeepingFirstRow(current: 10, mark: stale, appendedCount: 3, in: messages) == 13)
// The first row itself is gone (removed or evicted).
let mark = Policy.TimelineMark(contextKey: "mesh", messages: timeline(0..<27), windowCount: 10)
let withoutFirstRow = messages.filter { $0.id != "m17" }
#expect(Policy.windowCountKeepingFirstRow(current: 10, mark: mark, appendedCount: 3, in: withoutFirstRow) == 13)
// Nothing appended and nothing to hold: the window stays.
#expect(Policy.windowCountKeepingFirstRow(current: 10, mark: nil, appendedCount: 0, in: messages) == 10)
}
@Test
func windowCountKeepingFirstRow_neverShrinksNorOutgrowsTheTimeline() {
// A timeline shorter than the window keeps the window size.
let short = timeline(0..<5)
let shortMark = Policy.TimelineMark(contextKey: "mesh", messages: short, windowCount: 300)
#expect(Policy.windowCountKeepingFirstRow(current: 300, mark: shortMark, appendedCount: 2, in: short + timeline(5..<7)) == 300)
// Growth stops at the timeline's length.
let messages = timeline(0..<12)
#expect(Policy.windowCountKeepingFirstRow(current: 10, mark: nil, appendedCount: 50, in: messages) == 12)
// Removals below the first row never shrink the window.
let mark = Policy.TimelineMark(contextKey: "mesh", messages: messages, windowCount: 10)
let removedBelow = messages.filter { $0.id != "m9" && $0.id != "m10" }
#expect(Policy.windowCountKeepingFirstRow(current: 10, mark: mark, appendedCount: 0, in: removedBelow) == 10)
}
// MARK: - Gates
@Test
func canExpandWindow_waitsForTheRestoreAndForTheBottomOfThisContext() {
#expect(Policy.canExpandWindow(isRestoringExpansion: false, bottomSettledContextKey: "mesh", contextKey: "mesh"))
// A previous expansion's position restore is still queued.
#expect(!Policy.canExpandWindow(isRestoringExpansion: true, bottomSettledContextKey: "mesh", contextKey: "mesh"))
// The initial scroll to the bottom has not landed yet.
#expect(!Policy.canExpandWindow(isRestoringExpansion: false, bottomSettledContextKey: nil, contextKey: "mesh"))
// It landed in another conversation.
#expect(!Policy.canExpandWindow(isRestoringExpansion: false, bottomSettledContextKey: "geo:u4pruy", contextKey: "mesh"))
}
@Test
func shouldRunDeferredFollowScroll_requiresTheBottomOfTheSameTimeline() {
#expect(Policy.shouldRunDeferredFollowScroll(isAtBottom: true, scheduledContextKey: "mesh", currentContextKey: "mesh"))
// The reader dragged away while the timer was held back.
#expect(!Policy.shouldRunDeferredFollowScroll(isAtBottom: false, scheduledContextKey: "mesh", currentContextKey: "mesh"))
// The timeline was switched before the timer fired.
#expect(!Policy.shouldRunDeferredFollowScroll(isAtBottom: true, scheduledContextKey: "mesh", currentContextKey: "geo:u4pruy"))
}
@Test
func needsScroll_skipsTheBottomRetryOnceTheNewestRowIsOnScreen() {
#expect(Policy.needsScroll(toNewestRowID: "mesh|m9", bottomRowID: "mesh|m8"))
#expect(Policy.needsScroll(toNewestRowID: "mesh|m9", bottomRowID: nil))
// The first scroll landed: the retry would be a queued no-op.
#expect(!Policy.needsScroll(toNewestRowID: "mesh|m9", bottomRowID: "mesh|m9"))
// No row to scroll to.
#expect(!Policy.needsScroll(toNewestRowID: nil, bottomRowID: nil))
}
// MARK: - Row callbacks
@Test
func isRow_matchesOnlyRowsOfItsOwnContext() {
#expect(Policy.isRow("mesh|m1", inContext: "mesh"))
#expect(Policy.isRow("geo:u4pruy|m1", inContext: "geo:u4pruy"))
#expect(Policy.isRow("dm:0011223344556677|m1", inContext: "dm:0011223344556677"))
// The old timeline's rows after a switch.
#expect(!Policy.isRow("geo:u4pruy|m1", inContext: "mesh"))
#expect(!Policy.isRow("dm:aaaa|m1", inContext: "dm:bbbb"))
// A context that is a prefix of another is not that context.
#expect(!Policy.isRow("geo:u4pruyd|m1", inContext: "geo:u4pruy"))
#expect(!Policy.isRow("mesh", inContext: "mesh"))
}
// MARK: - Reactions
private func reaction(
mark: Policy.TimelineMark?,
_ messages: [BitchatMessage],
newestIsOwn: Bool = false,
appended: Int = 0,
windowCount: Int = 10,
isAtBottom: Bool
) -> Policy.TimelineReaction {
Policy.reaction(
mark: mark,
messages: messages,
newestIsOwn: newestIsOwn,
appendedCount: appended,
windowCount: windowCount,
isAtBottom: isAtBottom
)
}
@Test
func reaction_landsInATimelineWithoutAMarkInItsContext() {
// A channel or DM switch: whatever isAtBottom says (the old
// timeline's rows report on their way out), the list lands.
#expect(reaction(mark: nil, timeline(0..<10), isAtBottom: false) == .land)
#expect(reaction(mark: nil, timeline(0..<10), newestIsOwn: true, isAtBottom: true) == .land)
// Even into an empty timeline.
#expect(reaction(mark: nil, [], isAtBottom: false) == .land)
}
@Test
func reaction_followsAtTheBottomWheneverTheRenderedRowsMayHaveMoved() {
let messages = timeline(0..<20)
let mark = Policy.TimelineMark(contextKey: "mesh", messages: messages, windowCount: 10)
// Appended below the bottom.
#expect(reaction(mark: mark, messages + timeline(20..<22), appended: 2, isAtBottom: true) == .follow)
// A late message landing among the visible rows pushes the newest one
// down: nothing was appended, but the bottom moved.
let lateAmongVisibleRows = inserting(message(100, at: 18.5), before: 19, in: messages)
#expect(reaction(mark: mark, lateAmongVisibleRows, isAtBottom: true) == .follow)
// A removal changes the rows too.
#expect(reaction(mark: mark, messages.filter { $0.id != "m15" }, isAtBottom: true) == .follow)
}
@Test
func reaction_holdsAtTheBottomWhenTheRenderedRowsAreUnchanged() {
// At the store cap a late message landing above the window evicts the
// oldest message, also above it: the rendered rows are the same, and
// a scroll would be a queued no-op that snaps the next drag back.
let capped = timeline(0..<20)
let mark = Policy.TimelineMark(contextKey: "mesh", messages: capped, windowCount: 10)
let lateAboveTheWindow = Array(inserting(message(100, at: 4.5), before: 5, in: capped).dropFirst())
#expect(reaction(mark: mark, lateAboveTheWindow, isAtBottom: true) == .hold)
}
@Test
func reaction_keepsAScrolledUpReaderInPlace() {
let messages = timeline(0..<10)
let mark = Policy.TimelineMark(contextKey: "mesh", messages: messages, windowCount: 300)
#expect(reaction(mark: mark, messages + timeline(10..<13), appended: 3, isAtBottom: false) == .keepPosition)
#expect(reaction(mark: mark, messages, isAtBottom: false) == .keepPosition)
}
@Test
func reaction_followsTheReadersOwnNewMessageFromAnywhere() {
let messages = timeline(0..<10)
let mark = Policy.TimelineMark(contextKey: "mesh", messages: messages, windowCount: 300)
#expect(reaction(mark: mark, messages + [message(10)], newestIsOwn: true, appended: 1, isAtBottom: false) == .follow)
// A message of mine that was already the newest (m9) does not pull a
// scrolled-up reader down when late messages land above it.
let lateAboveMine = inserting(message(100, at: 7.5), before: 8, in: messages)
#expect(reaction(mark: mark, lateAboveMine, newestIsOwn: true, isAtBottom: false) == .keepPosition)
}
@Test
func reaction_followsOnlyAMessageOfMineThatLandedSinceTheMark() {
// m8 is mine; m9 after it, the newest seen, is a bridge alias.
let messages = timeline(0..<10)
let mark = Policy.TimelineMark(contextKey: "mesh", messages: messages, windowCount: 300)
// The radio copy retracts the alias a batch before it lands itself:
// m8 is the newest again, but nothing landed since the mark.
let retracted = Array(messages.dropLast())
let appended = Policy.appended(since: mark, in: retracted)
#expect(appended == Policy.Appended())
#expect(reaction(mark: mark, retracted, newestIsOwn: true, appended: appended.total, isAtBottom: false) == .keepPosition)
// At the bottom the removal still moves the rows.
#expect(reaction(mark: mark, retracted, newestIsOwn: true, appended: appended.total, windowCount: 300, isAtBottom: true) == .follow)
// A message of mine landing in the same change is new.
let retractedWithMine = retracted + [message(10)]
let appendedWithMine = Policy.appended(since: mark, in: retractedWithMine)
#expect(appendedWithMine == Policy.Appended(total: 1, unseen: 1))
#expect(reaction(mark: mark, retractedWithMine, newestIsOwn: true, appended: appendedWithMine.total, isAtBottom: false) == .follow)
}
@Test
func reaction_holdsWhenTheTimelineEmptied() {
let mark = Policy.TimelineMark(contextKey: "mesh", messages: timeline(0..<10), windowCount: 300)
#expect(reaction(mark: mark, [], isAtBottom: false) == .hold)
#expect(reaction(mark: mark, [], isAtBottom: true) == .hold)
}
@Test
func isRenderedWindowUnchanged_onlyForAFullWindowOfTheSameRows() {
let capped = timeline(0..<20)
let mark = Policy.TimelineMark(contextKey: "mesh", messages: capped, windowCount: 10)
func isUnchanged(_ messages: [BitchatMessage], appended: Int = 0, windowCount: Int = 10) -> Bool {
Policy.isRenderedWindowUnchanged(since: mark, appendedCount: appended, windowCount: windowCount, in: messages)
}
// Late message above the window at the cap (the oldest evicted).
#expect(isUnchanged(Array(inserting(message(100, at: 4.5), before: 5, in: capped).dropFirst())))
// Late message inside the window at the cap: its first row moves.
#expect(!isUnchanged(Array(inserting(message(101, at: 14.5), before: 15, in: capped).dropFirst())))
// Below the cap any insert changes the count.
#expect(!isUnchanged(inserting(message(102, at: 4.5), before: 5, in: capped)))
// Something appended.
#expect(!isUnchanged(Array((capped + [message(20)]).dropFirst()), appended: 1))
// The window was resized since the mark.
#expect(!isUnchanged(capped, windowCount: 12))
// A timeline shorter than its window renders every message.
let short = timeline(0..<5)
let shortMark = Policy.TimelineMark(contextKey: "mesh", messages: short, windowCount: 10)
#expect(!Policy.isRenderedWindowUnchanged(since: shortMark, appendedCount: 0, windowCount: 10, in: short))
}
}

View File

@ -0,0 +1,113 @@
//
// PeerListModelTests.swift
// bitchatTests
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import BitFoundation
import Combine
import Foundation
import Testing
@testable import bitchat
@MainActor
struct PeerListModelTests {
/// Every @Published write re-renders every view observing the model
/// (root view, header, open people sheet), so a refresh trigger that
/// leaves the rows as they were must not write anything.
@Test func refreshThatChangesNothingDoesNotRepublish() async {
let viewModel = makeViewModel()
let model = PeerListModel(
chatViewModel: viewModel,
conversations: viewModel.conversations,
locationChannelsModel: LocationChannelsModel(manager: makeLocationManager())
)
await drainMainQueue()
var changes = 0
let cancellable = model.objectWillChange.sink { _ in changes += 1 }
let roster = viewModel.allPeers
for _ in 0..<5 {
NotificationCenter.default.post(name: Notification.Name("peerStatusUpdated"), object: nil)
// Every mesh snapshot republishes the roster, usually unchanged.
viewModel.allPeers = roster
}
await drainMainQueue()
#expect(changes == 0)
_ = cancellable
}
/// `BitchatPeer.==` compares only peer IDs, so a roster in which someone
/// changed name, connection or favorite compares equal to the previous
/// one. Their row must still be rebuilt from it.
@Test func rosterChangeWithTheSameIDsUpdatesTheRow() async throws {
let transport = MockTransport()
let viewModel = makeViewModel(transport: transport)
let model = PeerListModel(
chatViewModel: viewModel,
conversations: viewModel.conversations,
locationChannelsModel: LocationChannelsModel(manager: makeLocationManager())
)
let peerID = PeerID(str: "00000000000000c7")
let noiseKey = Data(repeating: 0xC7, count: 32)
func snapshots(nickname: String) -> [TransportPeerSnapshot] {
[TransportPeerSnapshot(
peerID: peerID,
nickname: nickname,
isConnected: true,
noisePublicKey: noiseKey,
lastSeen: Date()
)]
}
// Through the transport rather than assigning `viewModel.allPeers`:
// anything else that rebuilds the roster (a favorites change from a
// parallel test) then yields these same peers.
transport.updatePeerSnapshots(snapshots(nickname: "alice"))
let listed = await TestHelpers.waitUntil({
model.meshRows.contains { $0.peerID == peerID && $0.displayName == "alice" }
}, timeout: TestConstants.settleTimeout)
try #require(listed)
// Same peer, same place in the roster, new name.
transport.updatePeerSnapshots(snapshots(nickname: "alicia"))
let renamed = await TestHelpers.waitUntil({
model.meshRows.contains { $0.peerID == peerID && $0.displayName == "alicia" }
}, timeout: TestConstants.settleTimeout)
#expect(renamed)
}
// MARK: - Helpers
private func makeViewModel(transport: MockTransport = MockTransport()) -> ChatViewModel {
let keychain = MockKeychain()
return ChatViewModel(
keychain: keychain,
idBridge: NostrIdentityBridge(keychain: MockKeychainHelper()),
identityManager: MockIdentityManager(keychain),
transport: transport,
locationManager: makeLocationManager()
)
}
private func makeLocationManager() -> LocationChannelManager {
let suiteName = "PeerListModelTests.\(UUID().uuidString)"
let storage = UserDefaults(suiteName: suiteName) ?? .standard
storage.removePersistentDomain(forName: suiteName)
return LocationChannelManager(storage: storage)
}
/// The model's triggers hop to the main queue and then coalesce onto one
/// more hop, so let a few main-queue turns run.
private func drainMainQueue() async {
for _ in 0..<4 {
await withCheckedContinuation { continuation in
DispatchQueue.main.async { continuation.resume() }
}
}
}
}

View File

@ -0,0 +1,44 @@
//
// PeopleListOrderingTests.swift
// bitchatTests
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import Testing
@testable import bitchat
struct PeopleListOrderingTests {
@Test func firstLayoutUsesProducerOrder() {
let order = PeopleListOrdering.stableOrder(previous: [], current: ["c", "a", "b"])
#expect(order == ["c", "a", "b"])
}
@Test func shownRowsKeepTheirPlaceWhenTheProducerReorders() {
// A heartbeat moved "b" to the front of the recency-sorted roster;
// the open list must not reshuffle under the reader.
let order = PeopleListOrdering.stableOrder(previous: ["a", "b", "c"], current: ["b", "c", "a"])
#expect(order == ["a", "b", "c"])
}
@Test func newcomersAppendInProducerOrder() {
let order = PeopleListOrdering.stableOrder(previous: ["a", "b"], current: ["e", "b", "d", "a"])
#expect(order == ["a", "b", "e", "d"])
}
@Test func departuresDropOut() {
let order = PeopleListOrdering.stableOrder(previous: ["a", "b", "c"], current: ["c", "a"])
#expect(order == ["a", "c"])
}
@Test func duplicateIDsCollapseToTheFirstOccurrence() {
let order = PeopleListOrdering.stableOrder(previous: ["a", "a"], current: ["b", "a", "b"])
#expect(order == ["a", "b"])
}
@Test func emptyRosterClearsTheOrder() {
#expect(PeopleListOrdering.stableOrder(previous: ["a", "b"], current: []).isEmpty)
}
}

View File

@ -0,0 +1,185 @@
//
// PerformanceBaselineTests+Geochat.swift
// bitchatTests
//
// Geochat (location channel) benchmarks at a busy-room size. Each guards a
// cost that used to grow with the number of participants N:
//
// - the people sheet resolved every row's color by rebuilding the whole
// roster, so one render was O(N^2);
// - every roster rebuild hex-encoded our own key once per participant with
// String(format:) per byte;
// - every inbound event (presence heartbeats arrive ~N/60 times a second)
// rebuilt and republished the roster.
//
// perf-floors.json keeps each floor far above those regression values.
//
import XCTest
import BitFoundation
@testable import bitchat
extension PerformanceBaselineTests {
/// The room size at which the regressions above cost seconds.
private static let geochatParticipants = 500
// MARK: - Geochat people list colors
/// One people-sheet render resolves a color for every row.
func testGeochatPeopleListColors() {
let fixture = GeochatPerfFixture(participants: Self.geochatParticipants)
let pubkeys = fixture.pubkeys
var samples: [TimeInterval] = []
measure {
let start = Date()
for pubkey in pubkeys {
_ = fixture.viewModel.colorForNostrPubkey(pubkey, isDark: true)
}
samples.append(Date().timeIntervalSince(start))
}
reportThroughput("geochat.peopleListColors", samples: samples, operations: pubkeys.count, unit: "rows")
}
// MARK: - Geochat participant heartbeats
/// Presence heartbeats and messages from people already in the room.
func testGeochatParticipantHeartbeats() {
let fixture = GeochatPerfFixture(participants: Self.geochatParticipants)
let tracker = fixture.viewModel.participantTracker
let pubkeys = fixture.pubkeys
let events = 2_000
var samples: [TimeInterval] = []
measure {
let start = Date()
for index in 0..<events {
tracker.recordParticipant(pubkeyHex: pubkeys[index % pubkeys.count], geohash: GeochatPerfFixture.geohash)
}
samples.append(Date().timeIntervalSince(start))
}
XCTAssertEqual(tracker.visiblePeople.count, pubkeys.count)
reportThroughput("geochat.participantHeartbeat", samples: samples, operations: events, unit: "events")
}
// MARK: - Geochat message formatting
/// First render of new geochat messages (formatting cache miss), whose
/// sender color comes from the roster palette.
func testGeochatFormatNewMessages() {
let fixture = GeochatPerfFixture(participants: Self.geochatParticipants)
let batchCount = 16 // > XCTest's default 10 measure iterations
let batchSize = 200
let batches: [[BitchatMessage]] = (0..<batchCount).map { batch in
(0..<batchSize).map { index in
let pubkey = fixture.pubkeys[(batch * batchSize + index) % fixture.pubkeys.count]
return BitchatMessage(
id: "geo-fmt-\(batch)-\(index)",
sender: "peer\(index)#\(pubkey.suffix(4))",
content: "anyone near the station tonight? heading over in ten minutes",
timestamp: Date(timeIntervalSince1970: 1_700_000_000 + Double(index)),
isRelay: false,
senderPeerID: PeerID(nostr: pubkey)
)
}
}
var pass = 0
var samples: [TimeInterval] = []
measure {
precondition(pass < batches.count, "add more pre-built batches")
let batch = batches[pass]
pass += 1
let start = Date()
for message in batch {
_ = fixture.viewModel.formatMessageAsText(message, colorScheme: .dark)
}
samples.append(Date().timeIntervalSince(start))
}
reportThroughput("geochat.formatMessage", samples: samples, operations: batchSize, unit: "messages")
}
// MARK: - Hex encoding
/// Nostr public keys are hex-encoded on roster and formatting paths.
func testHexEncodePublicKeys() {
let keys: [Data] = (0..<1_000).map { index in
Data((0..<32).map { UInt8(truncatingIfNeeded: index &* 31 &+ $0) })
}
let rounds = 10
var samples: [TimeInterval] = []
measure {
let start = Date()
var characters = 0
for _ in 0..<rounds {
for key in keys {
characters += key.hexEncodedString().utf8.count
}
}
samples.append(Date().timeIntervalSince(start))
XCTAssertEqual(characters, rounds * keys.count * 64)
}
reportThroughput("hex.encodePublicKey", samples: samples, operations: rounds * keys.count, unit: "keys")
}
}
/// A real `ChatViewModel` in a geohash channel with `participants` people
/// present, each nicknamed the way inbound events nickname them.
@MainActor
private final class GeochatPerfFixture {
static let geohash = "u4pruyd"
let viewModel: ChatViewModel
let pubkeys: [String]
init(participants: Int) {
let keychain = MockKeychain()
let locationSuite = "PerformanceBaselineTests.geochat.\(UUID().uuidString)"
let locationStorage = UserDefaults(suiteName: locationSuite) ?? .standard
locationStorage.removePersistentDomain(forName: locationSuite)
viewModel = ChatViewModel(
keychain: keychain,
idBridge: NostrIdentityBridge(keychain: MockKeychainHelper()),
identityManager: MockIdentityManager(keychain),
transport: MockTransport(),
conversations: ConversationStore(),
locationManager: LocationChannelManager(storage: locationStorage)
)
// The view model delivers its initial (mesh) channel asynchronously,
// which clears the tracker's active geohash. Let startup settle
// before seeding the room so it can't empty mid-benchmark.
Self.drainMainQueue()
// In the channel the way a channel switch leaves the view model, so
// display names and colors take their real paths (which compare
// against our own key for this geohash).
viewModel.activeChannel = .location(GeohashChannel(level: .neighborhood, geohash: Self.geohash))
viewModel.currentGeohash = Self.geohash
let tracker = viewModel.participantTracker
tracker.setActiveGeohash(Self.geohash)
pubkeys = (0..<participants).map { String(format: "%064x", 0x6E0_0000 + $0) }
for (index, pubkey) in pubkeys.enumerated() {
viewModel.setGeoNickname("peer\(index)", forPubkey: pubkey)
tracker.recordParticipant(pubkeyHex: pubkey, geohash: Self.geohash)
}
}
/// Runs the main run loop until it has been idle for a few polls.
private static func drainMainQueue() {
var idlePolls = 0
let deadline = Date().addingTimeInterval(10)
while idlePolls < 3, Date() < deadline {
if CFRunLoopRunInMode(CFRunLoopMode.defaultMode, 0.001, true) == .handledSource {
idlePolls = 0
} else {
idlePolls += 1
}
}
}
}

View File

@ -42,7 +42,8 @@ final class PerformanceBaselineTests: XCTestCase {
/// appended to the file named by `BITCHAT_PERF_LOG` (if set): under
/// `swift test --parallel` the runner swallows stdout of passing tests,
/// so the CI floor gate (scripts/check-perf-floors.sh) reads the file.
private func reportThroughput(_ name: String, samples: [TimeInterval], operations: Int, unit: String) {
/// Internal so benchmark extensions in other files report the same way.
func reportThroughput(_ name: String, samples: [TimeInterval], operations: Int, unit: String) {
guard !samples.isEmpty else { return }
let avg = samples.reduce(0, +) / Double(samples.count)
let opsPerSec = avg > 0 ? Double(operations) / avg : .infinity
@ -712,8 +713,11 @@ private final class PerfNostrContext: ChatNostrContext {
func stopGeoParticipantRefreshTimer() {}
func setActiveParticipantGeohash(_ geohash: String?) {}
private(set) var participantRecords = 0
func recordGeoParticipant(pubkeyHex: String) { participantRecords += 1 }
func recordGeoParticipant(pubkeyHex: String, geohash: String) { participantRecords += 1 }
func recordGeoParticipant(pubkeyHex: String, seenAt: Date) -> Bool {
participantRecords += 1
return true
}
func recordGeoParticipant(pubkeyHex: String, geohash: String, seenAt: Date) { participantRecords += 1 }
func geoParticipantCount(for geohash: String) -> Int { 0 }
func setGeoNickname(_ nickname: String, forPubkey pubkeyHex: String) { geoNicknames[pubkeyHex.lowercased()] = nickname }
func markGeoTeleported(_ pubkeyHexLowercased: String) { teleportedKeys.insert(pubkeyHexLowercased) }

View File

@ -34,6 +34,16 @@
"store.steadyStateAppend_before": 2315,
"store.steadyStateAppend": 53976
},
"_reference_local_numbers_2026_10": {
"geochat.peopleListColors_before": 112,
"geochat.peopleListColors": 406134,
"geochat.participantHeartbeat_before": 110,
"geochat.participantHeartbeat": 1581264,
"geochat.formatMessage_before": 107,
"geochat.formatMessage": 18006,
"hex.encodePublicKey_before": 64366,
"hex.encodePublicKey": 1194627
},
"floors": {
"nostrInbound.fresh": 450,
"nostrInbound.duplicate": 250000,
@ -46,7 +56,11 @@
"pipeline.publicIngest": 2400,
"store.append": 48000,
"store.steadyStateAppend": 10000,
"store.audit": 70
"store.audit": 70,
"geochat.peopleListColors": 40000,
"geochat.participantHeartbeat": 150000,
"geochat.formatMessage": 2500,
"hex.encodePublicKey": 250000
},
"_slowest_observed_ci_numbers_2026_06": {
"nostrInbound.fresh": 918,
@ -60,5 +74,11 @@
"pipeline.publicIngest": 5006,
"store.append": 97423,
"store.audit": 140
},
"_slowest_observed_ci_numbers_2026_10": {
"geochat.peopleListColors": 212895,
"geochat.participantHeartbeat": 717459,
"geochat.formatMessage": 5176,
"hex.encodePublicKey": 655398
}
}

View File

@ -21,7 +21,6 @@ private final class TestPipelineDelegate: PublicMessagePipelineDelegate {
/// Message IDs the commit rejects (simulates the store's ID dedup).
var rejectedMessageIDs: Set<String> = []
private(set) var recordedContentKeys: [String] = []
private(set) var batchingStates: [Bool] = []
func messages(in conversationID: ConversationID) -> [BitchatMessage] {
committed.filter { $0.conversationID == conversationID }.map(\.message)
@ -47,10 +46,6 @@ private final class TestPipelineDelegate: PublicMessagePipelineDelegate {
}
func pipelinePrewarmMessage(_: PublicMessagePipeline, message: BitchatMessage) {}
func pipelineSetBatchingState(_: PublicMessagePipeline, isBatching: Bool) {
batchingStates.append(isBatching)
}
}
@MainActor
@ -80,8 +75,6 @@ struct PublicMessagePipelineTests {
pipeline.flushIfNeeded()
#expect(delegate.messages(in: .mesh).map { $0.id } == ["b", "a"])
// Batching state wrapped the flush.
#expect(delegate.batchingStates == [true, false])
}
@Test @MainActor

View File

@ -35,6 +35,40 @@ struct AutocompleteServiceTests {
#expect(result.range == nil)
}
@Test("Mention token detection is true exactly where suggestions are possible")
func hasMentionTokenMatchesSuggestionContext() {
let service = AutocompleteService()
let samples: [(text: String, cursor: Int, hasToken: Bool)] = [
("", 0, false),
("plain text", 10, false),
("hi @al there", 12, false),
("a @b-c", 6, false),
("@", 1, true),
("hi @al", 6, true),
("hi @al there", 6, true),
("@@al", 4, true),
("salut @émi", 10, true),
("@x_1", 4, true),
("mail me@host", 12, true)
]
for sample in samples {
#expect(
AutocompleteService.hasMentionToken(in: sample.text, cursorPosition: sample.cursor) == sample.hasToken,
"\(sample.text) @ \(sample.cursor)"
)
// A peer named after the token's own prefix always matches it, so
// suggestions appear exactly when a token is detected.
let prefix = String(sample.text.prefix(sample.cursor).split(separator: "@", omittingEmptySubsequences: false).last ?? "")
let result = service.getSuggestions(
for: sample.text,
peers: [prefix + "z"],
cursorPosition: sample.cursor
)
#expect(result.suggestions.isEmpty == !sample.hasToken, "\(sample.text) @ \(sample.cursor)")
}
}
@Test("Applying suggestions replaces the range and adds command spacing only when needed")
func applySuggestionReplacesRangeAndHandlesCommandSpacing() {
let service = AutocompleteService()

View File

@ -741,14 +741,14 @@ struct BLEAnnounceHandlerTests {
)
let handler = BLEAnnounceHandler(environment: environment)
func makeSignedAnnounce(nickname: String, signer: NoiseEncryptionService) throws -> BitchatPacket {
func makeSignedAnnounce(nickname: String, signer: NoiseEncryptionService) -> BitchatPacket? {
let announcement = AnnouncementPacket(
nickname: nickname,
noisePublicKey: victimNoiseKey,
signingPublicKey: signer.getSigningPublicKeyData(),
directNeighbors: nil
)
let payload = try #require(announcement.encode())
guard let payload = announcement.encode() else { return nil }
let packet = BitchatPacket(
type: MessageType.announce.rawValue,
senderID: Data(hexString: peerID.id) ?? Data(),
@ -758,11 +758,11 @@ struct BLEAnnounceHandlerTests {
signature: nil,
ttl: TransportConfig.messageTTLDefault
)
return try #require(signer.signPacket(packet))
return signer.signPacket(packet)
}
// Legitimate announce from the victim is accepted and pinned.
let victimAnnounce = try makeSignedAnnounce(nickname: "victim", signer: victim)
let victimAnnounce = try #require(makeSignedAnnounce(nickname: "victim", signer: victim))
handler.handle(victimAnnounce, from: peerID)
#expect(box.registry.info(for: peerID)?.nickname == "victim")
@ -770,7 +770,7 @@ struct BLEAnnounceHandlerTests {
#expect(box.persistedIdentities.count == 1)
// Attacker announce with a valid self-signature must be rejected.
let attackerAnnounce = try makeSignedAnnounce(nickname: "attacker", signer: attacker)
let attackerAnnounce = try #require(makeSignedAnnounce(nickname: "attacker", signer: attacker))
handler.handle(attackerAnnounce, from: peerID)
#expect(box.registry.info(for: peerID)?.nickname == "victim")
@ -778,7 +778,7 @@ struct BLEAnnounceHandlerTests {
#expect(box.persistedIdentities.count == 1)
// The victim's subsequent announces (same pinned key) still work.
let victimRename = try makeSignedAnnounce(nickname: "victim-renamed", signer: victim)
let victimRename = try #require(makeSignedAnnounce(nickname: "victim-renamed", signer: victim))
handler.handle(victimRename, from: peerID)
#expect(box.registry.info(for: peerID)?.nickname == "victim-renamed")
@ -862,14 +862,14 @@ struct BLEAnnounceHandlerTests {
}
let handler = BLEAnnounceHandler(environment: makeEnvironment(identityManager: identityManager))
func makeSignedAnnounce(nickname: String, signer: NoiseEncryptionService) throws -> BitchatPacket {
func makeSignedAnnounce(nickname: String, signer: NoiseEncryptionService) -> BitchatPacket? {
let announcement = AnnouncementPacket(
nickname: nickname,
noisePublicKey: victimNoiseKey,
signingPublicKey: signer.getSigningPublicKeyData(),
directNeighbors: nil
)
let payload = try #require(announcement.encode())
guard let payload = announcement.encode() else { return nil }
let packet = BitchatPacket(
type: MessageType.announce.rawValue,
senderID: Data(hexString: peerID.id) ?? Data(),
@ -879,7 +879,7 @@ struct BLEAnnounceHandlerTests {
signature: nil,
ttl: TransportConfig.messageTTLDefault
)
return try #require(signer.signPacket(packet))
return signer.signPacket(packet)
}
func persistedIdentity() -> CryptographicIdentity? {
@ -888,7 +888,7 @@ struct BLEAnnounceHandlerTests {
}
// 1. Victim announces: pinned in the registry and persisted.
handler.handle(try makeSignedAnnounce(nickname: "victim", signer: victim), from: peerID)
handler.handle(try #require(makeSignedAnnounce(nickname: "victim", signer: victim)), from: peerID)
#expect(box.registry.info(for: peerID)?.signingPublicKey == victim.getSigningPublicKeyData())
#expect(persistedIdentity()?.signingPublicKey == victim.getSigningPublicKeyData())
@ -898,13 +898,13 @@ struct BLEAnnounceHandlerTests {
// 3. Attacker replay with own signing key: rejected via the persisted
// pin, and neither the registry nor the persisted identity change.
handler.handle(try makeSignedAnnounce(nickname: "attacker", signer: attacker), from: peerID)
handler.handle(try #require(makeSignedAnnounce(nickname: "attacker", signer: attacker)), from: peerID)
#expect(box.registry.info(for: peerID) == nil)
#expect(persistedIdentity()?.signingPublicKey == victim.getSigningPublicKeyData())
#expect(identityManager.getSocialIdentity(for: victimNoiseKey.sha256Fingerprint())?.claimedNickname == "victim")
// 4. Victim re-announces with the same signing key: accepted again.
handler.handle(try makeSignedAnnounce(nickname: "victim", signer: victim), from: peerID)
handler.handle(try #require(makeSignedAnnounce(nickname: "victim", signer: victim)), from: peerID)
#expect(box.registry.info(for: peerID)?.nickname == "victim")
#expect(box.registry.info(for: peerID)?.signingPublicKey == victim.getSigningPublicKeyData())
@ -919,7 +919,7 @@ struct BLEAnnounceHandlerTests {
)
box.registry = BLEPeerRegistry()
let restartedHandler = BLEAnnounceHandler(environment: makeEnvironment(identityManager: reloadedManager))
restartedHandler.handle(try makeSignedAnnounce(nickname: "attacker", signer: attacker), from: peerID)
restartedHandler.handle(try #require(makeSignedAnnounce(nickname: "attacker", signer: attacker)), from: peerID)
#expect(box.registry.info(for: peerID) == nil)
#expect(
reloadedManager.getCryptoIdentitiesByPeerIDPrefix(peerID).first?.signingPublicKey
@ -927,7 +927,7 @@ struct BLEAnnounceHandlerTests {
)
// ...while the victim is accepted after the restart.
restartedHandler.handle(try makeSignedAnnounce(nickname: "victim", signer: victim), from: peerID)
restartedHandler.handle(try #require(makeSignedAnnounce(nickname: "victim", signer: victim)), from: peerID)
#expect(box.registry.info(for: peerID)?.signingPublicKey == victim.getSigningPublicKeyData())
}

View File

@ -6,14 +6,14 @@ import BitFoundation
@Suite(.serialized)
struct ComposerDraftStoreTests {
/// Isolate each test from leftover in-memory drafts.
private func withCleanStore(_ body: () throws -> Void) rethrows {
private func withCleanStore(_ body: () -> Void) {
ComposerDraftStore.replaceAllForTesting([:])
defer { ComposerDraftStore.replaceAllForTesting([:]) }
try body()
body()
}
@Test func emptyDraftIsNotStored() throws {
try withCleanStore {
@Test func emptyDraftIsNotStored() {
withCleanStore {
ComposerDraftStore.save("hello", for: .mesh)
ComposerDraftStore.save(" ", for: .mesh)
// Whitespace-only is still a draft the user typed; empty string clears.
@ -23,8 +23,8 @@ struct ComposerDraftStoreTests {
}
}
@Test func draftsAreIsolatedPerConversation() throws {
try withCleanStore {
@Test func draftsAreIsolatedPerConversation() {
withCleanStore {
let peer = PeerID(str: "aabbccddeeff0011")
ComposerDraftStore.save("mesh draft", for: .mesh)
ComposerDraftStore.save("geo draft", for: .location(geohash: "u4pruy"))
@ -37,8 +37,8 @@ struct ComposerDraftStoreTests {
}
}
@Test func geohashKeysAreCaseInsensitive() throws {
try withCleanStore {
@Test func geohashKeysAreCaseInsensitive() {
withCleanStore {
ComposerDraftStore.save("city chat", for: .location(geohash: "U4PRUY"))
#expect(ComposerDraftStore.load(.location(geohash: "u4pruy")) == "city chat")
}
@ -61,16 +61,16 @@ struct ComposerDraftStoreTests {
#expect(withoutFP == .privateChat(stableID: peer.id))
}
@Test func longDraftsAreTruncated() throws {
try withCleanStore {
@Test func longDraftsAreTruncated() {
withCleanStore {
let long = String(repeating: "a", count: ComposerDraftStore.maxDraftLength + 50)
ComposerDraftStore.save(long, for: .mesh)
#expect(ComposerDraftStore.load(.mesh).count == ComposerDraftStore.maxDraftLength)
}
}
@Test func resetClearsAllDrafts() throws {
try withCleanStore {
@Test func resetClearsAllDrafts() {
withCleanStore {
ComposerDraftStore.save("keep quiet", for: .mesh)
ComposerDraftStore.reset()
#expect(ComposerDraftStore.load(.mesh).isEmpty)
@ -78,8 +78,8 @@ struct ComposerDraftStoreTests {
}
}
@Test func maxDraftCountEvictsOldestKeys() throws {
try withCleanStore {
@Test func maxDraftCountEvictsOldestKeys() {
withCleanStore {
for index in 0..<ComposerDraftStore.maxDraftCount {
ComposerDraftStore.save(
"d\(index)",
@ -92,8 +92,8 @@ struct ComposerDraftStoreTests {
}
}
@Test func clearingDraftRemovesKeySoItDoesNotResurrect() throws {
try withCleanStore {
@Test func clearingDraftRemovesKeySoItDoesNotResurrect() {
withCleanStore {
ComposerDraftStore.save("old text", for: .mesh)
ComposerDraftStore.save("", for: .mesh)
#expect(ComposerDraftStore.load(.mesh).isEmpty)

View File

@ -271,6 +271,7 @@ private final class DiagnosticsMockContext: CommandContextProvider {
func getVisibleGeoParticipants() -> [CommandGeoParticipant] { [] }
func nostrPubkeyForDisplayName(_ displayName: String) -> String? { nil }
func geohashBlockListDidChange() {}
func startPrivateChat(with peerID: PeerID) {}
func sendPrivateMessage(_ content: String, to peerID: PeerID) {}
func clearCurrentPublicTimeline() {}

View File

@ -258,6 +258,147 @@ struct PrivateChatManagerTests {
#expect(!manager.unreadMessages.contains(tempPeerID))
}
@Test @MainActor
func consolidateMessages_leavesMyGeoDMThreadOutOfANamesakesChat() async {
// My geo DMs carry my plain nickname (sendGeohashDM), so a thread of
// my rows matches any mesh peer who shares that nickname, though my
// rows say nothing about who the thread is with. Folded into the
// namesake's chat, my thread with a geohash stranger would send a
// reply typed there to the namesake.
let transport = MockTransport()
transport.myPeerID = PeerID(str: "a1b2c3d4e5f60718")
let (manager, store) = Self.makeManager(transport: transport)
let namesakePeerID = PeerID(str: "0011223344556677")
let tempPeerID = PeerID(nostr_: String(repeating: "42", count: 32))
store.append(
BitchatMessage(
id: "my-geo-dm",
sender: "alice",
content: "hi from the geohash",
timestamp: Date(),
isRelay: false,
isPrivate: true,
recipientNickname: "alice",
senderPeerID: transport.myPeerID,
deliveryStatus: .delivered(to: "alice", at: Date())
),
to: .directPeer(tempPeerID)
)
_ = manager.consolidateMessages(for: namesakePeerID, peerNickname: "alice", persistedReadReceipts: [])
// The thread stays where it is, my row still mine...
#expect(manager.privateChats[tempPeerID]?.map(\.id) == ["my-geo-dm"])
#expect(manager.privateChats[tempPeerID]?.first?.senderPeerID == transport.myPeerID)
// ...and no thread with the namesake appears.
#expect(manager.privateChats[namesakePeerID] == nil)
// Opening the namesake's chat finds no sent rows of mine to sync
// receipts for, and sends none.
var externalReceipts = Set<String>()
manager.syncReadReceiptsForSentMessages(peerID: namesakePeerID, externalReceipts: &externalReceipts)
#expect(externalReceipts.isEmpty)
#expect(manager.sentReadReceipts.isEmpty)
manager.markAsRead(from: namesakePeerID)
#expect(transport.sentReadReceipts.isEmpty)
}
@Test @MainActor
func consolidateMessages_stillMovesThePeersOwnGeoDMThreadBesideMine() async {
// Skipping my thread is per thread: the peer's own thread, with the
// same nickname, still folds into their chat.
let transport = MockTransport()
transport.myPeerID = PeerID(str: "a1b2c3d4e5f60718")
let (manager, store) = Self.makeManager(transport: transport)
let peerID = PeerID(str: "0011223344556677")
let myThread = PeerID(nostr_: String(repeating: "42", count: 32))
let theirThread = PeerID(nostr_: String(repeating: "43", count: 32))
store.append(
BitchatMessage(
id: "my-geo-dm",
sender: "alice",
content: "hi from the geohash",
timestamp: Date(),
isRelay: false,
isPrivate: true,
recipientNickname: "alice",
senderPeerID: transport.myPeerID,
deliveryStatus: .sent
),
to: .directPeer(myThread)
)
store.append(
BitchatMessage(
id: "their-geo-dm",
sender: "alice",
content: "hi from them",
timestamp: Date(),
isRelay: false,
isPrivate: true,
recipientNickname: "alice",
senderPeerID: theirThread
),
to: .directPeer(theirThread)
)
store.markUnread(.directPeer(theirThread))
let hadUnread = manager.consolidateMessages(for: peerID, peerNickname: "alice", persistedReadReceipts: [])
#expect(hadUnread)
#expect(manager.privateChats[theirThread] == nil)
#expect(manager.privateChats[peerID]?.map(\.id) == ["their-geo-dm"])
#expect(manager.privateChats[peerID]?.first?.senderPeerID == peerID)
#expect(manager.unreadMessages.contains(peerID))
#expect(manager.privateChats[myThread]?.map(\.id) == ["my-geo-dm"])
}
@Test @MainActor
func consolidateMessages_leavesAThreadWithMyRepliesOutOfANamesakesChat() async {
// One row of mine is enough, not a thread of only mine: their rows
// and my replies all read "alice", so the nickname check alone would
// fold the thread, my replies with it.
let transport = MockTransport()
transport.myPeerID = PeerID(str: "a1b2c3d4e5f60718")
let (manager, store) = Self.makeManager(transport: transport)
let namesakePeerID = PeerID(str: "0011223344556677")
let thread = PeerID(nostr_: String(repeating: "44", count: 32))
store.append(
BitchatMessage(
id: "their-geo-dm",
sender: "alice",
content: "hi from them",
timestamp: Date().addingTimeInterval(-60),
isRelay: false,
isPrivate: true,
recipientNickname: "alice",
senderPeerID: thread
),
to: .directPeer(thread)
)
store.append(
BitchatMessage(
id: "my-reply",
sender: "alice",
content: "hi back",
timestamp: Date(),
isRelay: false,
isPrivate: true,
recipientNickname: "alice",
senderPeerID: transport.myPeerID,
deliveryStatus: .sent
),
to: .directPeer(thread)
)
_ = manager.consolidateMessages(for: namesakePeerID, peerNickname: "alice", persistedReadReceipts: [])
#expect(manager.privateChats[thread]?.map(\.id) == ["their-geo-dm", "my-reply"])
#expect(manager.privateChats[namesakePeerID] == nil)
}
@Test @MainActor
func syncReadReceiptsForSentMessages_onlyCopiesDeliveredAndRead() async {
let transport = MockTransport()
@ -304,7 +445,7 @@ struct PrivateChatManagerTests {
}
var externalReceipts = Set<String>()
manager.syncReadReceiptsForSentMessages(peerID: peerID, nickname: "Me", externalReceipts: &externalReceipts)
manager.syncReadReceiptsForSentMessages(peerID: peerID, externalReceipts: &externalReceipts)
#expect(externalReceipts == Set(["sent-read", "sent-delivered"]))
#expect(manager.sentReadReceipts == Set(["sent-read", "sent-delivered"]))

View File

@ -0,0 +1,68 @@
import CoreGraphics
import SwiftUI
import Testing
@testable import bitchat
/// The themed backdrop has to cover the safe-area insets too. If it stops at
/// the safe area, a sheet's own background shows through the home-indicator
/// inset: a dark-gray band under the Matrix people list in dark mode.
@Suite("ThemedRootBackground")
@MainActor
struct ThemedRootBackgroundTests {
@Test(arguments: AppTheme.allCases, ColorScheme.allCases)
func sheetBackground_fillsBottomSafeAreaInset(theme: AppTheme, colorScheme: ColorScheme) throws {
// A SwiftUI safe-area inset stands in for the home indicator: it
// reserves the bottom 20 pt, the way a sheet's bottom inset does.
let view = Color.clear
.themedSheetBackground()
.safeAreaInset(edge: .bottom, spacing: 0) {
Color.clear.frame(height: 20)
}
.frame(width: 40, height: 100)
.environment(\.appTheme, theme)
.environment(\.colorScheme, colorScheme)
let image = try RenderedPixels(view)
// Sanity check: the backdrop renders inside the safe area.
#expect(image.alpha(x: 20, y: 40) == 255)
// Regression: the backdrop also covers the inset.
#expect(image.alpha(x: 20, y: 90) == 255)
}
}
/// RGBA8 pixels of a view rendered offscreen at 1x.
@MainActor
private struct RenderedPixels {
private let width: Int
private let bytes: [UInt8]
init(_ view: some View) throws {
let renderer = ImageRenderer(content: view)
renderer.scale = 1
let image = try #require(renderer.cgImage)
width = image.width
var buffer = [UInt8](repeating: 0, count: image.width * image.height * 4)
let drawn = buffer.withUnsafeMutableBytes { raw -> Bool in
guard let context = CGContext(
data: raw.baseAddress,
width: image.width,
height: image.height,
bitsPerComponent: 8,
bytesPerRow: image.width * 4,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
) else {
return false
}
context.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height))
return true
}
try #require(drawn)
bytes = buffer
}
/// Alpha at (x, y), with y measured from the top edge.
func alpha(x: Int, y: Int) -> UInt8 {
bytes[(y * width + x) * 4 + 3]
}
}

View File

@ -669,6 +669,8 @@ struct ViewSmokeTests {
isPrivate: false,
deliveryStatus: .sent
)
// Stamped with my peer ID, as every DM I send is, so the row takes
// the own-DM delivery-status branch.
let paymentMessage = BitchatMessage(
sender: viewModel.nickname,
content: "lightning:lnbc1test cashuA_test-token",
@ -676,6 +678,7 @@ struct ViewSmokeTests {
isRelay: false,
isPrivate: true,
recipientNickname: "Bob",
senderPeerID: viewModel.meshService.myPeerID,
deliveryStatus: .partiallyDelivered(reached: 1, total: 2)
)

View File

@ -44,7 +44,19 @@ public final class BitchatMessage: Codable {
public func setCachedFormattedText(_ text: AttributedString, isDark: Bool, isSelf: Bool, variant: String = "") {
_cachedFormattedText["\(variant)\(isDark)-\(isSelf)"] = text
}
// Cached content scan for row rendering (not included in Codable).
// `content` is immutable, so a cached scan never goes stale.
private var _cachedContentScan: ContentScan?
public func getCachedContentScan() -> ContentScan? {
_cachedContentScan
}
public func setCachedContentScan(_ scan: ContentScan) {
_cachedContentScan = scan
}
// Codable implementation
enum CodingKeys: String, CodingKey {
case id, sender, content, timestamp, isRelay, originalSender
@ -100,6 +112,26 @@ public final class BitchatMessage: Codable {
}
}
// MARK: - Content Scan
extension BitchatMessage {
/// What a message row derives from `content`: the payment links rendered
/// as chips and whether the text collapses behind "show more". Deriving
/// them takes several regex passes over the content, so the renderer
/// computes them once and caches the result on the message.
public struct ContentScan: Equatable {
public let cashuLinks: [String]
public let lightningLinks: [String]
public let isLongForDisplay: Bool
public init(cashuLinks: [String], lightningLinks: [String], isLongForDisplay: Bool) {
self.cashuLinks = cashuLinks
self.lightningLinks = lightningLinks
self.isLongForDisplay = isLongForDisplay
}
}
}
// MARK: - Equatable Conformance
extension BitchatMessage: Equatable {

View File

@ -9,13 +9,28 @@
import struct Foundation.Data
public extension Data {
/// Lowercase hex, two digits per byte, no separators.
///
/// Table lookup instead of `String(format:)` per byte: Nostr public keys
/// are re-encoded on hot paths (geochat roster rebuilds touch one per
/// participant), and the formatted version cost ~14 µs per 32-byte key.
func hexEncodedString() -> String {
if self.isEmpty {
return ""
}
return self.map { String(format: "%02x", $0) }.joined()
return String(unsafeUninitializedCapacity: count * 2) { buffer in
var index = 0
for byte in self {
buffer[index] = Self.lowercaseHexDigits[Int(byte >> 4)]
buffer[index + 1] = Self.lowercaseHexDigits[Int(byte & 0x0F)]
index += 2
}
return index
}
}
private static let lowercaseHexDigits: [UInt8] = Array("0123456789abcdef".utf8)
/// Initialize Data from a hex string.
/// - Parameter hexString: A hex string, optionally prefixed with "0x" or "0X".
/// Whitespace is trimmed. Must have even length after prefix removal.

View File

@ -32,6 +32,39 @@ struct DataHexTests {
#expect(Data(hexString: bytes.hexEncodedString()) == bytes)
}
// MARK: - Encoding
/// Hex strings are identities (Nostr pubkeys, peer IDs) and wire values,
/// so the encoder must stay byte-identical to the `%02x` formatting it
/// replaced: lowercase, zero-padded, no separators.
@Test func encodes_every_byte_like_printf_hex() {
let bytes = Data((0...255).map { UInt8($0) })
let expected = bytes.map { String(format: "%02x", $0) }.joined()
#expect(bytes.hexEncodedString() == expected)
}
@Test func encodes_empty_data_as_empty_string() {
#expect(Data().hexEncodedString() == "")
}
@Test func encodes_slices_from_their_own_start_index() {
let bytes = Data([0x00, 0xde, 0xad, 0xbe, 0xef, 0xff])
let slice = bytes[1..<5]
#expect(slice.hexEncodedString() == "deadbeef")
}
@Test func encodes_varied_lengths_like_printf_hex() {
var state: UInt64 = 0x9E37_79B9_7F4A_7C15
for length in 1...96 {
let bytes = Data((0..<length).map { _ in
state = state &* 6_364_136_223_846_793_005 &+ 1_442_695_040_888_963_407
return UInt8(truncatingIfNeeded: state >> 56)
})
let expected = bytes.map { String(format: "%02x", $0) }.joined()
#expect(bytes.hexEncodedString() == expected)
}
}
// MARK: - Rejected forms
@Test func rejects_odd_length() {