diff --git a/Mactrix.xctestplan b/Mactrix.xctestplan index 96cc2b41..35370c3f 100644 --- a/Mactrix.xctestplan +++ b/Mactrix.xctestplan @@ -41,6 +41,13 @@ "identifier" : "ContactLinkingTests", "name" : "ContactLinkingTests" } + }, + { + "target" : { + "containerPath" : "container:", + "identifier" : "MatrixIntegrationTests", + "name" : "MatrixIntegrationTests" + } } ], "version" : 1 diff --git a/Mactrix/Localizable.xcstrings b/Mactrix/Localizable.xcstrings index e4b75d61..42f6e315 100644 --- a/Mactrix/Localizable.xcstrings +++ b/Mactrix/Localizable.xcstrings @@ -4,6 +4,28 @@ "" : { "shouldTranslate" : false }, + "%@, %lld unread in other accounts" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "%1$@, %2$lld unread in other accounts" + } + } + } + }, + "%@, needs attention" : {}, + "%@, sync: %@" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "%1$@, sync: %2$@" + } + } + } + }, + "%lld unread" : {}, "(edited)" : { "localizations" : { "da" : { @@ -124,6 +146,7 @@ } } }, + "%@, verification requested in another account" : {}, "%lld other events" : { "localizations" : { "da" : { @@ -458,6 +481,7 @@ } } }, + "Active Account" : {}, "Activities" : { "localizations" : { "da" : { @@ -474,6 +498,8 @@ } } }, + "Add Account" : {}, + "Add Account…" : {}, "Add Reaction" : { "localizations" : { "da" : { @@ -3546,6 +3572,7 @@ } }, "logged out" : { + "extractionState" : "stale", "localizations" : { "da" : { "stringUnit" : { @@ -3955,6 +3982,7 @@ } } }, + "No Account" : {}, "No backup found" : { "localizations" : { "da" : { @@ -4131,6 +4159,8 @@ } } }, + "Not sent yet" : {}, + "Not sent. %@ Click to retry or delete." : {}, "Not signed in" : { "localizations" : { "da" : { @@ -4896,6 +4926,7 @@ } } }, + "Remove Account" : {}, "Reply" : { "localizations" : { "da" : { @@ -5088,6 +5119,7 @@ } } }, + "Restarting…" : {}, "Restoring encryption secrets…" : { "localizations" : { "da" : { @@ -5136,6 +5168,7 @@ } } }, + "Retry Sending" : {}, "revoked invitation for %@ to join the room" : { "localizations" : { "da" : { @@ -5773,6 +5806,8 @@ } } }, + "Sign In Again as %@" : {}, + "Sign In Again…" : {}, "Sign in to continue." : { "localizations" : { "da" : { @@ -5815,6 +5850,12 @@ } } }, + "Sign Out" : {}, + "Sign out of %@?" : {}, + "Sign Out of %@…" : {}, + "Sign Out of This Account" : {}, + "Signed Out" : {}, + "Signed out" : {}, "Smileys & Emotion" : { "localizations" : { "da" : { @@ -5831,6 +5872,8 @@ } } }, + "Some devices in this room aren't verified." : {}, + "Someone in this room changed their identity." : {}, "Space" : { "localizations" : { "da" : { @@ -7415,6 +7458,9 @@ } } }, + "Switch account" : {}, + "Switch account, current: %@" : {}, + "Switch accounts from the sidebar or the Account menu." : {}, "Symbols" : { "localizations" : { "da" : { @@ -7463,6 +7509,8 @@ } } }, + "The attachment is no longer available." : {}, + "The attachment's file type isn't recognized." : {}, "The original message isn't loaded." : { "localizations" : { "da" : { @@ -7505,6 +7553,7 @@ } } }, + "The server couldn't be reached." : {}, "They don't match" : { "localizations" : { "da" : { @@ -7537,6 +7586,7 @@ } } }, + "This account will be signed out on this Mac. Your other accounts stay signed in." : {}, "This device is verified" : { "localizations" : { "da" : { @@ -7601,6 +7651,7 @@ } } }, + "This session was ended by the server or another device." : {}, "This will remove the message for everyone in the room. This action cannot be undone." : { "localizations" : { "da" : { @@ -8095,6 +8146,7 @@ } } }, + "Unread rooms in your other accounts" : {}, "Unsupported attachment (%@): %@" : { "localizations" : { "da" : { @@ -8309,6 +8361,7 @@ } } }, + "Verification requested" : {}, "Verification status unknown" : { "localizations" : { "da" : { @@ -8389,6 +8442,7 @@ } } }, + "Verify this session to send messages." : {}, "Verify with Recovery Key" : { "localizations" : { "da" : { @@ -8725,6 +8779,8 @@ } } }, + "You were signed out." : {}, + "You're already signed in as %@." : {}, "Your account recognizes this device as trusted." : { "localizations" : { "da" : { @@ -8756,7 +8812,8 @@ } } } - } + }, + "Your session expired." : {} }, "version" : "1.0" -} \ No newline at end of file +} diff --git a/Mactrix/MactrixApp.swift b/Mactrix/MactrixApp.swift index a964ab88..700de409 100644 --- a/Mactrix/MactrixApp.swift +++ b/Mactrix/MactrixApp.swift @@ -15,10 +15,14 @@ struct MactrixApp: App { .windowToolbarStyle(.automatic) .environment(appState) .commands { - AppCommands() + AppCommands(appState: appState) } - .onChange(of: windowState == nil, focusNotification) - .onChange(of: appState.matrixClient?.notifications.selectedRoomId == nil, focusNotification) + .onChange(of: windowState.map(ObjectIdentifier.init)) { + if let windowState { appState.focus(windowState) } + focusNotification() + } + .onChange(of: appState.notificationRouter.pendingTarget, focusNotification) + .onChange(of: appState.restoration, focusNotification) Settings { SettingsView() @@ -27,12 +31,6 @@ struct MactrixApp: App { } func focusNotification() { - guard let windowState else { return } - guard let notificationRoomId = appState.matrixClient?.notifications.selectedRoomId else { - return - } - - windowState.selectedRoomId = notificationRoomId - appState.matrixClient?.notifications.selectedRoomId = nil + appState.showNotificationTarget() } } diff --git a/Package.swift b/Package.swift index 65aeedb6..65efe71c 100644 --- a/Package.swift +++ b/Package.swift @@ -41,6 +41,7 @@ let package = Package( .product(name: "MatrixRustSDK", package: "matrix-rust-components-swift"), ] ), + .testTarget(name: "MatrixIntegrationTests", dependencies: ["MatrixIntegration"]), .target( name: "MactrixApp", dependencies: [ diff --git a/Sources/MactrixApp/Commands.swift b/Sources/MactrixApp/Commands.swift index da73544c..36eb4705 100644 --- a/Sources/MactrixApp/Commands.swift +++ b/Sources/MactrixApp/Commands.swift @@ -1,25 +1,65 @@ import SwiftUI public struct AppCommands: Commands { + let appState: AppState @FocusedValue(WindowState.self) private var windowState: WindowState? @AppStorage("fontSize") var fontSize: Int = 13 - public init() {} + public init(appState: AppState) { + self.appState = appState + } public var body: some Commands { - SidebarCommands() - InspectorCommands() - TextEditingCommands() - ToolbarCommands() + // Older SDKs' CommandsBuilder accepts at most 10 children, so the + // built-in command sets are grouped into one property. + builtInCommands about newTab createRoom quickNavigation fontSizeCommands + accountCommands conversationCommands } + @CommandsBuilder + var builtInCommands: some Commands { + SidebarCommands() + InspectorCommands() + TextEditingCommands() + ToolbarCommands() + } + + var accountCommands: some Commands { + CommandMenu("Account") { + ForEach(Array(appState.accounts.enumerated()), id: \.element.storeID) { index, account in + Toggle( + isOn: Binding( + get: { windowState?.accountID == account.storeID }, + set: { if $0, let windowState { appState.show(account, in: windowState) } }) + ) { + Text(account.accountMenuTitle) + } + .disabled(windowState == nil) + .keyboardShortcut( + index < 9 + ? KeyboardShortcut( + KeyEquivalent(Character("\(index + 1)")), modifiers: [.command, .control]) + : nil) + } + + if !appState.accounts.isEmpty { + Divider() + } + + Button("Add Account…") { + windowState?.loginSheet = .addAccount + } + .disabled(windowState == nil) + } + } + var about: some Commands { CommandGroup(replacing: .appInfo) { Button("About Mactrix") { diff --git a/Sources/MactrixApp/MainView.swift b/Sources/MactrixApp/MainView.swift index 6775c089..fe9d80c8 100644 --- a/Sources/MactrixApp/MainView.swift +++ b/Sources/MactrixApp/MainView.swift @@ -11,8 +11,6 @@ public struct MainView: View { @SceneStorage("MainView.windowState") private var windowState: WindowState = .init() - @State private var showWelcomeSheet: Bool = false - let x: Bool = false public init() {} @@ -25,20 +23,21 @@ public struct MainView: View { case .previewRoom(let room, let eventId, let routingVia): MactrixUI.RoomPreviewView( preview: room.info(), - imageLoader: appState.matrixClient, - actions: appState.matrixClient?.roomPreviewActions( + imageLoader: windowState.matrixClient, + actions: windowState.matrixClient?.roomPreviewActions( forRoomWithId: room.info().roomId, windowState: windowState, eventId: eventId, routingVia: routingVia) ) .id(screen.id) case .newRoom: MactrixUI.CreateRoomScreen(onSubmit: { params in - guard let matrixClient = appState.matrixClient else { return } + guard let matrixClient = windowState.matrixClient else { return } guard windowState.selectedScreen === screen else { return } let newRoom = try await matrixClient.client.createRoom( request: params.asMatrixRequest) try Task.checkCancellation() - guard windowState.selectedScreen === screen, appState.matrixClient === matrixClient else { + guard windowState.selectedScreen === screen, windowState.matrixClient === matrixClient + else { return } windowState.selectRoom(newRoom) @@ -49,11 +48,11 @@ public struct MainView: View { case .user(let profile): UserProfileView( profile: profile, - isUserIgnored: appState.matrixClient?.isUserIgnored(profile.userId) ?? false, - actions: appState.matrixClient?.userProfileActions( + isUserIgnored: windowState.matrixClient?.isUserIgnored(profile.userId) ?? false, + actions: windowState.matrixClient?.userProfileActions( forUserId: profile.userId, windowState: windowState), timelineActions: nil, - imageLoader: appState.matrixClient + imageLoader: windowState.matrixClient ) case .none: ContentUnavailableView("Select a room", systemImage: "message.fill") @@ -62,16 +61,16 @@ public struct MainView: View { var verificationSheetPresented: Binding { Binding( - get: { appState.matrixClient?.sessionVerificationData != nil }, + get: { windowState.matrixClient?.sessionVerificationData != nil }, set: { isPresented in if !isPresented { Task { do { - try await appState.matrixClient?.client + try await windowState.matrixClient?.client .getSessionVerificationController().declineVerification() } catch { Logger.viewCycle.error("failed to decline verification: \(error)") - appState.matrixClient?.sessionVerificationData = nil + windowState.matrixClient?.sessionVerificationData = nil } } } @@ -94,21 +93,31 @@ public struct MainView: View { } ) .background { - let matrixClient = appState.matrixClient + let matrixClient = windowState.matrixClient QuickNavigationOverlayAttachment( coordinator: windowState.quickNavigation, matrixClient: matrixClient, onSelectRoom: { [weak windowState] roomID in windowState?.selectRoom(roomID) }) } + .background { + WindowReader( + onChange: { [weak windowState] window in + windowState?.window = window + }, + onClose: { [weak windowState] in + if let windowState { appState.unregister(windowState) } + }) + } .task { await attemptLoadUserSession() } - .sheet(isPresented: $showWelcomeSheet, onDismiss: onLoginModalDismiss) { - WelcomeSheetView() + .sheet(item: $windowState.loginSheet, onDismiss: onLoginModalDismiss) { request in + WelcomeSheetView(request: request) + .environment(windowState) } .sheet( isPresented: verificationSheetPresented, content: { - if let verificationData = appState.matrixClient?.sessionVerificationData { + if let verificationData = windowState.matrixClient?.sessionVerificationData { MactrixUI.SessionVerificationModal( verificationData: verificationData.asModel, onComplete: { response in @@ -116,23 +125,23 @@ public struct MainView: View { switch response { case .accept: do { - try await appState.matrixClient?.client + try await windowState.matrixClient?.client .getSessionVerificationController() .approveVerification() } catch { Logger.viewCycle.error( "failed to approve verification: \(error)") - appState.matrixClient?.sessionVerificationData = nil + windowState.matrixClient?.sessionVerificationData = nil } case .decline: do { - try await appState.matrixClient?.client + try await windowState.matrixClient?.client .getSessionVerificationController() .declineVerification() } catch { Logger.viewCycle.error( "failed to decline verification: \(error)") - appState.matrixClient?.sessionVerificationData = nil + windowState.matrixClient?.sessionVerificationData = nil } } } @@ -140,17 +149,15 @@ public struct MainView: View { } } ) - .onChange(of: appState.matrixClient == nil) { _, matrixClientIsNil in - if matrixClientIsNil { - Logger.viewCycle.info("Matrix client is nil, present welcome sheet") - showWelcomeSheet = true - } + // Scene storage may swap in the restored window state after the first render. + .onChange(of: ObjectIdentifier(windowState), initial: true) { + appState.register(windowState) } - .onChange(of: appState.matrixClient?.authenticationFailed) { _, authFailed in - if authFailed == true { - Logger.viewCycle.info("Logging out since auth failed") - appState.matrixClient = nil - } + .onChange(of: appState.restoration == .restored && appState.accounts.isEmpty, initial: true) { + _, signedOut in + guard signedOut else { return } + Logger.viewCycle.info("No signed in accounts, present welcome sheet") + windowState.loginSheet = .firstAccount } .onOpenURL { url in Logger.viewCycle.debug("onOpenUrl \(url)") @@ -171,39 +178,14 @@ public struct MainView: View { } func attemptLoadUserSession() async { - guard appState.matrixClient == nil else { return } - - do { - if let matrixClient = try await MatrixClient.attemptRestore() { - appState.matrixClient = matrixClient - } - } catch { - Logger.viewCycle.error("Failed to restore matrix session: \(error)") - } - - showWelcomeSheet = appState.matrixClient == nil - if let matrixClient = appState.matrixClient { - onMatrixLoaded(matrixClient: matrixClient) - } - } - - func onMatrixLoaded(matrixClient: MatrixClient) { - Task { - do { - try await matrixClient.startSync() - } catch { - Logger.matrixClient.error("Failed to start sync: \(error)") - } - } + await appState.restoreAccounts() } func onLoginModalDismiss() { Task { do { try await Task.sleep(for: .milliseconds(100)) - if let matrixClient = appState.matrixClient { - onMatrixLoaded(matrixClient: matrixClient) - } else { + if appState.accounts.isEmpty { NSApp.terminate(nil) } } catch is CancellationError { diff --git a/Sources/MactrixApp/Models/AppState.swift b/Sources/MactrixApp/Models/AppState.swift index 83f347a7..a61d4d91 100644 --- a/Sources/MactrixApp/Models/AppState.swift +++ b/Sources/MactrixApp/Models/AppState.swift @@ -1,19 +1,326 @@ +import AppKit +import Foundation import MatrixIntegration import OSLog import Observation +/// The signed-in accounts, and the windows showing them. +/// +/// Every account syncs in the background. Each window shows one account of its own choosing, +/// holding a weak reference to its client. @MainActor @Observable public final class AppState { - public var matrixClient: MatrixClient? + public enum Restoration: Equatable { + case pending + /// Stored accounts have been restored. + case restored + } + + public enum AccountError: LocalizedError { + case alreadySignedIn(userID: String) + + public var errorDescription: String? { + switch self { + case .alreadySignedIn(let userID): + String(localized: "You're already signed in as \(userID).") + } + } + } + + /// Signed-in accounts in display order. + public private(set) var accounts: [MatrixClient] = [] { + didSet { updateNotificationLabels() } + } + /// The account of the most recently focused window, which new windows open on. + public private(set) var lastFocusedAccountID: String? + private var hasRestored = false + /// Open windows, most recently focused first. + private var windows: [WeakWindowState] = [] + + @ObservationIgnored private let accountStore: AccountStore + @ObservationIgnored private var restoreTask: Task? + @ObservationIgnored private var lastAppliedDockUnreadCount: Int? + @ObservationIgnored private var networkMonitor: NetworkMonitor? + /// The Mac's network connection, passed on to every account. + @ObservationIgnored private var networkConditions = NetworkConditions() { + didSet { + for client in accounts { + client.networkConditions = networkConditions + } + } + } + + /// Routes clicked notifications from every account. + public let notificationRouter = NotificationRouter() + + public init() { + // Before any account opens its stores. + OpenFileLimit.raise() + accountStore = AccountStore() + observeDockBadge() + } + + /// The account of the most recently focused window, which the Settings window shows. + public var lastFocusedAccount: MatrixClient? { + accounts.first { $0.storeID == lastFocusedAccountID } + } + + /// The number of unread rooms across accounts other than `accountID`. + public func unreadRoomCount(excludingAccountID accountID: String?) -> Int { + accounts.reduce(0) { count, account in + guard account.storeID != accountID, !account.authenticationFailed else { return count } + return count + account.unreadRoomCount + } + } + + public var restoration: Restoration { + hasRestored ? .restored : .pending + } + + /// Restores stored accounts and starts syncing them. Runs once; later calls wait for the first. + public func restoreAccounts() async { + if let restoreTask { + await restoreTask.value + return + } + let task = Task { await performRestore() } + restoreTask = task + await task.value + } + + private func performRestore() async { + let clients = await MatrixClient.restoreAll(accountStore: accountStore) + accounts = clients + setLastFocusedAccount(accountStore.lastFocusedStoreID) + hasRestored = true + for window in openWindows { + attach(window) + } + for client in clients { + startSync(client) + } + networkMonitor = NetworkMonitor( + onConditionsChange: { [weak self] conditions in + self?.networkConditions = conditions + }, + onReconnect: { [weak self] in self?.reconnectAccounts() }) + } - public init() {} + /// Restarts every account's sync, so accounts that went offline reconnect now that the network + /// is back instead of at their next scheduled check. Accounts already online are unaffected. + private func reconnectAccounts() { + for client in accounts { + startSync(client) + } + } + + /// Adds a newly signed-in account and shows it in `windowState`. + /// + /// Signing in to an account that is already listed is rejected: the new session is signed out + /// again so it doesn't linger as an extra device. If the listed account was signed out by the + /// server, the new session replaces it, in every window showing it. + public func add(_ client: MatrixClient, in windowState: WindowState) async throws { + if let existing = accounts.first(where: { $0.userID == client.userID }) { + if existing.authenticationFailed { + let index = accounts.firstIndex { $0 === existing }! + let replacedWindows = openWindows.filter { $0.accountID == existing.storeID } + await discard(existing) + accounts.insert(client, at: min(index, accounts.count)) + accountStore.setOrder(accounts.map(\.storeID)) + for window in replacedWindows { + show(client, in: window) + } + } else { + Logger.matrixClient.info("Rejecting duplicate sign-in for store \(client.storeID)") + await discard(client) + show(existing, in: windowState) + throw AccountError.alreadySignedIn(userID: client.userID) + } + } else { + accounts.append(client) + } + show(client, in: windowState) + startSync(client) + } + /// Shows `account` in `windowState`. + public func show(_ account: MatrixClient, in windowState: WindowState) { + windowState.showAccount(account, knownAccountIDs: Set(accounts.map(\.storeID))) + if windowState === openWindows.first { + setLastFocusedAccount(account.storeID) + } + } + + /// Signs out of `client` and removes it, switching the windows that showed it to another account. + public func remove(_ client: MatrixClient) async { + accounts.removeAll { $0 === client } + // Switch before signing out, which waits for the server. + if lastFocusedAccountID == client.storeID { + setLastFocusedAccount(nil) + } + for window in openWindows where window.accountID == client.storeID { + attach(window) + } + await discard(client) + } + + /// Signs out of the account the Settings window shows. public func reset() async throws { + guard let lastFocusedAccount else { return } + await remove(lastFocusedAccount) + } + + // MARK: Windows + + /// Records that `windowState` is open, and shows an account in it once accounts are restored. + public func register(_ windowState: WindowState) { + windows.removeAll { $0.value == nil || $0.value === windowState } + windows.append(WeakWindowState(windowState)) + if hasRestored { + attach(windowState) + } + } + + /// Records that `windowState`'s window closed, so nothing is routed to it. + public func unregister(_ windowState: WindowState) { + windows.removeAll { $0.value == nil || $0.value === windowState } + } + + /// Records that `windowState` is the focused window. + public func focus(_ windowState: WindowState) { + windows.removeAll { $0.value == nil || $0.value === windowState } + windows.insert(WeakWindowState(windowState), at: 0) + if let accountID = windowState.accountID { + setLastFocusedAccount(accountID) + } + } + + /// Open windows, most recently focused first. + var openWindows: [WindowState] { + windows.compactMap(\.value) + } + + /// Connects `windowState` to its account's client, or to a fallback if its account is gone. + /// + /// A window keeps its own account if it still exists. Otherwise it shows the last focused + /// window's account, then the first account. + func attach(_ windowState: WindowState) { + let account = Self.accountToShow( + windowAccountID: windowState.accountID, lastFocusedAccountID: lastFocusedAccountID, + accountIDs: accounts.map(\.storeID) + ).flatMap { id in accounts.first { $0.storeID == id } } + guard account !== windowState.matrixClient || account?.storeID != windowState.accountID else { + return + } + windowState.showAccount(account, knownAccountIDs: Set(accounts.map(\.storeID))) + } + + /// The window that handles `accountID`'s verification requests: the most recently focused + /// window showing that account. + func verificationWindow(forAccountID accountID: String?) -> WindowState? { + guard let accountID else { return nil } + return openWindows.first { $0.accountID == accountID } + } + + /// Accounts with a verification request that no window shows, which the frontmost window's + /// switcher flags. + var accountsWithUnseenVerificationRequests: [MatrixClient] { + accounts.filter { account in + account.sessionVerificationRequest != nil + && !openWindows.contains { $0.accountID == account.storeID } + } + } + + /// Which account a window shows, given the account it showed before. + static func accountToShow( + windowAccountID: String?, lastFocusedAccountID: String?, accountIDs: [String] + ) -> String? { + [windowAccountID, lastFocusedAccountID].lazy.compactMap { $0 } + .first { accountIDs.contains($0) } ?? accountIDs.first + } + + private func setLastFocusedAccount(_ storeID: String?) { + let storeID = + storeID.flatMap { id in accounts.contains { $0.storeID == id } ? id : nil } + ?? accounts.first?.storeID + lastFocusedAccountID = storeID + accountStore.lastFocusedStoreID = storeID + // Banners for the focused window's account would duplicate what is on screen. + notificationRouter.activeAccountID = storeID + } + + private func discard(_ client: MatrixClient) async { + accounts.removeAll { $0 === client } do { - try await matrixClient?.reset() + try await client.reset() } catch { Logger.viewCycle.error("Failed to reset matrix client: \(error)") } - matrixClient = nil + } + + /// Opens the room of a clicked notification. + /// + /// The room opens in the most recently focused window already showing its account, brought to + /// the front. If no window shows the account, the frontmost window switches to it. + public func showNotificationTarget() { + // A click that launched the app arrives before accounts are restored or a window opens; + // handle it afterwards. + guard hasRestored, let target = notificationRouter.pendingTarget, + let windowState = Self.window(forAccountID: target.accountID, in: openWindows) + else { return } + notificationRouter.pendingTarget = nil + + if let accountID = target.accountID { + guard let account = accounts.first(where: { $0.storeID == accountID }) else { + Logger.viewCycle.info("Ignoring notification from a removed account") + return + } + // Switch the window now so the room below isn't treated as the previous account's. + show(account, in: windowState) + } + windowState.selectedRoomId = target.roomId + windowState.bringToFront() + } + + /// The window to show something of `accountID` in: the most recently focused window showing + /// that account, or else the frontmost window. `windows` is ordered most recently focused first. + static func window(forAccountID accountID: String?, in windows: [WindowState]) -> WindowState? { + windows.first { accountID != nil && $0.accountID == accountID } ?? windows.first + } + + /// Names the receiving account in notifications once more than one account is signed in. + private func updateNotificationLabels() { + let showsLabels = accounts.count > 1 + for account in accounts { + account.notifications.accountLabel = showsLabels ? account.userID : nil + } + } + + /// Shows the number of unread rooms across all accounts on the Dock icon. + private func observeDockBadge() { + let count = withObservationTracking { + accounts.reduce(0) { $0 + $1.unreadRoomCount } + } onChange: { [weak self] in + Task { @MainActor [weak self] in + self?.observeDockBadge() + } + } + + guard count != lastAppliedDockUnreadCount else { return } + NSApp?.dockTile.badgeLabel = count > 0 ? "\(count)" : nil + lastAppliedDockUnreadCount = count + } + + private func startSync(_ client: MatrixClient) { + client.networkConditions = networkConditions + Task { await client.startSync() } + } +} + +private struct WeakWindowState { + weak var value: WindowState? + + init(_ value: WindowState) { + self.value = value } } diff --git a/Sources/MactrixApp/Models/NetworkMonitor.swift b/Sources/MactrixApp/Models/NetworkMonitor.swift new file mode 100644 index 00000000..04dd07e8 --- /dev/null +++ b/Sources/MactrixApp/Models/NetworkMonitor.swift @@ -0,0 +1,60 @@ +import Foundation +import MatrixIntegration +import Network +import OSLog + +/// Reports the Mac's network connection: whether there is one and what it allows, and when it +/// comes back or switches to another interface. +/// +/// The sync service's offline mode only notices the network is back on its next scheduled check, +/// which backs off to several seconds apart. Restarting sync on a reconnect reconnects at once. +@MainActor +final class NetworkMonitor { + private let monitor = NWPathMonitor() + private var lastPath: NWPath? + + /// Starts reporting network changes. + /// + /// - Parameters: + /// - onConditionsChange: Called with the connection's conditions, whenever they change. + /// - onReconnect: Called each time the network comes back or switches interface. + init( + onConditionsChange: @escaping @MainActor (NetworkConditions) -> Void, + onReconnect: @escaping @MainActor () -> Void + ) { + monitor.pathUpdateHandler = { [weak self] path in + Task { @MainActor in + guard let self else { return } + let previous = self.lastPath + self.lastPath = path + let conditions = Self.conditions(of: path) + if previous.map(Self.conditions(of:)) != conditions { + onConditionsChange(conditions) + } + guard let previous, Self.isReconnect(from: previous, to: path) else { return } + Logger.matrixClient.info( + "Network came back on \(path.availableInterfaces.map(\.name), privacy: .public)") + onReconnect() + } + } + monitor.start(queue: DispatchQueue(label: "Mactrix.NetworkMonitor")) + } + + deinit { + monitor.cancel() + } + + nonisolated static func conditions(of path: NWPath) -> NetworkConditions { + NetworkConditions( + isAvailable: path.status == .satisfied, isExpensive: path.isExpensive, + isConstrained: path.isConstrained) + } + + /// Whether going from `previous` to `path` means requests that failed may work now: the + /// network came back, or it moved to other interfaces, such as from Wi-Fi to Ethernet. + nonisolated static func isReconnect(from previous: NWPath, to path: NWPath) -> Bool { + guard path.status == .satisfied else { return false } + return previous.status != .satisfied + || previous.availableInterfaces.map(\.name) != path.availableInterfaces.map(\.name) + } +} diff --git a/Sources/MactrixApp/Models/WindowState.swift b/Sources/MactrixApp/Models/WindowState.swift index f635bc14..60b788cd 100644 --- a/Sources/MactrixApp/Models/WindowState.swift +++ b/Sources/MactrixApp/Models/WindowState.swift @@ -70,6 +70,23 @@ public final class SelectedScreen: Identifiable { public static var none: SelectedScreen { SelectedScreen(.none) } } +/// Why the sign-in sheet is shown. +public enum LoginSheet: Identifiable, Equatable { + /// No account is signed in. + case firstAccount + case addAccount + /// The server ended this account's session. + case signInAgain(userID: String) + + public var id: String { + switch self { + case .firstAccount: "first" + case .addAccount: "add" + case .signInAgain(let userID): "again:\(userID)" + } + } +} + @MainActor @Observable public final class WindowState { public var selectedScreen: SelectedScreen = .none { @@ -87,6 +104,25 @@ public final class WindowState { var conversationSelection: ConversationMessageSelection? + /// The account whose rooms `selectedRoomId` and `selectedSpaceId` refer to. + public private(set) var accountID: String? + + /// The client of the account this window shows. `AppState` owns the clients. + public private(set) weak var matrixClient: MatrixClient? + + /// The window showing this state. + @ObservationIgnored weak var window: NSWindow? + + /// Brings this window to the front, selecting its tab and restoring it from the Dock. + func bringToFront() { + guard let window else { return } + if window.isMiniaturized { + window.deminiaturize(nil) + } + window.tabGroup?.selectedWindow = window + window.makeKeyAndOrderFront(nil) + } + public var selectedRoomId: String? { get { switch selectedScreen.content { @@ -122,12 +158,16 @@ public final class WindowState { } public var selectedSpaceId: String? + /// The last selection of accounts other than `accountID`, restored when switching back. + var accountSelections: [String: AccountSelection] = [:] public var inspectorVisible: Bool = false public var inspectorContent: InspectorContent = .roomInfo public var requestedVerification = false + public var loginSheet: LoginSheet? + public var searchQuery: String = "" public var searchTokens: [SearchToken] = [] public var searchDirectResult: SearchDirectResult? @@ -151,6 +191,41 @@ public final class WindowState { ) } + /// Shows `account`, remembering the current account's selection and restoring the new one's. + public func showAccount(_ account: MatrixClient?, knownAccountIDs: Set) { + showAccount(account?.storeID, knownAccountIDs: knownAccountIDs) + matrixClient = account + } + + /// Shows `newAccountID`, remembering the current account's selection and restoring the new one's. + /// + /// `knownAccountIDs` lists the accounts that still exist; selections of others are dropped. + public func showAccount(_ newAccountID: String?, knownAccountIDs: Set) { + accountSelections = accountSelections.filter { knownAccountIDs.contains($0.key) } + guard newAccountID != accountID else { return } + + // State saved before multi-account support has no account; it belongs to the first one shown. + if accountID == nil, newAccountID != nil, accountSelections.isEmpty { + accountID = newAccountID + return + } + + if let accountID, knownAccountIDs.contains(accountID) { + accountSelections[accountID] = AccountSelection( + roomId: selectedRoomId, spaceId: selectedSpaceId) + } + let restored = newAccountID.flatMap { accountSelections.removeValue(forKey: $0) } + accountID = newAccountID + selectedScreen = .none + selectedRoomId = restored?.roomId + selectedSpaceId = restored?.spaceId + inspectorContent = .roomInfo + searchQuery = "" + searchTokens = [] + searchDirectResult = nil + requestedVerification = false + } + public func toggleInspector() { if inspectorVisible { if inspectorContent == .roomInfo { @@ -235,18 +310,28 @@ public final class WindowState { } } +struct AccountSelection: Codable, Equatable { + var roomId: String? + var spaceId: String? +} + extension WindowState: @MainActor RawRepresentable { public struct SceneStorageRepresentation: Codable { let selectedRoomId: String? let selectedSpaceId: String? let inspectorVisible: Bool let sidebarSections: SidebarSectionCollapsibility + // Absent in state saved before multi-account support. + let accountID: String? + let accountSelections: [String: AccountSelection]? @MainActor init(windowState: WindowState) { self.selectedRoomId = windowState.selectedRoomId self.selectedSpaceId = windowState.selectedSpaceId self.inspectorVisible = windowState.inspectorVisible self.sidebarSections = windowState.sidebarSections + self.accountID = windowState.accountID + self.accountSelections = windowState.accountSelections } @MainActor func restore(windowState: WindowState) { @@ -254,6 +339,8 @@ extension WindowState: @MainActor RawRepresentable { windowState.selectedSpaceId = selectedSpaceId windowState.inspectorVisible = inspectorVisible windowState.sidebarSections = sidebarSections + windowState.accountID = accountID + windowState.accountSelections = accountSelections ?? [:] } } diff --git a/Sources/MactrixApp/Views/ChatView/ChatRoomViewController.swift b/Sources/MactrixApp/Views/ChatView/ChatRoomViewController.swift index 76be2171..d8b9babf 100644 --- a/Sources/MactrixApp/Views/ChatView/ChatRoomViewController.swift +++ b/Sources/MactrixApp/Views/ChatView/ChatRoomViewController.swift @@ -8,15 +8,15 @@ final class ChatRoomViewController: NSViewController { private var composerAccessory: NSViewController? init( - appState: AppState, windowState: WindowState, timeline: LiveTimeline, + windowState: WindowState, timeline: LiveTimeline, composer: ChatComposerState ) { timelineController = TimelineViewController( - appState: appState, windowState: windowState, timeline: timeline, composer: composer) + windowState: windowState, timeline: timeline, composer: composer) composerController = ChatInputViewController( room: timeline.room.room, timeline: timeline, composer: composer, - imageLoader: appState.matrixClient, - avatarURLLookup: { [weak matrixClient = appState.matrixClient] userID in + imageLoader: windowState.matrixClient, + avatarURLLookup: { [weak matrixClient = windowState.matrixClient] userID in guard let matrixClient else { return nil } let profile = try await matrixClient.client.getProfile(userId: userID) return profile.avatarUrl diff --git a/Sources/MactrixApp/Views/ChatView/ChatRoomViewRepresentable.swift b/Sources/MactrixApp/Views/ChatView/ChatRoomViewRepresentable.swift index 5060c824..c03847e9 100644 --- a/Sources/MactrixApp/Views/ChatView/ChatRoomViewRepresentable.swift +++ b/Sources/MactrixApp/Views/ChatView/ChatRoomViewRepresentable.swift @@ -2,7 +2,6 @@ import MatrixIntegration import SwiftUI struct ChatRoomViewRepresentable: NSViewControllerRepresentable { - @Environment(AppState.self) private var appState @Environment(WindowState.self) private var windowState @Environment(\.accessibilityReduceTransparency) private var reduceTransparency @AppStorage("fontSize") private var fontSize = 13 @@ -12,7 +11,7 @@ struct ChatRoomViewRepresentable: NSViewControllerRepresentable { func makeNSViewController(context: Context) -> ChatRoomViewController { ChatRoomViewController( - appState: appState, windowState: windowState, timeline: timeline, composer: composer) + windowState: windowState, timeline: timeline, composer: composer) } func updateNSViewController(_ controller: ChatRoomViewController, context: Context) { diff --git a/Sources/MactrixApp/Views/ChatView/ChatView.swift b/Sources/MactrixApp/Views/ChatView/ChatView.swift index 4910ebdb..54ce03a9 100644 --- a/Sources/MactrixApp/Views/ChatView/ChatView.swift +++ b/Sources/MactrixApp/Views/ChatView/ChatView.swift @@ -13,7 +13,7 @@ private struct TimelineReadKey: Equatable { } struct ChatJoinedRoom: View { - @Environment(AppState.self) private var appState + @Environment(WindowState.self) private var windowState @Environment(\.appearsActive) private var appearsActive @Bindable var timeline: LiveTimeline @State private var composer = ChatComposerState() @@ -42,7 +42,8 @@ struct ChatJoinedRoom: View { .task(priority: .background) { do { try await Task.sleep(for: .seconds(2)) - try await appState.matrixClient?.client.trackRecentlyVisitedRoom(room: timeline.room.id) + try await windowState.matrixClient?.client.trackRecentlyVisitedRoom( + room: timeline.room.id) Logger.viewCycle.debug("marked room as recently visited: \(timeline.room.id)") } catch is CancellationError { /* sleep cancelled */ diff --git a/Sources/MactrixApp/Views/ChatView/TimelineView/MessageHoverOverlayView.swift b/Sources/MactrixApp/Views/ChatView/TimelineView/MessageHoverOverlayView.swift index 3e1777ec..30487cc6 100644 --- a/Sources/MactrixApp/Views/ChatView/TimelineView/MessageHoverOverlayView.swift +++ b/Sources/MactrixApp/Views/ChatView/TimelineView/MessageHoverOverlayView.swift @@ -10,6 +10,7 @@ final class MessageHoverOverlayView: NSView { case pin case edit case delete + case retrySend case copyMessageLink case showSource case downloadToFile(Int) @@ -44,6 +45,8 @@ final class MessageHoverOverlayView: NSView { private let copyLinkMenuItem = NSMenuItem( title: String(localized: "Copy Message Link"), action: #selector(copyMessageLink), keyEquivalent: "") + private let retrySendMenuItem = NSMenuItem( + title: String(localized: "Retry Sending"), action: #selector(retrySend), keyEquivalent: "") private let deleteMenuItem = NSMenuItem( title: String(localized: "Delete message"), action: #selector(deleteMessage), keyEquivalent: "") private let editButton = HoverActionButton( @@ -119,6 +122,11 @@ final class MessageHoverOverlayView: NSView { let sourceMenuItem = NSMenuItem( title: String(localized: "Show Source"), action: #selector(showSource), keyEquivalent: "") + retrySendMenuItem.target = self + retrySendMenuItem.image = NSImage( + systemSymbolName: "arrow.clockwise", accessibilityDescription: retrySendMenuItem.title) + menu.addItem(retrySendMenuItem) + pinMenuItem.target = self menu.addItem(pinMenuItem) @@ -165,8 +173,9 @@ final class MessageHoverOverlayView: NSView { func configure( canReply: Bool, canEdit: Bool = false, canDelete: Bool = false, canReact: Bool = true, canPin: Bool = false, isPinned: Bool = false, - canCopyLink: Bool = false, downloadFilenames: [String] = [] + canCopyLink: Bool = false, canRetrySend: Bool = false, downloadFilenames: [String] = [] ) { + retrySendMenuItem.isHidden = !canRetrySend reactionPickerButton.isEnabled = canReact for button in quickReactionButtons { button.isEnabled = canReact @@ -250,6 +259,10 @@ final class MessageHoverOverlayView: NSView { onAction?(.pin) } + @objc private func retrySend() { + onAction?(.retrySend) + } + @objc private func deleteMessage() { onAction?(.delete) } diff --git a/Sources/MactrixApp/Views/ChatView/TimelineView/TimelineRowViews/MessageRowView.swift b/Sources/MactrixApp/Views/ChatView/TimelineView/TimelineRowViews/MessageRowView.swift index c42344ff..140fd2a3 100644 --- a/Sources/MactrixApp/Views/ChatView/TimelineView/TimelineRowViews/MessageRowView.swift +++ b/Sources/MactrixApp/Views/ChatView/TimelineView/TimelineRowViews/MessageRowView.swift @@ -11,6 +11,8 @@ final class MessageRowView: NSView { var onHoverChange: ((MessageRowView, Bool, NSEvent) -> Bool)? var onSelectRequest: ((MessageRowView) -> Void)? var onArrowKey: ((TimelineSelectionDirection) -> Void)? + /// Called when the send status icon of an unsent message is clicked, with the icon to anchor to. + var onSendStatusClick: ((NSView) -> Void)? var onMediaPreviewRequest: (() -> Bool)? { didSet { (contentView as? any MessageMediaPreviewContentView)?.onMediaPreviewRequest = @@ -34,6 +36,8 @@ final class MessageRowView: NSView { private let timestamp = NSTextField(labelWithString: "") private let editedLabel = NSTextField(labelWithString: String(localized: "(edited)")) + /// Takes the timestamp's place while the message hasn't reached the server. + private let sendStatusButton = NSButton() private lazy var timestampWidthConstraint = timestamp.widthAnchor.constraint( equalToConstant: Self.timestampWidth) private let contentView: any MessageContentRowView @@ -94,6 +98,13 @@ final class MessageRowView: NSView { editedLabel.isHidden = true editedLabel.translatesAutoresizingMaskIntoConstraints = false + sendStatusButton.isBordered = false + sendStatusButton.imagePosition = .imageOnly + sendStatusButton.target = self + sendStatusButton.action = #selector(sendStatusClicked) + sendStatusButton.isHidden = true + sendStatusButton.translatesAutoresizingMaskIntoConstraints = false + contentView.translatesAutoresizingMaskIntoConstraints = false contentView.onSelectRequest = { [weak self] in guard let self else { return } @@ -115,6 +126,7 @@ final class MessageRowView: NSView { addSubview(timestamp) addSubview(editedLabel) + addSubview(sendStatusButton) addSubview(contentView) // NSTableView may retain an old encapsulated height while a reused row is reconfigured. @@ -126,6 +138,8 @@ final class MessageRowView: NSView { editedLabel.leadingAnchor.constraint(equalTo: timestamp.leadingAnchor), editedLabel.trailingAnchor.constraint(equalTo: timestamp.trailingAnchor), editedLabel.topAnchor.constraint(equalTo: timestamp.bottomAnchor, constant: 1), + sendStatusButton.trailingAnchor.constraint(equalTo: timestamp.trailingAnchor), + sendStatusButton.centerYAnchor.constraint(equalTo: timestamp.centerYAnchor), contentView.leadingAnchor.constraint(equalTo: timestamp.trailingAnchor, constant: 16), contentView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10), @@ -177,6 +191,7 @@ final class MessageRowView: NSView { let date = Date(timeIntervalSince1970: Double(event.timestamp) / 1000) timestamp.stringValue = Self.timeFormatter.string(from: date) editedLabel.isHidden = !Self.hasBeenEdited(content) + configureSendStatus(MessageSendStatus(event.localSendState)) contentView.handleMatrixUri = handleMatrixUri contentView.configure(content: content, matrixClient: matrixClient) configureReply(details: replyDetails, onClick: onReplyClick) @@ -189,6 +204,29 @@ final class MessageRowView: NSView { updateBackground() } + private func configureSendStatus(_ status: MessageSendStatus?) { + timestamp.isHidden = status != nil + sendStatusButton.isHidden = status == nil + // Dimmed until the message reaches the server, so it doesn't pass for a sent one. + contentView.alphaValue = status == nil ? 1 : 0.5 + guard let status else { + sendStatusButton.toolTip = nil + return + } + let configuration = NSImage.SymbolConfiguration( + pointSize: TimelineTypography.scaled(NSFont.labelFontSize), weight: .regular) + sendStatusButton.image = NSImage( + systemSymbolName: status.symbolName, accessibilityDescription: status.toolTip)? + .withSymbolConfiguration(configuration) + sendStatusButton.contentTintColor = status.tintColor + sendStatusButton.toolTip = status.toolTip + sendStatusButton.setAccessibilityLabel(status.toolTip) + } + + @objc private func sendStatusClicked() { + onSendStatusClick?(sendStatusButton) + } + private func configureThread(summary: MatrixRustSDK.ThreadSummary?, onClick: (() -> Void)?) { guard let summary else { threadSummaryView?.isHidden = true diff --git a/Sources/MactrixApp/Views/ChatView/TimelineView/TimelineRowViews/Support/MessageSendStatus.swift b/Sources/MactrixApp/Views/ChatView/TimelineView/TimelineRowViews/Support/MessageSendStatus.swift new file mode 100644 index 00000000..8b843150 --- /dev/null +++ b/Sources/MactrixApp/Views/ChatView/TimelineView/TimelineRowViews/Support/MessageSendStatus.swift @@ -0,0 +1,69 @@ +import AppKit +import MatrixRustSDK + +/// Whether a message the user sent is still on its way to the server, or failed to get there. +/// +/// Messages that reached the server, and other people's messages, have no status. +enum MessageSendStatus: Equatable { + /// The message is queued or being sent. + case queued + /// Sending failed. The message stays queued until it's retried or deleted. + case failed(reason: String) + + init?(_ state: MatrixRustSDK.EventSendState?) { + switch state { + case .notSentYet: + self = .queued + case .sendingFailed(let error, let isRecoverable): + // A recoverable failure is a network or server error, which the error itself doesn't + // describe any better. + self = .failed( + reason: isRecoverable + ? String(localized: "The server couldn't be reached.") : Self.reason(for: error)) + case .sent, nil: + return nil + } + } + + var symbolName: String { + switch self { + case .queued: "clock" + case .failed: "exclamationmark.circle.fill" + } + } + + var tintColor: NSColor { + switch self { + case .queued: .secondaryLabelColor + case .failed: .systemRed + } + } + + var toolTip: String { + switch self { + case .queued: + String(localized: "Not sent yet") + case .failed(let reason): + String(localized: "Not sent. \(reason) Click to retry or delete.") + } + } + + private static func reason(for error: MatrixRustSDK.QueueWedgeError) -> String { + switch error { + case .insecureDevices: + String(localized: "Some devices in this room aren't verified.") + case .identityViolations: + String(localized: "Someone in this room changed their identity.") + case .crossVerificationRequired: + String(localized: "Verify this session to send messages.") + case .expiredAccessToken: + String(localized: "Your session expired.") + case .missingMediaContent: + String(localized: "The attachment is no longer available.") + case .invalidMimeType: + String(localized: "The attachment's file type isn't recognized.") + case .genericApiError(let message): + message + } + } +} diff --git a/Sources/MactrixApp/Views/ChatView/TimelineView/TimelineTableView.swift b/Sources/MactrixApp/Views/ChatView/TimelineView/TimelineTableView.swift index bda75862..013f02ac 100644 --- a/Sources/MactrixApp/Views/ChatView/TimelineView/TimelineTableView.swift +++ b/Sources/MactrixApp/Views/ChatView/TimelineView/TimelineTableView.swift @@ -104,7 +104,6 @@ extension TimelineItemRowInfo: Identifiable { class TimelineViewController: NSViewController, LiveTimelineFocusDelegate, LiveTimelineDiffDelegate { - let appState: AppState let windowState: WindowState private var actionTasks: [UUID: Task] = [:] @@ -156,10 +155,9 @@ class TimelineViewController: NSViewController, LiveTimelineFocusDelegate, LiveT private(set) var timelineItems: [TimelineItemRowInfo] = [] init( - appState: AppState, windowState: WindowState, timeline: LiveTimeline, + windowState: WindowState, timeline: LiveTimeline, composer: ChatComposerState ) { - self.appState = appState self.windowState = windowState self.timeline = timeline self.composer = composer @@ -266,7 +264,7 @@ class TimelineViewController: NSViewController, LiveTimelineFocusDelegate, LiveT } else { let view = MessageProfileRowView() view.initialize( - imageLoader: appState.matrixClient, + imageLoader: windowState.matrixClient, focusUser: { [weak self] in self?.windowState.focusUser(userId: $0) }) @@ -329,6 +327,9 @@ class TimelineViewController: NSViewController, LiveTimelineFocusDelegate, LiveT self.showMediaPreview( url: url, handle: handle, eventIdentifier: event.eventOrTransactionId.id) } + view.onSendStatusClick = { [weak self] anchor in + self?.showSendStatusMenu(for: event, from: anchor) + } view.configureEditing(messageEdit?.id == event.eventOrTransactionId ? messageEdit : nil) view.configure( event: event, @@ -338,12 +339,12 @@ class TimelineViewController: NSViewController, LiveTimelineFocusDelegate, LiveT onThreadClick: { [weak self] in self?.windowState.focusThread(rootEventId: event.eventOrTransactionId.id) }, - ownUserId: try? self.appState.matrixClient?.client.userId(), + ownUserId: try? self.windowState.matrixClient?.client.userId(), onReactionClick: { [weak self] key in self?.toggleReaction(key, for: event) }, roomMembers: self.timeline.room.members, - matrixClient: self.appState.matrixClient, + matrixClient: self.windowState.matrixClient, handleMatrixUri: { [weak self] matrixUri in guard let self else { return false } self.handleMatrixUri(matrixUri) @@ -412,7 +413,7 @@ class TimelineViewController: NSViewController, LiveTimelineFocusDelegate, LiveT listenForRecentReactions() listenForRoomInfo() listenForTimelinePagination() - if let recentReactions = appState.matrixClient?.recentReactions { + if let recentReactions = windowState.matrixClient?.recentReactions { startActionTask { _ = await recentReactions.refresh() } @@ -549,7 +550,7 @@ class TimelineViewController: NSViewController, LiveTimelineFocusDelegate, LiveT } private func listenForRecentReactions() { - guard let recentReactions = appState.matrixClient?.recentReactions else { return } + guard let recentReactions = windowState.matrixClient?.recentReactions else { return } let keys = withObservationTracking { recentReactions.isActive ? recentReactions.cachedKeys : [] } onChange: { [weak self] in @@ -597,6 +598,7 @@ class TimelineViewController: NSViewController, LiveTimelineFocusDelegate, LiveT canPin: canPerformMessageAction(.pin, for: event), isPinned: isMessagePinned(event), canCopyLink: canPerformMessageAction(.copyMessageLink, for: event), + canRetrySend: canPerformMessageAction(.retrySend, for: event), downloadFilenames: MessageDownloadAttachment.attachments(for: event).map(\.suggestedFilename)) } @@ -701,7 +703,7 @@ class TimelineViewController: NSViewController, LiveTimelineFocusDelegate, LiveT private func toggleReaction(_ key: String, for event: MatrixRustSDK.EventTimelineItem) { guard let sdkTimeline = timeline.timeline else { return } - let recents = appState.matrixClient?.recentReactions + let recents = windowState.matrixClient?.recentReactions startActionTask { do { if let recents { @@ -718,6 +720,35 @@ class TimelineViewController: NSViewController, LiveTimelineFocusDelegate, LiveT } } + /// Shows what can be done with a message that hasn't been sent, below its send status icon. + private func showSendStatusMenu(for event: MatrixRustSDK.EventTimelineItem, from anchor: NSView) { + let menu = NSMenu() + menu.autoenablesItems = false + for (action, title, symbol) in [ + ( + MessageHoverOverlayView.Action.retrySend, String(localized: "Retry Sending"), + "arrow.clockwise" + ), + (.delete, String(localized: "Delete message"), "trash"), + ] where canPerformMessageAction(action, for: event) { + let item = NSMenuItem( + title: title, action: #selector(performSendStatusMenuItem(_:)), keyEquivalent: "") + item.target = self + item.image = NSImage(systemSymbolName: symbol, accessibilityDescription: title) + item.representedObject = PendingMessageAction(action: action, event: event) + menu.addItem(item) + } + guard !menu.items.isEmpty else { return } + let origin = NSPoint( + x: anchor.bounds.minX, y: anchor.isFlipped ? anchor.bounds.maxY + 4 : anchor.bounds.minY - 4) + menu.popUp(positioning: nil, at: origin, in: anchor) + } + + @objc private func performSendStatusMenuItem(_ sender: NSMenuItem) { + guard let pending = sender.representedObject as? PendingMessageAction else { return } + performMessageAction(pending.action, for: pending.event) + } + private func canDeleteMessage(_ event: MatrixRustSDK.EventTimelineItem) -> Bool { guard let powerLevels = timeline.room.roomInfo?.powerLevels else { return false } return event.isOwn @@ -761,13 +792,16 @@ class TimelineViewController: NSViewController, LiveTimelineFocusDelegate, LiveT && timeline.room.roomInfo?.powerLevels?.canOwnUserPinUnpin() == true case .delete: return timeline.timeline != nil && canDeleteMessage(event) + case .retrySend: + guard case .sendingFailed = event.localSendState else { return false } + return event.lazyProvider.getSendHandle() != nil case .copyMessageLink: if case .eventId = event.eventOrTransactionId { return true } return false case .showSource: return true case .downloadToFile(let index): - return appState.matrixClient != nil + return windowState.matrixClient != nil && MessageDownloadAttachment.attachments(for: event).indices.contains(index) } } @@ -800,13 +834,29 @@ class TimelineViewController: NSViewController, LiveTimelineFocusDelegate, LiveT Logger.timelineTableView.error("Failed to copy message link: \(error)") } } + case .retrySend: + guard case .sendingFailed = event.localSendState, + let sendHandle = event.lazyProvider.getSendHandle() + else { return } + let room = timeline.room.room + startActionTask { + // A network failure turned the room's send queue off; an unrecoverable one parked the + // message. Undo both, so the message goes out whichever it was. + room.enableSendQueue(enable: true) + do { + try await sendHandle.tryResend() + } catch { + guard !Task.isCancelled else { return } + Logger.timelineTableView.error("Failed to retry sending message: \(error)") + } + } case .showSource: MessageSourceWindowController.show(source: event.lazyProvider.latestJson()) case .downloadToFile(let index): let attachments = MessageDownloadAttachment.attachments(for: event) guard attachments.indices.contains(index) else { return } startActionTask { [weak self] in - guard let self = self, let matrixClient = appState.matrixClient else { return } + guard let self = self, let matrixClient = windowState.matrixClient else { return } await MessageDownloadAttachment.downloadToFile( view: view, matrixClient: matrixClient, attachment: attachments[index]) } @@ -1375,7 +1425,7 @@ extension TimelineViewController: NSPopoverDelegate { let picker = ReactionPickerViewController( model: try ReactionPickerModel.loadBundled(), - recentReactions: appState.matrixClient?.recentReactions) + recentReactions: windowState.matrixClient?.recentReactions) let popover = NSPopover() popover.behavior = .transient popover.contentViewController = picker @@ -1622,7 +1672,7 @@ extension TimelineViewController { let state = MessageEditState(id: event.eventOrTransactionId, text: text) state.mentionCandidateProvider = { [weak room = timeline.room] in room?.members ?? [] } - state.imageLoader = appState.matrixClient + state.imageLoader = windowState.matrixClient state.onChange = { [weak self, weak state] in guard let self, let state, self.messageEdit === state, let row = self.rowForEventId(id: state.id) @@ -1883,3 +1933,14 @@ final class TimelineDocumentView: NSView { scrollView.reflectScrolledClipView(clipView) } } + +/// A message action waiting on a menu item, which can only hold an object. +private final class PendingMessageAction: NSObject { + let action: MessageHoverOverlayView.Action + let event: MatrixRustSDK.EventTimelineItem + + init(action: MessageHoverOverlayView.Action, event: MatrixRustSDK.EventTimelineItem) { + self.action = action + self.event = event + } +} diff --git a/Sources/MactrixApp/Views/Inspector/InspectorScreen.swift b/Sources/MactrixApp/Views/Inspector/InspectorScreen.swift index 878a0baf..c3c86dd4 100644 --- a/Sources/MactrixApp/Views/Inspector/InspectorScreen.swift +++ b/Sources/MactrixApp/Views/Inspector/InspectorScreen.swift @@ -6,7 +6,6 @@ import OSLog import SwiftUI struct InspectorScreen: View { - @Environment(AppState.self) var appState @Environment(WindowState.self) var windowState func onSelectUser(user: MatrixRustSDK.RoomMember) { @@ -38,7 +37,7 @@ struct InspectorScreen: View { case .joinedRoom(let timeline): MactrixUI.RoomInspectorView( room: timeline.room, members: timeline.room.members, roomInfo: timeline.room.roomInfo, - imageLoader: appState.matrixClient, onSelectUser: onSelectUser, + imageLoader: windowState.matrixClient, onSelectUser: onSelectUser, inspectorVisible: $windowState.inspectorVisible) case .none, .newRoom, .previewRoom, .loadMatrixUrl(_), .loadingRoom, .user(profile: _): Text("No room selected") diff --git a/Sources/MactrixApp/Views/Inspector/InspectorUserInfo.swift b/Sources/MactrixApp/Views/Inspector/InspectorUserInfo.swift index 4b791b91..dbff01d6 100644 --- a/Sources/MactrixApp/Views/Inspector/InspectorUserInfo.swift +++ b/Sources/MactrixApp/Views/Inspector/InspectorUserInfo.swift @@ -5,7 +5,6 @@ import OSLog import SwiftUI struct InspectorUserInfo: View { - @Environment(AppState.self) private var appState @Environment(WindowState.self) private var windowState let userId: String @@ -13,7 +12,7 @@ struct InspectorUserInfo: View { @State private var profile: MatrixRustSDK.UserProfile? var isUserIgnored: Bool { - appState.matrixClient?.ignoredUserIds.contains(userId) == true + windowState.matrixClient?.ignoredUserIds.contains(userId) == true } @ViewBuilder @@ -22,10 +21,10 @@ struct InspectorUserInfo: View { MactrixUI.UserProfileView( profile: profile, isUserIgnored: isUserIgnored, - actions: appState.matrixClient?.userProfileActions( + actions: windowState.matrixClient?.userProfileActions( forUserId: userId, windowState: windowState), timelineActions: nil, - imageLoader: appState.matrixClient + imageLoader: windowState.matrixClient ) } else { MactrixUI.UserProfileView( @@ -33,7 +32,7 @@ struct InspectorUserInfo: View { isUserIgnored: isUserIgnored, actions: nil, timelineActions: nil, - imageLoader: appState.matrixClient + imageLoader: windowState.matrixClient ) .redacted(reason: .placeholder) } @@ -42,7 +41,7 @@ struct InspectorUserInfo: View { var body: some View { content .task(id: userId) { - guard let matrixClient = appState.matrixClient else { return } + guard let matrixClient = windowState.matrixClient else { return } do { profile = try await matrixClient.client.getProfile(userId: userId) diff --git a/Sources/MactrixApp/Views/LoadDestinationScreen.swift b/Sources/MactrixApp/Views/LoadDestinationScreen.swift index 041bd23b..bd4ff0a3 100644 --- a/Sources/MactrixApp/Views/LoadDestinationScreen.swift +++ b/Sources/MactrixApp/Views/LoadDestinationScreen.swift @@ -5,7 +5,6 @@ import SwiftUI import Utils struct LoadDestinationScreen: View { - @Environment(AppState.self) var appState @Environment(WindowState.self) var windowState let screen: SelectedScreen @@ -51,7 +50,7 @@ struct LoadDestinationScreen: View { } .task( id: LoadRequest( - attempt: retryAttempt, client: appState.matrixClient.map { ObjectIdentifier($0) }) + attempt: retryAttempt, client: windowState.matrixClient.map { ObjectIdentifier($0) }) ) { await load() } @@ -61,7 +60,7 @@ struct LoadDestinationScreen: View { private func load() async { guard windowState.selectedScreen === screen, !Task.isCancelled else { return } errorMessage = nil - guard let matrixClient = appState.matrixClient else { + guard let matrixClient = windowState.matrixClient else { errorMessage = String(localized: "Sign in to continue.") return } @@ -69,13 +68,13 @@ struct LoadDestinationScreen: View { do { let destination = try await resolve(using: matrixClient) try Task.checkCancellation() - guard windowState.selectedScreen === screen, appState.matrixClient === matrixClient else { + guard windowState.selectedScreen === screen, windowState.matrixClient === matrixClient else { return } windowState.selectedScreen = destination } catch { guard !Task.isCancelled, windowState.selectedScreen === screen, - appState.matrixClient === matrixClient + windowState.matrixClient === matrixClient else { return } Logger.viewCycle.error("Failed to open destination: \(error)") errorMessage = error.localizedDescription @@ -112,7 +111,7 @@ struct LoadDestinationScreen: View { } try Task.checkCancellation() - guard windowState.selectedScreen === screen, appState.matrixClient === matrixClient else { + guard windowState.selectedScreen === screen, windowState.matrixClient === matrixClient else { throw CancellationError() } diff --git a/Sources/MactrixApp/Views/MatrixImageView.swift b/Sources/MactrixApp/Views/MatrixImageView.swift index a8637f03..f7efd472 100644 --- a/Sources/MactrixApp/Views/MatrixImageView.swift +++ b/Sources/MactrixApp/Views/MatrixImageView.swift @@ -7,7 +7,7 @@ struct MatrixImageView: View { let mediaSource: MediaSource? let mimeType: String? - @Environment(AppState.self) private var appState + @Environment(WindowState.self) private var windowState @State private var image: Image? = nil @State private var errorMessage: String? = nil @@ -44,7 +44,7 @@ struct MatrixImageView: View { content .task(id: mediaSource?.url(), priority: .utility) { guard image == nil else { return } - guard let matrixClient = appState.matrixClient else { + guard let matrixClient = windowState.matrixClient else { errorMessage = String(localized: "Matrix client not available") return } diff --git a/Sources/MactrixApp/Views/Search/SearchInspectorView.swift b/Sources/MactrixApp/Views/Search/SearchInspectorView.swift index 4699df3d..7ff24d54 100644 --- a/Sources/MactrixApp/Views/Search/SearchInspectorView.swift +++ b/Sources/MactrixApp/Views/Search/SearchInspectorView.swift @@ -5,7 +5,6 @@ import OSLog import SwiftUI struct SearchResolvedRoomInspectorView: View { - @Environment(AppState.self) var appState @Environment(WindowState.self) var windowState @State private var roomPreview: MatrixRustSDK.RoomPreview? @@ -15,7 +14,7 @@ struct SearchResolvedRoomInspectorView: View { var roomActions: RoomPreviewActions? { guard let preview = roomPreview else { return nil } - return appState.matrixClient?.roomPreviewActions( + return windowState.matrixClient?.roomPreviewActions( forRoomWithId: preview.info().roomId, windowState: windowState, routingVia: resolvedRoom.servers) } @@ -25,13 +24,13 @@ struct SearchResolvedRoomInspectorView: View { if let roomPreview { MactrixUI.RoomPreviewView( preview: roomPreview.info(), - imageLoader: appState.matrixClient, + imageLoader: windowState.matrixClient, actions: roomActions ) } else { MactrixUI.RoomPreviewView( preview: MockRoomPreviewInfo(), - imageLoader: appState.matrixClient, + imageLoader: windowState.matrixClient, actions: roomActions ) .redacted(reason: .placeholder) @@ -39,7 +38,7 @@ struct SearchResolvedRoomInspectorView: View { } .task(id: alias, priority: .utility) { do { - guard let matrixClient = appState.matrixClient else { return } + guard let matrixClient = windowState.matrixClient else { return } let preview = try await matrixClient.client.getRoomPreviewFromRoomId( roomId: resolvedRoom.roomId, viaServers: matrixClient.routingServers(hints: resolvedRoom.servers)) @@ -52,7 +51,6 @@ struct SearchResolvedRoomInspectorView: View { } struct SearchInspectorView: View { - @Environment(AppState.self) var appState @Environment(WindowState.self) var windowState @ViewBuilder @@ -71,18 +69,18 @@ struct SearchInspectorView: View { case .resolvedRoomId(let roomPreview): MactrixUI.RoomPreviewView( preview: roomPreview.info(), - imageLoader: appState.matrixClient, - actions: appState.matrixClient?.roomPreviewActions( + imageLoader: windowState.matrixClient, + actions: windowState.matrixClient?.roomPreviewActions( forRoomWithId: roomPreview.info().roomId, windowState: windowState) ) case .resolvedUser(profile: let userProfile): MactrixUI.UserProfileView( profile: userProfile, - isUserIgnored: appState.matrixClient?.isUserIgnored(userProfile.userId) == true, - actions: appState.matrixClient?.userProfileActions( + isUserIgnored: windowState.matrixClient?.isUserIgnored(userProfile.userId) == true, + actions: windowState.matrixClient?.userProfileActions( forUserId: userProfile.userId, windowState: windowState), timelineActions: nil, - imageLoader: appState.matrixClient + imageLoader: windowState.matrixClient ) case nil: ContentUnavailableView("Select a search term", systemImage: "magnifyingglass") diff --git a/Sources/MactrixApp/Views/Search/SearchMessagesInspectorView.swift b/Sources/MactrixApp/Views/Search/SearchMessagesInspectorView.swift index 6ba81007..4a6c40a5 100644 --- a/Sources/MactrixApp/Views/Search/SearchMessagesInspectorView.swift +++ b/Sources/MactrixApp/Views/Search/SearchMessagesInspectorView.swift @@ -4,22 +4,24 @@ import OSLog import SwiftUI struct SearchMessagesInspectorView: View { - @Environment(AppState.self) var appState @Environment(WindowState.self) var windowState @State var selectedMessage: String? = nil @State var searchService: LiveSearchService? = nil + /// The account `searchService` searches. + @State private var searchServiceStoreID: String? = nil @ViewBuilder var content: some View { let results = searchService?.results ?? [] let query = windowState.searchQuery + let matrixClient = windowState.matrixClient ForEach(results) { searchResult in let paginationQuery = searchResult.id == results.last?.id && searchService?.activeQuery == query ? query : nil - SearchMessageRowView(result: searchResult, query: query, matrixClient: appState.matrixClient) + SearchMessageRowView(result: searchResult, query: query, matrixClient: matrixClient) .task(id: paginationQuery) { guard let paginationQuery, paginationQuery == windowState.searchQuery else { return } do { @@ -59,16 +61,18 @@ struct SearchMessagesInspectorView: View { .task(id: query) { do { try await Task.sleep(for: .milliseconds(500)) - guard let matrixClient = appState.matrixClient else { return } + guard let matrixClient = windowState.matrixClient else { return } + // The window may have switched accounts since the service was made. let searchService: LiveSearchService - if let s = self.searchService { + if let s = self.searchService, searchServiceStoreID == matrixClient.storeID { searchService = s } else { searchService = await LiveSearchService( searchService: matrixClient.client.searchService()) try Task.checkCancellation() self.searchService = searchService + searchServiceStoreID = matrixClient.storeID } try await searchService.search(query: query) diff --git a/Sources/MactrixApp/Views/Search/SearchRoomInspectorView.swift b/Sources/MactrixApp/Views/Search/SearchRoomInspectorView.swift index fdab1e25..781b8880 100644 --- a/Sources/MactrixApp/Views/Search/SearchRoomInspectorView.swift +++ b/Sources/MactrixApp/Views/Search/SearchRoomInspectorView.swift @@ -5,7 +5,6 @@ import OSLog import SwiftUI struct SearchRoomInspectorView: View { - @Environment(AppState.self) var appState @Environment(WindowState.self) var windowState @State var searching: Bool = true @@ -46,7 +45,7 @@ struct SearchRoomInspectorView: View { } .task(id: windowState.searchQuery) { do { - guard let matrixClient = appState.matrixClient else { return } + guard let matrixClient = windowState.matrixClient else { return } let roomSearch: LiveRoomSearch if let rs = self.roomSearch { diff --git a/Sources/MactrixApp/Views/Search/SearchUserInspectorView.swift b/Sources/MactrixApp/Views/Search/SearchUserInspectorView.swift index 2f88c305..422f286b 100644 --- a/Sources/MactrixApp/Views/Search/SearchUserInspectorView.swift +++ b/Sources/MactrixApp/Views/Search/SearchUserInspectorView.swift @@ -4,7 +4,6 @@ import OSLog import SwiftUI struct SearchUserInspectorView: View { - @Environment(AppState.self) var appState @Environment(WindowState.self) var windowState @State var searchedUsers: [UserProfile] = [] @@ -22,7 +21,7 @@ struct SearchUserInspectorView: View { }.redacted(reason: .placeholder) } else { ForEach(searchedUsers) { user in - MactrixUI.UserProfileRow(profile: user, imageLoader: appState.matrixClient) + MactrixUI.UserProfileRow(profile: user, imageLoader: windowState.matrixClient) } } } @@ -34,7 +33,7 @@ struct SearchUserInspectorView: View { } .task(id: windowState.searchQuery) { do { - guard let matrixClient = appState.matrixClient else { return } + guard let matrixClient = windowState.matrixClient else { return } guard !windowState.searchQuery.isEmpty else { searchedUsers = [] return diff --git a/Sources/MactrixApp/Views/Search/SearchViewModifier.swift b/Sources/MactrixApp/Views/Search/SearchViewModifier.swift index a40f7e1b..1ba290dc 100644 --- a/Sources/MactrixApp/Views/Search/SearchViewModifier.swift +++ b/Sources/MactrixApp/Views/Search/SearchViewModifier.swift @@ -4,7 +4,6 @@ import SwiftUI import Utils struct SearchViewModifier: ViewModifier { - @Environment(AppState.self) var appState @Environment(WindowState.self) var windowState func body(content: Content) -> some View { @@ -129,7 +128,7 @@ struct SearchViewModifier: ViewModifier { }() do { - guard let matrixClient = appState.matrixClient else { return } + guard let matrixClient = windowState.matrixClient else { return } try await Task.sleep(for: .milliseconds(300)) let roomAliasRegex = /\#[^:]+\:[^\s]*/ diff --git a/Sources/MactrixApp/Views/Settings/AccountSettingsView.swift b/Sources/MactrixApp/Views/Settings/AccountSettingsView.swift index a9b82a3d..67833f8f 100644 --- a/Sources/MactrixApp/Views/Settings/AccountSettingsView.swift +++ b/Sources/MactrixApp/Views/Settings/AccountSettingsView.swift @@ -48,20 +48,32 @@ struct AccountSettingsView: View { @State private var displayName: String? = nil var body: some View { - if let matrixClient = appState.matrixClient { + if let matrixClient = appState.lastFocusedAccount { Form { + Section { + AccountLabel(account: matrixClient) + } header: { + Text("Active Account") + } footer: { + if appState.accounts.count > 1 { + Text("Switch accounts from the sidebar or the Account menu.") + } + } + ChangableField( name: "Display name", value: displayName ?? String(localized: "Loading…"), onSave: { newDisplayName in do { try await matrixClient.client.setDisplayName(name: newDisplayName) displayName = newDisplayName + await matrixClient.refreshOwnProfile() } catch { Logger.viewCycle.error("Failed to update display name: \(error)") } } ) - .task { + .task(id: matrixClient.storeID) { + displayName = nil do { displayName = try await matrixClient.client.displayName() } catch { @@ -80,7 +92,11 @@ struct AccountSettingsView: View { } HStack { - Button("Sign out", role: .destructive) { + Button( + appState.accounts.count > 1 + ? String(localized: "Sign Out of This Account") : String(localized: "Sign out"), + role: .destructive + ) { Task { do { try await appState.reset() @@ -99,7 +115,7 @@ struct AccountSettingsView: View { Button("Clear cache") { Task { do { - try await appState.matrixClient?.clearCache() + try await appState.lastFocusedAccount?.clearCache() } catch { Logger.viewCycle.error("Failed to clear cache: \(error)") } diff --git a/Sources/MactrixApp/Views/Settings/RecoveryKeyVerificationSheet.swift b/Sources/MactrixApp/Views/Settings/RecoveryKeyVerificationSheet.swift index 3dbbb9b6..450cc7d4 100644 --- a/Sources/MactrixApp/Views/Settings/RecoveryKeyVerificationSheet.swift +++ b/Sources/MactrixApp/Views/Settings/RecoveryKeyVerificationSheet.swift @@ -114,7 +114,7 @@ struct RecoveryKeyVerificationSheet: View { .frame(width: 440) .interactiveDismissDisabled(state.isVerifying) .onAppear { keyFieldFocused = true } - .onChange(of: appState.matrixClient.map { ObjectIdentifier($0) }) { + .onChange(of: appState.lastFocusedAccount.map { ObjectIdentifier($0) }) { dismiss() } .onDisappear { verificationTask?.cancel() } @@ -129,7 +129,7 @@ struct RecoveryKeyVerificationSheet: View { } private func verify() { - guard appState.matrixClient === matrixClient, + guard appState.lastFocusedAccount === matrixClient, verificationTask == nil, canVerify, !matrixClient.isRecoveringWithRecoveryKey else { return } diff --git a/Sources/MactrixApp/Views/Settings/SessionsSettingsView.swift b/Sources/MactrixApp/Views/Settings/SessionsSettingsView.swift index b22a7f54..9a07bc86 100644 --- a/Sources/MactrixApp/Views/Settings/SessionsSettingsView.swift +++ b/Sources/MactrixApp/Views/Settings/SessionsSettingsView.swift @@ -118,8 +118,18 @@ struct SessionsSettingsView: View { } var body: some View { - if let matrixClient = appState.matrixClient { + if let matrixClient = appState.lastFocusedAccount { Form { + Section { + AccountLabel(account: matrixClient) + } header: { + Text("Active Account") + } footer: { + if appState.accounts.count > 1 { + Text("Switch accounts from the sidebar or the Account menu.") + } + } + Section("Device Verification") { sessionVerificationView(matrixClient: matrixClient) if matrixClient.verificationState == .unverified { diff --git a/Sources/MactrixApp/Views/Sidebar/AccountStatus.swift b/Sources/MactrixApp/Views/Sidebar/AccountStatus.swift new file mode 100644 index 00000000..58940263 --- /dev/null +++ b/Sources/MactrixApp/Views/Sidebar/AccountStatus.swift @@ -0,0 +1,244 @@ +import MatrixIntegration +import MatrixRustSDK +import OSLog +import SwiftUI + +extension SyncServiceState { + var label: String { + switch self { + case .idle: + String(localized: "idle") + case .running: + String(localized: "online") + case .terminated: + String(localized: "terminated") + case .error: + String(localized: "error") + case .offline: + String(localized: "offline") + } + } + + var color: Color { + switch self { + case .running: .green + case .idle: .gray + case .offline: .orange + case .terminated, .error: .red + } + } +} + +extension MatrixClient { + /// Whether this account needs the user to act, which the account switcher flags. + var needsAttention: Bool { + authenticationFailed || sessionVerificationRequest != nil || verificationState == .unverified + } + + /// Whether the account switcher popover has anything to say about this account's status. + var hasStatus: Bool { + needsAttention || verificationState == .unknown || syncState != .running + } +} + +/// A small dot showing an account's sync state. +struct SyncStateDot: View { + let state: SyncServiceState + var size: CGFloat = 8 + + var body: some View { + Circle() + .fill(state.color) + .frame(width: size, height: size) + } +} + +/// The active account's status at the top of the account switcher popover: its sync state, and +/// anything that needs the user's attention. +struct AccountStatusSection: View { + @Environment(AppState.self) var appState + @Environment(WindowState.self) var windowState + + let account: MatrixClient + /// Closes the popover, before presenting a sheet. + let dismiss: () -> Void + + @State private var removing = false + + var body: some View { + VStack(alignment: .leading, spacing: 10) { + if account.authenticationFailed { + signedOut + } else { + if let request = account.sessionVerificationRequest { + verificationRequest(request) + } else { + switch account.verificationState { + case .unverified: + unverified + case .unknown: + AccountStatusItem(systemImage: "questionmark.circle", tint: .secondary) { + Text("Unknown verification state") + } + case .verified, nil: + EmptyView() + } + } + if account.syncState != .running { + syncStatus + } + } + } + } + + /// Another of the user's devices asked to verify this session. + private func verificationRequest(_ request: SessionVerificationRequestDetails) -> some View { + AccountStatusItem(systemImage: "person.badge.key", tint: .green) { + Text("Verification request from \(request.senderProfile.userId)") + } actions: { + Button("Start Verification") { + dismiss() + Task { + do { + try await account.acceptVerificationRequest(request: request) + } catch { + Logger.viewCycle.error("failed to accept verification request: \(error)") + account.sessionVerificationRequest = nil + } + } + } + .buttonStyle(.borderedProminent) + + Button("Decline") { + Task { + do { + try await account.declineVerificationRequest(request: request) + } catch { + Logger.viewCycle.error("failed to decline verification request: \(error)") + account.sessionVerificationRequest = nil + } + } + } + } + } + + private var unverified: some View { + AccountStatusItem(systemImage: "exclamationmark.shield", tint: .red) { + Text("This session is unverified.") + } message: { + VStack(alignment: .leading, spacing: 4) { + Text("Verify the session for better security and to decrypt all messages.") + if windowState.requestedVerification { + HStack(spacing: 6) { + ProgressView() + .controlSize(.mini) + Text("Requesting verification from your trusted devices...") + } + } + } + } actions: { + Button(windowState.requestedVerification ? "Try again" : "Verify session...") { + Task { + do { + try await account.requestDeviceVerification() + windowState.requestedVerification = true + } catch { + Logger.viewCycle.error("request device verification failed: \(error)") + } + } + } + } + } + + /// Shown when the server has ended the account's session. + private var signedOut: some View { + AccountStatusItem(systemImage: "person.crop.circle.badge.exclamationmark", tint: .orange) { + Text("You were signed out.") + } message: { + Text("This session was ended by the server or another device.") + } actions: { + Button("Sign In Again…") { + dismiss() + windowState.loginSheet = .signInAgain(userID: account.userID) + } + Button("Remove Account") { + Task { + removing = true + defer { removing = false } + await appState.remove(account) + } + } + .disabled(removing) + } + } + + private var syncStatus: some View { + AccountStatusItem(systemImage: "arrow.triangle.2.circlepath", tint: account.syncState.color) { + Text("Sync: \(account.syncState.label)") + } actions: { + // The account tracks whether a start is in flight, so every window's button reflects it + // and repeated clicks join the same start. + Button { + Task { await account.startSync() } + } label: { + if account.isStartingSync { + Text("Restarting…") + } else { + Text("Restart sync") + } + } + .disabled(account.isStartingSync) + } + } +} + +/// One status message in the account switcher popover, with optional actions below it. +struct AccountStatusItem: View { + let systemImage: String + let tint: Color + @ViewBuilder let title: Title + @ViewBuilder let message: Message + @ViewBuilder let actions: Actions + + init( + systemImage: String, tint: Color, + @ViewBuilder title: () -> Title, + @ViewBuilder message: () -> Message = { EmptyView() }, + @ViewBuilder actions: () -> Actions = { EmptyView() } + ) { + self.systemImage = systemImage + self.tint = tint + self.title = title() + self.message = message() + self.actions = actions() + } + + var body: some View { + HStack(alignment: .firstTextBaseline, spacing: 8) { + Image(systemName: systemImage) + .foregroundStyle(tint) + .frame(width: 14) + + VStack(alignment: .leading, spacing: 6) { + VStack(alignment: .leading, spacing: 2) { + title + .font(.body.weight(.semibold)) + message + .font(.callout) + .foregroundStyle(.secondary) + } + .fixedSize(horizontal: false, vertical: true) + + if Actions.self != EmptyView.self { + HStack(spacing: 6) { + actions + } + .controlSize(.small) + } + } + Spacer(minLength: 0) + } + .padding(.horizontal, 6) + .padding(.vertical, 4) + } +} diff --git a/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift b/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift new file mode 100644 index 00000000..3025eaf0 --- /dev/null +++ b/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift @@ -0,0 +1,311 @@ +import MactrixUI +import MatrixIntegration +import MatrixRustSDK +import SwiftUI + +extension MatrixClient { + /// The primary name shown for this account: its display name, or its Matrix ID. + var accountName: String { + ownDisplayName ?? userID + } + + /// A one-line title that always includes the Matrix ID, since display names aren't unique. + var accountMenuTitle: String { + ownDisplayName.map { "\($0) — \(userID)" } ?? userID + } +} + +/// An account's avatar with its sync state, display name, and Matrix ID. +struct AccountLabel: View { + let account: MatrixClient + var showsUserID = true + var avatarSize: CGFloat = 28 + + var body: some View { + HStack(spacing: 8) { + AvatarImage( + userID: account.userID, kind: .user, displayName: account.ownDisplayName, + avatarUrl: account.ownAvatarUrl, imageLoader: account + ) + .frame(width: avatarSize, height: avatarSize) + .overlay(alignment: .bottomTrailing) { + SyncStateDot(state: account.syncState) + .padding(1.5) + .background(.background, in: Circle()) + .offset(x: 2, y: 2) + .help(String(localized: "Sync: \(account.syncState.label)")) + } + + VStack(alignment: .leading, spacing: 1) { + Text(account.accountName) + .font(.body.weight(.semibold)) + .lineLimit(1) + if showsUserID, account.ownDisplayName != nil { + Text(account.userID) + .font(.callout) + .foregroundStyle(.secondary) + .lineLimit(1) + .truncationMode(.middle) + } + } + } + .accessibilityElement(children: .combine) + } +} + +/// A button at the bottom of the sidebar that shows the active account's status and opens a +/// popover for switching, adding, and signing out of accounts. +struct AccountSwitcher: View { + @Environment(AppState.self) var appState + @Environment(WindowState.self) var windowState + + @State private var isPresented = false + @State private var isHovered = false + @State private var accountToSignOut: MatrixClient? + + var body: some View { + Button { + isPresented.toggle() + } label: { + HStack(spacing: 6) { + if let active = windowState.matrixClient { + AccountLabel(account: active) + } else if isLoading { + ProgressView() + .controlSize(.small) + Text("Loading…") + .font(.body.weight(.semibold)) + .foregroundStyle(.secondary) + } else { + Text("No Account") + .font(.body.weight(.semibold)) + } + Spacer(minLength: 0) + if windowState.matrixClient?.needsAttention == true || !unseenVerificationAccounts.isEmpty { + Image(systemName: "exclamationmark.circle.fill") + .foregroundStyle(.orange) + } + if otherAccountsUnreadCount > 0 { + UnreadBadge(count: otherAccountsUnreadCount) + .help("Unread rooms in your other accounts") + } + Image(systemName: "chevron.up.chevron.down") + .font(.caption.weight(.semibold)) + .foregroundStyle(.secondary) + } + .padding(.horizontal, 6) + .padding(.vertical, 4) + .contentShape(.rect) + .background( + .quaternary.opacity(isHovered || isPresented ? 1 : 0), + in: RoundedRectangle(cornerRadius: 6, style: .continuous)) + } + .buttonStyle(.plain) + .disabled(isLoading) + .onHover { isHovered = $0 } + .help("Switch account") + .accessibilityLabel(accessibilityLabel) + .popover(isPresented: $isPresented, arrowEdge: .top) { + popoverContent + } + // Verification requests time out, so don't leave one waiting behind a closed popover. Only + // one window per account opens it. + .onChange(of: windowState.matrixClient?.sessionVerificationRequest?.flowId) { _, flowID in + if flowID != nil, + appState.verificationWindow(forAccountID: windowState.accountID) === windowState + { + isPresented = true + } + } + .confirmationDialog( + "Sign out of \(accountToSignOut?.userID ?? "")?", + isPresented: Binding( + get: { accountToSignOut != nil }, + set: { if !$0 { accountToSignOut = nil } }), + presenting: accountToSignOut + ) { account in + Button("Sign Out", role: .destructive) { + Task { await appState.remove(account) } + } + } message: { _ in + Text("This account will be signed out on this Mac. Your other accounts stay signed in.") + } + } + + /// Whether stored accounts are still being restored at launch. + private var isLoading: Bool { + windowState.matrixClient == nil && appState.restoration == .pending + } + + /// Accounts with a verification request that no window shows, flagged in the frontmost window. + private var unseenVerificationAccounts: [MatrixClient] { + guard appState.openWindows.first === windowState else { return [] } + return appState.accountsWithUnseenVerificationRequests + } + + private var otherAccountsUnreadCount: Int { + appState.unreadRoomCount(excludingAccountID: windowState.accountID) + } + + private var accessibilityLabel: String { + guard let active = windowState.matrixClient else { + return isLoading ? String(localized: "Loading…") : String(localized: "Switch account") + } + var label = String(localized: "Switch account, current: \(active.accountMenuTitle)") + if active.syncState != .running { + label = String(localized: "\(label), sync: \(active.syncState.label)") + } + if active.needsAttention { + label = String(localized: "\(label), needs attention") + } + if !unseenVerificationAccounts.isEmpty { + label = String(localized: "\(label), verification requested in another account") + } + let unread = otherAccountsUnreadCount + return unread > 0 + ? String(localized: "\(label), \(unread) unread in other accounts") : label + } + + private var popoverContent: some View { + VStack(alignment: .leading, spacing: 2) { + if let active = windowState.matrixClient, active.hasStatus { + AccountStatusSection(account: active) { isPresented = false } + Divider() + .padding(.vertical, 4) + } + + ForEach(appState.accounts, id: \.storeID) { account in + AccountRow(account: account, isActive: windowState.accountID == account.storeID) { + appState.show(account, in: windowState) + isPresented = false + } + } + + Divider() + .padding(.vertical, 4) + + PopoverActionRow(title: String(localized: "Add Account…"), systemImage: "plus") { + isPresented = false + windowState.loginSheet = .addAccount + } + + if let active = windowState.matrixClient { + PopoverActionRow( + title: String(localized: "Sign Out of \(active.accountName)…"), + systemImage: "rectangle.portrait.and.arrow.right" + ) { + isPresented = false + accountToSignOut = active + } + } + } + .padding(6) + .frame(width: 300) + } +} + +/// A selectable account in the switcher popover. +private struct AccountRow: View { + let account: MatrixClient + let isActive: Bool + let action: () -> Void + + @State private var isHovered = false + + var body: some View { + Button(action: action) { + HStack(spacing: 8) { + Image(systemName: "checkmark") + .font(.callout.weight(.semibold)) + .foregroundStyle(.tint) + .opacity(isActive ? 1 : 0) + .frame(width: 14) + + AccountLabel(account: account) + + Spacer(minLength: 8) + + if account.authenticationFailed { + Text("Signed Out") + .font(.caption.weight(.medium)) + .foregroundStyle(.orange) + } else if !isActive, account.sessionVerificationRequest != nil { + Image(systemName: "exclamationmark.circle.fill") + .foregroundStyle(.orange) + .help("Verification requested") + } else if account.unreadRoomCount > 0 { + UnreadBadge(count: account.unreadRoomCount) + } + } + .padding(.horizontal, 6) + .padding(.vertical, 5) + .contentShape(.rect) + .background( + .quaternary.opacity(isHovered ? 1 : 0), + in: RoundedRectangle(cornerRadius: 6, style: .continuous)) + } + .buttonStyle(.plain) + .onHover { isHovered = $0 } + .accessibilityAddTraits(isActive ? .isSelected : []) + .accessibilityValue(accessibilityValue) + } + + private var accessibilityValue: String { + if account.authenticationFailed { return String(localized: "Signed out") } + var values: [String] = [] + if !isActive, account.sessionVerificationRequest != nil { + values.append(String(localized: "Verification requested")) + } + if account.syncState != .running { + values.append(String(localized: "Sync: \(account.syncState.label)")) + } + if account.unreadRoomCount > 0 { + values.append(String(localized: "\(account.unreadRoomCount) unread")) + } + return values.joined(separator: ", ") + } +} + +/// The number of unread rooms, in a tinted capsule. +private struct UnreadBadge: View { + let count: Int + + var body: some View { + Text(verbatim: "\(count)") + .font(.caption.weight(.semibold).monospacedDigit()) + .foregroundStyle(.white) + .padding(.horizontal, 6) + .padding(.vertical, 1) + .background(.tint, in: Capsule()) + } +} + +/// An action such as "Add Account…" at the bottom of the switcher popover. +private struct PopoverActionRow: View { + let title: String + let systemImage: String + let action: () -> Void + + @State private var isHovered = false + + var body: some View { + Button(action: action) { + HStack(spacing: 8) { + Image(systemName: systemImage) + .frame(width: 14) + .foregroundStyle(.secondary) + Text(title) + .lineLimit(1) + Spacer(minLength: 0) + } + .padding(.horizontal, 6) + .padding(.vertical, 5) + .contentShape(.rect) + .background( + .quaternary.opacity(isHovered ? 1 : 0), + in: RoundedRectangle(cornerRadius: 6, style: .continuous)) + } + .buttonStyle(.plain) + .onHover { isHovered = $0 } + } +} diff --git a/Sources/MactrixApp/Views/Sidebar/SidebarGroupsList.swift b/Sources/MactrixApp/Views/Sidebar/SidebarGroupsList.swift index cca53bfc..5a7df241 100644 --- a/Sources/MactrixApp/Views/Sidebar/SidebarGroupsList.swift +++ b/Sources/MactrixApp/Views/Sidebar/SidebarGroupsList.swift @@ -4,15 +4,15 @@ import MatrixRustSDK import SwiftUI struct SidebarGroupsList: View { - @Environment(AppState.self) var appState + @Environment(WindowState.self) var windowState var spaces: [SidebarSpaceRoom] { - appState.matrixClient?.spaceService.spaceRooms ?? [] + windowState.matrixClient?.spaceService.spaceRooms ?? [] } var unreadRoomIDs: Set { Set( - (appState.matrixClient?.rooms ?? []).compactMap { room in + (windowState.matrixClient?.rooms ?? []).compactMap { room in guard !room.room.isSpace(), let info = room.roomInfo else { return nil } let isUnread = info.isMarkedUnread || info.numUnreadNotifications > 0 || info.numUnreadMentions > 0 @@ -23,7 +23,7 @@ struct SidebarGroupsList: View { var body: some View { let unreadIDs = unreadRoomIDs - let service = appState.matrixClient?.spaceService + let service = windowState.matrixClient?.spaceService let homeNotifications = unreadIDs.subtracting(service?.roomsWithJoinedSpaceParents ?? []).count let spaceNotifications = Dictionary( (service?.spaceFilters ?? []) @@ -47,7 +47,7 @@ struct SidebarGroupsList: View { ) { AvatarImage( userID: space.id, kind: .room, displayName: space.spaceRoom.displayName, - avatarUrl: space.spaceRoom.avatarUrl, imageLoader: appState.matrixClient) + avatarUrl: space.spaceRoom.avatarUrl, imageLoader: windowState.matrixClient) } .contextMenu { SpaceContextMenu(space: space) diff --git a/Sources/MactrixApp/Views/Sidebar/SidebarSessionVerification.swift b/Sources/MactrixApp/Views/Sidebar/SidebarSessionVerification.swift deleted file mode 100644 index c99f0044..00000000 --- a/Sources/MactrixApp/Views/Sidebar/SidebarSessionVerification.swift +++ /dev/null @@ -1,109 +0,0 @@ -import MatrixRustSDK -import OSLog -import SwiftUI - -struct SessionVerificationStatusView: View { - @Environment(AppState.self) var appState - @Environment(WindowState.self) var windowState - @Environment(\.colorScheme) var colorScheme - - @ViewBuilder - var selfVerificationView: some View { - switch appState.matrixClient?.verificationState { - case nil: - EmptyView() - case .unknown: - Text("Unknown verification state") - .padding(10) - .background(Color.gray.opacity(0.2)) - .clipShape(RoundedRectangle(cornerRadius: 8)) - .frame(maxWidth: .infinity) - case .verified: - EmptyView() - case .unverified: - VStack { - Label { - Text("This session is unverified.") - .bold() - - // NOTE(alicerunsonfedora): Setting a hard line limit because SwiftUI will otherwise truncate the - // text, even when there's enough room to do so. - Text("Verify the session for better security and to decrypt all messages.") - .lineLimit(9) - } icon: { - Image(systemName: "exclamationmark.shield") - .bold() - } - .labelStyle(.multiline) - .frame(maxWidth: .infinity) - HStack { - if windowState.requestedVerification { - ProgressView("Requesting verification from your trusted devices...") - } - Button(windowState.requestedVerification ? "Try again" : "Verify session...") { - Task { - await startVerificationRequest() - } - } - } - } - .padding(10) - .background(Color.red.opacity(0.2)) - .foregroundStyle(Color.red.mix(with: colorScheme == .light ? .black : .white, by: 0.5)) - .clipShape(RoundedRectangle(cornerRadius: 8)) - } - } - - var body: some View { - if let verificationRequest = appState.matrixClient?.sessionVerificationRequest { - VStack { - Label( - "Verification request from \(verificationRequest.senderProfile.userId)", - systemImage: "person.badge.key" - ) - .frame(maxWidth: .infinity) - HStack { - Button("Start Verification") { - Task { - do { - try await appState.matrixClient?.acceptVerificationRequest( - request: verificationRequest) - } catch { - Logger.viewCycle.error("failed to accept verification request: \(error)") - appState.matrixClient?.sessionVerificationRequest = nil - } - } - } - .buttonStyle(.borderedProminent) - - Button("Decline") { - Task { - do { - try await appState.matrixClient?.declineVerificationRequest( - request: verificationRequest) - } catch { - Logger.viewCycle.error("failed to decline verification request: \(error)") - appState.matrixClient?.sessionVerificationRequest = nil - } - } - } - } - } - .padding(10) - .background(Color.green.opacity(0.2)) - .foregroundStyle(Color.green.mix(with: colorScheme == .light ? .black : .white, by: 0.5)) - .clipShape(RoundedRectangle(cornerRadius: 8)) - } else { - selfVerificationView - } - } - - private func startVerificationRequest() async { - do { - try await appState.matrixClient?.requestDeviceVerification() - windowState.requestedVerification = true - } catch { - Logger.viewCycle.error("request device verification failed: \(error)") - } - } -} diff --git a/Sources/MactrixApp/Views/Sidebar/SidebarSyncState.swift b/Sources/MactrixApp/Views/Sidebar/SidebarSyncState.swift deleted file mode 100644 index f61b420e..00000000 --- a/Sources/MactrixApp/Views/Sidebar/SidebarSyncState.swift +++ /dev/null @@ -1,54 +0,0 @@ -import MatrixRustSDK -import OSLog -import SwiftUI - -struct SidebarSyncStateView: View { - @Environment(AppState.self) var appState - - @State var restarting: Bool = false - - var syncState: String { - switch appState.matrixClient?.syncState { - case .idle: - String(localized: "idle") - case .running: - String(localized: "online") - case .terminated: - String(localized: "terminated") - case .error: - String(localized: "error") - case .offline: - String(localized: "offline") - case nil: - String(localized: "logged out") - } - } - - var canRestart: Bool { - return [.error, .offline, .terminated].contains(where: { - $0 == appState.matrixClient?.syncState - }) - } - - var body: some View { - VStack { - Text("Sync: \(syncState)") - .foregroundStyle(.secondary) - if canRestart { - Button("Restart sync") { - Task { - restarting = true - defer { restarting = false } - - do { - try await appState.matrixClient?.startSync() - } catch { - Logger.viewCycle.error("failed to restart sync: \(error)") - } - } - } - .disabled(restarting) - } - } - } -} diff --git a/Sources/MactrixApp/Views/Sidebar/SidebarView.swift b/Sources/MactrixApp/Views/Sidebar/SidebarView.swift index 2ff497da..c2168fba 100644 --- a/Sources/MactrixApp/Views/Sidebar/SidebarView.swift +++ b/Sources/MactrixApp/Views/Sidebar/SidebarView.swift @@ -5,7 +5,6 @@ import MatrixRustSDK import SwiftUI struct SidebarView: View { - @Environment(AppState.self) var appState @Environment(WindowState.self) var windowState @State private var members: [MatrixRustSDK.RoomMember] = [] @@ -14,8 +13,8 @@ struct SidebarView: View { var visibleRooms: [SidebarRoom] { // filter out rooms whose room info hasn't loaded yet, to avoid flickering - let joinedRooms = (appState.matrixClient?.rooms ?? []).filter { $0.roomInfo != nil } - let spaceService = appState.matrixClient?.spaceService + let joinedRooms = (windowState.matrixClient?.rooms ?? []).filter { $0.roomInfo != nil } + let spaceService = windowState.matrixClient?.spaceService if let selectedSpaceId = windowState.selectedSpaceId { let roomIDs = Set( @@ -59,7 +58,7 @@ struct SidebarView: View { } var spaces: [SidebarSpaceRoom] { - appState.matrixClient?.spaceService.spaceRooms ?? [] + windowState.matrixClient?.spaceService.spaceRooms ?? [] } var content: some View { @@ -99,12 +98,9 @@ struct SidebarView: View { } private var statusContent: some View { - VStack(spacing: 8) { - SidebarSyncStateView() - SessionVerificationStatusView() - } - .frame(maxWidth: .infinity) - .padding(12) + AccountSwitcher() + .frame(maxWidth: .infinity) + .padding(6) } /// The room name, or the linked contact's name for direct chats. @@ -125,7 +121,7 @@ struct SidebarView: View { title: title(for: room, fallback: String(localized: "Unknown room")), avatarUrl: room.room.avatarUrl(), roomInfo: room.roomInfo, - imageLoader: appState.matrixClient, + imageLoader: windowState.matrixClient, joinRoom: nil ) .contextMenu { @@ -141,7 +137,7 @@ struct SidebarView: View { title: title(for: room, fallback: String(localized: "Unknown user")), avatarUrl: room.room.avatarUrl(), roomInfo: room.roomInfo, - imageLoader: appState.matrixClient, + imageLoader: windowState.matrixClient, joinRoom: nil ) .contextMenu { @@ -156,7 +152,7 @@ struct SidebarView: View { title: room.room.displayName() ?? String(localized: "Unknown room"), avatarUrl: room.room.avatarUrl(), roomInfo: room.roomInfo, - imageLoader: appState.matrixClient, + imageLoader: windowState.matrixClient, joinRoom: nil ) .contextMenu { diff --git a/Sources/MactrixApp/Views/Sidebar/SpaceContextMenu.swift b/Sources/MactrixApp/Views/Sidebar/SpaceContextMenu.swift index c4aa038f..4844ca22 100644 --- a/Sources/MactrixApp/Views/Sidebar/SpaceContextMenu.swift +++ b/Sources/MactrixApp/Views/Sidebar/SpaceContextMenu.swift @@ -4,7 +4,6 @@ import OSLog import SwiftUI struct SpaceContextMenu: View { - @Environment(AppState.self) var appState @Environment(WindowState.self) var windowState let space: SidebarSpaceRoom @@ -14,7 +13,8 @@ struct SpaceContextMenu: View { Button { Task { do { - guard let room = try appState.matrixClient?.client.getRoom(roomId: space.spaceRoom.roomId) + guard + let room = try windowState.matrixClient?.client.getRoom(roomId: space.spaceRoom.roomId) else { Logger.viewCycle.error("unable to copy space room link: could not get room") return @@ -35,7 +35,8 @@ struct SpaceContextMenu: View { Button { Task { do { - guard let room = try appState.matrixClient?.client.getRoom(roomId: space.spaceRoom.roomId) + guard + let room = try windowState.matrixClient?.client.getRoom(roomId: space.spaceRoom.roomId) else { Logger.viewCycle.error("unable to leave space: could not get room") return diff --git a/Sources/MactrixApp/Views/Sidebar/SpaceDisclosureGroup.swift b/Sources/MactrixApp/Views/Sidebar/SpaceDisclosureGroup.swift index 49ee6b78..4db3a1c0 100644 --- a/Sources/MactrixApp/Views/Sidebar/SpaceDisclosureGroup.swift +++ b/Sources/MactrixApp/Views/Sidebar/SpaceDisclosureGroup.swift @@ -5,7 +5,6 @@ import OSLog import SwiftUI struct SpaceDisclosureGroup: View { - @Environment(AppState.self) var appState @Environment(WindowState.self) var windowState @State var space: SidebarSpaceRoom @@ -52,10 +51,10 @@ struct SpaceDisclosureGroup: View { } var joinRoom: (() async throws -> Void)? { - if appState.matrixClient?.rooms.contains(where: { $0.room.id() == space.id }) == false { + if windowState.matrixClient?.rooms.contains(where: { $0.room.id() == space.id }) == false { return { Logger.viewCycle.error("Joining room: \(space.id)") - guard let matrixClient = appState.matrixClient else { return } + guard let matrixClient = windowState.matrixClient else { return } let sourceScreen = windowState.selectedScreen let room = try await matrixClient.client.joinRoomById(roomId: space.id) try Task.checkCancellation() @@ -69,7 +68,7 @@ struct SpaceDisclosureGroup: View { } var joinedRoom: SidebarRoom? { - return appState.matrixClient?.rooms.first(where: { $0.room.id() == space.id }) + return windowState.matrixClient?.rooms.first(where: { $0.room.id() == space.id }) } @ViewBuilder @@ -79,7 +78,7 @@ struct SpaceDisclosureGroup: View { title: space.spaceRoom.displayName, avatarUrl: space.spaceRoom.avatarUrl, roomInfo: joinedRoom.roomInfo, - imageLoader: appState.matrixClient, + imageLoader: windowState.matrixClient, joinRoom: nil ) } else { @@ -87,7 +86,7 @@ struct SpaceDisclosureGroup: View { title: space.spaceRoom.displayName, avatarUrl: space.spaceRoom.avatarUrl, roomInfo: nil, - imageLoader: appState.matrixClient, + imageLoader: windowState.matrixClient, joinRoom: joinRoom ) } diff --git a/Sources/MactrixApp/Views/WelcomeSheetView.swift b/Sources/MactrixApp/Views/WelcomeSheetView.swift index b835ec81..9bfd56eb 100644 --- a/Sources/MactrixApp/Views/WelcomeSheetView.swift +++ b/Sources/MactrixApp/Views/WelcomeSheetView.swift @@ -1,10 +1,14 @@ import AuthenticationServices import MatrixIntegration import MatrixRustSDK +import OSLog import SwiftUI struct WelcomeSheetView: View { + var request: LoginSheet = .firstAccount + @Environment(AppState.self) private var appState + @Environment(WindowState.self) private var windowState @Environment(\.dismiss) private var dismiss @Environment(\.webAuthenticationSession) private var webAuthenticationSession @@ -49,6 +53,17 @@ struct WelcomeSheetView: View { } } + /// Replaces the spent login with a fresh one, since a client can't sign in a second time. + /// + /// Failures are ignored so the sign-in error stays on screen. + private func renewHomeserverLogin() async { + do { + homeserverLogin = try await MatrixClient.loginDetails(homeServer: homeserverField) + } catch { + Logger.viewCycle.error("Failed to renew homeserver login: \(error)") + } + } + func signInPassword() { Task { guard let homeserverLogin = homeserverLogin else { return } @@ -58,10 +73,11 @@ struct WelcomeSheetView: View { do { let client = try await homeserverLogin.loginPassword( homeServer: homeserverField, username: usernameField, password: passwordField) - appState.matrixClient = client + try await appState.add(client, in: windowState) dismiss() } catch { showError = error + await renewHomeserverLogin() } } } @@ -74,10 +90,11 @@ struct WelcomeSheetView: View { do { let client = try await homeserverLogin.loginOidc(webAuthSession: webAuthenticationSession) - appState.matrixClient = client + try await appState.add(client, in: windowState) dismiss() } catch { showError = error + await renewHomeserverLogin() } } } @@ -113,7 +130,7 @@ struct WelcomeSheetView: View { @ViewBuilder var content: some View { VStack { - Text("Welcome to Mactrix") + Text(title) .font(.headline) .padding(.bottom) @@ -159,8 +176,29 @@ struct WelcomeSheetView: View { .foregroundStyle(Color.red) .textSelection(.enabled) } + + if request != .firstAccount { + Button("Cancel", role: .cancel) { dismiss() } + .keyboardShortcut(.cancelAction) + .padding(.top) + } } .padding() + .onAppear { + // Look up the homeserver straight away when signing in to a known account again. + if case .signInAgain(let userID) = request, homeserverField.isEmpty { + homeserverField = userID + loadHomeserver() + } + } + } + + private var title: LocalizedStringKey { + switch request { + case .firstAccount: "Welcome to Mactrix" + case .addAccount: "Add Account" + case .signInAgain(let userID): "Sign In Again as \(userID)" + } } var body: some View { diff --git a/Sources/MactrixApp/Views/WindowReader.swift b/Sources/MactrixApp/Views/WindowReader.swift new file mode 100644 index 00000000..6625921f --- /dev/null +++ b/Sources/MactrixApp/Views/WindowReader.swift @@ -0,0 +1,54 @@ +import AppKit +import SwiftUI + +/// Reports the window that hosts it, the window it moves to later, and when that window closes. +struct WindowReader: NSViewRepresentable { + let onChange: (NSWindow?) -> Void + let onClose: () -> Void + + func makeNSView(context: Context) -> ReportingView { + ReportingView(onChange: onChange, onClose: onClose) + } + + func updateNSView(_ view: ReportingView, context: Context) { + view.onChange = onChange + view.onClose = onClose + // The receiver may be new, so report the current window to it too. + if let window = view.window { + onChange(window) + } + } + + final class ReportingView: NSView { + var onChange: (NSWindow?) -> Void + var onClose: () -> Void + private var closeObserver: NSObjectProtocol? + + init(onChange: @escaping (NSWindow?) -> Void, onClose: @escaping () -> Void) { + self.onChange = onChange + self.onClose = onClose + super.init(frame: .zero) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func viewDidMoveToWindow() { + super.viewDidMoveToWindow() + if let closeObserver { + NotificationCenter.default.removeObserver(closeObserver) + self.closeObserver = nil + } + if let window { + closeObserver = NotificationCenter.default.addObserver( + forName: NSWindow.willCloseNotification, object: window, queue: .main + ) { [weak self] _ in + MainActor.assumeIsolated { self?.onClose() } + } + } + onChange(window) + } + } +} diff --git a/Sources/MatrixIntegration/AccountStore.swift b/Sources/MatrixIntegration/AccountStore.swift new file mode 100644 index 00000000..fffbd4c3 --- /dev/null +++ b/Sources/MatrixIntegration/AccountStore.swift @@ -0,0 +1,176 @@ +import Foundation +import OSLog + +/// Persists the sessions of all signed-in accounts. +/// +/// Each account is identified by its `storeID`, which also names its SQLite store directories. +/// Secrets live in one keychain item per account (`session.`); the keychain is the +/// source of truth for which accounts exist. Non-secret metadata (display order, active account) +/// lives in `UserDefaults`. +public struct AccountStore: Sendable { + static let legacySessionKey = "UserSession" + static let sessionKeyPrefix = "session." + static let currentSchemaVersion = 1 + + enum DefaultsKey { + static let order = "accounts.order" + // Named before each window had its own account; kept so the stored value carries over. + static let lastFocused = "accounts.active" + static let schemaVersion = "accounts.schemaVersion" + } + + private let keychain: any KeychainStore + nonisolated(unsafe) private let defaults: UserDefaults + + public init() { + self.init(keychain: AppKeychain(), defaults: .standard) + } + + init(keychain: any KeychainStore, defaults: UserDefaults) { + self.keychain = keychain + self.defaults = defaults + } + + static func sessionKey(for storeID: String) -> String { + sessionKeyPrefix + storeID + } + + // MARK: Sessions + + /// Returns all stored sessions in display order. Unreadable items are skipped. + func loadAll() throws -> [UserSession] { + var sessions: [String: UserSession] = [:] + for storeID in try allStoreIDs() { + do { + if let session = try load(storeID: storeID) { + sessions[storeID] = session + } + } catch { + Logger.matrixClient.error("Skipping unreadable session \(storeID): \(error)") + } + } + + let order = orderedStoreIDs(existing: Set(sessions.keys)) + return order.compactMap { sessions[$0] } + } + + /// The store IDs of every stored session, including ones that can't be decoded. + func allStoreIDs() throws -> Set { + Set( + try keychain.keys(withPrefix: Self.sessionKeyPrefix) + .map { String($0.dropFirst(Self.sessionKeyPrefix.count)) }) + } + + /// Whether a session from before per-account storage is still present. + func hasLegacySession() throws -> Bool { + try keychain.load(forKey: Self.legacySessionKey) != nil + } + + func load(storeID: String) throws -> UserSession? { + guard let data = try keychain.load(forKey: Self.sessionKey(for: storeID)) else { return nil } + return try JSONDecoder().decode(UserSession.self, from: data) + } + + /// Creates or updates the session for `session.storeID`, appending new accounts to the order. + func save(_ session: UserSession) throws { + let data = try JSONEncoder().encode(session) + try keychain.save(data, forKey: Self.sessionKey(for: session.storeID)) + + var order = storedOrder + if !order.contains(session.storeID) { + order.append(session.storeID) + defaults.set(order, forKey: DefaultsKey.order) + } + } + + /// Removes the account's session and metadata. Other accounts are untouched. + func remove(storeID: String) throws { + try keychain.delete(forKey: Self.sessionKey(for: storeID)) + defaults.set(storedOrder.filter { $0 != storeID }, forKey: DefaultsKey.order) + if lastFocusedStoreID == storeID { + lastFocusedStoreID = nil + } + } + + // MARK: Metadata + + /// The account of the most recently focused window, if it still exists. New windows open on it. + public var lastFocusedStoreID: String? { + get { defaults.string(forKey: DefaultsKey.lastFocused) } + nonmutating set { defaults.set(newValue, forKey: DefaultsKey.lastFocused) } + } + + /// Persists the display order of accounts. + public func setOrder(_ storeIDs: [String]) { + defaults.set(storeIDs, forKey: DefaultsKey.order) + } + + private var storedOrder: [String] { + defaults.stringArray(forKey: DefaultsKey.order) ?? [] + } + + /// Orders `existing` by the stored order, appending unknown IDs (sorted, for stability), and + /// prunes stored IDs that no longer have a session. + private func orderedStoreIDs(existing: Set) -> [String] { + let stored = storedOrder + var order = stored.filter { existing.contains($0) } + order += existing.subtracting(order).sorted() + if order != stored { + defaults.set(order, forKey: DefaultsKey.order) + } + return order + } + + // MARK: Migration + + /// Moves a session stored by earlier versions under the single `UserSession` key to the + /// per-account format. + /// + /// Safe to run on every launch and to interrupt at any point: the new item is written and + /// verified before the legacy item is removed, and an unreadable legacy item is never removed. + func migrateLegacyIfNeeded() throws { + if defaults.integer(forKey: DefaultsKey.schemaVersion) >= Self.currentSchemaVersion { + // A previous migration may have been interrupted before removing the legacy item. + removeLegacySession() + return + } + + guard let legacyData = try keychain.load(forKey: Self.legacySessionKey) else { + defaults.set(Self.currentSchemaVersion, forKey: DefaultsKey.schemaVersion) + return + } + + let legacySession: UserSession + do { + legacySession = try JSONDecoder().decode(UserSession.self, from: legacyData) + } catch { + Logger.matrixClient.error("Legacy session is unreadable, leaving it in place: \(error)") + return + } + + Logger.matrixClient.info("Migrating legacy session to store \(legacySession.storeID)") + try save(legacySession) + guard try load(storeID: legacySession.storeID) == legacySession else { + throw AccountStoreError.migrationVerificationFailed + } + if lastFocusedStoreID == nil { + lastFocusedStoreID = legacySession.storeID + } + defaults.set(Self.currentSchemaVersion, forKey: DefaultsKey.schemaVersion) + removeLegacySession() + } + + /// The session is already migrated at this point, so failing to remove the old copy must not + /// fail the migration; it is retried on the next launch. + private func removeLegacySession() { + do { + try keychain.delete(forKey: Self.legacySessionKey) + } catch { + Logger.matrixClient.error("Failed to remove legacy session, will retry: \(error)") + } + } +} + +enum AccountStoreError: Error { + case migrationVerificationFailed +} diff --git a/Sources/MatrixIntegration/AppKeychain.swift b/Sources/MatrixIntegration/AppKeychain.swift index e7462add..47e028fa 100644 --- a/Sources/MatrixIntegration/AppKeychain.swift +++ b/Sources/MatrixIntegration/AppKeychain.swift @@ -5,7 +5,15 @@ enum KeychainError: Error { case unexpectedStatus(OSStatus) } -struct AppKeychain { +/// Key-value storage for secrets. Abstracted so account storage can be tested without the system keychain. +protocol KeychainStore: Sendable { + func save(_ data: Data, forKey key: String) throws + func load(forKey key: String) throws -> Data? + func delete(forKey key: String) throws + func keys(withPrefix prefix: String) throws -> [String] +} + +struct AppKeychain: KeychainStore { private let service: String init(service: String = Bundle.main.bundleIdentifier!) { @@ -58,11 +66,29 @@ struct AppKeychain { return result as? Data } - /// Removes all keychain items stored under this service. - func removeAll() throws { - let status = SecItemDelete(baseQuery as CFDictionary) + /// Removes the item stored for the given key. Succeeds if no item exists. + func delete(forKey key: String) throws { + var query = baseQuery + query[kSecAttrAccount] = key + let status = SecItemDelete(query as CFDictionary) guard status == errSecSuccess || status == errSecItemNotFound else { throw KeychainError.unexpectedStatus(status) } } + + /// Returns the keys of all items in this service starting with `prefix`. + func keys(withPrefix prefix: String) throws -> [String] { + var query = baseQuery + query[kSecReturnAttributes] = true + query[kSecMatchLimit] = kSecMatchLimitAll + + var result: AnyObject? + let status = unsafe SecItemCopyMatching(query as CFDictionary, &result) + if status == errSecItemNotFound { return [] } + guard status == errSecSuccess else { + throw KeychainError.unexpectedStatus(status) + } + let items = result as? [[CFString: Any]] ?? [] + return items.compactMap { $0[kSecAttrAccount] as? String }.filter { $0.hasPrefix(prefix) } + } } diff --git a/Sources/MatrixIntegration/HomeserverLogin.swift b/Sources/MatrixIntegration/HomeserverLogin.swift index daf964e9..e27b5e01 100644 --- a/Sources/MatrixIntegration/HomeserverLogin.swift +++ b/Sources/MatrixIntegration/HomeserverLogin.swift @@ -4,6 +4,9 @@ import MatrixRustSDK import OSLog import SwiftUI +/// Login details and the client that signs in with them. +/// +/// Single use: after a login attempt, request new login details. public struct HomeserverLogin { public let storeID: String private let storePassphrase: String @@ -60,15 +63,12 @@ public struct HomeserverLogin { @MainActor fileprivate func onSuccessfullLogin() async throws -> MatrixClient { - let matrixClient = await MatrixClient( - storeID: storeID, storePassphrase: storePassphrase, client: unauthenticatedClient) + let accountStore = AccountStore() + let matrixClient = try await MatrixClient( + storeID: storeID, storePassphrase: storePassphrase, client: unauthenticatedClient, + accountStore: accountStore) - let userSession = try matrixClient.userSession() - do { - try userSession.saveUserToKeychain() - } catch { - print(error.localizedDescription) - } + try accountStore.save(matrixClient.userSession()) return matrixClient } diff --git a/Sources/MatrixIntegration/MatrixClient+Listeners.swift b/Sources/MatrixIntegration/MatrixClient+Listeners.swift index d89e949b..6963e780 100644 --- a/Sources/MatrixIntegration/MatrixClient+Listeners.swift +++ b/Sources/MatrixIntegration/MatrixClient+Listeners.swift @@ -51,7 +51,8 @@ extension MatrixClient { } } - var unreadRoomCount: Int { + /// The number of rooms with unread messages, notifications, or mentions. + public var unreadRoomCount: Int { rooms.reduce(0) { count, room in guard let info = room.roomInfo else { return count } let isUnread = @@ -59,26 +60,24 @@ extension MatrixClient { return count + (isUnread ? 1 : 0) } } - - func observeDockIconUnreadCount() { - let count = withObservationTracking { - unreadRoomCount - } onChange: { [weak self] in - Task { @MainActor [weak self] in - self?.observeDockIconUnreadCount() - } - } - - guard count != lastAppliedDockUnreadCount else { return } - NSApp.dockTile.badgeLabel = count > 0 ? "\(count)" : nil - lastAppliedDockUnreadCount = count - } } extension MatrixClient: SyncServiceStateObserver { nonisolated public func onUpdate(state: MatrixRustSDK.SyncServiceState) { Task { @MainActor in + Logger.matrixClient.info( + "Sync state \(String(describing: state), privacy: .public), store \(self.storeID)") syncState = state + if state == .offline { + scheduleOfflineRestarts() + } + if state == .running { + // Setup that failed while offline can succeed now that the homeserver answers. + retryPendingSetupSteps() + // A send that fails on a network error turns its room's send queue off, holding the + // message until the queue is turned back on. Resend those now. + await client.enableAllSendQueues(enable: true) + } } } } @@ -133,9 +132,11 @@ extension MatrixClient: MatrixRustSDK.ClientDelegate { nonisolated public func didReceiveAuthError(isSoftLogout: Bool) { Task { @MainActor in Logger.matrixClient.debug( - "did receive auth error: soft logout \(isSoftLogout, privacy: .public)") + "did receive auth error: soft logout \(isSoftLogout, privacy: .public), store \(self.storeID)") if !isSoftLogout { authenticationFailed = true + // The session is gone; keep the account listed but stop using it. + await syncService?.stop() } } } diff --git a/Sources/MatrixIntegration/MatrixClient.swift b/Sources/MatrixIntegration/MatrixClient.swift index e4196da6..9a6aaa12 100644 --- a/Sources/MatrixIntegration/MatrixClient.swift +++ b/Sources/MatrixIntegration/MatrixClient.swift @@ -11,22 +11,27 @@ import Utils @MainActor @Observable public class MatrixClient { public let storeID: String + /// The Matrix user ID of this account. + public let userID: String @ObservationIgnored let roomSubscriptions = RoomSubscriptions() @ObservationIgnored public private(set) lazy var recentReactions = RecentReactionsStore( client: SDKRecentReactionsClient(client: client)) private let storePassphrase: String + @ObservationIgnored nonisolated let accountStore: AccountStore public internal(set) var client: ClientProtocol! public internal(set) var rooms: [SidebarRoom] = [] - @ObservationIgnored var lastAppliedDockUnreadCount: Int? - public internal(set) var spaceService: LiveSpaceService! private var clientDelegateHandle: TaskHandle? public internal(set) var authenticationFailed: Bool = false - public let notifications: MatrixNotifications = .init() + /// This account's own display name and avatar, for identifying the account in the UI. + public private(set) var ownDisplayName: String? + public private(set) var ownAvatarUrl: String? + + public let notifications: MatrixNotifications public let viaServers = ["matrix.org"] @@ -35,12 +40,16 @@ public class MatrixClient { return (hints + viaServers).filter { seen.insert($0).inserted } } - init(userSession: UserSession) async throws { + init(userSession: UserSession, accountStore: AccountStore) async throws { storeID = userSession.storeID + userID = userSession.userID + notifications = MatrixNotifications(accountID: userSession.storeID) storePassphrase = userSession.storePassphrase + self.accountStore = accountStore client = try await Self.clientBuilder( - homeServer: userSession.homeserverURL, storeId: storeID, storePassphrase: storePassphrase + homeserver: .stored(url: userSession.homeserverURL), storeId: storeID, + storePassphrase: storePassphrase ) // .enableOidcRefreshLock() .setSessionDelegate(sessionDelegate: self) @@ -50,17 +59,20 @@ public class MatrixClient { spaceService = LiveSpaceService(client: self.client, spaceService: await client.spaceService()) clientDelegateHandle = try? client.setDelegate(delegate: self) - observeDockIconUnreadCount() } - init(storeID: String, storePassphrase: String, client: ClientProtocol) async { + init( + storeID: String, storePassphrase: String, client: ClientProtocol, accountStore: AccountStore + ) async throws { self.storeID = storeID + self.userID = try client.userId() + notifications = MatrixNotifications(accountID: storeID) self.storePassphrase = storePassphrase + self.accountStore = accountStore self.client = client spaceService = LiveSpaceService(client: self.client, spaceService: await client.spaceService()) clientDelegateHandle = try? self.client.setDelegate(delegate: self) - observeDockIconUnreadCount() } func userSession() throws -> UserSession { @@ -68,27 +80,57 @@ public class MatrixClient { session: client.session(), storeID: storeID, storePassphrase: storePassphrase) } - static func clientBuilder(homeServer: String, storeId: String, storePassphrase: String) + /// The most connections each of an account's SQLite databases keeps open. + /// + /// The SDK otherwise sizes each pool at four connections per CPU core. With four databases per + /// account and two file descriptors per connection, a few accounts would then exhaust the + /// process's file descriptors, failing database opens, network requests, and rendering. + static let sqlitePoolMaxSize: UInt32 = 8 + + /// Where a client's homeserver comes from. + enum Homeserver { + /// A server name or URL entered at sign-in. Building the client looks up the homeserver and + /// checks that it supports native sliding sync, which takes network requests. + case discover(serverNameOrURL: String) + /// The homeserver of a stored session, which already uses native sliding sync. Building the + /// client takes no network requests, so restoring at launch doesn't wait for, or need, the + /// network. + case stored(url: String) + } + + static func clientBuilder(homeserver: Homeserver, storeId: String, storePassphrase: String) -> ClientBuilder { let sqliteConfig = SqliteStoreBuilder( - dataPath: URL.sessionData(for: storeId).path(percentEncoded: false), - cachePath: URL.sessionCaches(for: storeId).path(percentEncoded: false) + dataPath: StoreDirectories.data(for: storeId).path(percentEncoded: false), + cachePath: StoreDirectories.caches(for: storeId).path(percentEncoded: false) ) .passphrase(passphrase: storePassphrase) + .poolMaxSize(poolMaxSize: sqlitePoolMaxSize) - return ClientBuilder() - .serverNameOrHomeserverUrl(serverNameOrUrl: homeServer) + let builder = ClientBuilder() .sqliteStore(config: sqliteConfig) .withSearchIndexStore( - path: URL.sessionCaches(for: storeId).appending(component: "SearchIndex") + path: StoreDirectories.caches(for: storeId).appending(component: "SearchIndex") .path(percentEncoded: false), key: storePassphrase ) - .slidingSyncVersionBuilder(versionBuilder: .discoverNative) .threadsEnabled(enabled: true, threadSubscriptions: true) .autoEnableCrossSigning(autoEnableCrossSigning: true) .userAgent(userAgent: "Mactrix macOS") + + switch homeserver { + case .discover(let serverNameOrURL): + return + builder + .serverNameOrHomeserverUrl(serverNameOrUrl: serverNameOrURL) + .slidingSyncVersionBuilder(versionBuilder: .discoverNative) + case .stored(let url): + return + builder + .homeserverUrl(url: url) + .slidingSyncVersionBuilder(versionBuilder: .native) + } } struct SecureRandomBytesError: LocalizedError { @@ -114,7 +156,8 @@ public class MatrixClient { let storePassphrase = try Self.generateStorePassphrase() let client = try await Self.clientBuilder( - homeServer: homeServer, storeId: storeID, storePassphrase: storePassphrase + homeserver: .discover(serverNameOrURL: homeServer), storeId: storeID, + storePassphrase: storePassphrase ).build() let details = await client.homeserverLoginDetails() @@ -123,22 +166,65 @@ public class MatrixClient { loginDetails: details) } - public static func attemptRestore() async throws -> MatrixClient? { - guard let userSession = try UserSession.loadUserFromKeychain() else { return nil } + /// Restores every stored account. Accounts that fail to restore are skipped and logged. + public static func restoreAll(accountStore: AccountStore) async -> [MatrixClient] { + let sessions: [UserSession] + do { + try accountStore.migrateLegacyIfNeeded() + removeOrphanedStores(accountStore: accountStore) + sessions = try accountStore.loadAll() + } catch { + Logger.matrixClient.error("Failed to load stored accounts: \(error)") + return [] + } + + // Start every restore before awaiting any, so launch waits for the slowest account rather + // than all of them in turn. Awaiting in order keeps the stored account order. + let restores = sessions.map { session in + Task { @MainActor in + try await MatrixClient(userSession: session, accountStore: accountStore) + } + } + var clients: [MatrixClient] = [] + for (session, restore) in zip(sessions, restores) { + do { + clients.append(try await restore.value) + } catch { + Logger.matrixClient.error("Failed to restore store \(session.storeID): \(error)") + } + } + return clients + } - return try await MatrixClient(userSession: userSession) + /// Deletes store directories left behind by abandoned logins. + static func removeOrphanedStores(accountStore: AccountStore) { + do { + // An unmigrated legacy session's store isn't listed yet, so it must not be swept. + guard try !accountStore.hasLegacySession() else { return } + StoreDirectories.removeOrphans( + in: [StoreDirectories.dataRoot, StoreDirectories.cachesRoot], + keeping: try accountStore.allStoreIDs(), + createdBefore: Date.now.addingTimeInterval(-10 * 60)) + } catch { + Logger.matrixClient.error("Skipping orphaned store cleanup: \(error)") + } } public func reset() async throws { recentReactions.invalidate() isResettingSession = true + offlineRestarter.cancel() await roomSubscriptions.invalidate() - Logger.matrixClient.debug("matrix client sign out") + // A start in flight stops at its next step; wait so it can't start syncing a signed-out + // session after the stop below. + await syncStartTask?.value + await syncService?.stop() + Logger.matrixClient.debug("matrix client sign out, store \(self.storeID)") try? await client.logout() - try? FileManager.default.removeItem(at: .sessionData(for: storeID)) - try? FileManager.default.removeItem(at: .sessionCaches(for: storeID)) - try AppKeychain().removeAll() - Logger.matrixClient.debug("matrix client sign out complete") + try? FileManager.default.removeItem(at: StoreDirectories.data(for: storeID)) + try? FileManager.default.removeItem(at: StoreDirectories.caches(for: storeID)) + try accountStore.remove(storeID: storeID) + Logger.matrixClient.debug("matrix client sign out complete, store \(self.storeID)") } public internal(set) var syncService: SyncService? @@ -216,8 +302,94 @@ public class MatrixClient { var notificationClient: NotificationClient? - public func startSync() async throws { + /// Account setup that comes with syncing. + /// + /// Some steps fail while the homeserver can't be reached, so none of them stop the sync loop from + /// starting. A failed step is retried whenever sync comes back online. + enum SyncSetupStep: String, CaseIterable { + case roomList = "room list" + case notifications + case verification + case ignoredUsers = "ignored users" + case ownProfile = "own profile" + } + + /// The setup steps that haven't succeeded yet. + @ObservationIgnored private var pendingSetupSteps = SyncSetupStep.allCases + @ObservationIgnored private var setupRetryTask: Task? + + /// Whether a call to `startSync()` is in flight. + public private(set) var isStartingSync = false + @ObservationIgnored private var syncStartTask: Task? + + /// Starts syncing, or restarts a sync that stopped, failed, or went offline. + /// + /// Calls made while a start is in flight wait for it instead of starting another, so this is + /// safe to call repeatedly. + public func startSync() async { + if let syncStartTask { + await syncStartTask.value + return + } + let task = Task { await performStartSync() } + syncStartTask = task + isStartingSync = true + await task.value + syncStartTask = nil + isStartingSync = false + } + + /// The Mac's network connection. Without one, an offline account isn't restarted until it + /// comes back, and on a connection that saves data it's restarted fewer times. + @ObservationIgnored public var networkConditions = NetworkConditions() + + @ObservationIgnored private lazy var offlineRestarter = OfflineRestarter( + canRestart: { [weak self] in + // A restart briefly reports running before it can fail again, so only a later check that + // finds the account online ends the restarts. Errors other than being offline aren't the + // network's, so restarting wouldn't help them. Without a network, the restart when it + // comes back takes over. + guard let self else { return false } + return [.offline, .idle].contains(syncState) && !isResettingSession + && !authenticationFailed && networkConditions.isAvailable + }, + isSavingPower: { [weak self] in + ProcessInfo.processInfo.isLowPowerModeEnabled + || self?.networkConditions.isSavingData == true + }, + restart: { [weak self] in await self?.startSync() }) + + /// Restarts sync a few times while the account stays offline, fewer in Low Power Mode or on a + /// connection that saves data. Going offline again, or the network coming back, starts another + /// round. See `OfflineRestarter`. + func scheduleOfflineRestarts() { + guard !isResettingSession else { return } + offlineRestarter.start() + } + + private func performStartSync() async { + guard !isResettingSession, !authenticationFailed else { return } + // Once built, the sync service is only restarted, keeping its listeners. Its `start()` does + // nothing while running, and reconnects straight away when offline. + if let syncService { + Logger.matrixClient.info( + "Restarting sync from \(String(describing: self.syncState), privacy: .public), store \(self.storeID)" + ) + await syncService.start() + retryPendingSetupSteps() + await client.enableAllSendQueues(enable: true) + return + } + do { + try await setUpSync() + } catch { + Logger.matrixClient.error("Failed to start sync, store \(self.storeID): \(error)") + } + } + + private func setUpSync() async throws { let _syncService = try await client.syncService().withOfflineMode().finish() + guard !isResettingSession else { return } syncService = _syncService syncStateHandle = _syncService.state(listener: self) @@ -228,36 +400,104 @@ public class MatrixClient { syncIndicatorHandle = _roomListService.syncIndicator( delayBeforeShowingInMs: 200, delayBeforeHidingInMs: 200, listener: self) - let roomEntriesListener = AsyncSDKListener<[RoomListEntriesUpdate]>() - let _roomListEntriesHandle = try await _roomListService.allRooms().entriesWithDynamicAdapters( - pageSize: 100, listener: roomEntriesListener) - _ = _roomListEntriesHandle.controller().setFilter(kind: .all(filters: [])) - roomListEntriesHandle = _roomListEntriesHandle - - Task { [weak self] in - for await roomEntries in roomEntriesListener { - guard let self else { break } - self.updateRoomEntries(roomEntriesUpdate: roomEntries) - } - } - - notificationClient = try await client.notificationClient( - processSetup: .singleProcess(syncService: _syncService)) - await client.registerNotificationHandler(listener: notifications) - - try await client.getSessionVerificationController().setDelegate(delegate: self) - let encryption = client.encryption() verificationStateHandle = encryption.verificationStateListener(listener: self) recoveryStateHandle = encryption.recoveryStateListener(listener: self) backupStateHandle = encryption.backupStateListener(listener: self) ignoredUsersHandle = client.subscribeToIgnoredUsers(listener: self) - ignoredUserIds = try await client.ignoredUsers() - // Start the sync loop. + // The room list and notification handler come from the local store. Set them up before the + // first sync, so it doesn't miss rooms or notifications. No retry can overlap this: retries + // only start once sync is running. + await runSetupSteps([.roomList, .notifications]) + guard !isResettingSession else { return } + + // Start the sync loop. In offline mode it keeps retrying until the homeserver can be reached. await _syncService.start() - Logger.matrixClient.info("Matrix sync started") + Logger.matrixClient.info("Matrix sync started, store \(self.storeID)") + + retryPendingSetupSteps() + } + + /// Retries the setup steps that haven't succeeded yet, unless a retry is already running. + func retryPendingSetupSteps() { + guard setupRetryTask == nil, !pendingSetupSteps.isEmpty, !isResettingSession else { return } + setupRetryTask = Task { [weak self] in + guard let self else { return } + await self.runSetupSteps(self.pendingSetupSteps) + self.setupRetryTask = nil + } + } + + /// Runs each of `steps` that is still pending, keeping the ones that fail for a later retry. + private func runSetupSteps(_ steps: [SyncSetupStep]) async { + for step in steps where pendingSetupSteps.contains(step) { + guard !isResettingSession else { return } + do { + try await runSetupStep(step) + pendingSetupSteps.removeAll { $0 == step } + } catch { + Logger.matrixClient.error( + "Sync setup step \(step.rawValue, privacy: .public) failed, store \(self.storeID): \(error)" + ) + } + } + } + + private func runSetupStep(_ step: SyncSetupStep) async throws { + switch step { + case .roomList: + guard let roomListService else { return } + let roomEntriesListener = AsyncSDKListener<[RoomListEntriesUpdate]>() + let _roomListEntriesHandle = try await roomListService.allRooms() + .entriesWithDynamicAdapters(pageSize: 100, listener: roomEntriesListener) + _ = _roomListEntriesHandle.controller().setFilter(kind: .all(filters: [])) + roomListEntriesHandle = _roomListEntriesHandle + + Task { [weak self] in + for await roomEntries in roomEntriesListener { + guard let self else { break } + self.updateRoomEntries(roomEntriesUpdate: roomEntries) + } + } + case .notifications: + guard let syncService else { return } + notificationClient = try await client.notificationClient( + processSetup: .singleProcess(syncService: syncService)) + await client.registerNotificationHandler(listener: notifications) + case .verification: + try await client.getSessionVerificationController().setDelegate(delegate: self) + case .ignoredUsers: + ignoredUserIds = try await client.ignoredUsers() + case .ownProfile: + try await loadOwnProfile() + } + } + + /// Reloads `ownDisplayName` and `ownAvatarUrl`, falling back to cached values when offline. + public func refreshOwnProfile() async { + try? await loadOwnProfile() + } + + /// Reloads `ownDisplayName` and `ownAvatarUrl`, throwing if the homeserver can't be reached. The + /// cached avatar fills in while there is none yet. + private func loadOwnProfile() async throws { + let displayName: String + do { + displayName = try await client.displayName() + } catch { + if ownAvatarUrl == nil { + ownAvatarUrl = try? await client.cachedAvatarUrl() + } + throw error + } + ownDisplayName = displayName + if let avatarUrl = try? await client.avatarUrl() { + ownAvatarUrl = avatarUrl + } else if ownAvatarUrl == nil { + ownAvatarUrl = try? await client.cachedAvatarUrl() + } } public func clearCache() async throws { @@ -304,42 +544,25 @@ extension MatrixClient: MatrixRustSDK.ClientSessionDelegate { Logger.matrixClient.debug( "client session delegate: retrieve session from keychain: \(userId, privacy: .sensitive)") - let userSession = try UserSession.loadUserFromKeychain() - if let userSession { - if userSession.userID == userId { - return userSession.session - } else { - Logger.matrixClient.debug( - "restored user session has wrong userId: \(userSession.userID, privacy: .sensitive), expected \(userId, privacy: .sensitive)" - ) - throw MatrixClientRestoreSessionError.wrongUserId - } - } else { + guard let userSession = try accountStore.load(storeID: storeID) else { throw MatrixClientRestoreSessionError.sessionNotFound } + guard userSession.userID == userId else { + Logger.matrixClient.debug( + "restored user session has wrong userId: \(userSession.userID, privacy: .sensitive), expected \(userId, privacy: .sensitive)" + ) + throw MatrixClientRestoreSessionError.wrongUserId + } + return userSession.session } public nonisolated func saveSessionInKeychain(session: MatrixRustSDK.Session) { - Logger.matrixClient.debug("client session delegate: save session in keychain") + Logger.matrixClient.debug("client session delegate: save session in keychain, store \(self.storeID)") do { - try UserSession(session: session, storeID: storeID, storePassphrase: storePassphrase) - .saveUserToKeychain() + try accountStore.save( + UserSession(session: session, storeID: storeID, storePassphrase: storePassphrase)) } catch { - Logger.matrixClient.error("failed to save session in keychain: \(error)") + Logger.matrixClient.error("failed to save session in keychain, store \(self.storeID): \(error)") } } } - -extension URL { - fileprivate static func sessionData(for sessionID: String) -> URL { - applicationSupportDirectory - .appending(component: "dk.qpqp.mactrix") - .appending(component: sessionID) - } - - fileprivate static func sessionCaches(for sessionID: String) -> URL { - cachesDirectory - .appending(component: "dk.qpqp.mactrix") - .appending(component: sessionID) - } -} diff --git a/Sources/MatrixIntegration/MatrixClientSessionDelegate.swift b/Sources/MatrixIntegration/MatrixClientSessionDelegate.swift deleted file mode 100644 index f0d60d6f..00000000 --- a/Sources/MatrixIntegration/MatrixClientSessionDelegate.swift +++ /dev/null @@ -1,46 +0,0 @@ -import Foundation -import MatrixRustSDK -import OSLog -import Observation -import UniformTypeIdentifiers -import Utils - -final class MatrixClientSessionDelegate: MatrixRustSDK.ClientSessionDelegate { - let storeID: String - let storePassphrase: String - - init(storeID: String, storePassphrase: String) { - self.storeID = storeID - self.storePassphrase = storePassphrase - } - - func retrieveSessionFromKeychain(userId: String) throws -> MatrixRustSDK.Session { - Logger.matrixClient.debug( - "client session delegate: retrieve session from keychain: \(userId, privacy: .sensitive)" - ) - - let userSession = try UserSession.loadUserFromKeychain() - if let userSession { - if userSession.userID == userId { - return userSession.session - } else { - Logger.matrixClient.debug( - "restored user session has wrong userId: \(userSession.userID, privacy: .sensitive), expected \(userId, privacy: .sensitive)" - ) - throw MatrixClientRestoreSessionError.wrongUserId - } - } else { - throw MatrixClientRestoreSessionError.sessionNotFound - } - } - - func saveSessionInKeychain(session: MatrixRustSDK.Session) { - Logger.matrixClient.debug("client session delegate: save session in keychain") - do { - try UserSession(session: session, storeID: storeID, storePassphrase: storePassphrase) - .saveUserToKeychain() - } catch { - Logger.matrixClient.error("failed to save session in keychain: \(error)") - } - } -} diff --git a/Sources/MatrixIntegration/MatrixNotifications.swift b/Sources/MatrixIntegration/MatrixNotifications.swift index e5f927f0..b868fd66 100644 --- a/Sources/MatrixIntegration/MatrixNotifications.swift +++ b/Sources/MatrixIntegration/MatrixNotifications.swift @@ -5,7 +5,15 @@ import UserNotifications // This class is Sendable because MatrixRustSDK.SyncNotificationListener requires it to be so @MainActor @Observable public final class MatrixNotifications: NSObject, Sendable { - public var selectedRoomId: String? + enum UserInfoKey { + static let roomId = "roomId" + static let accountID = "accountID" + } + + /// The `storeID` of the account these notifications belong to. + let accountID: String + /// Names the account in notifications; set when more than one account is signed in. + public var accountLabel: String? typealias NotificationEvent = (item: MatrixRustSDK.NotificationItem, roomId: String) @@ -13,12 +21,12 @@ import UserNotifications AsyncStream.Continuation @ObservationIgnored private var streamTask: Task? - public override init() { + init(accountID: String) { + self.accountID = accountID let (stream, continuation) = AsyncStream.makeStream() notificationContinuation = continuation super.init() - UNUserNotificationCenter.current().delegate = self streamTask = Task { [weak self] in for await (notification, roomId) in stream { @@ -29,16 +37,6 @@ import UserNotifications } } -extension MatrixNotifications: @MainActor UNUserNotificationCenterDelegate { - public func userNotificationCenter( - _ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse - ) async { - let roomId = response.notification.request.content.userInfo["roomId"] as? String - Logger.notification.info("Notification delegate didReceive: \(roomId ?? "")") - selectedRoomId = roomId - } -} - extension MatrixNotifications: MatrixRustSDK.SyncNotificationListener { public nonisolated func onNotification( notification: MatrixRustSDK.NotificationItem, roomId: String @@ -65,10 +63,16 @@ extension MatrixNotifications { let content = UNMutableNotificationContent() content.title = notificationTitle(for: notification) - content.subtitle = notificationBody(for: notification) + if let accountLabel { + content.subtitle = accountLabel + content.body = notificationBody(for: notification) + } else { + content.subtitle = notificationBody(for: notification) + } content.sound = UNNotificationSound.default content.interruptionLevel = .timeSensitive - content.userInfo = ["roomId": roomId] + content.threadIdentifier = accountID + content.userInfo = [UserInfoKey.roomId: roomId, UserInfoKey.accountID: accountID] let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.01, repeats: false) let request = UNNotificationRequest( diff --git a/Sources/MatrixIntegration/NetworkConditions.swift b/Sources/MatrixIntegration/NetworkConditions.swift new file mode 100644 index 00000000..210a8682 --- /dev/null +++ b/Sources/MatrixIntegration/NetworkConditions.swift @@ -0,0 +1,18 @@ +/// What the Mac's current network connection allows. +public struct NetworkConditions: Sendable, Equatable { + /// Whether there is a connection at all. + public var isAvailable: Bool + /// Whether the connection is one the user may pay for, such as a phone's hotspot. + public var isExpensive: Bool + /// Whether the user turned on Low Data Mode for the connection. + public var isConstrained: Bool + + public init(isAvailable: Bool = true, isExpensive: Bool = false, isConstrained: Bool = false) { + self.isAvailable = isAvailable + self.isExpensive = isExpensive + self.isConstrained = isConstrained + } + + /// Whether requests that can wait should be kept to a minimum on this connection. + public var isSavingData: Bool { isExpensive || isConstrained } +} diff --git a/Sources/MatrixIntegration/NotificationRouter.swift b/Sources/MatrixIntegration/NotificationRouter.swift new file mode 100644 index 00000000..0f01a531 --- /dev/null +++ b/Sources/MatrixIntegration/NotificationRouter.swift @@ -0,0 +1,57 @@ +import OSLog +import Observation +import UserNotifications + +/// Receives clicks on notifications from every account. +/// +/// The notification center has a single delegate, so this is owned by the app rather than by each +/// account's ``MatrixNotifications``. +@MainActor @Observable public final class NotificationRouter: NSObject { + public struct Target: Equatable, Sendable { + /// The `storeID` of the account that received the notification. `nil` for notifications + /// posted by versions without multi-account support. + public let accountID: String? + public let roomId: String + } + + /// The room of the most recently clicked notification, until the app has shown it. + public var pendingTarget: Target? + + /// The `storeID` of the account shown in the app, whose notifications stay silent while the app + /// is frontmost. + @ObservationIgnored public var activeAccountID: String? + + public override init() { + super.init() + UNUserNotificationCenter.current().delegate = self + } +} + +extension NotificationRouter: @MainActor UNUserNotificationCenterDelegate { + public func userNotificationCenter( + _ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse + ) async { + let userInfo = response.notification.request.content.userInfo + guard let roomId = userInfo[MatrixNotifications.UserInfoKey.roomId] as? String else { return } + let accountID = userInfo[MatrixNotifications.UserInfoKey.accountID] as? String + Logger.notification.info("Notification clicked for room \(roomId) in store \(accountID ?? "?")") + pendingTarget = Target(accountID: accountID, roomId: roomId) + } + + /// Shows notifications from accounts other than the active one while the app is frontmost, + /// since their rooms aren't visible. macOS would otherwise hide them. + public func userNotificationCenter( + _ center: UNUserNotificationCenter, willPresent notification: UNNotification + ) async -> UNNotificationPresentationOptions { + let accountID = + notification.request.content.userInfo[MatrixNotifications.UserInfoKey.accountID] as? String + return Self.foregroundPresentation(forAccountID: accountID, activeAccountID: activeAccountID) + } + + static func foregroundPresentation(forAccountID accountID: String?, activeAccountID: String?) + -> UNNotificationPresentationOptions + { + guard let accountID, accountID != activeAccountID else { return [] } + return [.banner, .list, .sound] + } +} diff --git a/Sources/MatrixIntegration/OfflineRestarter.swift b/Sources/MatrixIntegration/OfflineRestarter.swift new file mode 100644 index 00000000..8f082b15 --- /dev/null +++ b/Sources/MatrixIntegration/OfflineRestarter.swift @@ -0,0 +1,77 @@ +/// Restarts an offline account's sync a few times, then leaves reconnecting to the sync service's +/// offline mode. +/// +/// The sync service's offline mode only reconnects once a reachability check succeeds, and a +/// check on a connection that went dead when the network changed hangs until it times out, +/// keeping the account offline for a minute or more. A restart cancels that check and tries again +/// at once. A homeserver that's down or unreachable can stay that way for a long time, though, and +/// offline mode keeps checking on its own, so restarting for longer would only spend battery. +@MainActor +final class OfflineRestarter { + /// How long to wait before each restart. Each wait is shortened by up to half at random, so + /// clients of a homeserver that went down don't all retry at once. + static let delays: [Duration] = [2, 4, 8, 16, 30].map { .seconds($0) } + + /// The waits used instead of `delays` in Low Power Mode or on a connection that saves data, + /// where each restart's new connection and full sync request cost more. + static let savingDelays: [Duration] = [5, 20].map { .seconds($0) } + + private let canRestart: @MainActor () -> Bool + private let isSavingPower: @MainActor () -> Bool + private let restart: @MainActor () async -> Void + private let sleep: @MainActor (Duration) async -> Void + private let jitter: @MainActor () -> Double + private var task: Task? + + /// - Parameters: + /// - canRestart: Whether the account is still offline and a restart could help. Checked + /// after each wait; the round ends once it's `false`. + /// - isSavingPower: Whether to use `savingDelays`. Checked before and after each wait, so + /// turning it on partway through cuts the round short. + /// - restart: Restarts sync. + /// - sleep: Waits for the given time. Replaced in tests. + /// - jitter: The fraction of each delay to wait, from 0.5 to 1. Replaced in tests. + init( + canRestart: @escaping @MainActor () -> Bool, + isSavingPower: @escaping @MainActor () -> Bool, + restart: @escaping @MainActor () async -> Void, + sleep: @escaping @MainActor (Duration) async -> Void = { try? await Task.sleep(for: $0) }, + jitter: @escaping @MainActor () -> Double = { .random(in: 0.5...1) } + ) { + self.canRestart = canRestart + self.isSavingPower = isSavingPower + self.restart = restart + self.sleep = sleep + self.jitter = jitter + } + + /// Starts a round of restarts, unless one is already going. + func start() { + guard task == nil else { return } + task = Task { [weak self] in + await self?.run() + if !Task.isCancelled { + self?.task = nil + } + } + } + + /// Ends the current round. + func cancel() { + task?.cancel() + } + + private var currentDelays: [Duration] { isSavingPower() ? Self.savingDelays : Self.delays } + + /// Runs one round of restarts, returning when it ends. + func run() async { + var restarts = 0 + while restarts < currentDelays.count { + await sleep(currentDelays[restarts] * jitter()) + // Saving power may have turned on during the wait, leaving no restarts in this round. + guard !Task.isCancelled, restarts < currentDelays.count, canRestart() else { return } + await restart() + restarts += 1 + } + } +} diff --git a/Sources/MatrixIntegration/OpenFileLimit.swift b/Sources/MatrixIntegration/OpenFileLimit.swift new file mode 100644 index 00000000..0917c3df --- /dev/null +++ b/Sources/MatrixIntegration/OpenFileLimit.swift @@ -0,0 +1,35 @@ +import Darwin +import OSLog + +/// The number of files the process may have open at once. +/// +/// Each signed-in account keeps dozens of SQLite files and sockets open, so the default soft +/// limit of 256 leaves little room for several accounts. +public enum OpenFileLimit { + /// The soft limit to raise to, well below the kernel's `OPEN_MAX` of 10240. + static let target: rlim_t = 4096 + + /// Raises the soft limit to `target`, or as far as the hard limit allows. Never lowers it. + public static func raise() { + var limit = rlimit() + guard getrlimit(RLIMIT_NOFILE, &limit) == 0 else { + Logger.matrixClient.error("Failed to read the open file limit: errno \(errno)") + return + } + guard let soft = raisedSoftLimit(current: limit.rlim_cur, hard: limit.rlim_max) else { return } + + let previous = limit.rlim_cur + limit.rlim_cur = soft + if setrlimit(RLIMIT_NOFILE, &limit) == 0 { + Logger.matrixClient.info("Raised the open file limit from \(previous) to \(soft)") + } else { + Logger.matrixClient.error("Failed to raise the open file limit: errno \(errno)") + } + } + + /// The soft limit to set, or `nil` if `current` is already at least `target` or the hard limit. + static func raisedSoftLimit(current: rlim_t, hard: rlim_t, target: rlim_t = target) -> rlim_t? { + let soft = min(target, hard) + return soft > current ? soft : nil + } +} diff --git a/Sources/MatrixIntegration/StoreDirectories.swift b/Sources/MatrixIntegration/StoreDirectories.swift new file mode 100644 index 00000000..ab5e7785 --- /dev/null +++ b/Sources/MatrixIntegration/StoreDirectories.swift @@ -0,0 +1,57 @@ +import Foundation +import OSLog + +/// Locations of the per-account SQLite stores, which are named by `storeID`. +enum StoreDirectories { + static let appDirectoryName = "dk.qpqp.mactrix" + + static var dataRoot: URL { + URL.applicationSupportDirectory.appending(component: appDirectoryName) + } + + static var cachesRoot: URL { + URL.cachesDirectory.appending(component: appDirectoryName) + } + + static func data(for storeID: String) -> URL { + dataRoot.appending(component: storeID) + } + + static func caches(for storeID: String) -> URL { + cachesRoot.appending(component: storeID) + } + + /// Deletes store directories that belong to no account, such as those created for a login + /// that was abandoned. + /// + /// Only directories named by a UUID (as created for new stores) and created before `cutoff` + /// are removed. Returns the removed directories. + @discardableResult + static func removeOrphans( + in roots: [URL], keeping storeIDs: Set, createdBefore cutoff: Date, + fileManager: FileManager = .default + ) -> [URL] { + var removed: [URL] = [] + for root in roots { + let children = + (try? fileManager.contentsOfDirectory( + at: root, includingPropertiesForKeys: [.creationDateKey, .isDirectoryKey])) ?? [] + for child in children { + let name = child.lastPathComponent + guard UUID(uuidString: name) != nil, !storeIDs.contains(name) else { continue } + let values = try? child.resourceValues(forKeys: [.creationDateKey, .isDirectoryKey]) + guard values?.isDirectory == true, + let created = values?.creationDate, created < cutoff + else { continue } + do { + try fileManager.removeItem(at: child) + removed.append(child) + Logger.matrixClient.info("Removed orphaned store \(name)") + } catch { + Logger.matrixClient.error("Failed to remove orphaned store \(name): \(error)") + } + } + } + return removed + } +} diff --git a/Sources/MatrixIntegration/UserSession.swift b/Sources/MatrixIntegration/UserSession.swift index b80a0bfe..55f7dee1 100644 --- a/Sources/MatrixIntegration/UserSession.swift +++ b/Sources/MatrixIntegration/UserSession.swift @@ -1,13 +1,7 @@ -import AsyncAlgorithms import Foundation import MatrixRustSDK -import OSLog -import Observation -import Security -import UniformTypeIdentifiers -import Utils -struct UserSession: Codable { +struct UserSession: Codable, Equatable { let accessToken: String let refreshToken: String? let userID: String @@ -38,19 +32,4 @@ struct UserSession: Codable { oauthData: oauthData, slidingSyncVersion: .native) } - - fileprivate static var keychainKey: String { "UserSession" } - - func saveUserToKeychain() throws { - let keychainData = try JSONEncoder().encode(self) - try AppKeychain().save(keychainData, forKey: Self.keychainKey) - } - - static func loadUserFromKeychain() throws -> Self? { - Logger.matrixClient.debug("Load user from keychain") - if let keychainData = try AppKeychain().load(forKey: keychainKey) { - return try JSONDecoder().decode(Self.self, from: keychainData) - } - return nil - } } diff --git a/Tests/MactrixAppTests/AccountStoreTests.swift b/Tests/MactrixAppTests/AccountStoreTests.swift new file mode 100644 index 00000000..a4df31a4 --- /dev/null +++ b/Tests/MactrixAppTests/AccountStoreTests.swift @@ -0,0 +1,154 @@ +import Foundation +import MatrixRustSDK +import Synchronization +import Testing + +@testable import MatrixIntegration + +final class FakeKeychain: KeychainStore, Sendable { + let items = Mutex<[String: Data]>([:]) + let failingDeletes = Mutex>([]) + + func save(_ data: Data, forKey key: String) throws { + items.withLock { $0[key] = data } + } + + func load(forKey key: String) throws -> Data? { + items.withLock { $0[key] } + } + + func delete(forKey key: String) throws { + if failingDeletes.withLock({ $0.contains(key) }) { + throw KeychainError.unexpectedStatus(-1) + } + items.withLock { $0[key] = nil } + } + + func keys(withPrefix prefix: String) throws -> [String] { + items.withLock { Array($0.keys) }.filter { $0.hasPrefix(prefix) } + } +} + +func makeUserSession(storeID: String, userID: String = "@alice:example.org", token: String = "t") + -> UserSession +{ + UserSession( + session: Session( + accessToken: token, refreshToken: nil, userId: userID, deviceId: "DEVICE", + homeserverUrl: "https://example.org", oauthData: nil, slidingSyncVersion: .native), + storeID: storeID, storePassphrase: "passphrase") +} + +struct AccountStoreTests { + let keychain = FakeKeychain() + let defaults: UserDefaults + let store: AccountStore + + init() { + let suite = "AccountStoreTests.\(UUID().uuidString)" + defaults = UserDefaults(suiteName: suite)! + defaults.removePersistentDomain(forName: suite) + store = AccountStore(keychain: keychain, defaults: defaults) + } + + func storeLegacy(_ session: UserSession) throws { + try keychain.save(JSONEncoder().encode(session), forKey: AccountStore.legacySessionKey) + } + + @Test func freshInstallHasNoAccounts() throws { + try store.migrateLegacyIfNeeded() + #expect(try store.loadAll().isEmpty) + #expect(store.lastFocusedStoreID == nil) + #expect(defaults.integer(forKey: AccountStore.DefaultsKey.schemaVersion) == 1) + } + + @Test func migratesLegacySession() throws { + let legacy = makeUserSession(storeID: "A") + try storeLegacy(legacy) + + try store.migrateLegacyIfNeeded() + + #expect(try store.loadAll() == [legacy]) + #expect(store.lastFocusedStoreID == "A") + #expect(try keychain.load(forKey: AccountStore.legacySessionKey) == nil) + } + + @Test func migrationIsIdempotent() throws { + let legacy = makeUserSession(storeID: "A") + try storeLegacy(legacy) + + try store.migrateLegacyIfNeeded() + try store.migrateLegacyIfNeeded() + + #expect(try store.loadAll() == [legacy]) + } + + @Test func interruptedMigrationRemovesLegacyWithoutOverwritingNewerSession() throws { + let legacy = makeUserSession(storeID: "A", token: "old") + try storeLegacy(legacy) + keychain.failingDeletes.withLock { $0.insert(AccountStore.legacySessionKey) } + + // The legacy item survives the first run. The migrated account is still usable. + try store.migrateLegacyIfNeeded() + #expect(try keychain.load(forKey: AccountStore.legacySessionKey) != nil) + #expect(try store.loadAll() == [legacy]) + + // The SDK refreshes the token before the next launch. + let refreshed = makeUserSession(storeID: "A", token: "new") + try store.save(refreshed) + + keychain.failingDeletes.withLock { $0.removeAll() } + try store.migrateLegacyIfNeeded() + + #expect(try store.loadAll() == [refreshed]) + #expect(try keychain.load(forKey: AccountStore.legacySessionKey) == nil) + } + + @Test func unreadableLegacySessionIsKept() throws { + try keychain.save(Data("not json".utf8), forKey: AccountStore.legacySessionKey) + + try store.migrateLegacyIfNeeded() + + #expect(try store.loadAll().isEmpty) + #expect(try keychain.load(forKey: AccountStore.legacySessionKey) == Data("not json".utf8)) + } + + @Test func accountsAreIsolated() throws { + let a = makeUserSession(storeID: "A", userID: "@a:example.org") + let b = makeUserSession(storeID: "B", userID: "@b:example.org") + try store.save(a) + try store.save(b) + + let refreshedA = makeUserSession(storeID: "A", userID: "@a:example.org", token: "new") + try store.save(refreshedA) + #expect(try store.load(storeID: "B") == b) + + try store.remove(storeID: "A") + #expect(try store.loadAll() == [b]) + } + + @Test func preservesOrderAndPrunesMissingAccounts() throws { + try store.save(makeUserSession(storeID: "B")) + try store.save(makeUserSession(storeID: "A")) + try store.save(makeUserSession(storeID: "C")) + #expect(try store.loadAll().map(\.storeID) == ["B", "A", "C"]) + + // An item removed behind our back is dropped from the order. + try keychain.delete(forKey: AccountStore.sessionKey(for: "A")) + #expect(try store.loadAll().map(\.storeID) == ["B", "C"]) + #expect(defaults.stringArray(forKey: AccountStore.DefaultsKey.order) == ["B", "C"]) + } + + @Test func removingActiveAccountClearsActive() throws { + try store.save(makeUserSession(storeID: "A")) + store.lastFocusedStoreID = "A" + try store.remove(storeID: "A") + #expect(store.lastFocusedStoreID == nil) + } + + @Test func skipsUnreadableSessions() throws { + try store.save(makeUserSession(storeID: "A")) + try keychain.save(Data("garbage".utf8), forKey: AccountStore.sessionKey(for: "B")) + #expect(try store.loadAll().map(\.storeID) == ["A"]) + } +} diff --git a/Tests/MactrixAppTests/NotificationRouterTests.swift b/Tests/MactrixAppTests/NotificationRouterTests.swift new file mode 100644 index 00000000..0a4b5705 --- /dev/null +++ b/Tests/MactrixAppTests/NotificationRouterTests.swift @@ -0,0 +1,24 @@ +import Testing + +@testable import MatrixIntegration + +@MainActor +struct NotificationRouterTests { + @Test func showsInactiveAccountsWhileFrontmost() { + let options = NotificationRouter.foregroundPresentation( + forAccountID: "inactive", activeAccountID: "active") + #expect(options == [.banner, .list, .sound]) + } + + @Test func keepsActiveAccountSilentWhileFrontmost() { + let options = NotificationRouter.foregroundPresentation( + forAccountID: "active", activeAccountID: "active") + #expect(options.isEmpty) + } + + @Test func keepsNotificationsWithoutAccountSilent() { + let options = NotificationRouter.foregroundPresentation( + forAccountID: nil, activeAccountID: "active") + #expect(options.isEmpty) + } +} diff --git a/Tests/MactrixAppTests/NotificationWindowTests.swift b/Tests/MactrixAppTests/NotificationWindowTests.swift new file mode 100644 index 00000000..9727b7b6 --- /dev/null +++ b/Tests/MactrixAppTests/NotificationWindowTests.swift @@ -0,0 +1,41 @@ +import Testing + +@testable import MactrixApp + +@MainActor +struct NotificationWindowTests { + @Test func notificationOpensInWindowShowingItsAccount() { + let frontmost = window(showing: "A") + let background = window(showing: "B") + let older = window(showing: "B") + + let chosen = AppState.window(forAccountID: "B", in: [frontmost, background, older]) + #expect(chosen === background) + } + + @Test func notificationSwitchesFrontmostWindowWhenNoneShowsItsAccount() { + let frontmost = window(showing: "A") + let background = window(showing: "B") + + let chosen = AppState.window(forAccountID: "C", in: [frontmost, background]) + #expect(chosen === frontmost) + } + + @Test func notificationWithoutAccountOpensInFrontmostWindow() { + let frontmost = window(showing: nil) + let background = window(showing: "B") + + let chosen = AppState.window(forAccountID: nil, in: [frontmost, background]) + #expect(chosen === frontmost) + } + + @Test func notificationWaitsForAWindow() { + #expect(AppState.window(forAccountID: "A", in: []) == nil) + } + + private func window(showing accountID: String?) -> WindowState { + let windowState = WindowState() + windowState.showAccount(accountID, knownAccountIDs: Set([accountID].compactMap { $0 })) + return windowState + } +} diff --git a/Tests/MactrixAppTests/OpenFileLimitTests.swift b/Tests/MactrixAppTests/OpenFileLimitTests.swift new file mode 100644 index 00000000..715fccdf --- /dev/null +++ b/Tests/MactrixAppTests/OpenFileLimitTests.swift @@ -0,0 +1,30 @@ +import Darwin +import Testing + +@testable import MatrixIntegration + +struct OpenFileLimitTests { + /// Darwin's `RLIM_INFINITY`, which isn't imported into Swift. + let unlimited = rlim_t(Int64.max) + + @Test func raisesToTarget() { + #expect(OpenFileLimit.raisedSoftLimit(current: 256, hard: unlimited, target: 4096) == 4096) + } + + @Test func stopsAtHardLimit() { + #expect(OpenFileLimit.raisedSoftLimit(current: 256, hard: 1024, target: 4096) == 1024) + } + + @Test func neverLowers() { + #expect(OpenFileLimit.raisedSoftLimit(current: 8192, hard: unlimited, target: 4096) == nil) + #expect(OpenFileLimit.raisedSoftLimit(current: 1024, hard: 1024, target: 4096) == nil) + } + + @Test func raiseAppliesToProcess() { + OpenFileLimit.raise() + + var limit = rlimit() + #expect(getrlimit(RLIMIT_NOFILE, &limit) == 0) + #expect(limit.rlim_cur >= min(OpenFileLimit.target, limit.rlim_max)) + } +} diff --git a/Tests/MactrixAppTests/StoreDirectoriesTests.swift b/Tests/MactrixAppTests/StoreDirectoriesTests.swift new file mode 100644 index 00000000..762ad511 --- /dev/null +++ b/Tests/MactrixAppTests/StoreDirectoriesTests.swift @@ -0,0 +1,48 @@ +import Foundation +import Testing + +@testable import MatrixIntegration + +struct StoreDirectoriesTests { + let root: URL + let fileManager = FileManager.default + + init() throws { + root = fileManager.temporaryDirectory.appending(component: "StoreDirectoriesTests-\(UUID())") + try fileManager.createDirectory(at: root, withIntermediateDirectories: true) + } + + func makeDirectory(_ name: String, createdAt date: Date) throws -> URL { + let url = root.appending(component: name) + try fileManager.createDirectory(at: url, withIntermediateDirectories: true) + try fileManager.setAttributes([.creationDate: date], ofItemAtPath: url.path) + return url + } + + @Test func removesOnlyOldUnreferencedStores() throws { + let old = Date.now.addingTimeInterval(-3600) + let kept = UUID().uuidString + let orphan = UUID().uuidString + let inProgress = UUID().uuidString + + let keptURL = try makeDirectory(kept, createdAt: old) + let orphanURL = try makeDirectory(orphan, createdAt: old) + let inProgressURL = try makeDirectory(inProgress, createdAt: .now) + let unrelatedURL = try makeDirectory("not-a-store", createdAt: old) + + let removed = StoreDirectories.removeOrphans( + in: [root], keeping: [kept], createdBefore: Date.now.addingTimeInterval(-600)) + + #expect(removed.map(\.lastPathComponent) == [orphan]) + #expect(fileManager.fileExists(atPath: keptURL.path)) + #expect(!fileManager.fileExists(atPath: orphanURL.path)) + #expect(fileManager.fileExists(atPath: inProgressURL.path)) + #expect(fileManager.fileExists(atPath: unrelatedURL.path)) + } + + @Test func missingRootIsIgnored() { + let removed = StoreDirectories.removeOrphans( + in: [root.appending(component: "missing")], keeping: [], createdBefore: .now) + #expect(removed.isEmpty) + } +} diff --git a/Tests/MactrixAppTests/WindowAccountFallbackTests.swift b/Tests/MactrixAppTests/WindowAccountFallbackTests.swift new file mode 100644 index 00000000..14c962e9 --- /dev/null +++ b/Tests/MactrixAppTests/WindowAccountFallbackTests.swift @@ -0,0 +1,36 @@ +import Testing + +@testable import MactrixApp + +@MainActor +struct WindowAccountFallbackTests { + @Test func windowKeepsItsOwnAccount() { + let shown = AppState.accountToShow( + windowAccountID: "B", lastFocusedAccountID: "A", accountIDs: ["A", "B"]) + #expect(shown == "B") + } + + @Test func newWindowOpensOnLastFocusedAccount() { + let shown = AppState.accountToShow( + windowAccountID: nil, lastFocusedAccountID: "B", accountIDs: ["A", "B"]) + #expect(shown == "B") + } + + @Test func removedAccountFallsBackToLastFocused() { + let shown = AppState.accountToShow( + windowAccountID: "C", lastFocusedAccountID: "B", accountIDs: ["A", "B"]) + #expect(shown == "B") + } + + @Test func fallsBackToFirstAccountWhenLastFocusedIsGone() { + let shown = AppState.accountToShow( + windowAccountID: "C", lastFocusedAccountID: "D", accountIDs: ["A", "B"]) + #expect(shown == "A") + } + + @Test func showsNothingWithoutAccounts() { + let shown = AppState.accountToShow( + windowAccountID: "A", lastFocusedAccountID: "A", accountIDs: []) + #expect(shown == nil) + } +} diff --git a/Tests/MactrixAppTests/WindowStateAccountTests.swift b/Tests/MactrixAppTests/WindowStateAccountTests.swift new file mode 100644 index 00000000..672ffa24 --- /dev/null +++ b/Tests/MactrixAppTests/WindowStateAccountTests.swift @@ -0,0 +1,100 @@ +import Foundation +import Testing + +@testable import MactrixApp + +@MainActor +struct WindowStateAccountTests { + @Test func stateSavedBeforeMultiAccountIsAdoptedByFirstAccount() throws { + let legacy = """ + {"selectedRoomId":"!room:example.org","selectedSpaceId":"!space:example.org",\ + "inspectorVisible":true,"sidebarSections":\(try sidebarJSON())} + """ + let windowState = try #require(WindowState(rawValue: legacy)) + #expect(windowState.accountID == nil) + + windowState.showAccount("A", knownAccountIDs: ["A"]) + + #expect(windowState.accountID == "A") + #expect(windowState.selectedRoomId == "!room:example.org") + #expect(windowState.selectedSpaceId == "!space:example.org") + #expect(windowState.inspectorVisible) + } + + @Test func switchingRestoresEachAccountsSelection() { + let windowState = WindowState() + windowState.showAccount("A", knownAccountIDs: ["A", "B"]) + windowState.selectedRoomId = "!a:example.org" + windowState.selectedSpaceId = "!a-space:example.org" + + windowState.showAccount("B", knownAccountIDs: ["A", "B"]) + #expect(windowState.selectedRoomId == nil) + #expect(windowState.selectedSpaceId == nil) + windowState.selectedRoomId = "!b:example.org" + + windowState.showAccount("A", knownAccountIDs: ["A", "B"]) + #expect(windowState.selectedRoomId == "!a:example.org") + #expect(windowState.selectedSpaceId == "!a-space:example.org") + + windowState.showAccount("B", knownAccountIDs: ["A", "B"]) + #expect(windowState.selectedRoomId == "!b:example.org") + } + + @Test func switchingResetsTransientState() { + let windowState = WindowState() + windowState.showAccount("A", knownAccountIDs: ["A", "B"]) + windowState.inspectorContent = .roomThreads + windowState.searchQuery = "hello" + windowState.searchTokens = [.rooms] + + windowState.showAccount("B", knownAccountIDs: ["A", "B"]) + + #expect(windowState.inspectorContent == .roomInfo) + #expect(windowState.searchQuery.isEmpty) + #expect(windowState.searchTokens.isEmpty) + if case .none = windowState.selectedScreen.content {} else { Issue.record("screen not reset") } + } + + @Test func removedAccountsAreForgotten() { + let windowState = WindowState() + windowState.showAccount("A", knownAccountIDs: ["A", "B"]) + windowState.selectedRoomId = "!a:example.org" + windowState.showAccount("B", knownAccountIDs: ["A", "B"]) + #expect(windowState.accountSelections.keys.contains("A")) + + // Account A is signed out while B is shown. + windowState.showAccount("B", knownAccountIDs: ["B"]) + #expect(windowState.accountSelections.isEmpty) + } + + @Test func signingOutOfLastAccountClearsSelection() { + let windowState = WindowState() + windowState.showAccount("A", knownAccountIDs: ["A"]) + windowState.selectedRoomId = "!a:example.org" + + windowState.showAccount(nil as String?, knownAccountIDs: []) + #expect(windowState.accountID == nil) + #expect(windowState.selectedRoomId == nil) + + windowState.showAccount("C", knownAccountIDs: ["C"]) + #expect(windowState.accountID == "C") + #expect(windowState.selectedRoomId == nil) + } + + @Test func roundTripsThroughSceneStorage() throws { + let windowState = WindowState() + windowState.showAccount("A", knownAccountIDs: ["A", "B"]) + windowState.selectedRoomId = "!a:example.org" + windowState.showAccount("B", knownAccountIDs: ["A", "B"]) + windowState.selectedRoomId = "!b:example.org" + + let restored = try #require(WindowState(rawValue: windowState.rawValue)) + #expect(restored.accountID == "B") + #expect(restored.selectedRoomId == "!b:example.org") + #expect(restored.accountSelections["A"] == AccountSelection(roomId: "!a:example.org")) + } + + private func sidebarJSON() throws -> String { + String(decoding: try JSONEncoder().encode(SidebarSectionCollapsibility()), as: UTF8.self) + } +} diff --git a/Tests/MatrixIntegrationTests/OfflineRestarterTests.swift b/Tests/MatrixIntegrationTests/OfflineRestarterTests.swift new file mode 100644 index 00000000..87334060 --- /dev/null +++ b/Tests/MatrixIntegrationTests/OfflineRestarterTests.swift @@ -0,0 +1,113 @@ +import Testing + +@testable import MatrixIntegration + +/// Drives an `OfflineRestarter` with no real waiting, recording each wait and restart. +@MainActor +final class RestarterHarness { + var isOffline = true + var isSavingPower = false + var jitter = 1.0 + var waits: [Duration] = [] + var restarts = 0 + /// Called after each wait, before the restarter checks whether to restart. + var afterWait: (RestarterHarness) -> Void = { _ in } + + lazy var restarter = OfflineRestarter( + canRestart: { [unowned self] in isOffline }, + isSavingPower: { [unowned self] in isSavingPower }, + restart: { [unowned self] in restarts += 1 }, + sleep: { [unowned self] duration in + waits.append(duration) + afterWait(self) + }, + jitter: { [unowned self] in jitter }) +} + +@MainActor +struct OfflineRestarterTests { + @Test func restartsFiveTimesThenStops() async { + let harness = RestarterHarness() + await harness.restarter.run() + + #expect(harness.restarts == 5) + #expect(harness.waits == [2, 4, 8, 16, 30].map { .seconds($0) }) + } + + @Test func restartsTwiceWhenSavingPower() async { + let harness = RestarterHarness() + harness.isSavingPower = true + await harness.restarter.run() + + #expect(harness.restarts == 2) + #expect(harness.waits == [5, 20].map { .seconds($0) }) + } + + @Test func savingPowerPartwayThroughCutsTheRoundShort() async { + let harness = RestarterHarness() + // Low Power Mode turns on during the third wait: two restarts are already as many as saving + // power allows, so none follow it. + harness.afterWait = { harness in + if harness.waits.count == 3 { harness.isSavingPower = true } + } + await harness.restarter.run() + + #expect(harness.restarts == 2) + #expect(harness.waits.count == 3) + } + + @Test func savingPowerAfterOneRestartAllowsOneMore() async { + let harness = RestarterHarness() + harness.afterWait = { harness in + if harness.waits.count == 1 { harness.isSavingPower = true } + } + await harness.restarter.run() + + // The second wait is the saving one. + #expect(harness.restarts == 2) + #expect(harness.waits == [.seconds(2), .seconds(20)]) + } + + @Test func stopsOnceOnline() async { + let harness = RestarterHarness() + harness.afterWait = { harness in + if harness.waits.count == 2 { harness.isOffline = false } + } + await harness.restarter.run() + + #expect(harness.restarts == 1) + #expect(harness.waits.count == 2) + } + + @Test func doesNotRestartWhenItCannot() async { + // Covers no network, a reset in progress, or a failed sign-in: `canRestart` is false. + let harness = RestarterHarness() + harness.isOffline = false + await harness.restarter.run() + + #expect(harness.restarts == 0) + #expect(harness.waits.count == 1) + } + + @Test func waitsAreScaledByJitter() async { + let harness = RestarterHarness() + harness.jitter = 0.5 + await harness.restarter.run() + + #expect(harness.waits == [1, 2, 4, 8, 15].map { .seconds($0) }) + } + + @Test func startRunsOneRoundAtATimeAndAnotherAfterItEnds() async { + let harness = RestarterHarness() + harness.restarter.start() + harness.restarter.start() + while harness.restarts < 5 { await Task.yield() } + // Let the finished round clear itself so the next start runs. + for _ in 0..<10 { await Task.yield() } + #expect(harness.restarts == 5) + + harness.restarter.start() + while harness.restarts < 10 { await Task.yield() } + #expect(harness.restarts == 10) + } +}