diff --git a/Intents/AddWebFeedIntentHandler.swift b/Intents/AddWebFeedIntentHandler.swift index 595d275c5..27fe48eb6 100644 --- a/Intents/AddWebFeedIntentHandler.swift +++ b/Intents/AddWebFeedIntentHandler.swift @@ -36,108 +36,117 @@ public class AddWebFeedIntentHandler: NSObject, AddWebFeedIntentHandling { } public func provideAccountNameOptions(for intent: AddWebFeedIntent, with completion: @escaping ([String]?, Error?) -> Void) { - guard let extensionContainers = ExtensionContainersFile.read() else { - completion(nil, AddWebFeedIntentHandlerError.communicationFailure) - return - } + Task { @MainActor in + guard let extensionContainers = ExtensionContainersFile.read() else { + completion(nil, AddWebFeedIntentHandlerError.communicationFailure) + return + } - let accountNames = extensionContainers.accounts.map { $0.name } - completion(accountNames, nil) + let accountNames = extensionContainers.accounts.map { $0.name } + completion(accountNames, nil) + } } public func resolveAccountName(for intent: AddWebFeedIntent, with completion: @escaping (AddWebFeedAccountNameResolutionResult) -> Void) { - guard let accountName = intent.accountName else { - completion(AddWebFeedAccountNameResolutionResult.notRequired()) - return - } + Task { @MainActor in + guard let accountName = intent.accountName else { + completion(AddWebFeedAccountNameResolutionResult.notRequired()) + return + } - guard let extensionContainers = ExtensionContainersFile.read() else { - completion(.unsupported(forReason: .communication)) - return - } + guard let extensionContainers = ExtensionContainersFile.read() else { + completion(.unsupported(forReason: .communication)) + return + } - if extensionContainers.findAccount(forName: accountName) == nil { - completion(.unsupported(forReason: .invalid)) - } else { - completion(.success(with: accountName)) + if extensionContainers.findAccount(forName: accountName) == nil { + completion(.unsupported(forReason: .invalid)) + } else { + completion(.success(with: accountName)) + } } } public func provideFolderNameOptions(for intent: AddWebFeedIntent, with completion: @escaping ([String]?, Error?) -> Void) { - guard let extensionContainers = ExtensionContainersFile.read() else { - completion(nil, AddWebFeedIntentHandlerError.communicationFailure) - return - } + Task { @MainActor in + guard let extensionContainers = ExtensionContainersFile.read() else { + completion(nil, AddWebFeedIntentHandlerError.communicationFailure) + return + } - guard let accountName = intent.accountName, let account = extensionContainers.findAccount(forName: accountName) else { - completion([String](), nil) - return - } + guard let accountName = intent.accountName, let account = extensionContainers.findAccount(forName: accountName) else { + completion([String](), nil) + return + } - let folderNames = account.folders.map { $0.name } - completion(folderNames, nil) + let folderNames = account.folders.map { $0.name } + completion(folderNames, nil) + } } public func resolveFolderName(for intent: AddWebFeedIntent, with completion: @escaping (AddWebFeedFolderNameResolutionResult) -> Void) { - guard let accountName = intent.accountName, let folderName = intent.folderName else { - completion(AddWebFeedFolderNameResolutionResult.notRequired()) + Task { @MainActor in + guard let accountName = intent.accountName, let folderName = intent.folderName else { + completion(AddWebFeedFolderNameResolutionResult.notRequired()) + return + } + + guard let extensionContainers = ExtensionContainersFile.read() else { + completion(.unsupported(forReason: .communication)) + return + } + + guard let account = extensionContainers.findAccount(forName: accountName) else { + completion(.unsupported(forReason: .invalid)) + return + } + + if account.findFolder(forName: folderName) == nil { + completion(.unsupported(forReason: .invalid)) + } else { + completion(.success(with: folderName)) + } return } - - guard let extensionContainers = ExtensionContainersFile.read() else { - completion(.unsupported(forReason: .communication)) - return - } - - guard let account = extensionContainers.findAccount(forName: accountName) else { - completion(.unsupported(forReason: .invalid)) - return - } - - if account.findFolder(forName: folderName) == nil { - completion(.unsupported(forReason: .invalid)) - } else { - completion(.success(with: folderName)) - } - return - } public func handle(intent: AddWebFeedIntent, completion: @escaping (AddWebFeedIntentResponse) -> Void) { - guard let url = intent.url, let extensionContainers = ExtensionContainersFile.read() else { - completion(AddWebFeedIntentResponse(code: .failure, userActivity: nil)) - return - } - - let account: ExtensionAccount? = { - if let accountName = intent.accountName { - return extensionContainers.findAccount(forName: accountName) - } else { - return extensionContainers.accounts.first + Task { @MainActor in + guard let url = intent.url, let extensionContainers = ExtensionContainersFile.read() else { + completion(AddWebFeedIntentResponse(code: .failure, userActivity: nil)) + return } - }() - - guard let validAccount = account else { - completion(AddWebFeedIntentResponse(code: .failure, userActivity: nil)) - return - } - - let container: ExtensionContainer? = { - if let folderName = intent.folderName { - return validAccount.findFolder(forName: folderName) - } else { - return validAccount + + let account: ExtensionAccount? = { + if let accountName = intent.accountName { + return extensionContainers.findAccount(forName: accountName) + } else { + return extensionContainers.accounts.first + } + }() + + guard let validAccount = account else { + completion(AddWebFeedIntentResponse(code: .failure, userActivity: nil)) + return } - }() - - guard let validContainer = container, let containerID = validContainer.containerID else { - completion(AddWebFeedIntentResponse(code: .failure, userActivity: nil)) - return + + let container: ExtensionContainer? = { + if let folderName = intent.folderName { + return validAccount.findFolder(forName: folderName) + } else { + return validAccount + } + }() + + guard let validContainer = container, let containerID = validContainer.containerID else { + completion(AddWebFeedIntentResponse(code: .failure, userActivity: nil)) + return + } + + let request = ExtensionFeedAddRequest(name: nil, feedURL: url, destinationContainerID: containerID) + ExtensionFeedAddRequestFile.save(request) + completion(AddWebFeedIntentResponse(code: .success, userActivity: nil)) } - - let request = ExtensionFeedAddRequest(name: nil, feedURL: url, destinationContainerID: containerID) - ExtensionFeedAddRequestFile.save(request) - completion(AddWebFeedIntentResponse(code: .success, userActivity: nil)) } } diff --git a/Mac/AppDelegate.swift b/Mac/AppDelegate.swift index 33c7041ac..f386d2dec 100644 --- a/Mac/AppDelegate.swift +++ b/Mac/AppDelegate.swift @@ -37,9 +37,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSUserInterfaceValidat private var shuttingDown = false { didSet { if shuttingDown { - refreshTimer?.shuttingDown = shuttingDown - refreshTimer?.invalidate() - ArticleStatusSyncTimer.shared.stop() + MainActor.assumeIsolated { + refreshTimer?.shuttingDown = shuttingDown + refreshTimer?.invalidate() + ArticleStatusSyncTimer.shared.stop() + } } } } @@ -55,8 +57,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSUserInterfaceValidat var unreadCount = 0 { didSet { if unreadCount != oldValue { - CoalescingQueue.standard.add(self, #selector(updateDockBadge)) - postUnreadCountDidChangeNotification() + MainActor.assumeIsolated { + CoalescingQueue.standard.add(self, #selector(updateDockBadge)) + postUnreadCountDidChangeNotification() + } } } } @@ -84,14 +88,15 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSUserInterfaceValidat private var keyboardShortcutsWindowController: WebViewWindowController? private var inspectorWindowController: InspectorWindowController? private var crashReportWindowController: CrashReportWindowController? // For testing only - private let appMovementMonitor = RSAppMovementMonitor() + private let appMovementMonitor: RSAppMovementMonitor private var softwareUpdater: SPUUpdater! private var crashReporter: PLCrashReporter! private var themeImportPath: String? - override init() { + @MainActor override init() { NSWindow.allowsAutomaticWindowTabbing = false + self.appMovementMonitor = RSAppMovementMonitor() super.init() appDelegate = self @@ -102,6 +107,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSUserInterfaceValidat AccountManager.shared.start() ArticleThemesManager.shared = ArticleThemesManager(folderPath: Platform.dataSubfolder(forApplication: nil, folderName: "Themes")!) + NotificationCenter.default.addObserver(self, selector: #selector(unreadCountDidChange(_:)), name: .UnreadCountDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(inspectableObjectsDidChange(_:)), name: .InspectableObjectsDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(importDownloadedTheme(_:)), name: .didEndDownloadingTheme, object: nil) @@ -304,25 +310,31 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSUserInterfaceValidat // MARK: Notifications @objc func unreadCountDidChange(_ note: Notification) { - if note.object is AccountManager { - unreadCount = AccountManager.shared.unreadCount + MainActor.assumeIsolated { + if note.object is AccountManager { + unreadCount = AccountManager.shared.unreadCount + } } } @objc func feedSettingDidChange(_ note: Notification) { - guard let feed = note.object as? Feed, let key = note.userInfo?[Feed.SettingUserInfoKey] as? String else { - return - } - if key == Feed.SettingKey.homePageURL || key == Feed.SettingKey.faviconURL { - _ = FaviconDownloader.shared.favicon(for: feed) + MainActor.assumeIsolated { + guard let feed = note.object as? Feed, let key = note.userInfo?[Feed.SettingUserInfoKey] as? String else { + return + } + if key == Feed.SettingKey.homePageURL || key == Feed.SettingKey.faviconURL { + _ = FaviconDownloader.shared.favicon(for: feed) + } } } @objc func inspectableObjectsDidChange(_ note: Notification) { - guard let inspectorWindowController = inspectorWindowController, inspectorWindowController.isOpen else { - return + MainActor.assumeIsolated { + guard let inspectorWindowController = inspectorWindowController, inspectorWindowController.isOpen else { + return + } + inspectorWindowController.objects = objectsForInspector() } - inspectorWindowController.objects = objectsForInspector() } @objc func userDefaultsDidChange(_ note: Notification) { @@ -340,7 +352,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSUserInterfaceValidat } @objc func didWakeNotification(_ note: Notification) { - fireOldTimers() + MainActor.assumeIsolated { + fireOldTimers() + } } @objc func importDownloadedTheme(_ note: Notification) { @@ -709,7 +723,7 @@ extension AppDelegate { } } -internal extension AppDelegate { +@MainActor internal extension AppDelegate { func fireOldTimers() { // It’s possible there’s a refresh timer set to go off in the past. @@ -942,27 +956,29 @@ private extension AppDelegate { } private func handleStatusNotification(userInfo: [AnyHashable: Any], statusKey: ArticleStatus.Key) { - guard let articlePathUserInfo = userInfo[UserInfoKey.articlePath] as? [AnyHashable : Any], - let accountID = articlePathUserInfo[ArticlePathKey.accountID] as? String, - let articleID = articlePathUserInfo[ArticlePathKey.articleID] as? String else { - assertionFailure("Expected valid articlePathUserInfo from userInfo \(userInfo)") - Self.logger.error("No valid articlePathUserInfo from userInfo \(userInfo) in status notification") - return - } + MainActor.assumeIsolated { + guard let articlePathUserInfo = userInfo[UserInfoKey.articlePath] as? [AnyHashable : Any], + let accountID = articlePathUserInfo[ArticlePathKey.accountID] as? String, + let articleID = articlePathUserInfo[ArticlePathKey.articleID] as? String else { + assertionFailure("Expected valid articlePathUserInfo from userInfo \(userInfo)") + Self.logger.error("No valid articlePathUserInfo from userInfo \(userInfo) in status notification") + return + } - guard let account = AccountManager.shared.existingAccount(with: accountID) else { - assertionFailure("Expected account with \(accountID)") - Self.logger.error("No account with accountID \(accountID) found from status notification") - return - } + guard let account = AccountManager.shared.existingAccount(with: accountID) else { + assertionFailure("Expected account with \(accountID)") + Self.logger.error("No account with accountID \(accountID) found from status notification") + return + } - guard let singleArticleSet = try? account.fetchArticles(.articleIDs([articleID])) else { - assertionFailure("Expected article with \(articleID)") - Self.logger.error("No article with articleID found \(articleID) from status notification") - return - } + guard let singleArticleSet = try? account.fetchArticles(.articleIDs([articleID])) else { + assertionFailure("Expected article with \(articleID)") + Self.logger.error("No article with articleID found \(articleID) from status notification") + return + } - assert(singleArticleSet.count == 1) - account.markArticles(singleArticleSet, statusKey: statusKey, flag: true) { _ in } + assert(singleArticleSet.count == 1) + account.markArticles(singleArticleSet, statusKey: statusKey, flag: true) { _ in } + } } } diff --git a/Mac/MainWindow/AddFeed/AddFeedController.swift b/Mac/MainWindow/AddFeed/AddFeedController.swift index 75bbd1153..90bfca758 100644 --- a/Mac/MainWindow/AddFeed/AddFeedController.swift +++ b/Mac/MainWindow/AddFeed/AddFeedController.swift @@ -22,7 +22,7 @@ import RSParser // Else, // display error sheet. -final class AddFeedController: AddFeedWindowControllerDelegate { +@MainActor final class AddFeedController: AddFeedWindowControllerDelegate { private let hostWindow: NSWindow private var addFeedWindowController: AddFeedWindowController? diff --git a/Mac/MainWindow/AddFeed/AddFeedWindowController.swift b/Mac/MainWindow/AddFeed/AddFeedWindowController.swift index c98c8b3fa..d69a2103e 100644 --- a/Mac/MainWindow/AddFeed/AddFeedWindowController.swift +++ b/Mac/MainWindow/AddFeed/AddFeedWindowController.swift @@ -12,7 +12,7 @@ import RSTree import Articles import Account -protocol AddFeedWindowControllerDelegate: AnyObject { +@MainActor protocol AddFeedWindowControllerDelegate: AnyObject { // userEnteredURL will have already been validated and normalized. func addFeedWindowController(_: AddFeedWindowController, userEnteredURL: URL, userEnteredTitle: String?, container: Container) func addFeedWindowControllerUserDidCancel(_: AddFeedWindowController) diff --git a/Mac/MainWindow/AddFeed/FolderTreeMenu.swift b/Mac/MainWindow/AddFeed/FolderTreeMenu.swift index 18d287d6d..f9eafb955 100644 --- a/Mac/MainWindow/AddFeed/FolderTreeMenu.swift +++ b/Mac/MainWindow/AddFeed/FolderTreeMenu.swift @@ -11,7 +11,7 @@ import RSCore import RSTree import Account -final class FolderTreeMenu { +@MainActor final class FolderTreeMenu { @MainActor static func createFolderPopupMenu(with rootNode: Node, restrictToSpecialAccounts: Bool = false) -> NSMenu { diff --git a/Mac/MainWindow/NNW3/NNW3ImportController.swift b/Mac/MainWindow/NNW3/NNW3ImportController.swift index bdeb7e466..3e51eabb0 100644 --- a/Mac/MainWindow/NNW3/NNW3ImportController.swift +++ b/Mac/MainWindow/NNW3/NNW3ImportController.swift @@ -13,7 +13,7 @@ struct NNW3ImportController { /// Import NNW3 subscriptions if they exist. /// Return true if Subscriptions.plist was found and subscriptions were imported. - static func importSubscriptionsIfFileExists(account: Account) -> Bool { + @MainActor static func importSubscriptionsIfFileExists(account: Account) -> Bool { guard let subscriptionsPlistURL = defaultFileURL else { return false } @@ -25,7 +25,7 @@ struct NNW3ImportController { } /// Run an NSOpenPanel and import subscriptions (if the user chooses to). - static func askUserToImportNNW3Subscriptions(window: NSWindow) { + @MainActor static func askUserToImportNNW3Subscriptions(window: NSWindow) { chooseFile(window) } } @@ -42,7 +42,7 @@ private extension NNW3ImportController { } /// Import Subscriptions.plist file. Convert to OPML and then import into specified Account. - static func importSubscriptionsPlist(_ subscriptionsPlistURL: URL, into account: Account) { + @MainActor static func importSubscriptionsPlist(_ subscriptionsPlistURL: URL, into account: Account) { guard let opmlURL = convertToOPMLFile(subscriptionsPlistURL: subscriptionsPlistURL) else { return } @@ -58,7 +58,7 @@ private extension NNW3ImportController { } /// Run the NSOpenPanel. On success, import subscriptions to the selected account. - static func chooseFile(_ window: NSWindow) { + @MainActor static func chooseFile(_ window: NSWindow) { let accessoryViewController = NNW3OpenPanelAccessoryViewController() let panel = NSOpenPanel() @@ -89,7 +89,7 @@ private extension NNW3ImportController { } /// Convert Subscriptions.plist on disk to a temporary OPML file. - static func convertToOPMLFile(subscriptionsPlistURL url: URL) -> URL? { + @MainActor static func convertToOPMLFile(subscriptionsPlistURL url: URL) -> URL? { guard let document = NNW3Document(subscriptionsPlistURL: url) else { return nil } diff --git a/Mac/MainWindow/SharingServicePickerDelegate.swift b/Mac/MainWindow/SharingServicePickerDelegate.swift index 9a1d42e98..f34349e5d 100644 --- a/Mac/MainWindow/SharingServicePickerDelegate.swift +++ b/Mac/MainWindow/SharingServicePickerDelegate.swift @@ -9,7 +9,7 @@ import AppKit import RSCore -@objc final class SharingServicePickerDelegate: NSObject, NSSharingServicePickerDelegate { +@objc final class SharingServicePickerDelegate: NSObject, @MainActor NSSharingServicePickerDelegate { private let sharingServiceDelegate: SharingServiceDelegate @@ -17,7 +17,7 @@ import RSCore sharingServiceDelegate = SharingServiceDelegate(window) } - func sharingServicePicker(_ sharingServicePicker: NSSharingServicePicker, sharingServicesForItems items: [Any], proposedSharingServices proposedServices: [NSSharingService]) -> [NSSharingService] { + @MainActor func sharingServicePicker(_ sharingServicePicker: NSSharingServicePicker, sharingServicesForItems items: [Any], proposedSharingServices proposedServices: [NSSharingService]) -> [NSSharingService] { let filteredServices = proposedServices.filter { $0.menuItemTitle != "NetNewsWire" } return filteredServices + SharingServicePickerDelegate.customSharingServices(for: items) } @@ -26,7 +26,7 @@ import RSCore return sharingServiceDelegate } - static func customSharingServices(for items: [Any]) -> [NSSharingService] { + @MainActor static func customSharingServices(for items: [Any]) -> [NSSharingService] { let customServices: [SendToCommand] = [SendToMarsEditCommand(), SendToMicroBlogCommand()] return customServices.compactMap { (sendToCommand) -> NSSharingService? in diff --git a/Mac/MainWindow/Sidebar/PasteboardFeed.swift b/Mac/MainWindow/Sidebar/PasteboardFeed.swift index ad83e3734..6bc246808 100644 --- a/Mac/MainWindow/Sidebar/PasteboardFeed.swift +++ b/Mac/MainWindow/Sidebar/PasteboardFeed.swift @@ -160,7 +160,7 @@ extension Feed: @retroactive PasteboardWriterOwner { } } -@objc final class FeedPasteboardWriter: NSObject, NSPasteboardWriting { +@objc final class FeedPasteboardWriter: NSObject, @MainActor NSPasteboardWriting { private let feed: Feed static let feedUTI = "com.ranchero.feed" @@ -181,7 +181,7 @@ extension Feed: @retroactive PasteboardWriterOwner { return [FeedPasteboardWriter.feedUTIType, .URL, .string, FeedPasteboardWriter.feedUTIInternalType] } - func pasteboardPropertyList(forType type: NSPasteboard.PasteboardType) -> Any? { + @MainActor func pasteboardPropertyList(forType type: NSPasteboard.PasteboardType) -> Any? { let plist: Any? @@ -204,15 +204,15 @@ extension Feed: @retroactive PasteboardWriterOwner { private extension FeedPasteboardWriter { - var pasteboardFeed: PasteboardFeed { + @MainActor var pasteboardFeed: PasteboardFeed { return PasteboardFeed(url: feed.url, feedID: feed.feedID, homePageURL: feed.homePageURL, name: feed.name, editedName: feed.editedName, accountID: feed.account?.accountID, accountType: feed.account?.type) } - var exportDictionary: PasteboardFeedDictionary { + @MainActor var exportDictionary: PasteboardFeedDictionary { return pasteboardFeed.exportDictionary() } - var internalDictionary: PasteboardFeedDictionary { + @MainActor var internalDictionary: PasteboardFeedDictionary { var dictionary = pasteboardFeed.internalDictionary() if dictionary[PasteboardFeed.Key.containerName] == nil, case let .folder(accountID, folderName) = containerID { diff --git a/Mac/MainWindow/Sidebar/PasteboardFolder.swift b/Mac/MainWindow/Sidebar/PasteboardFolder.swift index 6fc3ec614..7ef217bab 100644 --- a/Mac/MainWindow/Sidebar/PasteboardFolder.swift +++ b/Mac/MainWindow/Sidebar/PasteboardFolder.swift @@ -12,7 +12,7 @@ import RSCore typealias PasteboardFolderDictionary = [String: String] -struct PasteboardFolder: Hashable { +@MainActor struct PasteboardFolder: Hashable { private struct Key { static let name = "name" @@ -91,7 +91,7 @@ extension Folder: @retroactive PasteboardWriterOwner { } } -@objc final class FolderPasteboardWriter: NSObject, NSPasteboardWriting { +@MainActor @objc final class FolderPasteboardWriter: NSObject, @MainActor NSPasteboardWriting { private let folder: Folder static let folderUTIInternal = "com.ranchero.NetNewsWire-Evergreen.internal.folder" @@ -126,8 +126,8 @@ extension Folder: @retroactive PasteboardWriterOwner { } } -private extension FolderPasteboardWriter { - var pasteboardFolder: PasteboardFolder { +@MainActor private extension FolderPasteboardWriter { +var pasteboardFolder: PasteboardFolder { return PasteboardFolder(name: folder.name ?? "", folderID: String(folder.folderID), accountID: folder.account?.accountID) } diff --git a/Mac/MainWindow/Timeline/ArticlePasteboardWriter.swift b/Mac/MainWindow/Timeline/ArticlePasteboardWriter.swift index 52aa89b2c..336ab74f6 100644 --- a/Mac/MainWindow/Timeline/ArticlePasteboardWriter.swift +++ b/Mac/MainWindow/Timeline/ArticlePasteboardWriter.swift @@ -11,12 +11,12 @@ import Articles import RSCore extension Article: @retroactive PasteboardWriterOwner { - public var pasteboardWriter: NSPasteboardWriting { + @MainActor public var pasteboardWriter: NSPasteboardWriting { return ArticlePasteboardWriter(article: self) } } -@objc final class ArticlePasteboardWriter: NSObject, NSPasteboardWriting { +@MainActor @objc final class ArticlePasteboardWriter: NSObject, @MainActor NSPasteboardWriting { let article: Article static let articleUTI = "com.ranchero.article" diff --git a/Mac/MainWindow/Timeline/Cell/TimelineCellData.swift b/Mac/MainWindow/Timeline/Cell/TimelineCellData.swift index de446b329..837f1bffe 100644 --- a/Mac/MainWindow/Timeline/Cell/TimelineCellData.swift +++ b/Mac/MainWindow/Timeline/Cell/TimelineCellData.swift @@ -9,7 +9,7 @@ import AppKit import Articles -struct TimelineCellData { +@MainActor struct TimelineCellData { private static let noText = NSLocalizedString("(No Text)", comment: "No Text") diff --git a/Mac/MainWindow/Timeline/Cell/TimelineCellLayout.swift b/Mac/MainWindow/Timeline/Cell/TimelineCellLayout.swift index d46f565f7..e925eda03 100644 --- a/Mac/MainWindow/Timeline/Cell/TimelineCellLayout.swift +++ b/Mac/MainWindow/Timeline/Cell/TimelineCellLayout.swift @@ -9,7 +9,7 @@ import AppKit import RSCore -struct TimelineCellLayout { +@MainActor struct TimelineCellLayout { let width: CGFloat let height: CGFloat @@ -91,7 +91,7 @@ struct TimelineCellLayout { // MARK: - Calculate Rects -private extension TimelineCellLayout { +@MainActor private extension TimelineCellLayout { static func rectForTextBox(_ appearance: TimelineCellAppearance, _ cellData: TimelineCellData, _ showIcon: Bool, _ width: CGFloat) -> NSRect { diff --git a/Mac/Scriptability/Account+Scriptability.swift b/Mac/Scriptability/Account+Scriptability.swift index 485a53208..b85a70438 100644 --- a/Mac/Scriptability/Account+Scriptability.swift +++ b/Mac/Scriptability/Account+Scriptability.swift @@ -12,7 +12,7 @@ import Articles import RSCore @objc(ScriptableAccount) -final class ScriptableAccount: NSObject, UniqueIdScriptingObject, ScriptingObjectContainer { +@MainActor final class ScriptableAccount: NSObject, UniqueIdScriptingObject, ScriptingObjectContainer { let account:Account init (_ account:Account) { diff --git a/Mac/Scriptability/AppDelegate+Scriptability.swift b/Mac/Scriptability/AppDelegate+Scriptability.swift index 29906aba6..269dc4a76 100644 --- a/Mac/Scriptability/AppDelegate+Scriptability.swift +++ b/Mac/Scriptability/AppDelegate+Scriptability.swift @@ -92,7 +92,7 @@ extension AppDelegate : AppDelegateAppleEvents { } final class NetNewsWireCreateElementCommand : NSCreateCommand { - override func performDefaultImplementation() -> Any? { + @MainActor override func performDefaultImplementation() -> Any? { let classDescription = self.createClassDescription if (classDescription.className == "feed") { return ScriptableFeed.handleCreateElement(command:self) @@ -119,7 +119,7 @@ final class NetNewsWireDeleteCommand : NSDeleteCommand { Here the code unravels the case of objectToDelete being a list or a single object, ultimately calling container.deleteElement(element) for each element to delete */ - func delete(objectToDelete:Any, from container:ScriptingObjectContainer) { + @MainActor func delete(objectToDelete:Any, from container:ScriptingObjectContainer) { if let objectList = objectToDelete as? [Any] { for nthObject in objectList { self.delete(objectToDelete:nthObject, from:container) @@ -138,7 +138,7 @@ final class NetNewsWireDeleteCommand : NSDeleteCommand { After resolving, we call delete(objectToDelete:, from container:) with the container and the resolved objects */ - func delete(specifier:NSScriptObjectSpecifier, from container:Any) { + @MainActor func delete(specifier:NSScriptObjectSpecifier, from container:Any) { if let containerList = container as? [Any] { for nthObject in containerList { self.delete(specifier:specifier, from:nthObject) @@ -156,7 +156,7 @@ final class NetNewsWireDeleteCommand : NSDeleteCommand { the item to be deleted. keySpecifier is the thing in that container(s) to be deleted The first step is to resolve the receiversSpecifier and then call delete(specifier:, from container:) */ - override func performDefaultImplementation() -> Any? { + @MainActor override func performDefaultImplementation() -> Any? { if let receiversSpecifier = self.receiversSpecifier { if let receiverObjects = receiversSpecifier.objectsByEvaluatingSpecifier { self.delete(specifier:self.keySpecifier, from:receiverObjects) diff --git a/Mac/Scriptability/NSScriptCommand+NetNewsWire.swift b/Mac/Scriptability/NSScriptCommand+NetNewsWire.swift index c9b11bf5e..bf989de7a 100644 --- a/Mac/Scriptability/NSScriptCommand+NetNewsWire.swift +++ b/Mac/Scriptability/NSScriptCommand+NetNewsWire.swift @@ -9,7 +9,7 @@ import Foundation import Account -extension NSScriptCommand { +@MainActor extension NSScriptCommand { func property(forKey key:String) -> Any? { if let evaluatedArguments = self.evaluatedArguments { if let props = evaluatedArguments["KeyDictionary"] as? [String: Any] { diff --git a/Mac/Scriptability/ScriptingObject.swift b/Mac/Scriptability/ScriptingObject.swift index 64187b6dc..93e1b3a22 100644 --- a/Mac/Scriptability/ScriptingObject.swift +++ b/Mac/Scriptability/ScriptingObject.swift @@ -8,15 +8,15 @@ import Foundation -protocol ScriptingObject { +@MainActor protocol ScriptingObject { var objectSpecifier: NSScriptObjectSpecifier? { get } var scriptingKey: String { get } } -protocol NamedScriptingObject: ScriptingObject { +@MainActor protocol NamedScriptingObject: ScriptingObject { var name:String { get } } -protocol UniqueIdScriptingObject: ScriptingObject { - var scriptingUniqueId:Any { get } +@MainActor protocol UniqueIdScriptingObject: ScriptingObject { + var scriptingUniqueId:Any { get } } diff --git a/Mac/Scriptability/ScriptingObjectContainer.swift b/Mac/Scriptability/ScriptingObjectContainer.swift index d9bc2bf34..23891b56d 100644 --- a/Mac/Scriptability/ScriptingObjectContainer.swift +++ b/Mac/Scriptability/ScriptingObjectContainer.swift @@ -9,12 +9,12 @@ import AppKit import Account -protocol ScriptingObjectContainer: ScriptingObject { - var scriptingClassDescription:NSScriptClassDescription { get } - func deleteElement(_ element:ScriptingObject) +@MainActor protocol ScriptingObjectContainer: ScriptingObject { + var scriptingClassDescription:NSScriptClassDescription { get } + func deleteElement(_ element:ScriptingObject) } -extension ScriptingObjectContainer { +@MainActor extension ScriptingObjectContainer { func makeFormNameScriptObjectSpecifier(forObject object:NamedScriptingObject) -> NSScriptObjectSpecifier? { let containerClassDescription = self.scriptingClassDescription diff --git a/Modules/Account/Sources/Account/Account.swift b/Modules/Account/Sources/Account/Account.swift index 32f1566e0..a67c8116f 100644 --- a/Modules/Account/Sources/Account/Account.swift +++ b/Modules/Account/Sources/Account/Account.swift @@ -96,7 +96,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, return name } - public var name: String? { + @MainActor public var name: String? { get { return metadata.name } @@ -112,7 +112,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, } public let defaultName: String - public var isActive: Bool { + @MainActor public var isActive: Bool { get { return metadata.isActive } @@ -129,7 +129,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, public var topLevelFeeds = Set() public var folders: Set? = Set() - public var externalID: String? { + @MainActor public var externalID: String? { get { return metadata.externalID } @@ -138,7 +138,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, } } - public var sortedFolders: [Folder]? { + @MainActor public var sortedFolders: [Folder]? { if let folders = folders { return Array(folders).sorted(by: { $0.nameForDisplay.caseInsensitiveCompare($1.nameForDisplay) == .orderedAscending }) } @@ -165,7 +165,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, return Set(flattenedFeeds().map({ $0.url })) } - var username: String? { + @MainActor var username: String? { get { return metadata.username } @@ -176,7 +176,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, } } - public var endpointURL: URL? { + @MainActor public var endpointURL: URL? { get { return metadata.endpointURL } @@ -202,7 +202,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, private lazy var opmlFile = OPMLFile(filename: (dataFolder as NSString).appendingPathComponent("Subscriptions.opml"), account: self) private lazy var metadataFile = AccountMetadataFile(filename: (dataFolder as NSString).appendingPathComponent("Settings.plist"), account: self) - var metadata = AccountMetadata() { + @MainActor var metadata = AccountMetadata() { didSet { delegate.accountMetadata = metadata } @@ -301,9 +301,11 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, NotificationCenter.default.addObserver(self, selector: #selector(displayNameDidChange(_:)), name: .DisplayNameDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(childrenDidChange(_:)), name: .ChildrenDidChange, object: nil) - metadataFile.load() - feedMetadataFile.load() - opmlFile.load() + MainActor.assumeIsolated { + metadataFile.load() + feedMetadataFile.load() + opmlFile.load() + } DispatchQueue.main.async { self.database.cleanupDatabaseAtStartup(subscribedToFeedIDs: self.flattenedFeeds().feedIDs()) @@ -317,7 +319,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, // MARK: - API - public func storeCredentials(_ credentials: Credentials) throws { + @MainActor public func storeCredentials(_ credentials: Credentials) throws { username = credentials.username guard let server = delegate.server else { assertionFailure() @@ -327,14 +329,14 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, delegate.credentials = credentials } - public func retrieveCredentials(type: CredentialsType) throws -> Credentials? { + @MainActor public func retrieveCredentials(type: CredentialsType) throws -> Credentials? { guard let username = self.username, let server = delegate.server else { return nil } return try CredentialsManager.retrieveCredentials(type: type, server: server, username: username) } - public func removeCredentials(type: CredentialsType) throws { + @MainActor public func removeCredentials(type: CredentialsType) throws { guard let username = self.username, let server = delegate.server else { return } @@ -453,16 +455,18 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, } public func save() { - metadataFile.save() - feedMetadataFile.save() - opmlFile.save() + MainActor.assumeIsolated { + metadataFile.save() + feedMetadataFile.save() + opmlFile.save() + } } @MainActor public func prepareForDeletion() { delegate.accountWillBeDeleted(self) } - func addOPMLItems(_ items: [RSOPMLItem]) { + @MainActor func addOPMLItems(_ items: [RSOPMLItem]) { for item in items { if let feedSpecifier = item.feedSpecifier { addFeedToTreeAtTopLevel(newFeed(with: feedSpecifier)) @@ -479,7 +483,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, } } - func loadOPMLItems(_ items: [RSOPMLItem]) { + @MainActor func loadOPMLItems(_ items: [RSOPMLItem]) { addOPMLItems(OPMLNormalizer.normalize(items)) } @@ -494,7 +498,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, } } - func existingContainer(withExternalID externalID: String) -> Container? { + @MainActor func existingContainer(withExternalID externalID: String) -> Container? { guard self.externalID != externalID else { return self } @@ -515,7 +519,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, } @discardableResult - func ensureFolder(with name: String) -> Folder? { + @MainActor func ensureFolder(with name: String) -> Folder? { // TODO: support subfolders, maybe, some day if name.isEmpty { @@ -534,7 +538,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, return folder } - public func ensureFolder(withFolderNames folderNames: [String]) -> Folder? { + @MainActor public func ensureFolder(withFolderNames folderNames: [String]) -> Folder? { // TODO: support subfolders, maybe, some day. // Since we don’t, just take the last name and make sure there’s a Folder. @@ -544,7 +548,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, return ensureFolder(with: folderName) } - public func existingFolder(withDisplayName displayName: String) -> Folder? { + @MainActor public func existingFolder(withDisplayName displayName: String) -> Folder? { return folders?.first(where: { $0.nameForDisplay == displayName }) } @@ -552,7 +556,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, return folders?.first(where: { $0.externalID == externalID }) } - func newFeed(with opmlFeedSpecifier: RSOPMLFeedSpecifier) -> Feed { + @MainActor func newFeed(with opmlFeedSpecifier: RSOPMLFeedSpecifier) -> Feed { let feedURL = opmlFeedSpecifier.feedURL let metadata = feedMetadata(feedURL: feedURL, feedID: feedURL) let feed = Feed(account: self, url: opmlFeedSpecifier.feedURL, metadata: metadata) @@ -590,7 +594,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, } } - func createFeed(with name: String?, url: String, feedID: String, homePageURL: String?) -> Feed { + @MainActor func createFeed(with name: String?, url: String, feedID: String, homePageURL: String?) -> Feed { let metadata = feedMetadata(feedURL: url, feedID: feedID) let feed = Feed(account: self, url: url, metadata: metadata) feed.name = name @@ -680,7 +684,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, fetchUnreadCounts(for: feeds, completion: completion) } - public func fetchArticles(_ fetchType: FetchType) throws -> Set
{ + @MainActor public func fetchArticles(_ fetchType: FetchType) throws -> Set
{ switch fetchType { case .starred(let limit): return try fetchStarredArticles(limit: limit) @@ -705,7 +709,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, } } - public func fetchArticles(_ fetchType: FetchType) async throws -> Set
{ + @MainActor public func fetchArticles(_ fetchType: FetchType) async throws -> Set
{ try await withCheckedThrowingContinuation { continuation in fetchArticlesAsync(fetchType) { result in continuation.resume(with: result) @@ -713,7 +717,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, } } - public func fetchArticlesAsync(_ fetchType: FetchType, _ completion: @escaping ArticleSetResultBlock) { + @MainActor public func fetchArticlesAsync(_ fetchType: FetchType, _ completion: @escaping ArticleSetResultBlock) { switch fetchType { case .starred(let limit): fetchStarredArticlesAsync(limit: limit, completion) @@ -817,7 +821,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, } } - func update(_ feed: Feed, with parsedFeed: ParsedFeed, _ completion: @escaping UpdateArticlesCompletionBlock) { + @MainActor func update(_ feed: Feed, with parsedFeed: ParsedFeed, _ completion: @escaping UpdateArticlesCompletionBlock) { // Used only by an On My Mac or iCloud account. precondition(Thread.isMainThread) precondition(type == .onMyMac || type == .cloudKit) @@ -840,7 +844,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, } } - func update(_ feedID: String, with parsedItems: Set, deleteOlder: Bool = true, completion: @escaping UpdateArticlesCompletionBlock) { + @MainActor func update(_ feedID: String, with parsedItems: Set, deleteOlder: Bool = true, completion: @escaping UpdateArticlesCompletionBlock) { // Used only by an On My Mac or iCloud account. precondition(Thread.isMainThread) precondition(type == .onMyMac || type == .cloudKit) @@ -868,7 +872,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, } } - private func update(feedIDsAndItems: [String: Set], defaultRead: Bool, completion: @escaping DatabaseCompletionBlock) { + @MainActor private func update(feedIDsAndItems: [String: Set], defaultRead: Bool, completion: @escaping DatabaseCompletionBlock) { // Used only by syncing systems. precondition(Thread.isMainThread) precondition(type != .onMyMac && type != .cloudKit) @@ -889,7 +893,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, } @discardableResult - func update(_ articles: Set
, statusKey: ArticleStatus.Key, flag: Bool) async throws -> Set
{ + @MainActor func update(_ articles: Set
, statusKey: ArticleStatus.Key, flag: Bool) async throws -> Set
{ try await withCheckedThrowingContinuation { continuation in update(articles, statusKey: statusKey, flag: flag) { result in continuation.resume(with: result) @@ -897,7 +901,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, } } - func update(_ articles: Set
, statusKey: ArticleStatus.Key, flag: Bool, completion: @escaping ArticleSetResultBlock) { + @MainActor func update(_ articles: Set
, statusKey: ArticleStatus.Key, flag: Bool, completion: @escaping ArticleSetResultBlock) { // Returns set of Articles whose statuses did change. guard !articles.isEmpty else { completion(.success(Set
())) @@ -1176,7 +1180,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, // MARK: - AccountMetadataDelegate extension Account: AccountMetadataDelegate { - func valueDidChange(_ accountMetadata: AccountMetadata, key: AccountMetadata.CodingKeys) { + @MainActor func valueDidChange(_ accountMetadata: AccountMetadata, key: AccountMetadata.CodingKeys) { metadataFile.markAsDirty() } } @@ -1185,7 +1189,7 @@ extension Account: AccountMetadataDelegate { extension Account: FeedMetadataDelegate { - func valueDidChange(_ feedMetadata: FeedMetadata, key: FeedMetadata.CodingKeys) { + @MainActor func valueDidChange(_ feedMetadata: FeedMetadata, key: FeedMetadata.CodingKeys) { feedMetadataFile.markAsDirty() guard let feed = existingFeed(withFeedID: feedMetadata.feedID) else { return @@ -1238,13 +1242,13 @@ private extension Account { fetchUnreadArticlesAsync(forContainer: folder, limit: nil, completion) } - func fetchArticles(feed: Feed) throws -> Set
{ + @MainActor func fetchArticles(feed: Feed) throws -> Set
{ let articles = try database.fetchArticles(feed.feedID) validateUnreadCount(feed, articles) return articles } - func fetchArticlesAsync(feed: Feed, _ completion: @escaping ArticleSetResultBlock) { + @MainActor func fetchArticlesAsync(feed: Feed, _ completion: @escaping ArticleSetResultBlock) { database.fetchArticlesAsync(feed.feedID) { [weak self] articleSetResult in switch articleSetResult { case .success(let articles): @@ -1280,7 +1284,7 @@ private extension Account { return database.fetchArticlesAsync(articleIDs: articleIDs, completion) } - func fetchUnreadArticles(feed: Feed) throws -> Set
{ + @MainActor func fetchUnreadArticles(feed: Feed) throws -> Set
{ let articles = try database.fetchUnreadArticles(Set([feed.feedID]), nil) validateUnreadCount(feed, articles) return articles @@ -1354,7 +1358,7 @@ private extension Account { } } - func validateUnreadCount(_ feed: Feed, _ articles: Set
) { + @MainActor func validateUnreadCount(_ feed: Feed, _ articles: Set
) { // articles must contain all the unread articles for the feed. // The unread number should match the feed’s unread count. @@ -1422,7 +1426,7 @@ private extension Account { unreadCount = updatedUnreadCount } - func noteStatusesForArticlesDidChange(_ articles: Set
) { + @MainActor func noteStatusesForArticlesDidChange(_ articles: Set
) { let feeds = Set(articles.compactMap { $0.feed }) let statuses = Set(articles.map { $0.status }) let articleIDs = Set(articles.map { $0.articleID }) @@ -1516,7 +1520,7 @@ private extension Account { } } - func sendNotificationAbout(_ articleChanges: ArticleChanges) { + @MainActor func sendNotificationAbout(_ articleChanges: ArticleChanges) { var feeds = Set() if let newArticles = articleChanges.newArticles { diff --git a/Modules/Account/Sources/Account/AccountDelegate.swift b/Modules/Account/Sources/Account/AccountDelegate.swift index bb07d212f..b1de207d9 100644 --- a/Modules/Account/Sources/Account/AccountDelegate.swift +++ b/Modules/Account/Sources/Account/AccountDelegate.swift @@ -11,7 +11,7 @@ import Articles import RSWeb import Secrets -protocol AccountDelegate { +@MainActor protocol AccountDelegate { var behaviors: AccountBehaviors { get } diff --git a/Modules/Account/Sources/Account/AccountError.swift b/Modules/Account/Sources/Account/AccountError.swift index 92792a6b5..a9a556540 100644 --- a/Modules/Account/Sources/Account/AccountError.swift +++ b/Modules/Account/Sources/Account/AccountError.swift @@ -18,18 +18,10 @@ public enum AccountError: LocalizedError { case invalidResponse case urlNotFound case unknown - case wrappedError(error: Error, account: Account) - - public var account: Account? { - if case .wrappedError(_, let account) = self { - return account - } else { - return nil - } - } + case wrappedError(error: Error, accountID: String, accountName: String) public var isCredentialsError: Bool { - if case .wrappedError(let error, _) = self { + if case .wrappedError(let error, _, _) = self { if case TransportError.httpError(let status) = error { return isCredentialsError(status: status) } @@ -37,6 +29,17 @@ public enum AccountError: LocalizedError { return false } + @MainActor static func wrapped(_ error: Error, _ account: Account) -> AccountError { + AccountError.wrappedError(error: error, accountID: account.accountID, accountName: account.nameForDisplay) + } + + @MainActor public static func account(from error: AccountError?) -> Account? { + if case let .wrappedError(_, accountID, _) = error { + return AccountManager.shared.existingAccount(with: accountID) + } + return nil + } + public var errorDescription: String? { switch self { case .createErrorNotFound: @@ -53,17 +56,17 @@ public enum AccountError: LocalizedError { return NSLocalizedString("The URL request resulted in a not found error.", comment: "URL not found") case .unknown: return NSLocalizedString("Unknown error", comment: "Unknown error") - case .wrappedError(let error, let account): + case .wrappedError(let error, _, let accountName): switch error { case TransportError.httpError(let status): if isCredentialsError(status: status) { let localizedText = NSLocalizedString("Your “%@” credentials are invalid or expired.", comment: "Invalid or expired") - return NSString.localizedStringWithFormat(localizedText as NSString, account.nameForDisplay) as String + return NSString.localizedStringWithFormat(localizedText as NSString, accountName) as String } else { - return unknownError(error, account) + return unknownError(error, accountName) } default: - return unknownError(error, account) + return unknownError(error, accountName) } } } @@ -74,7 +77,7 @@ public enum AccountError: LocalizedError { return nil case .createErrorAlreadySubscribed: return nil - case .wrappedError(let error, _): + case .wrappedError(let error, _, _): switch error { case TransportError.httpError(let status): if isCredentialsError(status: status) { @@ -89,16 +92,15 @@ public enum AccountError: LocalizedError { return NSLocalizedString("Please try again later.", comment: "Try later") } } - } // MARK: Private private extension AccountError { - func unknownError(_ error: Error, _ account: Account) -> String { + func unknownError(_ error: Error, _ accountName: String) -> String { let localizedText = NSLocalizedString("An error occurred while processing the “%@” account: %@", comment: "Unknown error") - return NSString.localizedStringWithFormat(localizedText as NSString, account.nameForDisplay, error.localizedDescription) as String + return NSString.localizedStringWithFormat(localizedText as NSString, accountName, error.localizedDescription) as String } func isCredentialsError(status: Int) -> Bool { diff --git a/Modules/Account/Sources/Account/AccountManager.swift b/Modules/Account/Sources/Account/AccountManager.swift index c3e6ed0f1..a09851c0d 100644 --- a/Modules/Account/Sources/Account/AccountManager.swift +++ b/Modules/Account/Sources/Account/AccountManager.swift @@ -15,8 +15,8 @@ import RSDatabase // Main thread only. -public final class AccountManager: UnreadCountProvider { - public static var shared = AccountManager() +@MainActor public final class AccountManager: UnreadCountProvider { + @MainActor public static var shared = AccountManager() public static let netNewsWireNewsURL = "https://netnewswire.blog/feed.xml" private static let jsonNetNewsWireNewsURL = "https://netnewswire.blog/feed.json" @@ -30,7 +30,7 @@ public final class AccountManager: UnreadCountProvider { private let defaultAccountIdentifier = "OnMyMac" public var isSuspended = false - public var areUnreadCountsInitialized: Bool { + @MainActor public var areUnreadCountsInitialized: Bool { for account in activeAccounts { if !account.areUnreadCountsInitialized { return false @@ -51,7 +51,7 @@ public final class AccountManager: UnreadCountProvider { Array(accountsDictionary.values) } - public var sortedAccounts: [Account] { + @MainActor public var sortedAccounts: [Account] { sortByName(accounts) } @@ -65,16 +65,16 @@ public final class AccountManager: UnreadCountProvider { } - public var activeAccounts: [Account] { + @MainActor public var activeAccounts: [Account] { assert(Thread.isMainThread) return Array(accountsDictionary.values.filter { $0.isActive }) } - public var sortedActiveAccounts: [Account] { + @MainActor public var sortedActiveAccounts: [Account] { sortByName(activeAccounts) } - public var lastArticleFetchEndTime: Date? { + @MainActor public var lastArticleFetchEndTime: Date? { var lastArticleFetchEndTime: Date? = nil for account in activeAccounts { if let accountLastArticleFetchEndTime = account.metadata.lastArticleFetchEndTime { @@ -86,11 +86,11 @@ public final class AccountManager: UnreadCountProvider { return lastArticleFetchEndTime } - public func existingActiveAccount(forDisplayName displayName: String) -> Account? { + @MainActor public func existingActiveAccount(forDisplayName displayName: String) -> Account? { AccountManager.shared.activeAccounts.first(where: { $0.nameForDisplay == displayName }) } - public var refreshInProgress: Bool { + @MainActor public var refreshInProgress: Bool { for account in activeAccounts { if account.refreshInProgress { return true @@ -103,7 +103,7 @@ public final class AccountManager: UnreadCountProvider { private var isActive = false - public init() { + @MainActor public init() { self.accountsFolder = AppConfig.dataSubfolder(named: "Accounts").path // The local "On My Mac" account must always exist, even if it's empty. @@ -192,7 +192,7 @@ public final class AccountManager: UnreadCountProvider { NotificationCenter.default.post(name: .UserDidDeleteAccount, object: self, userInfo: userInfo) } - public func duplicateServiceAccount(type: AccountType, username: String?) -> Bool { + @MainActor public func duplicateServiceAccount(type: AccountType, username: String?) -> Bool { guard type != .onMyMac else { return false } @@ -208,7 +208,7 @@ public final class AccountManager: UnreadCountProvider { return accountsDictionary[accountID] } - public func existingContainer(with containerID: ContainerIdentifier) -> Container? { + @MainActor public func existingContainer(with containerID: ContainerIdentifier) -> Container? { switch containerID { case .account(let accountID): return existingAccount(with: accountID) @@ -220,7 +220,7 @@ public final class AccountManager: UnreadCountProvider { return nil } - public func existingFeed(with sidebarItemID: SidebarItemIdentifier) -> SidebarItem? { + @MainActor public func existingFeed(with sidebarItemID: SidebarItemIdentifier) -> SidebarItem? { switch sidebarItemID { case .folder(let accountID, let folderName): if let account = existingAccount(with: accountID) { @@ -259,7 +259,7 @@ public final class AccountManager: UnreadCountProvider { } } - public func receiveRemoteNotification(userInfo: [AnyHashable : Any]) async { + @MainActor public func receiveRemoteNotification(userInfo: [AnyHashable : Any]) async { await withTaskGroup(of: Void.self) { group in for account in activeAccounts { group.addTask { @MainActor in @@ -304,7 +304,7 @@ public final class AccountManager: UnreadCountProvider { } } - public func syncArticleStatusAll(completion: (() -> Void)? = nil) { + @MainActor public func syncArticleStatusAll(completion: (() -> Void)? = nil) { let group = DispatchGroup() for account in activeAccounts { @@ -323,7 +323,7 @@ public final class AccountManager: UnreadCountProvider { } } - public func anyAccountHasAtLeastOneFeed() -> Bool { + @MainActor public func anyAccountHasAtLeastOneFeed() -> Bool { for account in activeAccounts { if account.hasAtLeastOneFeed() { return true @@ -333,11 +333,11 @@ public final class AccountManager: UnreadCountProvider { return false } - public func anyAccountHasNetNewsWireNewsSubscription() -> Bool { + @MainActor public func anyAccountHasNetNewsWireNewsSubscription() -> Bool { anyAccountHasFeedWithURL(Self.netNewsWireNewsURL) || anyAccountHasFeedWithURL(Self.jsonNetNewsWireNewsURL) } - public func anyAccountHasFeedWithURL(_ urlString: String) -> Bool { + @MainActor public func anyAccountHasFeedWithURL(_ urlString: String) -> Bool { for account in activeAccounts { if let _ = account.existingFeed(withURL: urlString) { return true @@ -350,7 +350,7 @@ public final class AccountManager: UnreadCountProvider { // These fetch articles from active accounts and return a merged Set
. - public func fetchArticles(_ fetchType: FetchType) throws -> Set
{ + @MainActor public func fetchArticles(_ fetchType: FetchType) throws -> Set
{ precondition(Thread.isMainThread) var articles = Set
() @@ -360,7 +360,7 @@ public final class AccountManager: UnreadCountProvider { return articles } - public func fetchArticlesAsync(_ fetchType: FetchType, _ completion: @escaping ArticleSetResultBlock) { + @MainActor public func fetchArticlesAsync(_ fetchType: FetchType, _ completion: @escaping ArticleSetResultBlock) { precondition(Thread.isMainThread) guard activeAccounts.count > 0 else { @@ -401,7 +401,7 @@ public final class AccountManager: UnreadCountProvider { // MARK: - Fetching Article Counts - public func fetchCountForStarredArticles() throws -> Int { + @MainActor public func fetchCountForStarredArticles() throws -> Int { precondition(Thread.isMainThread) var count = 0 for account in activeAccounts { @@ -421,7 +421,7 @@ public final class AccountManager: UnreadCountProvider { // MARK: - Notifications - @objc func unreadCountDidInitialize(_ notification: Notification) { + @MainActor @objc func unreadCountDidInitialize(_ notification: Notification) { guard notification.object is Account else { return } @@ -430,14 +430,14 @@ public final class AccountManager: UnreadCountProvider { } } - @objc func unreadCountDidChange(_ notification: Notification) { + @MainActor @objc func unreadCountDidChange(_ notification: Notification) { guard notification.object is Account else { return } updateUnreadCount() } - @objc func accountStateDidChange(_ notification: Notification) { + @MainActor @objc func accountStateDidChange(_ notification: Notification) { updateUnreadCount() } } @@ -446,7 +446,7 @@ public final class AccountManager: UnreadCountProvider { private extension AccountManager { - func updateUnreadCount() { + @MainActor func updateUnreadCount() { unreadCount = calculateUnreadCount(activeAccounts) } @@ -462,7 +462,7 @@ private extension AccountManager { return nil } - func readAccountsFromDisk() { + @MainActor func readAccountsFromDisk() { var filenames: [String]? do { @@ -489,11 +489,11 @@ private extension AccountManager { } } - func duplicateServiceAccount(_ account: Account) -> Bool { + @MainActor func duplicateServiceAccount(_ account: Account) -> Bool { duplicateServiceAccount(type: account.type, username: account.username) } - func sortByName(_ accounts: [Account]) -> [Account] { + @MainActor func sortByName(_ accounts: [Account]) -> [Account] { // LocalAccount is first. return accounts.sorted { (account1, account2) -> Bool in diff --git a/Modules/Account/Sources/Account/AccountMetadata.swift b/Modules/Account/Sources/Account/AccountMetadata.swift index 55a82a788..0ae558a65 100644 --- a/Modules/Account/Sources/Account/AccountMetadata.swift +++ b/Modules/Account/Sources/Account/AccountMetadata.swift @@ -10,10 +10,10 @@ import Foundation import RSWeb protocol AccountMetadataDelegate: AnyObject { - func valueDidChange(_ accountMetadata: AccountMetadata, key: AccountMetadata.CodingKeys) + @MainActor func valueDidChange(_ accountMetadata: AccountMetadata, key: AccountMetadata.CodingKeys) } -final class AccountMetadata: Codable { +@MainActor final class AccountMetadata: @MainActor Codable { enum CodingKeys: String, CodingKey { case name @@ -27,7 +27,7 @@ final class AccountMetadata: Codable { case performedApril2020RetentionPolicyChange } - var name: String? { + @MainActor var name: String? { didSet { if name != oldValue { valueDidChange(.name) @@ -35,7 +35,7 @@ final class AccountMetadata: Codable { } } - var isActive: Bool = true { + @MainActor var isActive: Bool = true { didSet { if isActive != oldValue { valueDidChange(.isActive) @@ -43,7 +43,7 @@ final class AccountMetadata: Codable { } } - var username: String? { + @MainActor var username: String? { didSet { if username != oldValue { valueDidChange(.username) @@ -51,7 +51,7 @@ final class AccountMetadata: Codable { } } - var conditionalGetInfo = [String: HTTPConditionalGetInfo]() { + @MainActor var conditionalGetInfo = [String: HTTPConditionalGetInfo]() { didSet { if conditionalGetInfo != oldValue { valueDidChange(.conditionalGetInfo) @@ -59,7 +59,7 @@ final class AccountMetadata: Codable { } } - var lastArticleFetchStartTime: Date? { + @MainActor var lastArticleFetchStartTime: Date? { didSet { if lastArticleFetchStartTime != oldValue { valueDidChange(.lastArticleFetchStartTime) @@ -67,7 +67,7 @@ final class AccountMetadata: Codable { } } - var lastArticleFetchEndTime: Date? { + @MainActor var lastArticleFetchEndTime: Date? { didSet { if lastArticleFetchEndTime != oldValue { valueDidChange(.lastArticleFetchEndTime) @@ -75,7 +75,7 @@ final class AccountMetadata: Codable { } } - var endpointURL: URL? { + @MainActor var endpointURL: URL? { didSet { if endpointURL != oldValue { valueDidChange(.endpointURL) @@ -85,7 +85,7 @@ final class AccountMetadata: Codable { var performedApril2020RetentionPolicyChange: Bool? // No longer used. - var externalID: String? { + @MainActor var externalID: String? { didSet { if externalID != oldValue { valueDidChange(.externalID) @@ -93,9 +93,9 @@ final class AccountMetadata: Codable { } } - weak var delegate: AccountMetadataDelegate? + @MainActor weak var delegate: AccountMetadataDelegate? - func valueDidChange(_ key: CodingKeys) { + @MainActor func valueDidChange(_ key: CodingKeys) { delegate?.valueDidChange(self, key: key) } } diff --git a/Modules/Account/Sources/Account/AccountMetadataFile.swift b/Modules/Account/Sources/Account/AccountMetadataFile.swift index f0b5ff3cb..fd7e0aaad 100644 --- a/Modules/Account/Sources/Account/AccountMetadataFile.swift +++ b/Modules/Account/Sources/Account/AccountMetadataFile.swift @@ -14,7 +14,7 @@ final class AccountMetadataFile { private let fileURL: URL private let account: Account - private var isDirty = false { + @MainActor private var isDirty = false { didSet { queueSaveToDiskIfNeeded() } @@ -27,11 +27,11 @@ final class AccountMetadataFile { self.account = account } - func markAsDirty() { + @MainActor func markAsDirty() { isDirty = true } - func load() { + @MainActor func load() { if let fileData = try? Data(contentsOf: fileURL) { let decoder = PropertyListDecoder() account.metadata = (try? decoder.decode(AccountMetadata.self, from: fileData)) ?? AccountMetadata() @@ -39,7 +39,7 @@ final class AccountMetadataFile { account.metadata.delegate = account } - func save() { + @MainActor func save() { guard !account.isDeleted else { return } let encoder = PropertyListEncoder() @@ -57,11 +57,11 @@ final class AccountMetadataFile { private extension AccountMetadataFile { - func queueSaveToDiskIfNeeded() { + @MainActor func queueSaveToDiskIfNeeded() { saveQueue.add(self, #selector(saveToDiskIfNeeded)) } - @objc func saveToDiskIfNeeded() { + @MainActor @objc func saveToDiskIfNeeded() { if isDirty { isDirty = false save() diff --git a/Modules/Account/Sources/Account/ArticleFetcher.swift b/Modules/Account/Sources/Account/ArticleFetcher.swift index 43bf58d68..ed600aebb 100644 --- a/Modules/Account/Sources/Account/ArticleFetcher.swift +++ b/Modules/Account/Sources/Account/ArticleFetcher.swift @@ -12,13 +12,13 @@ import ArticlesDatabase public protocol ArticleFetcher { - func fetchArticles() throws -> Set
- func fetchArticlesAsync(_ completion: @escaping ArticleSetResultBlock) - func fetchUnreadArticles() throws -> Set
- func fetchUnreadArticlesAsync(_ completion: @escaping ArticleSetResultBlock) + @MainActor func fetchArticles() throws -> Set
+ @MainActor func fetchArticlesAsync(_ completion: @escaping ArticleSetResultBlock) + @MainActor func fetchUnreadArticles() throws -> Set
+ @MainActor func fetchUnreadArticlesAsync(_ completion: @escaping ArticleSetResultBlock) } -extension Feed: ArticleFetcher { +@MainActor extension Feed: ArticleFetcher { public func fetchArticles() throws -> Set
{ return try account?.fetchArticles(.feed(self)) ?? Set
() diff --git a/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift b/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift index 35908e5e7..2bf8a8727 100644 --- a/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift +++ b/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift @@ -29,8 +29,8 @@ enum CloudKitAccountDelegateError: LocalizedError { } } -final class CloudKitAccountDelegate: AccountDelegate { - private static let logger = cloudKitLogger +@MainActor final class CloudKitAccountDelegate: AccountDelegate { + nonisolated private static let logger = cloudKitLogger private let syncDatabase: SyncDatabase @@ -309,12 +309,12 @@ final class CloudKitAccountDelegate: AccountDelegate { folder.externalID = externalID account.addFolderToTree(folder) - + await withTaskGroup(of: Void.self) { group in for feed in feedsToRestore { folder.topLevelFeeds.remove(feed) - - group.addTask { + + group.addTask { @MainActor in do { try await self.restoreFeed(for: account, feed: feed, container: folder) self.syncProgress.completeTask() @@ -462,7 +462,7 @@ private extension CloudKitAccountDelegate { } } - func createRSSFeed(for account: Account, url: URL, editedName: String?, container: Container, validateFeed: Bool) async throws -> Feed { + @MainActor func createRSSFeed(for account: Account, url: URL, editedName: String?, container: Container, validateFeed: Bool) async throws -> Feed { syncProgress.addToNumberOfTasksAndRemaining(5) do { @@ -501,7 +501,7 @@ private extension CloudKitAccountDelegate { } } - func createAndSyncFeed(account: Account, feedURL: URL, bestFeedSpecifier: FeedSpecifier, editedName: String?, container: Container) async throws -> Feed { + @MainActor func createAndSyncFeed(account: Account, feedURL: URL, bestFeedSpecifier: FeedSpecifier, editedName: String?, container: Container) async throws -> Feed { let feed = account.createFeed(with: nil, url: feedURL.absoluteString, feedID: feedURL.absoluteString, homePageURL: nil) feed.editedName = editedName container.addFeedToTreeAtTopLevel(feed) @@ -522,7 +522,7 @@ private extension CloudKitAccountDelegate { } } - func downloadAndParseFeed(feedURL: URL, feed: Feed) async throws -> ParsedFeed { + @MainActor func downloadAndParseFeed(feedURL: URL, feed: Feed) async throws -> ParsedFeed { let (parsedFeed, response) = try await InitialFeedDownloader.download(feedURL) syncProgress.completeTask() feed.lastCheckDate = Date() @@ -540,7 +540,7 @@ private extension CloudKitAccountDelegate { return parsedFeed } - func updateAndCreateFeedInCloud(account: Account, feed: Feed, parsedFeed: ParsedFeed, bestFeedSpecifier: FeedSpecifier, editedName: String?, container: Container) async throws { + @MainActor func updateAndCreateFeedInCloud(account: Account, feed: Feed, parsedFeed: ParsedFeed, bestFeedSpecifier: FeedSpecifier, editedName: String?, container: Container) async throws { let _ = try await account.update(feed, with: parsedFeed) let externalID = try await accountZone.createFeed(url: bestFeedSpecifier.urlString, @@ -553,7 +553,7 @@ private extension CloudKitAccountDelegate { sendNewArticlesToTheCloud(account, feed) } - func addDeadFeed(account: Account, url: URL, editedName: String?, container: Container) async throws -> Feed { + @MainActor func addDeadFeed(account: Account, url: URL, editedName: String?, container: Container) async throws -> Feed { let feed = account.createFeed(with: editedName, url: url.absoluteString, feedID: url.absoluteString, homePageURL: nil) container.addFeedToTreeAtTopLevel(feed) @@ -589,7 +589,7 @@ private extension CloudKitAccountDelegate { } } - func processAccountError(_ account: Account, _ error: Error) { + @MainActor func processAccountError(_ account: Account, _ error: Error) { if case CloudKitZoneError.userDeletedZone = error { account.removeFeedsFromTreeAtTopLevel(account.topLevelFeeds) for folder in account.folders ?? Set() { @@ -646,7 +646,7 @@ private extension CloudKitAccountDelegate { } } - func removeFeedFromCloud(for account: Account, with feed: Feed, from container: Container) async throws { + @MainActor func removeFeedFromCloud(for account: Account, with feed: Feed, from container: Container) async throws { syncProgress.addToNumberOfTasksAndRemaining(2) do { diff --git a/Modules/Account/Sources/Account/CloudKit/CloudKitAccountZone.swift b/Modules/Account/Sources/Account/CloudKit/CloudKitAccountZone.swift index db43e6f23..faed33a92 100644 --- a/Modules/Account/Sources/Account/CloudKit/CloudKitAccountZone.swift +++ b/Modules/Account/Sources/Account/CloudKit/CloudKitAccountZone.swift @@ -89,7 +89,7 @@ final class CloudKitAccountZone: CloudKitZone { } /// Persist a web feed record to iCloud and return the external key - func createFeed(url: String, name: String?, editedName: String?, homePageURL: String?, container: Container) async throws -> String { + @MainActor func createFeed(url: String, name: String?, editedName: String?, homePageURL: String?, container: Container) async throws -> String { let recordID = CKRecord.ID(recordName: url.md5String, zoneID: zoneID) let record = CKRecord(recordType: CloudKitFeed.recordType, recordID: recordID) record[CloudKitFeed.Fields.url] = url @@ -111,7 +111,7 @@ final class CloudKitAccountZone: CloudKitZone { } /// Rename the given web feed - func renameFeed(_ feed: Feed, editedName: String?) async throws { + @MainActor func renameFeed(_ feed: Feed, editedName: String?) async throws { guard let externalID = feed.externalID else { throw CloudKitZoneError.corruptAccount } @@ -124,7 +124,7 @@ final class CloudKitAccountZone: CloudKitZone { } /// Removes a web feed from a container and optionally deletes it, returning true if deleted - func removeFeed(_ feed: Feed, from: Container) async throws -> Bool { + @MainActor func removeFeed(_ feed: Feed, from: Container) async throws -> Bool { guard let fromContainerExternalID = from.externalID else { throw CloudKitZoneError.corruptAccount } @@ -155,7 +155,7 @@ final class CloudKitAccountZone: CloudKitZone { } } - func moveFeed(_ feed: Feed, from: Container, to: Container) async throws { + @MainActor func moveFeed(_ feed: Feed, from: Container, to: Container) async throws { guard let fromContainerExternalID = from.externalID, let toContainerExternalID = to.externalID else { throw CloudKitZoneError.corruptAccount } @@ -170,7 +170,7 @@ final class CloudKitAccountZone: CloudKitZone { } } - func addFeed(_ feed: Feed, to: Container) async throws { + @MainActor func addFeed(_ feed: Feed, to: Container) async throws { guard let toContainerExternalID = to.externalID else { throw CloudKitZoneError.corruptAccount } @@ -184,7 +184,7 @@ final class CloudKitAccountZone: CloudKitZone { } } - func findFeedExternalIDs(for folder: Folder) async throws -> [String] { + @MainActor func findFeedExternalIDs(for folder: Folder) async throws -> [String] { guard let folderExternalID = folder.externalID else { throw CloudKitAccountZoneError.unknown } @@ -267,7 +267,7 @@ final class CloudKitAccountZone: CloudKitZone { try await createContainer(name: name, isAccount: false) } - func renameFolder(_ folder: Folder, to name: String) async throws { + @MainActor func renameFolder(_ folder: Folder, to name: String) async throws { guard let externalID = folder.externalID else { throw CloudKitZoneError.corruptAccount } diff --git a/Modules/Account/Sources/Account/CloudKit/CloudKitAccountZoneDelegate.swift b/Modules/Account/Sources/Account/CloudKit/CloudKitAccountZoneDelegate.swift index 70cd090d0..244bc1f8b 100644 --- a/Modules/Account/Sources/Account/CloudKit/CloudKitAccountZoneDelegate.swift +++ b/Modules/Account/Sources/Account/CloudKit/CloudKitAccountZoneDelegate.swift @@ -28,7 +28,7 @@ final class CloudKitAcountZoneDelegate: CloudKitZoneDelegate { self.articlesZone = articlesZone } - func cloudKitDidModify(changed: [CKRecord], deleted: [CloudKitRecordKey]) async throws { + @MainActor func cloudKitDidModify(changed: [CKRecord], deleted: [CloudKitRecordKey]) async throws { for deletedRecordKey in deleted { switch deletedRecordKey.recordType { case CloudKitAccountZone.CloudKitFeed.recordType: @@ -52,7 +52,7 @@ final class CloudKitAcountZoneDelegate: CloudKitZoneDelegate { } } - func addOrUpdateFeed(_ record: CKRecord) { + @MainActor func addOrUpdateFeed(_ record: CKRecord) { guard let account = account, let urlString = record[CloudKitAccountZone.CloudKitFeed.Fields.url] as? String, let containerExternalIDs = record[CloudKitAccountZone.CloudKitFeed.Fields.containerExternalIDs] as? [String], @@ -77,7 +77,7 @@ final class CloudKitAcountZoneDelegate: CloudKitZoneDelegate { } } - func removeFeed(_ externalID: String) { + @MainActor func removeFeed(_ externalID: String) { if let feed = account?.existingFeed(withExternalID: externalID), let containers = account?.existingContainers(withFeed: feed) { for container in containers { feed.dropConditionalGetInfo() @@ -86,7 +86,7 @@ final class CloudKitAcountZoneDelegate: CloudKitZoneDelegate { } } - func addOrUpdateContainer(_ record: CKRecord) { + @MainActor func addOrUpdateContainer(_ record: CKRecord) { guard let account = account, let name = record[CloudKitAccountZone.CloudKitContainer.Fields.name] as? String, let isAccount = record[CloudKitAccountZone.CloudKitContainer.Fields.isAccount] as? String, @@ -125,7 +125,7 @@ final class CloudKitAcountZoneDelegate: CloudKitZoneDelegate { } } - func removeContainer(_ externalID: String) { + @MainActor func removeContainer(_ externalID: String) { if let folder = account?.existingFolder(withExternalID: externalID) { account?.removeFolderFromTree(folder) } @@ -135,7 +135,7 @@ final class CloudKitAcountZoneDelegate: CloudKitZoneDelegate { private extension CloudKitAcountZoneDelegate { - func updateFeed(_ feed: Feed, name: String?, editedName: String?, homePageURL: String?, containerExternalIDs: [String]) { + @MainActor func updateFeed(_ feed: Feed, name: String?, editedName: String?, homePageURL: String?, containerExternalIDs: [String]) { guard let account = account else { return } feed.name = name @@ -163,7 +163,7 @@ private extension CloudKitAcountZoneDelegate { } } - func createFeedIfNecessary(url: URL, name: String?, editedName: String?, homePageURL: String?, feedExternalID: String, container: Container) { + @MainActor func createFeedIfNecessary(url: URL, name: String?, editedName: String?, homePageURL: String?, feedExternalID: String, container: Container) { guard let account = account else { return } if account.existingFeed(withExternalID: feedExternalID) != nil { diff --git a/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZone.swift b/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZone.swift index b129629e4..0dc49510c 100644 --- a/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZone.swift +++ b/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZone.swift @@ -76,7 +76,7 @@ final class CloudKitArticlesZone: CloudKitZone { } } - func saveNewArticles(_ articles: Set
) async throws { + @MainActor func saveNewArticles(_ articles: Set
) async throws { guard !articles.isEmpty else { return } @@ -101,7 +101,7 @@ final class CloudKitArticlesZone: CloudKitZone { try await delete(ckQuery: ckQuery) } - func modifyArticles(_ statusUpdates: [CloudKitArticleStatusUpdate]) async throws { + @MainActor func modifyArticles(_ statusUpdates: [CloudKitArticleStatusUpdate]) async throws { guard !statusUpdates.isEmpty else { return } @@ -161,7 +161,7 @@ private extension CloudKitArticlesZone { return "a|\(id)" } - func makeStatusRecord(_ article: Article) -> CKRecord { + @MainActor func makeStatusRecord(_ article: Article) -> CKRecord { let recordID = CKRecord.ID(recordName: statusID(article.articleID), zoneID: zoneID) let record = CKRecord(recordType: CloudKitArticleStatus.recordType, recordID: recordID) if let feedExternalID = article.feed?.externalID { @@ -172,7 +172,7 @@ private extension CloudKitArticlesZone { return record } - func makeStatusRecord(_ statusUpdate: CloudKitArticleStatusUpdate) -> CKRecord { + @MainActor func makeStatusRecord(_ statusUpdate: CloudKitArticleStatusUpdate) -> CKRecord { let recordID = CKRecord.ID(recordName: statusID(statusUpdate.articleID), zoneID: zoneID) let record = CKRecord(recordType: CloudKitArticleStatus.recordType, recordID: recordID) @@ -186,7 +186,7 @@ private extension CloudKitArticlesZone { return record } - func makeArticleRecord(_ article: Article) -> CKRecord { + @MainActor func makeArticleRecord(_ article: Article) -> CKRecord { let recordID = CKRecord.ID(recordName: articleID(article.articleID), zoneID: zoneID) let record = CKRecord(recordType: CloudKitArticle.recordType, recordID: recordID) diff --git a/Modules/Account/Sources/Account/CloudKit/CloudKitSendStatusOperation.swift b/Modules/Account/Sources/Account/CloudKit/CloudKitSendStatusOperation.swift index bd7c9d72c..a2f4e7101 100644 --- a/Modules/Account/Sources/Account/CloudKit/CloudKitSendStatusOperation.swift +++ b/Modules/Account/Sources/Account/CloudKit/CloudKitSendStatusOperation.swift @@ -86,7 +86,7 @@ private extension CloudKitSendStatusOperation { } } - func processStatuses(_ syncStatuses: [SyncStatus], completion: @escaping (Bool) -> Void) { + @MainActor func processStatuses(_ syncStatuses: [SyncStatus], completion: @escaping (Bool) -> Void) { guard let account, let articlesZone else { completion(true) return @@ -149,7 +149,7 @@ private extension CloudKitSendStatusOperation { } } - func processAccountError(_ account: Account, _ error: Error) { + @MainActor func processAccountError(_ account: Account, _ error: Error) { if case CloudKitZoneError.userDeletedZone = error { account.removeFeedsFromTreeAtTopLevel(account.topLevelFeeds) for folder in account.folders ?? Set() { diff --git a/Modules/Account/Sources/Account/CombinedRefreshProgress.swift b/Modules/Account/Sources/Account/CombinedRefreshProgress.swift index 5982f8cab..fef31b68b 100644 --- a/Modules/Account/Sources/Account/CombinedRefreshProgress.swift +++ b/Modules/Account/Sources/Account/CombinedRefreshProgress.swift @@ -42,7 +42,7 @@ public final class CombinedRefreshProgress { isStarted = false } - @objc func refreshProgressDidChange(_ notification: Notification) { + @MainActor @objc func refreshProgressDidChange(_ notification: Notification) { guard isStarted else { return diff --git a/Modules/Account/Sources/Account/Container.swift b/Modules/Account/Sources/Account/Container.swift index cc48865f8..3db716b70 100644 --- a/Modules/Account/Sources/Account/Container.swift +++ b/Modules/Account/Sources/Account/Container.swift @@ -16,7 +16,7 @@ extension Notification.Name { public static let ChildrenDidChange = Notification.Name("ChildrenDidChange") } -public protocol Container: AnyObject, ContainerIdentifiable { +@MainActor public protocol Container: AnyObject, ContainerIdentifiable { var account: Account? { get } var topLevelFeeds: Set { get set } @@ -26,8 +26,8 @@ public protocol Container: AnyObject, ContainerIdentifiable { func hasAtLeastOneFeed() -> Bool func objectIsChild(_ object: AnyObject) -> Bool - func hasChildFolder(with: String) -> Bool - func childFolder(with: String) -> Folder? + @MainActor func hasChildFolder(with: String) -> Bool + @MainActor func childFolder(with: String) -> Folder? func removeFeedFromTreeAtTopLevel(_ feed: Feed) func addFeedToTreeAtTopLevel(_ feed: Feed) @@ -40,23 +40,23 @@ public protocol Container: AnyObject, ContainerIdentifiable { func existingFeed(withFeedID: String) -> Feed? func existingFeed(withURL url: String) -> Feed? func existingFeed(withExternalID externalID: String) -> Feed? - func existingFolder(with name: String) -> Folder? + @MainActor func existingFolder(with name: String) -> Folder? func existingFolder(withID: Int) -> Folder? func postChildrenDidChangeNotification() } -public extension Container { +@MainActor public extension Container { func hasAtLeastOneFeed() -> Bool { return topLevelFeeds.count > 0 } - func hasChildFolder(with name: String) -> Bool { + @MainActor func hasChildFolder(with name: String) -> Bool { return childFolder(with: name) != nil } - func childFolder(with name: String) -> Folder? { + @MainActor func childFolder(with name: String) -> Folder? { guard let folders = folders else { return nil } @@ -128,7 +128,7 @@ public extension Container { return nil } - func existingFolder(with name: String) -> Folder? { + @MainActor func existingFolder(with name: String) -> Folder? { guard let folders = folders else { return nil } diff --git a/Modules/Account/Sources/Account/ContainerPath.swift b/Modules/Account/Sources/Account/ContainerPath.swift index ea48838f2..8d6e4aaf1 100644 --- a/Modules/Account/Sources/Account/ContainerPath.swift +++ b/Modules/Account/Sources/Account/ContainerPath.swift @@ -21,7 +21,7 @@ public struct ContainerPath { // folders should be from top-level down, as in ["Cats", "Tabbies"] - public init(account: Account, folders: [Folder]) { + @MainActor public init(account: Account, folders: [Folder]) { self.account = account self.names = folders.map { $0.nameForDisplay } self.isTopLevel = folders.isEmpty @@ -29,7 +29,7 @@ public struct ContainerPath { self.folderID = folders.last?.folderID } - public func resolveContainer() -> Container? { + @MainActor public func resolveContainer() -> Container? { // The only time it should fail is if the account no longer exists. // Otherwise the worst-case scenario is that it will create Folders if needed. diff --git a/Modules/Account/Sources/Account/DataExtensions.swift b/Modules/Account/Sources/Account/DataExtensions.swift index 3c7dbbd5e..0ad224a21 100644 --- a/Modules/Account/Sources/Account/DataExtensions.swift +++ b/Modules/Account/Sources/Account/DataExtensions.swift @@ -33,7 +33,7 @@ public extension Feed { extension Feed { - func takeSettings(from parsedFeed: ParsedFeed) { + @MainActor func takeSettings(from parsedFeed: ParsedFeed) { iconURL = parsedFeed.iconURL faviconURL = parsedFeed.faviconURL homePageURL = parsedFeed.homePageURL @@ -49,11 +49,11 @@ extension Feed { public extension Article { - var account: Account? { + @MainActor var account: Account? { return AccountManager.shared.existingAccount(with: accountID) } - var feed: Feed? { + @MainActor var feed: Feed? { return account?.existingFeed(withFeedID: feedID) } } diff --git a/Modules/Account/Sources/Account/Feed.swift b/Modules/Account/Sources/Account/Feed.swift index f2d753028..49a7fda7a 100644 --- a/Modules/Account/Sources/Account/Feed.swift +++ b/Modules/Account/Sources/Account/Feed.swift @@ -77,7 +77,7 @@ public final class Feed: SidebarItem, Renamable, Hashable { } } - public var name: String? { + @MainActor public var name: String? { didSet { if name != oldValue { postDisplayNameDidChangeNotification() @@ -102,7 +102,7 @@ public final class Feed: SidebarItem, Renamable, Hashable { } } - public var editedName: String? { + @MainActor public var editedName: String? { // Don’t let editedName == "" get { guard let s = metadata.editedName, !s.isEmpty else { @@ -331,7 +331,7 @@ extension Feed: OPMLRepresentable { } } -extension Set where Element == Feed { +@MainActor extension Set where Element == Feed { func feedIDs() -> Set { return Set(map { $0.feedID }) diff --git a/Modules/Account/Sources/Account/FeedMetadata.swift b/Modules/Account/Sources/Account/FeedMetadata.swift index c0df8f5c3..76c3bd383 100644 --- a/Modules/Account/Sources/Account/FeedMetadata.swift +++ b/Modules/Account/Sources/Account/FeedMetadata.swift @@ -11,7 +11,7 @@ import RSWeb import Articles protocol FeedMetadataDelegate: AnyObject { - func valueDidChange(_ feedMetadata: FeedMetadata, key: FeedMetadata.CodingKeys) + @MainActor func valueDidChange(_ feedMetadata: FeedMetadata, key: FeedMetadata.CodingKeys) } final class FeedMetadata: Codable { @@ -169,6 +169,14 @@ final class FeedMetadata: Codable { } func valueDidChange(_ key: CodingKeys) { - delegate?.valueDidChange(self, key: key) + if Thread.isMainThread { + MainActor.assumeIsolated { + delegate?.valueDidChange(self, key: key) + } + } else { + Task { @MainActor in + delegate?.valueDidChange(self, key: key) + } + } } } diff --git a/Modules/Account/Sources/Account/FeedMetadataFile.swift b/Modules/Account/Sources/Account/FeedMetadataFile.swift index d45499889..ea3601de2 100644 --- a/Modules/Account/Sources/Account/FeedMetadataFile.swift +++ b/Modules/Account/Sources/Account/FeedMetadataFile.swift @@ -10,11 +10,11 @@ import Foundation import os.log import RSCore -final class FeedMetadataFile { +@MainActor final class FeedMetadataFile { private let fileURL: URL private let account: Account - private var isDirty = false { + @MainActor private var isDirty = false { didSet { queueSaveToDiskIfNeeded() } @@ -28,7 +28,7 @@ final class FeedMetadataFile { self.account = account } - func markAsDirty() { + @MainActor func markAsDirty() { isDirty = true } @@ -59,11 +59,11 @@ final class FeedMetadataFile { private extension FeedMetadataFile { - func queueSaveToDiskIfNeeded() { + @MainActor func queueSaveToDiskIfNeeded() { saveQueue.add(self, #selector(saveToDiskIfNeeded)) } - @objc func saveToDiskIfNeeded() { + @MainActor @objc func saveToDiskIfNeeded() { if isDirty { isDirty = false save() diff --git a/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift b/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift index 630df4bca..aa74ea222 100644 --- a/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift +++ b/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift @@ -79,8 +79,7 @@ final class FeedbinAccountDelegate: AccountDelegate { try await refreshArticlesAndStatuses(account) } catch { refreshProgress.reset() - let wrappedError = AccountError.wrappedError(error: error, account: account) - throw wrappedError + throw AccountError.wrapped(error, account) } } @@ -163,8 +162,7 @@ final class FeedbinAccountDelegate: AccountDelegate { } } catch { Self.logger.info("Feedbin: OPML import failed: \(error.localizedDescription)") - let wrappedError = AccountError.wrappedError(error: error, account: account) - throw wrappedError + throw AccountError.wrapped(error, account) } } @@ -191,8 +189,7 @@ final class FeedbinAccountDelegate: AccountDelegate { renameFolderRelationship(for: account, fromName: folder.name ?? "", toName: name) folder.name = name } catch { - let wrappedError = AccountError.wrappedError(error: error, account: account) - throw wrappedError + throw AccountError.wrapped(error, account) } } @@ -252,8 +249,7 @@ final class FeedbinAccountDelegate: AccountDelegate { throw AccountError.createErrorNotFound } } catch { - let wrappedError = AccountError.wrappedError(error: error, account: account) - throw wrappedError + throw AccountError.wrapped(error, account) } } @@ -272,8 +268,7 @@ final class FeedbinAccountDelegate: AccountDelegate { try await caller.renameSubscription(subscriptionID: subscriptionID, newName: name) feed.editedName = name } catch { - let wrappedError = AccountError.wrappedError(error: error, account: account) - throw wrappedError + throw AccountError.wrapped(error, account) } } @@ -307,8 +302,7 @@ final class FeedbinAccountDelegate: AccountDelegate { account.removeFeedFromTreeAtTopLevel(feed) folder.addFeedToTreeAtTopLevel(feed) } catch { - let wrappedError = AccountError.wrappedError(error: error, account: account) - throw wrappedError + throw AccountError.wrapped(error, account) } } else if let account = container as? Account { account.addFeedIfNotInAnyFolder(feed) @@ -448,7 +442,7 @@ private extension FeedbinAccountDelegate { // This function can be deleted if Feedbin updates their taggings.json service to // show a change when a tag is renamed. - func forceExpireFolderFeedRelationship(_ account: Account, _ tags: [FeedbinTag]?) { + @MainActor func forceExpireFolderFeedRelationship(_ account: Account, _ tags: [FeedbinTag]?) { guard let tags = tags else { return } let folderNames: [String] = { @@ -470,7 +464,7 @@ private extension FeedbinAccountDelegate { } - func syncFolders(_ account: Account, _ tags: [FeedbinTag]?) { + @MainActor func syncFolders(_ account: Account, _ tags: [FeedbinTag]?) { guard let tags = tags else { return } assert(Thread.isMainThread) @@ -508,7 +502,7 @@ private extension FeedbinAccountDelegate { } - func syncFeeds(_ account: Account, _ subscriptions: [FeedbinSubscription]?) { + @MainActor func syncFeeds(_ account: Account, _ subscriptions: [FeedbinSubscription]?) { guard let subscriptions = subscriptions else { return } assert(Thread.isMainThread) @@ -562,7 +556,7 @@ private extension FeedbinAccountDelegate { } } - func syncFeedFolderRelationship(_ account: Account, _ taggings: [FeedbinTagging]?) { + @MainActor func syncFeedFolderRelationship(_ account: Account, _ taggings: [FeedbinTagging]?) { guard let taggings = taggings else { return } assert(Thread.isMainThread) @@ -624,7 +618,7 @@ private extension FeedbinAccountDelegate { } } - func nameToFolderDictionary(with folders: Set?) -> [String: Folder] { + @MainActor func nameToFolderDictionary(with folders: Set?) -> [String: Folder] { guard let folders = folders else { return [String: Folder]() } @@ -664,7 +658,7 @@ private extension FeedbinAccountDelegate { } } - func renameFolderRelationship(for account: Account, fromName: String, toName: String) { + @MainActor func renameFolderRelationship(for account: Account, fromName: String, toName: String) { for feed in account.flattenedFeeds() { if var folderRelationship = feed.folderRelationship { let relationship = folderRelationship[fromName] @@ -675,14 +669,14 @@ private extension FeedbinAccountDelegate { } } - func clearFolderRelationship(for feed: Feed, withFolderName folderName: String) { + @MainActor func clearFolderRelationship(for feed: Feed, withFolderName folderName: String) { if var folderRelationship = feed.folderRelationship { folderRelationship[folderName] = nil feed.folderRelationship = folderRelationship } } - func saveFolderRelationship(for feed: Feed, withFolderName folderName: String, id: String) { + @MainActor func saveFolderRelationship(for feed: Feed, withFolderName folderName: String, id: String) { if var folderRelationship = feed.folderRelationship { folderRelationship[folderName] = id feed.folderRelationship = folderRelationship @@ -891,8 +885,7 @@ private extension FeedbinAccountDelegate { folder.removeFeedFromTreeAtTopLevel(feed) account.addFeedIfNotInAnyFolder(feed) } catch { - let wrappedError = AccountError.wrappedError(error: error, account: account) - throw wrappedError + throw AccountError.wrapped(error, account) } } else { if let account = container as? Account { diff --git a/Modules/Account/Sources/Account/Feedly/FeedlyAPICaller.swift b/Modules/Account/Sources/Account/Feedly/FeedlyAPICaller.swift index 410af98a6..74a12ce5b 100644 --- a/Modules/Account/Sources/Account/Feedly/FeedlyAPICaller.swift +++ b/Modules/Account/Sources/Account/Feedly/FeedlyAPICaller.swift @@ -297,7 +297,7 @@ final class FeedlyAPICaller { } guard let encodedId = encodeForURLPath(id) else { return DispatchQueue.main.async { - completion(.failure(FeedlyAccountDelegateError.unexpectedResourceId(id))) + completion(.failure(FeedlyAccountDelegateError.unexpectedResourceID(id))) } } var components = baseUrlComponents @@ -342,7 +342,7 @@ final class FeedlyAPICaller { guard let encodedCollectionId = encodeForURLPath(collectionId) else { return DispatchQueue.main.async { - completion(.failure(FeedlyAccountDelegateError.unexpectedResourceId(collectionId))) + completion(.failure(FeedlyAccountDelegateError.unexpectedResourceID(collectionId))) } } @@ -406,7 +406,7 @@ extension FeedlyAPICaller: FeedlyAddFeedToCollectionService { guard let encodedId = encodeForURLPath(collectionId) else { return DispatchQueue.main.async { - completion(.failure(FeedlyAccountDelegateError.unexpectedResourceId(collectionId))) + completion(.failure(FeedlyAccountDelegateError.unexpectedResourceID(collectionId))) } } var components = baseUrlComponents diff --git a/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate.swift b/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate.swift index 07e89fe9a..25c9765b7 100644 --- a/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate.swift +++ b/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate.swift @@ -14,7 +14,7 @@ import SyncDatabase import os.log import Secrets -final class FeedlyAccountDelegate: AccountDelegate { +@MainActor final class FeedlyAccountDelegate: AccountDelegate { /// Feedly has a sandbox API and a production API. /// This property is referred to when clients need to know which environment it should be pointing to. @@ -262,7 +262,7 @@ final class FeedlyAccountDelegate: AccountDelegate { self.refreshProgress.completeTask() self.isOPMLImportInProgress = false DispatchQueue.main.async { - let wrappedError = AccountError.wrappedError(error: error, account: account) + let wrappedError = AccountError.wrapped(error, account) completion(.failure(wrappedError)) } } @@ -277,7 +277,7 @@ final class FeedlyAccountDelegate: AccountDelegate { } } - func createFolder(for account: Account, name: String, completion: @escaping (Result) -> Void) { + @MainActor func createFolder(for account: Account, name: String, completion: @escaping (Result) -> Void) { let progress = refreshProgress progress.addToNumberOfTasksAndRemaining(1) @@ -308,7 +308,7 @@ final class FeedlyAccountDelegate: AccountDelegate { } } - func renameFolder(for account: Account, with folder: Folder, to name: String, completion: @escaping (Result) -> Void) { + @MainActor func renameFolder(for account: Account, with folder: Folder, to name: String, completion: @escaping (Result) -> Void) { guard let id = folder.externalID else { return DispatchQueue.main.async { completion(.failure(FeedlyAccountDelegateError.unableToRenameFolder(folder.nameForDisplay, name))) @@ -411,7 +411,7 @@ final class FeedlyAccountDelegate: AccountDelegate { } } - private func renameFeed(for account: Account, with feed: Feed, to name: String, completion: @escaping (Result) -> Void) { + @MainActor private func renameFeed(for account: Account, with feed: Feed, to name: String, completion: @escaping (Result) -> Void) { let folderCollectionIds = account.folders?.filter { $0.has(feed) }.compactMap { $0.externalID } guard let collectionIds = folderCollectionIds, let collectionId = collectionIds.first else { completion(.failure(FeedlyAccountDelegateError.unableToRenameFeed(feed.nameForDisplay, name))) @@ -488,7 +488,7 @@ final class FeedlyAccountDelegate: AccountDelegate { private func removeFeed(for account: Account, with feed: Feed, from container: Container, completion: @escaping (Result) -> Void) { guard let folder = container as? Folder, let collectionId = folder.externalID else { return DispatchQueue.main.async { - completion(.failure(FeedlyAccountDelegateError.unableToRemoveFeed(feed))) + completion(.failure(FeedlyAccountDelegateError.unableToRemoveFeed(feed.nameForDisplay))) } } @@ -530,7 +530,7 @@ final class FeedlyAccountDelegate: AccountDelegate { completion(.success(())) case .failure: from.addFeedToTreeAtTopLevel(feed) - completion(.failure(FeedlyAccountDelegateError.unableToMoveFeedBetweenFolders(feed, from, to))) + completion(.failure(FeedlyAccountDelegateError.unableToMoveFeedBetweenFolders(feed.nameForDisplay, from.nameForDisplay, to.nameForDisplay))) } } case .failure(let error): diff --git a/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegateError.swift b/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegateError.swift index efe28b73e..f0e20f702 100644 --- a/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegateError.swift +++ b/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegateError.swift @@ -10,22 +10,22 @@ import Foundation enum FeedlyAccountDelegateError: LocalizedError { case notLoggedIn - case unexpectedResourceId(String) + case unexpectedResourceID(String) case unableToAddFolder(String) case unableToRenameFolder(String, String) case unableToRemoveFolder(String) - case unableToMoveFeedBetweenFolders(Feed, Folder, Folder) + case unableToMoveFeedBetweenFolders(String, String, String) // feedName, sourceFolderName, destinationFolderName case addFeedChooseFolder - case addFeedInvalidFolder(Folder) + case addFeedInvalidFolder(String) // folderName case unableToRenameFeed(String, String) - case unableToRemoveFeed(Feed) + case unableToRemoveFeed(String) var errorDescription: String? { switch self { case .notLoggedIn: return NSLocalizedString("Please add the Feedly account again. If this problem persists, open Keychain Access and delete all feedly.com entries, then try again.", comment: "Feedly – Credentials not found.") - case .unexpectedResourceId(let resourceId): + case .unexpectedResourceID(let resourceId): let template = NSLocalizedString("Could not encode the identifier “%@”.", comment: "Feedly – Could not encode resource id to send to Feedly.") return String(format: template, resourceId) @@ -41,24 +41,24 @@ enum FeedlyAccountDelegateError: LocalizedError { let template = NSLocalizedString("Could not remove the folder named “%@”.", comment: "Feedly – Could not remove a folder/collection.") return String(format: template, name) - case .unableToMoveFeedBetweenFolders(let feed, _, let to): + case .unableToMoveFeedBetweenFolders(let feedName, _, let destinationFolderName): let template = NSLocalizedString("Could not move “%@” to “%@”.", comment: "Feedly – Could not move a feed between folders/collections.") - return String(format: template, feed.nameForDisplay, to.nameForDisplay) + return String(format: template, feedName, destinationFolderName) case .addFeedChooseFolder: return NSLocalizedString("Please choose a folder to contain the feed.", comment: "Feedly – Feed can only be added to folders.") - case .addFeedInvalidFolder(let invalidFolder): + case .addFeedInvalidFolder(let folderName): let template = NSLocalizedString("Feeds cannot be added to the “%@” folder.", comment: "Feedly – Feed can only be added to folders.") - return String(format: template, invalidFolder.nameForDisplay) + return String(format: template, folderName) case .unableToRenameFeed(let from, let to): let template = NSLocalizedString("Could not rename “%@” to “%@”.", comment: "Feedly – Could not rename a feed.") return String(format: template, from, to) - case .unableToRemoveFeed(let feed): + case .unableToRemoveFeed(let feedName): let template = NSLocalizedString("Could not remove “%@”.", comment: "Feedly – Could not remove a feed.") - return String(format: template, feed.nameForDisplay) + return String(format: template, feedName) } } @@ -67,7 +67,7 @@ enum FeedlyAccountDelegateError: LocalizedError { case .notLoggedIn: return nil - case .unexpectedResourceId: + case .unexpectedResourceID: let template = NSLocalizedString("Please contact NetNewsWire support.", comment: "Feedly – Recovery suggestion for not being able to encode a resource id to send to Feedly..") return String(format: template) @@ -80,9 +80,9 @@ enum FeedlyAccountDelegateError: LocalizedError { case .unableToRemoveFolder: return nil - case .unableToMoveFeedBetweenFolders(let feed, let from, let to): + case .unableToMoveFeedBetweenFolders(let feedName, let sourceFolderName, let destinationFolderName): let template = NSLocalizedString("“%@” may be in both “%@” and “%@”.", comment: "Feedly – Could not move a feed between folders/collections.") - return String(format: template, feed.nameForDisplay, from.nameForDisplay, to.nameForDisplay) + return String(format: template, feedName, sourceFolderName, destinationFolderName) case .addFeedChooseFolder: return nil diff --git a/Modules/Account/Sources/Account/Feedly/FeedlyFeedContainerValidator.swift b/Modules/Account/Sources/Account/Feedly/FeedlyFeedContainerValidator.swift index 1aa87d07f..11070b567 100644 --- a/Modules/Account/Sources/Account/Feedly/FeedlyFeedContainerValidator.swift +++ b/Modules/Account/Sources/Account/Feedly/FeedlyFeedContainerValidator.swift @@ -11,13 +11,13 @@ import Foundation struct FeedlyFeedContainerValidator { var container: Container - func getValidContainer() throws -> (Folder, String) { + @MainActor func getValidContainer() throws -> (Folder, String) { guard let folder = container as? Folder else { throw FeedlyAccountDelegateError.addFeedChooseFolder } guard let collectionId = folder.externalID else { - throw FeedlyAccountDelegateError.addFeedInvalidFolder(folder) + throw FeedlyAccountDelegateError.addFeedInvalidFolder(folder.nameForDisplay) } return (folder, collectionId) diff --git a/Modules/Account/Sources/Account/Feedly/OAuthAccountAuthorizationOperation.swift b/Modules/Account/Sources/Account/Feedly/OAuthAccountAuthorizationOperation.swift index 13710f04b..5d49d9eab 100644 --- a/Modules/Account/Sources/Account/Feedly/OAuthAccountAuthorizationOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/OAuthAccountAuthorizationOperation.swift @@ -54,7 +54,7 @@ public final class OAuthAccountAuthorizationOperation: MainThreadOperation, @unc private var session: ASWebAuthenticationSession? private var error: Error? - public init(accountType: AccountType) { + @MainActor public init(accountType: AccountType) { self.accountType = accountType self.oauthClient = Account.oauthAuthorizationClient(for: accountType) super.init() diff --git a/Modules/Account/Sources/Account/Feedly/OAuthAcessTokenRefreshing.swift b/Modules/Account/Sources/Account/Feedly/OAuthAcessTokenRefreshing.swift index b2228c19f..265227217 100644 --- a/Modules/Account/Sources/Account/Feedly/OAuthAcessTokenRefreshing.swift +++ b/Modules/Account/Sources/Account/Feedly/OAuthAcessTokenRefreshing.swift @@ -40,7 +40,7 @@ public protocol OAuthAcessTokenRefreshRequesting { } /// Implemented by concrete types to perform the actual request. -protocol OAuthAccessTokenRefreshing: AnyObject { +@MainActor protocol OAuthAccessTokenRefreshing: AnyObject { func refreshAccessToken(with refreshToken: String, client: OAuthAuthorizationClient, completion: @escaping (Result) -> ()) } diff --git a/Modules/Account/Sources/Account/Feedly/OAuthAuthorizationCodeGranting.swift b/Modules/Account/Sources/Account/Feedly/OAuthAuthorizationCodeGranting.swift index 32a97e784..3a89a0619 100644 --- a/Modules/Account/Sources/Account/Feedly/OAuthAuthorizationCodeGranting.swift +++ b/Modules/Account/Sources/Account/Feedly/OAuthAuthorizationCodeGranting.swift @@ -165,7 +165,7 @@ public protocol OAuthAuthorizationCodeGrantRequesting { func requestAccessToken(_ authorizationRequest: OAuthAccessTokenRequest, completion: @escaping (Result) -> ()) } -protocol OAuthAuthorizationGranting: AccountDelegate { +@MainActor protocol OAuthAuthorizationGranting: AccountDelegate { static func oauthAuthorizationCodeGrantRequest() -> URLRequest diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyFetchIdsForMissingArticlesOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyFetchIdsForMissingArticlesOperation.swift index a2cf80bde..7b555f367 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyFetchIdsForMissingArticlesOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyFetchIdsForMissingArticlesOperation.swift @@ -20,7 +20,7 @@ final class FeedlyFetchIdsForMissingArticlesOperation: FeedlyOperation, FeedlyEn super.init() } - override func run() { + @MainActor override func run() { account.fetchArticleIDsForStatusesWithoutArticlesNewerThanCutoffDate { result in Task { @MainActor in switch result { diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyRefreshAccessTokenOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyRefreshAccessTokenOperation.swift index 197da1b7d..8cba4aa43 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyRefreshAccessTokenOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyRefreshAccessTokenOperation.swift @@ -24,7 +24,7 @@ final class FeedlyRefreshAccessTokenOperation: FeedlyOperation, @unchecked Senda super.init() } - override func run() { + @MainActor override func run() { let refreshToken: Credentials do { diff --git a/Modules/Account/Sources/Account/Folder.swift b/Modules/Account/Sources/Account/Folder.swift index 3dff2ffed..9aecd9e46 100644 --- a/Modules/Account/Sources/Account/Folder.swift +++ b/Modules/Account/Sources/Account/Folder.swift @@ -16,7 +16,7 @@ public final class Folder: SidebarItem, Renamable, Container, Hashable { return .read } - public var containerID: ContainerIdentifier? { + @MainActor public var containerID: ContainerIdentifier? { guard let accountID = account?.accountID else { assertionFailure("Expected feed.account, but got nil.") return nil @@ -24,7 +24,7 @@ public final class Folder: SidebarItem, Renamable, Container, Hashable { return ContainerIdentifier.folder(accountID, nameForDisplay) } - public var sidebarItemID: SidebarItemIdentifier? { + @MainActor public var sidebarItemID: SidebarItemIdentifier? { guard let accountID = account?.accountID else { assertionFailure("Expected feed.account, but got nil.") return nil @@ -36,7 +36,7 @@ public final class Folder: SidebarItem, Renamable, Container, Hashable { public var topLevelFeeds: Set = Set() public var folders: Set? = nil // subfolders are not supported, so this is always nil - public var name: String? { + @MainActor public var name: String? { didSet { postDisplayNameDidChangeNotification() } @@ -217,7 +217,7 @@ extension Folder: OPMLRepresentable { // MARK: Set -extension Set where Element == Folder { +@MainActor extension Set where Element == Folder { func sorted() -> Array { return sorted(by: { (folder1, folder2) -> Bool in diff --git a/Modules/Account/Sources/Account/LocalAccount/LocalAccountDelegate.swift b/Modules/Account/Sources/Account/LocalAccount/LocalAccountDelegate.swift index 43578ccef..711368d61 100644 --- a/Modules/Account/Sources/Account/LocalAccount/LocalAccountDelegate.swift +++ b/Modules/Account/Sources/Account/LocalAccount/LocalAccountDelegate.swift @@ -15,7 +15,7 @@ import FeedFinder import RSWeb import Secrets -final class LocalAccountDelegate: AccountDelegate { +@MainActor final class LocalAccountDelegate: AccountDelegate { weak var account: Account? diff --git a/Modules/Account/Sources/Account/LocalAccount/LocalAccountRefresher.swift b/Modules/Account/Sources/Account/LocalAccount/LocalAccountRefresher.swift index 3d6199965..bd8809631 100644 --- a/Modules/Account/Sources/Account/LocalAccount/LocalAccountRefresher.swift +++ b/Modules/Account/Sources/Account/LocalAccount/LocalAccountRefresher.swift @@ -14,11 +14,11 @@ import Articles import ArticlesDatabase import os -protocol LocalAccountRefresherDelegate { +@MainActor protocol LocalAccountRefresherDelegate { func localAccountRefresher(_ refresher: LocalAccountRefresher, articleChanges: ArticleChanges) } -final class LocalAccountRefresher { +@MainActor final class LocalAccountRefresher { var delegate: LocalAccountRefresherDelegate? var downloadProgress: DownloadProgress { @@ -80,7 +80,7 @@ final class LocalAccountRefresher { // MARK: - DownloadSessionDelegate -extension LocalAccountRefresher: DownloadSessionDelegate { +@MainActor extension LocalAccountRefresher: DownloadSessionDelegate { func downloadSession(_ downloadSession: DownloadSession, conditionalGetInfoFor url: URL) -> HTTPConditionalGetInfo? { diff --git a/Modules/Account/Sources/Account/NewsBlur/Internals/NewsBlurAccountDelegate+Internal.swift b/Modules/Account/Sources/Account/NewsBlur/Internals/NewsBlurAccountDelegate+Internal.swift index 2180bfc3b..e0176beeb 100644 --- a/Modules/Account/Sources/Account/NewsBlur/Internals/NewsBlurAccountDelegate+Internal.swift +++ b/Modules/Account/Sources/Account/NewsBlur/Internals/NewsBlurAccountDelegate+Internal.swift @@ -15,9 +15,9 @@ import RSWeb import SyncDatabase import os.log -extension NewsBlurAccountDelegate { +@MainActor extension NewsBlurAccountDelegate { - func refreshFeeds(for account: Account) async throws { + @MainActor func refreshFeeds(for account: Account) async throws { Self.logger.info("NewsBlur: Refreshing feeds") let (feeds, folders) = try await caller.retrieveFeeds() @@ -120,7 +120,7 @@ extension NewsBlurAccountDelegate { } } - func syncFeedFolderRelationship(_ account: Account, _ folders: [NewsBlurFolder]?) { + @MainActor func syncFeedFolderRelationship(_ account: Account, _ folders: [NewsBlurFolder]?) { guard let folders = folders else { return } assert(Thread.isMainThread) @@ -191,14 +191,14 @@ extension NewsBlurAccountDelegate { } - func clearFolderRelationship(for feed: Feed, withFolderName folderName: String) { + @MainActor func clearFolderRelationship(for feed: Feed, withFolderName folderName: String) { if var folderRelationship = feed.folderRelationship { folderRelationship[folderName] = nil feed.folderRelationship = folderRelationship } } - func saveFolderRelationship(for feed: Feed, withFolderName folderName: String, id: String) { + @MainActor func saveFolderRelationship(for feed: Feed, withFolderName folderName: String, id: String) { if var folderRelationship = feed.folderRelationship { folderRelationship[folderName] = id feed.folderRelationship = folderRelationship @@ -207,7 +207,7 @@ extension NewsBlurAccountDelegate { } } - func nameToFolderDictionary(with folders: Set?) -> [String: Folder] { + @MainActor func nameToFolderDictionary(with folders: Set?) -> [String: Folder] { guard let folders = folders else { return [String: Folder]() } @@ -222,7 +222,7 @@ extension NewsBlurAccountDelegate { return d } - func refreshUnreadStories(for account: Account, hashes: [NewsBlurStoryHash]?, updateFetchDate: Date?) async throws { + @MainActor func refreshUnreadStories(for account: Account, hashes: [NewsBlurStoryHash]?, updateFetchDate: Date?) async throws { guard let hashes = hashes, !hashes.isEmpty else { if let lastArticleFetch = updateFetchDate { self.accountMetadata?.lastArticleFetchStartTime = lastArticleFetch @@ -337,7 +337,7 @@ extension NewsBlurAccountDelegate { } } - func createFeed(account: Account, newsBlurFeed: NewsBlurFeed, name: String?, container: Container) async throws -> Feed { + @MainActor func createFeed(account: Account, newsBlurFeed: NewsBlurFeed, name: String?, container: Container) async throws -> Feed { let feed = account.createFeed(with: newsBlurFeed.name, url: newsBlurFeed.feedURL, feedID: String(newsBlurFeed.feedID), homePageURL: newsBlurFeed.homePageURL) feed.externalID = String(feed.feedID) feed.faviconURL = feed.faviconURL @@ -384,7 +384,7 @@ extension NewsBlurAccountDelegate { try await refreshMissingStories(for: account) } - func deleteFeed(for account: Account, with feed: Feed, from container: Container?) async throws { + @MainActor func deleteFeed(for account: Account, with feed: Feed, from container: Container?) async throws { // This error should never happen guard let feedID = feed.externalID else { throw AccountError.invalidParameter @@ -405,8 +405,7 @@ extension NewsBlurAccountDelegate { account.clearFeedMetadata(feed) } } catch { - let wrappedError = AccountError.wrappedError(error: error, account: account) - throw wrappedError + throw AccountError.wrapped(error, account) } } } diff --git a/Modules/Account/Sources/Account/NewsBlur/NewsBlurAccountDelegate.swift b/Modules/Account/Sources/Account/NewsBlur/NewsBlurAccountDelegate.swift index 800e9bc8c..78d008316 100644 --- a/Modules/Account/Sources/Account/NewsBlur/NewsBlurAccountDelegate.swift +++ b/Modules/Account/Sources/Account/NewsBlur/NewsBlurAccountDelegate.swift @@ -15,7 +15,7 @@ import SyncDatabase import os.log import Secrets -final class NewsBlurAccountDelegate: AccountDelegate { +@MainActor final class NewsBlurAccountDelegate: AccountDelegate { var behaviors: AccountBehaviors = [] var isOPMLImportInProgress: Bool = false @@ -79,8 +79,7 @@ final class NewsBlurAccountDelegate: AccountDelegate { refreshProgress.completeTask() } catch { refreshProgress.reset() - let wrappedError = AccountError.wrappedError(error: error, account: account) - throw wrappedError + throw AccountError.wrapped(error, account) } } @@ -313,8 +312,7 @@ final class NewsBlurAccountDelegate: AccountDelegate { let feed = try await createFeed(account: account, newsBlurFeed: newsBlurFeed, name: name, container: container) return feed } catch { - let wrappedError = AccountError.wrappedError(error: error, account: account) - throw wrappedError + throw AccountError.wrapped(error, account) } } @@ -332,7 +330,7 @@ final class NewsBlurAccountDelegate: AccountDelegate { try await caller.renameFeed(feedID: feedID, newName: name) feed.editedName = name } catch { - throw AccountError.wrappedError(error: error, account: account) + throw AccountError.wrapped(error, account) } } diff --git a/Modules/Account/Sources/Account/OPMLFile.swift b/Modules/Account/Sources/Account/OPMLFile.swift index 0c73b2869..20e967a83 100644 --- a/Modules/Account/Sources/Account/OPMLFile.swift +++ b/Modules/Account/Sources/Account/OPMLFile.swift @@ -32,7 +32,7 @@ final class OPMLFile { isDirty = true } - func load() { + @MainActor func load() { guard let fileData = opmlFileData(), let opmlItems = parsedOPMLItems(fileData: fileData) else { return } @@ -42,7 +42,7 @@ final class OPMLFile { } } - func save() { + @MainActor func save() { guard !account.isDeleted else { return } let opmlDocumentString = opmlDocument() @@ -58,10 +58,18 @@ final class OPMLFile { private extension OPMLFile { func queueSaveToDiskIfNeeded() { - saveQueue.add(self, #selector(saveToDiskIfNeeded)) + if Thread.isMainThread { + MainActor.assumeIsolated { + saveQueue.add(self, #selector(saveToDiskIfNeeded)) + } + } else { + Task { @MainActor in + saveQueue.add(self, #selector(saveToDiskIfNeeded)) + } + } } - @objc func saveToDiskIfNeeded() { + @MainActor @objc func saveToDiskIfNeeded() { if isDirty { isDirty = false save() @@ -94,7 +102,7 @@ private extension OPMLFile { return opmlDocument?.children } - func opmlDocument() -> String { + @MainActor func opmlDocument() -> String { let escapedTitle = account.nameForDisplay.escapingSpecialXMLCharacters let openingText = """ diff --git a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift index ecbd72fa5..484a3d533 100644 --- a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift +++ b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift @@ -52,7 +52,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate { return behaviors } - var server: String? { + @MainActor var server: String? { get { return caller.server } @@ -127,7 +127,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate { } catch { refreshProgress.reset() - let wrappedError = AccountError.wrappedError(error: error, account: account) + let wrappedError = AccountError.wrapped(error, account) if wrappedError.isCredentialsError, let basicCredentials = try? account.retrieveCredentials(type: .readerBasic), let endpoint = account.endpointURL { self.caller.credentials = basicCredentials @@ -227,8 +227,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate { folder.externalID = "user/-/label/\(name)" folder.name = name } catch { - let wrappedError = AccountError.wrappedError(error: error, account: account) - throw wrappedError + throw AccountError.wrapped(error, account) } } @@ -334,8 +333,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate { refreshProgress.completeTask() } catch { refreshProgress.completeTask() - let wrappedError = AccountError.wrappedError(error: error, account: account) - throw wrappedError + throw AccountError.wrapped(error, account) } } @@ -353,8 +351,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate { account.clearFeedMetadata(feed) account.removeAllInstancesOfFeedFromTreeAtAllLevels(feed) } catch { - let wrappedError = AccountError.wrappedError(error: error, account: account) - throw wrappedError + throw AccountError.wrapped(error, account) } } @@ -405,8 +402,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate { } catch { refreshProgress.completeTask() - let wrappedError = AccountError.wrappedError(error: error, account: account) - throw wrappedError + throw AccountError.wrapped(error, account) } } else { @@ -493,7 +489,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate { private extension ReaderAPIAccountDelegate { - func refreshAccount(_ account: Account) async throws { + @MainActor func refreshAccount(_ account: Account) async throws { let tags = try await caller.retrieveTags() refreshProgress.completeTask() @@ -508,7 +504,7 @@ private extension ReaderAPIAccountDelegate { } } - func syncFolders(_ account: Account, _ tags: [ReaderAPITag]?) { + @MainActor func syncFolders(_ account: Account, _ tags: [ReaderAPITag]?) { guard let tags = tags else { return } assert(Thread.isMainThread) @@ -556,7 +552,7 @@ private extension ReaderAPIAccountDelegate { } - func syncFeeds(_ account: Account, _ subscriptions: [ReaderAPISubscription]?) { + @MainActor func syncFeeds(_ account: Account, _ subscriptions: [ReaderAPISubscription]?) { guard let subscriptions = subscriptions else { return } assert(Thread.isMainThread) @@ -714,7 +710,7 @@ private extension ReaderAPIAccountDelegate { } } - func createFeed(account: Account, subscription: ReaderAPISubscription, name: String?, container: Container) async throws -> Feed { + @MainActor func createFeed(account: Account, subscription: ReaderAPISubscription, name: String?, container: Container) async throws -> Feed { let feed = account.createFeed(with: subscription.name, url: subscription.url, feedID: String(subscription.feedID), homePageURL: subscription.homePageURL) feed.externalID = String(subscription.feedID) diff --git a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPICaller.swift b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPICaller.swift index b3a58276a..7274c2bcd 100644 --- a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPICaller.swift +++ b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPICaller.swift @@ -57,13 +57,13 @@ final class ReaderAPICaller { var variant: ReaderAPIVariant = .generic var credentials: Credentials? - var server: String? { + @MainActor var server: String? { get { return apiBaseURL?.host } } - private var apiBaseURL: URL? { + @MainActor private var apiBaseURL: URL? { get { switch variant { case .generic, .freshRSS: @@ -162,7 +162,7 @@ final class ReaderAPICaller { return accessToken } - public func retrieveTags() async throws -> [ReaderAPITag]? { + @MainActor public func retrieveTags() async throws -> [ReaderAPITag]? { guard let baseURL = apiBaseURL else { throw CredentialsError.incompleteCredentials @@ -187,7 +187,7 @@ final class ReaderAPICaller { return wrapper?.tags } - public func renameTag(oldName: String, newName: String) async throws { + @MainActor public func renameTag(oldName: String, newName: String) async throws { guard let baseURL = apiBaseURL else { throw CredentialsError.incompleteCredentials @@ -211,7 +211,7 @@ final class ReaderAPICaller { _ = try await transport.send(request: request, method: HTTPMethod.post, payload: postData!) } - public func deleteTag(folderExternalID: String) async throws { + @MainActor public func deleteTag(folderExternalID: String) async throws { guard let baseURL = apiBaseURL else { throw CredentialsError.incompleteCredentials @@ -229,7 +229,7 @@ final class ReaderAPICaller { _ = try await self.transport.send(request: request, method: HTTPMethod.post, payload: postData!) } - public func retrieveSubscriptions() async throws -> [ReaderAPISubscription]? { + @MainActor public func retrieveSubscriptions() async throws -> [ReaderAPISubscription]? { guard let baseURL = apiBaseURL else { throw CredentialsError.incompleteCredentials @@ -250,7 +250,7 @@ final class ReaderAPICaller { return container?.subscriptions } - public func createSubscription(url: String, name: String?) async throws -> CreateReaderAPISubscriptionResult { + @MainActor public func createSubscription(url: String, name: String?) async throws -> CreateReaderAPISubscriptionResult { guard let baseURL = apiBaseURL else { throw CredentialsError.incompleteCredentials @@ -299,7 +299,7 @@ final class ReaderAPICaller { try await changeSubscription(subscriptionID: subscriptionID, title: newName) } - public func deleteSubscription(subscriptionID: String) async throws { + @MainActor public func deleteSubscription(subscriptionID: String) async throws { guard let baseURL = apiBaseURL else { throw CredentialsError.incompleteCredentials @@ -332,7 +332,7 @@ final class ReaderAPICaller { try await changeSubscription(subscriptionID: subscriptionID, removeTagName: sourceTag, addTagName: destinationTag) } - private func changeSubscription(subscriptionID: String, removeTagName: String? = nil, addTagName: String? = nil, title: String? = nil) async throws { + @MainActor private func changeSubscription(subscriptionID: String, removeTagName: String? = nil, addTagName: String? = nil, title: String? = nil) async throws { guard removeTagName != nil || addTagName != nil || title != nil else { throw AccountError.invalidParameter @@ -363,7 +363,7 @@ final class ReaderAPICaller { _ = try await transport.send(request: request, method: HTTPMethod.post, payload: postData!) } - public func retrieveEntries(articleIDs: [String]) async throws -> [ReaderAPIEntry]? { + @MainActor public func retrieveEntries(articleIDs: [String]) async throws -> [ReaderAPIEntry]? { guard !articleIDs.isEmpty else { return [ReaderAPIEntry]() @@ -401,7 +401,7 @@ final class ReaderAPICaller { return entryWrapper.entries } - public func retrieveItemIDs(type: ItemIDType, feedID: String? = nil) async throws -> [String] { + @MainActor public func retrieveItemIDs(type: ItemIDType, feedID: String? = nil) async throws -> [String] { guard let baseURL = apiBaseURL else { throw CredentialsError.incompleteCredentials @@ -462,7 +462,7 @@ final class ReaderAPICaller { return try await retrieveItemIDs(type: type, url: callURL, dateInfo: dateInfo, itemIDs: itemIDs, continuation: entries?.continuation) } - func retrieveItemIDs(type: ItemIDType, url: URL, dateInfo: HTTPDateInfo?, itemIDs: [String], continuation: String?) async throws -> [String] { + @MainActor func retrieveItemIDs(type: ItemIDType, url: URL, dateInfo: HTTPDateInfo?, itemIDs: [String], continuation: String?) async throws -> [String] { guard let continuation else { if type == .allForAccount { @@ -536,7 +536,7 @@ private extension ReaderAPICaller { } } - private func updateStateToEntries(entries: [String], state: ReaderState, add: Bool) async throws { + @MainActor private func updateStateToEntries(entries: [String], state: ReaderState, add: Bool) async throws { guard let baseURL = apiBaseURL else { throw CredentialsError.incompleteCredentials diff --git a/Modules/Account/Sources/Account/SidebarItem.swift b/Modules/Account/Sources/Account/SidebarItem.swift index b46b45614..5ad176444 100644 --- a/Modules/Account/Sources/Account/SidebarItem.swift +++ b/Modules/Account/Sources/Account/SidebarItem.swift @@ -22,7 +22,7 @@ public protocol SidebarItem: SidebarItemIdentifiable, ArticleFetcher, DisplayNam } -public extension SidebarItem { +@MainActor public extension SidebarItem { func readFiltered(readFilterEnabledTable: [SidebarItemIdentifier: Bool]) -> Bool { guard defaultReadFilterType != .alwaysRead else { diff --git a/Modules/Account/Sources/Account/SidebarItemIdentifier.swift b/Modules/Account/Sources/Account/SidebarItemIdentifier.swift index aebd6943b..e3a95db99 100644 --- a/Modules/Account/Sources/Account/SidebarItemIdentifier.swift +++ b/Modules/Account/Sources/Account/SidebarItemIdentifier.swift @@ -8,7 +8,7 @@ import Foundation -public protocol SidebarItemIdentifiable { +@MainActor public protocol SidebarItemIdentifiable { var sidebarItemID: SidebarItemIdentifier? { get } } diff --git a/Modules/Account/Sources/Account/UnreadCountProvider.swift b/Modules/Account/Sources/Account/UnreadCountProvider.swift index 4c5cfe06a..2e6e5ed5b 100644 --- a/Modules/Account/Sources/Account/UnreadCountProvider.swift +++ b/Modules/Account/Sources/Account/UnreadCountProvider.swift @@ -13,7 +13,7 @@ public extension Notification.Name { static let UnreadCountDidChange = Notification.Name(rawValue: "UnreadCountDidChange") } -public protocol UnreadCountProvider { +@MainActor public protocol UnreadCountProvider { var unreadCount: Int { get } @@ -22,7 +22,7 @@ public protocol UnreadCountProvider { } -public extension UnreadCountProvider { +@MainActor public extension UnreadCountProvider { func postUnreadCountDidInitializeNotification() { NotificationCenter.default.post(name: .UnreadCountDidInitialize, object: self, userInfo: nil) diff --git a/Modules/Account/Tests/AccountTests/AccountCredentialsTest.swift b/Modules/Account/Tests/AccountTests/AccountCredentialsTest.swift index 665161613..07c0f71b3 100644 --- a/Modules/Account/Tests/AccountTests/AccountCredentialsTest.swift +++ b/Modules/Account/Tests/AccountTests/AccountCredentialsTest.swift @@ -11,7 +11,7 @@ import RSWeb @testable import Account import Secrets -final class AccountCredentialsTest: XCTestCase { +@MainActor final class AccountCredentialsTest: XCTestCase { private var account: Account! diff --git a/Modules/Account/Tests/AccountTests/Feedly/FeedlyTestSupport.swift b/Modules/Account/Tests/AccountTests/Feedly/FeedlyTestSupport.swift index 8bd33550a..16ee513c7 100644 --- a/Modules/Account/Tests/AccountTests/Feedly/FeedlyTestSupport.swift +++ b/Modules/Account/Tests/AccountTests/Feedly/FeedlyTestSupport.swift @@ -13,7 +13,7 @@ import Secrets import os.log import SyncDatabase -final class FeedlyTestSupport { +@MainActor final class FeedlyTestSupport { var accessToken = Credentials(type: .oauthAccessToken, username: "Test", secret: "t3st-access-tok3n") var refreshToken = Credentials(type: .oauthRefreshToken, username: "Test", secret: "t3st-refresh-tok3n") diff --git a/Modules/Account/Tests/AccountTests/TestAccountManager.swift b/Modules/Account/Tests/AccountTests/TestAccountManager.swift index f2e8e04f7..0c7ccf31a 100644 --- a/Modules/Account/Tests/AccountTests/TestAccountManager.swift +++ b/Modules/Account/Tests/AccountTests/TestAccountManager.swift @@ -11,7 +11,7 @@ import RSWeb @testable import Account -final class TestAccountManager { +@MainActor final class TestAccountManager { static let shared = TestAccountManager() diff --git a/Modules/RSCore/Package.swift b/Modules/RSCore/Package.swift index c66c33537..3827f6867 100644 --- a/Modules/RSCore/Package.swift +++ b/Modules/RSCore/Package.swift @@ -13,7 +13,11 @@ let package = Package( .target( name: "RSCore", dependencies: ["RSCoreObjC"], - swiftSettings: [.swiftLanguageMode(.v5)] + swiftSettings: [ + .enableUpcomingFeature("NonisolatedNonsendingByDefault"), + .enableUpcomingFeature("InferIsolatedConformances"), + .defaultIsolation(MainActor.self) + ] ), .target( name: "RSCoreObjC", diff --git a/Modules/RSCore/Sources/RSCore/AppKit/Keyboard.swift b/Modules/RSCore/Sources/RSCore/AppKit/Keyboard.swift index c4f9b8c2f..65fa3834f 100644 --- a/Modules/RSCore/Sources/RSCore/AppKit/Keyboard.swift +++ b/Modules/RSCore/Sources/RSCore/AppKit/Keyboard.swift @@ -19,7 +19,7 @@ public struct KeyboardConstant { public extension String { - var keyboardIntegerValue: Int? { + nonisolated var keyboardIntegerValue: Int? { if isEmpty { return nil } @@ -32,7 +32,7 @@ public extension String { } } -public struct KeyboardShortcut: Hashable { +nonisolated public struct KeyboardShortcut: Hashable, Sendable { public let key: KeyboardKey public let actionString: String @@ -50,8 +50,7 @@ public struct KeyboardShortcut: Hashable { self.actionString = actionString } - public func perform(with view: NSView) { - + @MainActor public func perform(with view: NSView) { let action = NSSelectorFromString(actionString) NSApplication.shared.sendAction(action, to: nil, from: view) } @@ -67,7 +66,7 @@ public struct KeyboardShortcut: Hashable { } } -public struct KeyboardKey: Hashable { +nonisolated public struct KeyboardKey: Hashable, Sendable { public let shiftKeyDown: Bool public let optionKeyDown: Bool diff --git a/Modules/RSCore/Sources/RSCore/AppKit/RSAppMovementMonitor.swift b/Modules/RSCore/Sources/RSCore/AppKit/RSAppMovementMonitor.swift index c42f7c6e3..248a6dd0e 100644 --- a/Modules/RSCore/Sources/RSCore/AppKit/RSAppMovementMonitor.swift +++ b/Modules/RSCore/Sources/RSCore/AppKit/RSAppMovementMonitor.swift @@ -78,18 +78,20 @@ public final class RSAppMovementMonitor: NSObject { // changes to the app bundle's path, such as when a containing folder or the // volume name changes. NotificationCenter.default.addObserver(forName: NSApplication.didBecomeActiveNotification, object: nil, queue: nil) { notification in - // Removing observer in invalidate doesn't seem to prevent this getting called? Maybe - // because it's on the same invocation of the runloop? - if self.isValid() && self.originalAppURL != self.appTrackingURL?.absoluteURL { - self.invokeEventHandler() + Task { @MainActor in + // Removing observer in invalidate doesn't seem to prevent this getting called? Maybe + // because it's on the same invocation of the runloop? + if self.isValid() && self.originalAppURL != self.appTrackingURL?.absoluteURL { + self.invokeEventHandler() + } } } } } - deinit { - self.invalidate() - } +// deinit { +// self.invalidate() +// } func invokeEventHandler() { // Prevent re-entry when the app is activated while running handler @@ -131,7 +133,9 @@ public final class RSAppMovementMonitor: NSObject { let configuration = NSWorkspace.OpenConfiguration() configuration.createsNewApplicationInstance = true NSWorkspace.shared.openApplication(at: appURL, configuration: configuration) { _, _ in - NSApp.terminate(self) + Task { @MainActor in + NSApp.terminate(self) + } } } diff --git a/Modules/RSCore/Sources/RSCore/Shared/Array+RSCore.swift b/Modules/RSCore/Sources/RSCore/Shared/Array+RSCore.swift index fc184e2d4..6d2e71e92 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/Array+RSCore.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/Array+RSCore.swift @@ -8,7 +8,7 @@ import Foundation -public extension Array { +nonisolated public extension Array { func chunked(into size: Int) -> [[Element]] { return stride(from: 0, to: count, by: size).map { diff --git a/Modules/RSCore/Sources/RSCore/Shared/BinaryDiskCache.swift b/Modules/RSCore/Sources/RSCore/Shared/BinaryDiskCache.swift index 62a7f8673..3252cd96f 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/BinaryDiskCache.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/BinaryDiskCache.swift @@ -67,7 +67,7 @@ nonisolated public final class BinaryDiskCache: Sendable { } } -private extension BinaryDiskCache { +nonisolated private extension BinaryDiskCache { func _data(forKey key: String) throws -> Data? { let url = urlForKey(key) diff --git a/Modules/RSCore/Sources/RSCore/Shared/Blocks.swift b/Modules/RSCore/Sources/RSCore/Shared/Blocks.swift index 3a2ad7114..28565e6a0 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/Blocks.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/Blocks.swift @@ -11,4 +11,4 @@ import Foundation public typealias VoidBlock = @Sendable () -> Void public typealias VoidCompletionBlock = VoidBlock -public typealias ImageResultBlock = (RSImage?) -> Void +public typealias ImageResultBlock = @Sendable (RSImage?) -> Void diff --git a/Modules/RSCore/Sources/RSCore/Shared/Cache.swift b/Modules/RSCore/Sources/RSCore/Shared/Cache.swift index 33ee208b5..e54272d56 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/Cache.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/Cache.swift @@ -6,13 +6,13 @@ // import Foundation -import os +import Synchronization -public protocol CacheRecord: Sendable { +nonisolated public protocol CacheRecord: Sendable { var dateCreated: Date { get } } -public final class Cache: Sendable { +nonisolated public final class Cache: Sendable { public let timeToLive: TimeInterval public let timeBetweenCleanups: TimeInterval @@ -21,8 +21,7 @@ public final class Cache: Sendable { var lastCleanupDate = Date() var cache = [String: T]() } - - private let stateLock = OSAllocatedUnfairLock(initialState: State()) + private let stateLock = Mutex(State()) public init(timeToLive: TimeInterval, timeBetweenCleanups: TimeInterval) { self.timeToLive = timeToLive @@ -60,7 +59,7 @@ public final class Cache: Sendable { } } -extension Cache { +nonisolated extension Cache { private func cleanupIfNeeded(_ state: inout State) { diff --git a/Modules/RSCore/Sources/RSCore/Shared/CoalescingQueue.swift b/Modules/RSCore/Sources/RSCore/Shared/CoalescingQueue.swift index a5cf123c4..f9bf028ae 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/CoalescingQueue.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/CoalescingQueue.swift @@ -7,53 +7,41 @@ // import Foundation -import Synchronization // Use when you want to coalesce calls for something like updating visible table cells. // Calls are uniqued. If you add a call with the same target and selector as a previous call, you’ll just get one call. // Targets are weakly-held. If a target goes to nil, the call is not performed. // The perform date is pushed off every time a call is added. // Calls are FIFO. -// Thread-safe: can be called from any thread, but performs calls on main thread. struct QueueCall: Equatable { + weak var target: AnyObject? let selector: Selector - @MainActor func perform() { - let _ = target?.perform(selector) + func perform() { + + _ = target?.perform(selector) } static func ==(lhs: QueueCall, rhs: QueueCall) -> Bool { + return lhs.target === rhs.target && lhs.selector == rhs.selector } } -nonisolated public final class CoalescingQueue: Sendable { +@objc public final class CoalescingQueue: NSObject { + public static let standard = CoalescingQueue(name: "Standard", interval: 0.05, maxInterval: 0.1) public let name: String + public var isPaused = false private let interval: TimeInterval private let maxInterval: TimeInterval + private var lastCallTime = Date.distantFuture + private var timer: Timer? + private var calls = [QueueCall]() - private struct State { - var isPaused = false - var lastCallTime = Date.distantFuture - var timer: Timer? = nil - var calls = [QueueCall]() - } - - private let state = Mutex(State()) - - public var isPaused: Bool { - get { - state.withLock { $0.isPaused } - } - set { - state.withLock { $0.isPaused = newValue } - } - } - - public init(name: String, interval: TimeInterval = 0.05, maxInterval: TimeInterval = 2.0) { + nonisolated public init(name: String, interval: TimeInterval = 0.05, maxInterval: TimeInterval = 2.0) { self.name = name self.interval = interval self.maxInterval = maxInterval @@ -61,73 +49,50 @@ nonisolated public final class CoalescingQueue: Sendable { public func add(_ target: AnyObject, _ selector: Selector) { let queueCall = QueueCall(target: target, selector: selector) - - let shouldFireImmediately = state.withLock { state -> Bool in - _add(queueCall, state: &state) - return Date().timeIntervalSince1970 - state.lastCallTime.timeIntervalSince1970 > maxInterval - } - - if shouldFireImmediately { - timerDidFire() + add(queueCall) + if Date().timeIntervalSince1970 - lastCallTime.timeIntervalSince1970 > maxInterval { + timerDidFire(nil) } } public func performCallsImmediately() { - let callsToMake = state.withLock { state -> [QueueCall]? in - guard !state.isPaused else { return nil } - let calls = state.calls - state.calls = [] - return calls - } - - guard let callsToMake else { return } - - // Always perform calls on main thread - if Thread.isMainThread { - MainActor.assumeIsolated { - callsToMake.forEach { $0.perform() } - } - } else { - DispatchQueue.main.async { - callsToMake.forEach { $0.perform() } - } + guard !isPaused else { return } + let callsToMake = calls // Make a copy in case calls are added to the queue while performing calls. + resetCalls() + for call in callsToMake { + call.perform() } } - func timerDidFire() { - state.withLock { $0.lastCallTime = Date() } + @objc func timerDidFire(_ sender: Any?) { + lastCallTime = Date() performCallsImmediately() } } private extension CoalescingQueue { - private func _add(_ call: QueueCall, state: inout State) { - _restartTimer(state: &state) - - if !state.calls.contains(call) { - state.calls.append(call) + func add(_ call: QueueCall) { + restartTimer() + + if !calls.contains(call) { + calls.append(call) } } - private func _restartTimer(state: inout State) { - _invalidateTimer(state: &state) - - // Schedule timer on main thread - DispatchQueue.main.async { [weak self] in - guard let self else { return } - self.state.withLock { state in - state.timer = Timer.scheduledTimer(withTimeInterval: self.interval, repeats: false) { [weak self] _ in - self?.timerDidFire() - } - } - } + func resetCalls() { + calls = [QueueCall]() } - private func _invalidateTimer(state: inout State) { - if let timer = state.timer, timer.isValid { + func restartTimer() { + invalidateTimer() + timer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(timerDidFire(_:)), userInfo: nil, repeats: false) + } + + func invalidateTimer() { + if let timer = timer, timer.isValid { timer.invalidate() } - state.timer = nil + timer = nil } } diff --git a/Modules/RSCore/Sources/RSCore/Shared/Data+RSCore.swift b/Modules/RSCore/Sources/RSCore/Shared/Data+RSCore.swift index 20881beb2..d84ae1a6d 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/Data+RSCore.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/Data+RSCore.swift @@ -9,7 +9,7 @@ import Foundation import CryptoKit -public extension Data { +nonisolated public extension Data { /// The MD5 hash of the data. var md5Hash: Data { diff --git a/Modules/RSCore/Sources/RSCore/Shared/Date+Extensions.swift b/Modules/RSCore/Sources/RSCore/Shared/Date+Extensions.swift index f1ef88f01..070e2865e 100755 --- a/Modules/RSCore/Sources/RSCore/Shared/Date+Extensions.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/Date+Extensions.swift @@ -8,7 +8,7 @@ import Foundation -public extension Date { +nonisolated public extension Date { // Below are for rough use only — they don't use the calendar. @@ -25,7 +25,7 @@ public extension Date { } } -public extension TimeInterval { +nonisolated public extension TimeInterval { init(days: Int) { self.init(days * 24 * 60 * 60) diff --git a/Modules/RSCore/Sources/RSCore/Shared/FileManager+RSCore.swift b/Modules/RSCore/Sources/RSCore/Shared/FileManager+RSCore.swift index f7d750f26..ceabd51b3 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/FileManager+RSCore.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/FileManager+RSCore.swift @@ -8,7 +8,7 @@ import Foundation -public extension FileManager { +nonisolated public extension FileManager { /// Returns whether a path refers to a folder. /// diff --git a/Modules/RSCore/Sources/RSCore/Shared/Geometry.swift b/Modules/RSCore/Sources/RSCore/Shared/Geometry.swift index b5805adaf..41d3db8b7 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/Geometry.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/Geometry.swift @@ -8,7 +8,7 @@ import Foundation #if os(macOS) -public extension CGRect { +nonisolated public extension CGRect { /// Centers a rectangle vertically in another rectangle. /// diff --git a/Modules/RSCore/Sources/RSCore/Shared/MacroProcessor.swift b/Modules/RSCore/Sources/RSCore/Shared/MacroProcessor.swift index 3fd33f026..dffe26260 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/MacroProcessor.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/MacroProcessor.swift @@ -54,7 +54,7 @@ nonisolated public final class MacroProcessor: Sendable { } -private extension MacroProcessor { +nonisolated private extension MacroProcessor { func processMacros() -> String { var result = String() diff --git a/Modules/RSCore/Sources/RSCore/Shared/NotificationCenter+RSCore.swift b/Modules/RSCore/Sources/RSCore/Shared/NotificationCenter+RSCore.swift index 48d68feed..570b67f41 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/NotificationCenter+RSCore.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/NotificationCenter+RSCore.swift @@ -7,11 +7,13 @@ import Foundation -public extension NotificationCenter { +nonisolated public extension NotificationCenter { func postOnMainThread(name: Notification.Name, object: Any?, userInfo: [AnyHashable : Any]? = nil) { + nonisolated(unsafe) let capturedObject = object + nonisolated(unsafe) let capturedUserInfo = userInfo Task { @MainActor in - NotificationCenter.default.post(name: name, object: object, userInfo: userInfo) + NotificationCenter.default.post(name: name, object: capturedObject, userInfo: capturedUserInfo) } } } diff --git a/Modules/RSCore/Sources/RSCore/Shared/OPMLRepresentable.swift b/Modules/RSCore/Sources/RSCore/Shared/OPMLRepresentable.swift index 046c78d3f..c63fd9a84 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/OPMLRepresentable.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/OPMLRepresentable.swift @@ -15,7 +15,7 @@ public protocol OPMLRepresentable { public extension OPMLRepresentable { - func OPMLString(indentLevel: Int) -> String { + @MainActor func OPMLString(indentLevel: Int) -> String { return OPMLString(indentLevel: indentLevel, allowCustomAttributes: false) } } diff --git a/Modules/RSCore/Sources/RSCore/Shared/Platform.swift b/Modules/RSCore/Sources/RSCore/Shared/Platform.swift index 396baac96..4ecb64ad7 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/Platform.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/Platform.swift @@ -11,14 +11,14 @@ import os public struct Platform { - private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "Platform") + nonisolated private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "Platform") /// Returns true if the app is currently running unit tests. - public static var isRunningUnitTests: Bool { + nonisolated public static var isRunningUnitTests: Bool { return _isRunningUnitTests } - private static let _isRunningUnitTests: Bool = { + nonisolated private static let _isRunningUnitTests: Bool = { func checkIfRunningUnitTests() -> Bool { // Check multiple indicators to be super-reliable diff --git a/Modules/RSCore/Sources/RSCore/Shared/RSImage.swift b/Modules/RSCore/Sources/RSCore/Shared/RSImage.swift index df01fd9c4..41988fb66 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/RSImage.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/RSImage.swift @@ -19,10 +19,10 @@ import UIKit public typealias RSImage = UIImage #endif -private let RSImageLogger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "RSImage") -private let debugLoggingEnabled = false +nonisolated private let RSImageLogger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "RSImage") +nonisolated private let debugLoggingEnabled = false -public extension RSImage { +nonisolated public extension RSImage { /// Create a colored image from the source image using a specified color. /// @@ -66,7 +66,7 @@ public extension RSImage { /// /// - Parameter color: The color to use to tint the image. /// - Returns: The tinted image. - func tinted(color: UIColor) -> UIImage? { + @MainActor func tinted(color: UIColor) -> UIImage? { let image = withRenderingMode(.alwaysTemplate) let imageView = UIImageView(image: image) imageView.tintColor = color diff --git a/Modules/RSCore/Sources/RSCore/Shared/RSScreen.swift b/Modules/RSCore/Sources/RSCore/Shared/RSScreen.swift index 0e1517703..772baa96f 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/RSScreen.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/RSScreen.swift @@ -11,7 +11,7 @@ import AppKit public final class RSScreen { - public static var maxScreenScale: CGFloat { + nonisolated public static var maxScreenScale: CGFloat { NSScreen.screens.map(\.backingScaleFactor).max() ?? 2.0 } } @@ -22,7 +22,7 @@ public final class RSScreen { import UIKit public final class RSScreen { - public static var maxScreenScale = CGFloat(3) + nonisolated public static let maxScreenScale = CGFloat(3) } #endif diff --git a/Modules/RSCore/Sources/RSCore/Shared/String+RSCore.swift b/Modules/RSCore/Sources/RSCore/Shared/String+RSCore.swift index fbb189088..58c7ebb6f 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/String+RSCore.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/String+RSCore.swift @@ -10,7 +10,7 @@ import Foundation import CommonCrypto import RSCoreObjC -public extension String { +nonisolated public extension String { func htmlByAddingLink(_ link: String, className: String? = nil) -> String { if let className = className { @@ -32,7 +32,7 @@ public extension String { } -public extension String { +nonisolated public extension String { /// An MD5 hash of the string's UTF-8 representation. var md5Hash: Data { diff --git a/Modules/RSWeb/Sources/RSWeb/DownloadSession.swift b/Modules/RSWeb/Sources/RSWeb/DownloadSession.swift index 094261659..27bd16739 100755 --- a/Modules/RSWeb/Sources/RSWeb/DownloadSession.swift +++ b/Modules/RSWeb/Sources/RSWeb/DownloadSession.swift @@ -13,7 +13,7 @@ import RSCore // Create a DownloadSessionDelegate, then create a DownloadSession. // To download things: call download with a set of URLs. DownloadSession will call the various delegate methods. -public protocol DownloadSessionDelegate { +@MainActor public protocol DownloadSessionDelegate { func downloadSession(_ downloadSession: DownloadSession, conditionalGetInfoFor: URL) -> HTTPConditionalGetInfo? func downloadSession(_ downloadSession: DownloadSession, downloadDidComplete: URL, response: URLResponse?, data: Data, error: NSError?) @@ -90,7 +90,7 @@ struct HTTP4xxResponse { } } - public func download(_ urls: Set) { + @MainActor public func download(_ urls: Set) { cleanUp4xxResponsesCache() let filteredURLs = Self.filteredURLs(urls) @@ -108,26 +108,27 @@ struct HTTP4xxResponse { extension DownloadSession: URLSessionTaskDelegate { public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { - - defer { - removeTask(task) - } - - guard let info = infoForTask(task) else { - if let url = task.originalRequest?.url { - Self.logger.debug("DownloadSession: no task info found for \(url)") - } else { - Self.logger.debug("DownloadSession: no task info found for unknown URL") + MainActor.assumeIsolated { + defer { + removeTask(task) } - return - } - if let url = task.originalRequest?.url, error == nil { - Self.logger.debug("DownloadSession: Caching response for \(url)") - cache.add(url.absoluteString, data: info.data as Data, response: info.urlResponse) - } + guard let info = infoForTask(task) else { + if let url = task.originalRequest?.url { + Self.logger.debug("DownloadSession: no task info found for \(url)") + } else { + Self.logger.debug("DownloadSession: no task info found for unknown URL") + } + return + } - delegate.downloadSession(self, downloadDidComplete: info.url, response: info.urlResponse, data: info.data as Data, error: error as NSError?) + if let url = task.originalRequest?.url, error == nil { + Self.logger.debug("DownloadSession: Caching response for \(url)") + cache.add(url.absoluteString, data: info.data as Data, response: info.urlResponse) + } + + delegate.downloadSession(self, downloadDidComplete: info.url, response: info.urlResponse, data: info.data as Data, error: error as NSError?) + } } private static let redirectStatusCodes = Set([HTTPResponseCode.redirectPermanent, HTTPResponseCode.redirectTemporary, HTTPResponseCode.redirectVeryTemporary, HTTPResponseCode.redirectPermanentPreservingMethod]) @@ -153,56 +154,58 @@ extension DownloadSession: URLSessionTaskDelegate { extension DownloadSession: URLSessionDataDelegate { public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { + MainActor.assumeIsolated { + defer { + updateDownloadProgress() + } - defer { - updateDownloadProgress() - } + tasksInProgress.insert(dataTask) + tasksPending.remove(dataTask) - tasksInProgress.insert(dataTask) - tasksPending.remove(dataTask) + let taskInfo = infoForTask(dataTask) + if let taskInfo { + taskInfo.urlResponse = response + } - let taskInfo = infoForTask(dataTask) - if let taskInfo { - taskInfo.urlResponse = response - } - - let statusCode = response.forcedStatusCode - if statusCode >= 400 { - if statusCode != HTTPResponseCode.tooManyRequests { - if let urlString = response.url?.absoluteString { - Self.logger.debug("DownloadSession: Caching >= 400 response for \(urlString)") - cache.add(urlString, data: nil, response: response) + let statusCode = response.forcedStatusCode + if statusCode >= 400 { + if statusCode != HTTPResponseCode.tooManyRequests { + if let urlString = response.url?.absoluteString { + Self.logger.debug("DownloadSession: Caching >= 400 response for \(urlString)") + cache.add(urlString, data: nil, response: response) + } } + + Self.logger.debug("DownloadSession: canceling task due to >= 400 response \(response)") + + completionHandler(.cancel) + removeTask(dataTask) + + if statusCode == HTTPResponseCode.tooManyRequests { + handle429Response(dataTask, response) + } else if (400...499).contains(statusCode), let url = response.url { + http4xxResponses[url] = HTTP4xxResponse(statusCode) + } + + return } - Self.logger.debug("DownloadSession: canceling task due to >= 400 response \(response)") - - completionHandler(.cancel) - removeTask(dataTask) - - if statusCode == HTTPResponseCode.tooManyRequests { - handle429Response(dataTask, response) - } else if (400...499).contains(statusCode), let url = response.url { - http4xxResponses[url] = HTTP4xxResponse(statusCode) - } - - return + addDataTaskFromQueueIfNecessary() + completionHandler(.allow) } - - addDataTaskFromQueueIfNecessary() - completionHandler(.allow) } public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { - - guard let info = infoForTask(dataTask) else { - return - } - info.addData(data) - - if !delegate.downloadSession(self, shouldContinueAfterReceivingData: info.data as Data, url: info.url) { - dataTask.cancel() - removeTask(dataTask) + MainActor.assumeIsolated { + guard let info = infoForTask(dataTask) else { + return + } + info.addData(data) + + if !delegate.downloadSession(self, shouldContinueAfterReceivingData: info.data as Data, url: info.url) { + dataTask.cancel() + removeTask(dataTask) + } } } } @@ -211,7 +214,7 @@ extension DownloadSession: URLSessionDataDelegate { private extension DownloadSession { - func addDataTask(_ url: URL) { + @MainActor func addDataTask(_ url: URL) { guard tasksPending.count < 500 else { queue.insert(url, at: 0) @@ -256,7 +259,7 @@ private extension DownloadSession { task.resume() } - func addDataTaskFromQueueIfNecessary() { + @MainActor func addDataTaskFromQueueIfNecessary() { guard tasksPending.count < 500, let url = queue.popLast() else { return } addDataTask(url) } @@ -265,7 +268,7 @@ private extension DownloadSession { return taskIdentifierToInfoDictionary[task.taskIdentifier] } - func removeTask(_ task: URLSessionTask) { + @MainActor func removeTask(_ task: URLSessionTask) { tasksInProgress.remove(task) tasksPending.remove(task) taskIdentifierToInfoDictionary[task.taskIdentifier] = nil @@ -332,7 +335,7 @@ private extension DownloadSession { // MARK: - Download Progress - func updateDownloadProgress() { + @MainActor func updateDownloadProgress() { downloadProgress.numberOfTasks = urlsInSession.count @@ -348,7 +351,7 @@ private extension DownloadSession { // MARK: - 429 Too Many Requests - func handle429Response(_ dataTask: URLSessionDataTask, _ response: URLResponse) { + @MainActor func handle429Response(_ dataTask: URLSessionDataTask, _ response: URLResponse) { guard let message = createHTTPResponse429(dataTask, response) else { return @@ -376,13 +379,13 @@ private extension DownloadSession { return HTTPResponse429(url: url, retryAfter: retryAfter) } - func cancelAndRemoveTasksWithHost(_ host: String) { + @MainActor func cancelAndRemoveTasksWithHost(_ host: String) { cancelAndRemoveTasksWithHost(host, in: tasksInProgress) cancelAndRemoveTasksWithHost(host, in: tasksPending) } - func cancelAndRemoveTasksWithHost(_ host: String, in tasks: Set) { + @MainActor func cancelAndRemoveTasksWithHost(_ host: String, in tasks: Set) { let lowercaseHost = host.lowercased(with: localeForLowercasing) diff --git a/Shared/Activity/ActivityManager.swift b/Shared/Activity/ActivityManager.swift index 172c806cb..1129512ac 100644 --- a/Shared/Activity/ActivityManager.swift +++ b/Shared/Activity/ActivityManager.swift @@ -15,7 +15,7 @@ import Articles import Intents import UniformTypeIdentifiers -final class ActivityManager { +@MainActor final class ActivityManager { private var nextUnreadActivity: NSUserActivity? private var selectingActivity: NSUserActivity? @@ -160,7 +160,7 @@ final class ActivityManager { // MARK: Private -private extension ActivityManager { +@MainActor private extension ActivityManager { func makeSelectFeedActivity(sidebarItem: SidebarItem) -> NSUserActivity { let activity = NSUserActivity(activityType: ActivityType.selectFeed.rawValue) diff --git a/Shared/Article Rendering/ArticleRenderer.swift b/Shared/Article Rendering/ArticleRenderer.swift index 29f21e56a..ca30a581d 100644 --- a/Shared/Article Rendering/ArticleRenderer.swift +++ b/Shared/Article Rendering/ArticleRenderer.swift @@ -14,7 +14,7 @@ import RSCore import Articles import Account -struct ArticleRenderer { +@MainActor struct ArticleRenderer { typealias Rendering = (style: String, html: String, title: String, baseURL: String) @@ -328,7 +328,7 @@ private extension ArticleRenderer { // MARK: - Article extension -private extension Article { +@MainActor private extension Article { var baseURL: URL? { var s = link diff --git a/Shared/Article Rendering/WebViewConfiguration.swift b/Shared/Article Rendering/WebViewConfiguration.swift index 9af763677..a59a615b1 100644 --- a/Shared/Article Rendering/WebViewConfiguration.swift +++ b/Shared/Article Rendering/WebViewConfiguration.swift @@ -11,7 +11,7 @@ import WebKit final class WebViewConfiguration { - static func configuration(with urlSchemeHandler: WKURLSchemeHandler) -> WKWebViewConfiguration { + @MainActor static func configuration(with urlSchemeHandler: WKURLSchemeHandler) -> WKWebViewConfiguration { assert(Thread.isMainThread) let configuration = WKWebViewConfiguration() diff --git a/Shared/Commands/DeleteCommand.swift b/Shared/Commands/DeleteCommand.swift index 655008626..841135b5f 100644 --- a/Shared/Commands/DeleteCommand.swift +++ b/Shared/Commands/DeleteCommand.swift @@ -94,7 +94,7 @@ final class DeleteCommand: UndoableCommand { // Remember as much as we can now about the items being deleted, // so they can be restored to the correct place. -private struct SidebarItemSpecifier { +@MainActor private struct SidebarItemSpecifier { private weak var account: Account? private let parentFolder: Folder? diff --git a/Shared/Commands/MarkStatusCommand.swift b/Shared/Commands/MarkStatusCommand.swift index a21a0c9fe..8ec7c4365 100644 --- a/Shared/Commands/MarkStatusCommand.swift +++ b/Shared/Commands/MarkStatusCommand.swift @@ -12,7 +12,7 @@ import Articles // Mark articles read/unread, starred/unstarred, deleted/undeleted. -final class MarkStatusCommand: UndoableCommand { +@MainActor final class MarkStatusCommand: UndoableCommand { let undoActionName: String let redoActionName: String @@ -61,7 +61,7 @@ final class MarkStatusCommand: UndoableCommand { } } -private extension MarkStatusCommand { +@MainActor private extension MarkStatusCommand { func mark(_ statusKey: ArticleStatus.Key, _ flag: Bool) { markArticles(articles, statusKey: statusKey, flag: flag, completion: completion) diff --git a/Shared/Exporters/OPMLExporter.swift b/Shared/Exporters/OPMLExporter.swift index 5cf027c9f..4c4405b85 100644 --- a/Shared/Exporters/OPMLExporter.swift +++ b/Shared/Exporters/OPMLExporter.swift @@ -10,7 +10,7 @@ import Foundation import Account import RSCore -struct OPMLExporter { +@MainActor struct OPMLExporter { static func OPMLString(with account: Account, title: String) -> String { diff --git a/Shared/ExtensionPoints/SendToMarsEditCommand.swift b/Shared/ExtensionPoints/SendToMarsEditCommand.swift index 19093a351..115752a68 100644 --- a/Shared/ExtensionPoints/SendToMarsEditCommand.swift +++ b/Shared/ExtensionPoints/SendToMarsEditCommand.swift @@ -10,7 +10,7 @@ import AppKit import RSCore import Articles -final class SendToMarsEditCommand: SendToCommand { +@MainActor final class SendToMarsEditCommand: SendToCommand { let title = "MarsEdit" let image: RSImage? = AppAssets.marsEditIcon diff --git a/Shared/ExtensionPoints/SendToMicroBlogCommand.swift b/Shared/ExtensionPoints/SendToMicroBlogCommand.swift index dbecdc77d..007f37265 100644 --- a/Shared/ExtensionPoints/SendToMicroBlogCommand.swift +++ b/Shared/ExtensionPoints/SendToMicroBlogCommand.swift @@ -12,7 +12,7 @@ import RSCore // Not undoable. -final class SendToMicroBlogCommand: SendToCommand { +@MainActor final class SendToMicroBlogCommand: SendToCommand { let title = "Micro.blog" let image: RSImage? = AppAssets.microblogIcon @@ -61,7 +61,7 @@ final class SendToMicroBlogCommand: SendToCommand { } } -private extension Article { +@MainActor private extension Article { var attributionString: String { diff --git a/Shared/Extensions/AddFeedDefaultContainer.swift b/Shared/Extensions/AddFeedDefaultContainer.swift index cd0c8abd6..8a962aac6 100644 --- a/Shared/Extensions/AddFeedDefaultContainer.swift +++ b/Shared/Extensions/AddFeedDefaultContainer.swift @@ -9,7 +9,7 @@ import Foundation import Account -struct AddFeedDefaultContainer { +@MainActor struct AddFeedDefaultContainer { static var defaultContainer: Container? { diff --git a/Shared/Extensions/ArticleStringFormatter.swift b/Shared/Extensions/ArticleStringFormatter.swift index 95ae5c3f3..1d68257cf 100644 --- a/Shared/Extensions/ArticleStringFormatter.swift +++ b/Shared/Extensions/ArticleStringFormatter.swift @@ -10,7 +10,7 @@ import Foundation import Articles import RSParser -struct ArticleStringFormatter { +@MainActor struct ArticleStringFormatter { private static var feedNameCache = [String: String]() private static var titleCache = [String: String]() diff --git a/Shared/Extensions/ArticleUtilities.swift b/Shared/Extensions/ArticleUtilities.swift index 79a3b4a21..d4631eb7d 100644 --- a/Shared/Extensions/ArticleUtilities.swift +++ b/Shared/Extensions/ArticleUtilities.swift @@ -13,7 +13,7 @@ import Account // These handle multiple accounts. -func markArticles(_ articles: Set
, statusKey: ArticleStatus.Key, flag: Bool, completion: (() -> Void)? = nil) { +@MainActor func markArticles(_ articles: Set
, statusKey: ArticleStatus.Key, flag: Bool, completion: (() -> Void)? = nil) { let d: [String: Set
] = accountAndArticlesDictionary(articles) @@ -40,7 +40,7 @@ private func accountAndArticlesDictionary(_ articles: Set
) -> [String: return d.mapValues{ Set($0) } } -extension Article { +@MainActor extension Article { var feed: Feed? { return account?.existingFeed(withFeedID: feedID) @@ -193,7 +193,7 @@ struct ArticlePathKey { static let articleID = "articleID" } -extension Article { +@MainActor extension Article { public var pathUserInfo: [AnyHashable : Any] { return [ @@ -208,7 +208,7 @@ extension Article { // MARK: SortableArticle -extension Article: SortableArticle { +@MainActor extension Article: SortableArticle { var sortableName: String { return feed?.name ?? "" diff --git a/Shared/Extensions/SmallIconProvider.swift b/Shared/Extensions/SmallIconProvider.swift index 4a2c0dff8..182af18d9 100644 --- a/Shared/Extensions/SmallIconProvider.swift +++ b/Shared/Extensions/SmallIconProvider.swift @@ -13,10 +13,10 @@ import RSCore protocol SmallIconProvider { - var smallIcon: IconImage? { get } + @MainActor var smallIcon: IconImage? { get } } -extension Account: SmallIconProvider { +@MainActor extension Account: SmallIconProvider { var smallIcon: IconImage? { if let image = AppAssets.image(for: type) { return IconImage(image) @@ -25,7 +25,7 @@ extension Account: SmallIconProvider { } } -extension Feed: SmallIconProvider { +@MainActor extension Feed: SmallIconProvider { var smallIcon: IconImage? { if let iconImage = FaviconDownloader.shared.favicon(for: self) { @@ -35,7 +35,7 @@ extension Feed: SmallIconProvider { } } -extension Folder: SmallIconProvider { +@MainActor extension Folder: SmallIconProvider { var smallIcon: IconImage? { AppAssets.mainFolderImage } diff --git a/Shared/Favicons/FaviconDownloader.swift b/Shared/Favicons/FaviconDownloader.swift index cce0a3a83..25eb83ae8 100644 --- a/Shared/Favicons/FaviconDownloader.swift +++ b/Shared/Favicons/FaviconDownloader.swift @@ -20,7 +20,7 @@ extension Notification.Name { static let FaviconDidBecomeAvailable = Notification.Name("FaviconDidBecomeAvailableNotification") // userInfo key: FaviconDownloader.UserInfoKey.faviconURL } -final class FaviconDownloader { +@MainActor final class FaviconDownloader { static let shared = FaviconDownloader() private static let saveQueue = CoalescingQueue(name: "Cache Save Queue", interval: 1.0) diff --git a/Shared/Favicons/FaviconGenerator.swift b/Shared/Favicons/FaviconGenerator.swift index 6c3cacb68..5ab09d90c 100644 --- a/Shared/Favicons/FaviconGenerator.swift +++ b/Shared/Favicons/FaviconGenerator.swift @@ -10,7 +10,7 @@ import Foundation import RSCore import Account -final class FaviconGenerator { +@MainActor final class FaviconGenerator { private static var faviconGeneratorCache = [String: IconImage]() // feedURL: RSImage diff --git a/Shared/Favicons/SingleFaviconDownloader.swift b/Shared/Favicons/SingleFaviconDownloader.swift index 8ebc6b127..92c1f67a8 100644 --- a/Shared/Favicons/SingleFaviconDownloader.swift +++ b/Shared/Favicons/SingleFaviconDownloader.swift @@ -98,7 +98,7 @@ private extension SingleFaviconDownloader { } } - func readFromDisk(_ completion: @escaping (RSImage?) -> Void) { + func readFromDisk(_ completion: @escaping @Sendable (RSImage?) -> Void) { guard diskStatus != .notOnDisk else { completion(nil) @@ -132,7 +132,7 @@ private extension SingleFaviconDownloader { } } - func downloadFavicon(_ completion: @escaping (RSImage?) -> Void) { + func downloadFavicon(_ completion: @escaping @Sendable (RSImage?) -> Void) { guard let url = URL(string: faviconURL) else { completion(nil) diff --git a/Shared/IconImageCache.swift b/Shared/IconImageCache.swift index 9f1370fe2..03ed959b7 100644 --- a/Shared/IconImageCache.swift +++ b/Shared/IconImageCache.swift @@ -10,7 +10,7 @@ import Foundation import Account import Articles -final class IconImageCache { +@MainActor final class IconImageCache { static var shared = IconImageCache() diff --git a/Shared/Images/AuthorAvatarDownloader.swift b/Shared/Images/AuthorAvatarDownloader.swift index 6caf8ce12..41334d42d 100644 --- a/Shared/Images/AuthorAvatarDownloader.swift +++ b/Shared/Images/AuthorAvatarDownloader.swift @@ -15,7 +15,7 @@ extension Notification.Name { static let AvatarDidBecomeAvailable = Notification.Name("AvatarDidBecomeAvailableNotification") // UserInfoKey.imageURL (which is an avatarURL) } -final class AuthorAvatarDownloader { +@MainActor final class AuthorAvatarDownloader { public static let shared = AuthorAvatarDownloader() @@ -66,12 +66,14 @@ final class AuthorAvatarDownloader { } } -private extension AuthorAvatarDownloader { +@MainActor private extension AuthorAvatarDownloader { func scaleAndCacheImageData(_ imageData: Data, _ avatarURL: String) { RSImage.scaledForIcon(imageData) { (image) in - if let image = image { - self.handleImageDidBecomeAvailable(avatarURL, image) + MainActor.assumeIsolated { + if let image { + self.handleImageDidBecomeAvailable(avatarURL, image) + } } } } diff --git a/Shared/Images/FeedIconDownloader.swift b/Shared/Images/FeedIconDownloader.swift index 84c4a1dde..b12543691 100644 --- a/Shared/Images/FeedIconDownloader.swift +++ b/Shared/Images/FeedIconDownloader.swift @@ -17,7 +17,7 @@ extension Notification.Name { static let feedIconDidBecomeAvailable = Notification.Name("FeedIconDidBecomeAvailable") // UserInfoKey.feed } -public final class FeedIconDownloader { +@MainActor public final class FeedIconDownloader { public static let shared = FeedIconDownloader() @@ -57,7 +57,7 @@ public final class FeedIconDownloader { return nil } - func checkHomePageURL() { + @MainActor func checkHomePageURL() { guard let homePageURL = feed.homePageURL else { return } @@ -73,15 +73,17 @@ public final class FeedIconDownloader { } } - func checkFeedIconURL() { + @MainActor func checkFeedIconURL() { if let iconURL = feed.iconURL { icon(forURL: iconURL, feed: feed) { (image) in - if let image = image { - self.cache[feed] = IconImage(image) - self.cacheIconURLForFeedURL(iconURL: iconURL, feedURL: feed.url) - self.postFeedIconDidBecomeAvailableNotification(feed) - } else { - checkHomePageURL() + MainActor.assumeIsolated { + if let image = image { + self.cache[feed] = IconImage(image) + self.cacheIconURLForFeedURL(iconURL: iconURL, feedURL: feed.url) + self.postFeedIconDidBecomeAvailableNotification(feed) + } else { + checkHomePageURL() + } } } } else { @@ -91,9 +93,11 @@ public final class FeedIconDownloader { if let previouslyFoundIconURL = feedURLToIconURLCache[feed.url] { icon(forURL: previouslyFoundIconURL, feed: feed) { image in - if let image { - self.postFeedIconDidBecomeAvailableNotification(feed) - self.cache[feed] = IconImage(image) + MainActor.assumeIsolated { + if let image { + self.postFeedIconDidBecomeAvailableNotification(feed) + self.cache[feed] = IconImage(image) + } } } @@ -154,7 +158,7 @@ private extension FeedIconDownloader { resultBlock(nil, nil) } - func icon(forURL url: String, feed: Feed, _ imageResultBlock: @escaping (RSImage?) -> Void) { + func icon(forURL url: String, feed: Feed, _ imageResultBlock: @escaping @Sendable (RSImage?) -> Void) { waitingForFeedURLs[url] = feed guard let imageData = imageDownloader.image(for: url) else { diff --git a/Shared/Images/ImageDownloader.swift b/Shared/Images/ImageDownloader.swift index 8482c15ec..f1a0d09cf 100644 --- a/Shared/Images/ImageDownloader.swift +++ b/Shared/Images/ImageDownloader.swift @@ -16,12 +16,12 @@ extension Notification.Name { static let imageDidBecomeAvailable = Notification.Name("ImageDidBecomeAvailableNotification") // UserInfoKey.url } -final class ImageDownloader { +@MainActor final class ImageDownloader { public static let shared = ImageDownloader() static private let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "ImageDownloader") - private var diskCache: BinaryDiskCache + nonisolated private let diskCache: BinaryDiskCache private let queue: DispatchQueue private var imageCache = [String: Data]() // url: image private var urlsInProgress = Set() @@ -122,7 +122,7 @@ private extension ImageDownloader { } } - func diskKey(_ url: String) -> String { + nonisolated func diskKey(_ url: String) -> String { url.md5String } diff --git a/Shared/Importers/DefaultFeedsImporter.swift b/Shared/Importers/DefaultFeedsImporter.swift index afccbf301..46dfd31df 100644 --- a/Shared/Importers/DefaultFeedsImporter.swift +++ b/Shared/Importers/DefaultFeedsImporter.swift @@ -10,7 +10,7 @@ import Foundation import Account import RSCore -struct DefaultFeedsImporter { +@MainActor struct DefaultFeedsImporter { static func importDefaultFeeds(account: Account) { let defaultFeedsURL = Bundle.main.url(forResource: "DefaultFeeds", withExtension: "opml")! diff --git a/Shared/ShareExtension/ExtensionContainers.swift b/Shared/ShareExtension/ExtensionContainers.swift index 641c02c68..f2c792243 100644 --- a/Shared/ShareExtension/ExtensionContainers.swift +++ b/Shared/ShareExtension/ExtensionContainers.swift @@ -55,7 +55,7 @@ struct ExtensionAccount: ExtensionContainer { let containerID: ContainerIdentifier? let folders: [ExtensionFolder] - init(account: Account) { + @MainActor init(account: Account) { self.name = account.nameForDisplay self.accountID = account.accountID self.type = account.type @@ -64,6 +64,26 @@ struct ExtensionAccount: ExtensionContainer { self.folders = account.sortedFolders?.map { ExtensionFolder(folder: $0) } ?? [ExtensionFolder]() } + nonisolated init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.name = try container.decode(String.self, forKey: .name) + self.accountID = try container.decode(String.self, forKey: .accountID) + self.type = try container.decode(AccountType.self, forKey: .type) + self.disallowFeedInRootFolder = try container.decode(Bool.self, forKey: .disallowFeedInRootFolder) + self.containerID = try container.decodeIfPresent(ContainerIdentifier.self, forKey: .containerID) + self.folders = try container.decode([ExtensionFolder].self, forKey: .folders) + } + + nonisolated func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + try container.encode(accountID, forKey: .accountID) + try container.encode(type, forKey: .type) + try container.encode(disallowFeedInRootFolder, forKey: .disallowFeedInRootFolder) + try container.encodeIfPresent(containerID, forKey: .containerID) + try container.encode(folders, forKey: .folders) + } + func findFolder(forName name: String) -> ExtensionFolder? { return folders.first(where: { $0.name == name }) } @@ -84,7 +104,7 @@ struct ExtensionFolder: ExtensionContainer { let name: String let containerID: ContainerIdentifier? - init(folder: Folder) { + @MainActor init(folder: Folder) { self.accountName = folder.account?.nameForDisplay ?? "" self.accountID = folder.account?.accountID ?? "" self.name = folder.nameForDisplay diff --git a/Shared/ShareExtension/ExtensionContainersFile.swift b/Shared/ShareExtension/ExtensionContainersFile.swift index c27ee667e..db0d13682 100644 --- a/Shared/ShareExtension/ExtensionContainersFile.swift +++ b/Shared/ShareExtension/ExtensionContainersFile.swift @@ -12,7 +12,7 @@ import RSCore import RSParser import Account -final class ExtensionContainersFile { +@MainActor final class ExtensionContainersFile { static let shared = ExtensionContainersFile() static private let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "ExtensionContainersFile") @@ -71,7 +71,7 @@ final class ExtensionContainersFile { } -private extension ExtensionContainersFile { +@MainActor private extension ExtensionContainersFile { @objc func markAsDirty() { isDirty = true diff --git a/Shared/ShareExtension/ExtensionFeedAddRequestFile.swift b/Shared/ShareExtension/ExtensionFeedAddRequestFile.swift index 27b3104dd..6bf002dd4 100644 --- a/Shared/ShareExtension/ExtensionFeedAddRequestFile.swift +++ b/Shared/ShareExtension/ExtensionFeedAddRequestFile.swift @@ -45,19 +45,23 @@ final class ExtensionFeedAddRequestFile: NSObject, NSFilePresenter { isActive = true NSFileCoordinator.addFilePresenter(self) - process() + Task { @MainActor in + process() + } } func presentedItemDidChange() { - DispatchQueue.main.async { - self.process() + Task { @MainActor in + process() } } func resume() { assert(isActive) NSFileCoordinator.addFilePresenter(self) - process() + Task { @MainActor in + process() + } } func suspend() { @@ -102,7 +106,7 @@ final class ExtensionFeedAddRequestFile: NSObject, NSFilePresenter { } } -private extension ExtensionFeedAddRequestFile { +@MainActor private extension ExtensionFeedAddRequestFile { func process() { diff --git a/Shared/ShareExtension/ShareDefaultContainer.swift b/Shared/ShareExtension/ShareDefaultContainer.swift index aabbe0c6e..3965b3f60 100644 --- a/Shared/ShareExtension/ShareDefaultContainer.swift +++ b/Shared/ShareExtension/ShareDefaultContainer.swift @@ -8,7 +8,7 @@ import Foundation -struct ShareDefaultContainer { +@MainActor struct ShareDefaultContainer { static func defaultContainer(containers: ExtensionContainers) -> ExtensionContainer? { diff --git a/Shared/SmartFeeds/SmartFeedDelegate.swift b/Shared/SmartFeeds/SmartFeedDelegate.swift index 7f37a2ae6..72c173b5a 100644 --- a/Shared/SmartFeeds/SmartFeedDelegate.swift +++ b/Shared/SmartFeeds/SmartFeedDelegate.swift @@ -12,12 +12,12 @@ import Articles import ArticlesDatabase import RSCore -protocol SmartFeedDelegate: SidebarItemIdentifiable, DisplayNameProvider, ArticleFetcher, SmallIconProvider { +@MainActor protocol SmartFeedDelegate: SidebarItemIdentifiable, DisplayNameProvider, ArticleFetcher, SmallIconProvider { var fetchType: FetchType { get } func fetchUnreadCount(for: Account, completion: @escaping SingleUnreadCountCompletionBlock) } -extension SmartFeedDelegate { +@MainActor extension SmartFeedDelegate { func fetchArticles() throws -> Set
{ return try AccountManager.shared.fetchArticles(fetchType) diff --git a/Shared/SmartFeeds/SmartFeedPasteboardWriter.swift b/Shared/SmartFeeds/SmartFeedPasteboardWriter.swift index 139f120d9..ba7d61808 100644 --- a/Shared/SmartFeeds/SmartFeedPasteboardWriter.swift +++ b/Shared/SmartFeeds/SmartFeedPasteboardWriter.swift @@ -10,7 +10,7 @@ import AppKit import Account import RSCore -@objc final class SmartFeedPasteboardWriter: NSObject, NSPasteboardWriting { +@MainActor @objc final class SmartFeedPasteboardWriter: NSObject, @MainActor NSPasteboardWriting { private let smartFeed: PseudoFeed diff --git a/Shared/SmartFeeds/SmartFeedsController.swift b/Shared/SmartFeeds/SmartFeedsController.swift index fb578f117..da9902ee3 100644 --- a/Shared/SmartFeeds/SmartFeedsController.swift +++ b/Shared/SmartFeeds/SmartFeedsController.swift @@ -10,11 +10,8 @@ import Foundation import RSCore import Account -final class SmartFeedsController: DisplayNameProvider, ContainerIdentifiable { - - var containerID: ContainerIdentifier? { - return ContainerIdentifier.smartFeedController - } +@MainActor final class SmartFeedsController: DisplayNameProvider, ContainerIdentifiable { + nonisolated let containerID: ContainerIdentifier? = ContainerIdentifier.smartFeedController public static let shared = SmartFeedsController() let nameForDisplay = NSLocalizedString("Smart Feeds", comment: "Smart Feeds group title") diff --git a/Shared/SmartFeeds/StarredFeedDelegate.swift b/Shared/SmartFeeds/StarredFeedDelegate.swift index 1eae46c08..569233d04 100644 --- a/Shared/SmartFeeds/StarredFeedDelegate.swift +++ b/Shared/SmartFeeds/StarredFeedDelegate.swift @@ -12,9 +12,7 @@ import Articles import ArticlesDatabase import Account -// Main thread only. - -struct StarredFeedDelegate: SmartFeedDelegate { +@MainActor struct StarredFeedDelegate: SmartFeedDelegate { var sidebarItemID: SidebarItemIdentifier? { return SidebarItemIdentifier.smartFeed(String(describing: StarredFeedDelegate.self)) diff --git a/Shared/Timeline/ArticleArray.swift b/Shared/Timeline/ArticleArray.swift index 802db632f..3d31fb065 100644 --- a/Shared/Timeline/ArticleArray.swift +++ b/Shared/Timeline/ArticleArray.swift @@ -11,7 +11,7 @@ import Articles typealias ArticleArray = [Article] -extension Array where Element == Article { +@MainActor extension Array where Element == Article { func articleAtRow(_ row: Int) -> Article? { if row < 0 || row == NSNotFound || row > count - 1 { diff --git a/Shared/Timeline/ArticleSorter.swift b/Shared/Timeline/ArticleSorter.swift index 2561ddc4c..9eefd698d 100644 --- a/Shared/Timeline/ArticleSorter.swift +++ b/Shared/Timeline/ArticleSorter.swift @@ -9,14 +9,14 @@ import Articles import Foundation -protocol SortableArticle { +@MainActor protocol SortableArticle { var sortableName: String { get } var sortableDate: Date { get } var sortableArticleID: String { get } var sortableFeedID: String { get } } -struct ArticleSorter { +@MainActor struct ArticleSorter { static func sortedByDate(articles: [T], sortDirection: ComparisonResult, diff --git a/Shared/Timeline/FetchRequestOperation.swift b/Shared/Timeline/FetchRequestOperation.swift index 95dae355d..f0864140e 100644 --- a/Shared/Timeline/FetchRequestOperation.swift +++ b/Shared/Timeline/FetchRequestOperation.swift @@ -16,7 +16,7 @@ import Articles typealias FetchRequestOperationResultBlock = (Set
, FetchRequestOperation) -> Void -final class FetchRequestOperation { +@MainActor final class FetchRequestOperation { let id: Int let readFilterEnabledTable: [SidebarItemIdentifier: Bool] diff --git a/Shared/Timeline/FetchRequestQueue.swift b/Shared/Timeline/FetchRequestQueue.swift index fcdf70c72..490df649c 100644 --- a/Shared/Timeline/FetchRequestQueue.swift +++ b/Shared/Timeline/FetchRequestQueue.swift @@ -8,10 +8,7 @@ import Foundation -// Main thread only. - -final class FetchRequestQueue { - +@MainActor final class FetchRequestQueue { private var pendingRequests = [FetchRequestOperation]() private var currentRequest: FetchRequestOperation? = nil diff --git a/Shared/Timer/AccountRefreshTimer.swift b/Shared/Timer/AccountRefreshTimer.swift index c642a37ae..5cfecd112 100644 --- a/Shared/Timer/AccountRefreshTimer.swift +++ b/Shared/Timer/AccountRefreshTimer.swift @@ -9,7 +9,7 @@ import Foundation import Account -final class AccountRefreshTimer { +@MainActor final class AccountRefreshTimer { var shuttingDown = false diff --git a/Shared/Timer/ArticleStatusSyncTimer.swift b/Shared/Timer/ArticleStatusSyncTimer.swift index e3de07200..f6b94aebb 100644 --- a/Shared/Timer/ArticleStatusSyncTimer.swift +++ b/Shared/Timer/ArticleStatusSyncTimer.swift @@ -9,7 +9,7 @@ import Foundation import Account -final class ArticleStatusSyncTimer { +@MainActor final class ArticleStatusSyncTimer { static let shared = ArticleStatusSyncTimer() private static let intervalSeconds = Double(120) diff --git a/Shared/UserNotifications/UserNotificationManager.swift b/Shared/UserNotifications/UserNotificationManager.swift index 436c27471..385262a53 100644 --- a/Shared/UserNotifications/UserNotificationManager.swift +++ b/Shared/UserNotifications/UserNotificationManager.swift @@ -11,7 +11,7 @@ import Account import Articles import UserNotifications -final class UserNotificationManager { +@MainActor final class UserNotificationManager { static let shared = UserNotificationManager() static private let notificationCategory = "NEW_ARTICLE_NOTIFICATION_CATEGORY" diff --git a/Shared/Widget/WidgetDataEncoder.swift b/Shared/Widget/WidgetDataEncoder.swift index 17c1c3210..116276832 100644 --- a/Shared/Widget/WidgetDataEncoder.swift +++ b/Shared/Widget/WidgetDataEncoder.swift @@ -67,7 +67,7 @@ public final class WidgetDataEncoder { } @available(iOS 14, *) - private func encodeWidgetData(completion: @escaping (WidgetData?) -> Void) { + @MainActor private func encodeWidgetData(completion: @escaping (WidgetData?) -> Void) { let dispatchGroup = DispatchGroup() var groupError: Error? = nil diff --git a/Tests/NetNewsWireTests/ArticleSorterTests.swift b/Tests/NetNewsWireTests/ArticleSorterTests.swift index 9bcd12b76..8987badef 100644 --- a/Tests/NetNewsWireTests/ArticleSorterTests.swift +++ b/Tests/NetNewsWireTests/ArticleSorterTests.swift @@ -12,7 +12,7 @@ import XCTest @testable import NetNewsWire -final class ArticleSorterTests: XCTestCase { +@MainActor final class ArticleSorterTests: XCTestCase { // MARK: sortByDate ascending tests diff --git a/Tests/NetNewsWireTests/SharingTests.swift b/Tests/NetNewsWireTests/SharingTests.swift index 371838462..c1fdbb69b 100644 --- a/Tests/NetNewsWireTests/SharingTests.swift +++ b/Tests/NetNewsWireTests/SharingTests.swift @@ -11,7 +11,7 @@ import XCTest @testable import NetNewsWire -final class SharingTests: XCTestCase { +@MainActor final class SharingTests: XCTestCase { func testSharingSubject() { let sharingServiceDelegate = SharingServiceDelegate(nil) diff --git a/iOS/AppAssets.swift b/iOS/AppAssets.swift index 6b1b8612a..c103bef0f 100644 --- a/iOS/AppAssets.swift +++ b/iOS/AppAssets.swift @@ -65,7 +65,7 @@ struct AppAssets { return UIImage(systemName: "doc.plaintext")! }() - static var articleExtractorOffTinted: UIImage = { + @MainActor static var articleExtractorOffTinted: UIImage = { let image = UIImage(named: "articleExtractorOff")! return image.tinted(color: AppAssets.primaryAccentColor)! }() @@ -78,7 +78,7 @@ struct AppAssets { return UIImage(named: "articleExtractorOnSF")! }() - static var articleExtractorOnTinted: UIImage = { + @MainActor static var articleExtractorOnTinted: UIImage = { let image = UIImage(named: "articleExtractorOn")! return image.tinted(color: AppAssets.primaryAccentColor)! }() diff --git a/iOS/MainTimeline/Cells/MainTimelineCellData.swift b/iOS/MainTimeline/Cells/MainTimelineCellData.swift index 2a151eefa..6a4fbf63f 100644 --- a/iOS/MainTimeline/Cells/MainTimelineCellData.swift +++ b/iOS/MainTimeline/Cells/MainTimelineCellData.swift @@ -9,7 +9,7 @@ import UIKit import Articles -struct MainTimelineCellData { +@MainActor struct MainTimelineCellData { private static let noText = NSLocalizedString("(No Text)", comment: "No Text") diff --git a/iOS/UIKit Extensions/UIViewController-Extensions.swift b/iOS/UIKit Extensions/UIViewController-Extensions.swift index 9402e665d..f6a853188 100644 --- a/iOS/UIKit Extensions/UIViewController-Extensions.swift +++ b/iOS/UIKit Extensions/UIViewController-Extensions.swift @@ -66,7 +66,8 @@ private extension UIViewController { let title = NSLocalizedString("Account Error", comment: "Account Error") let alertController = UIAlertController(title: title, message: error.localizedDescription, preferredStyle: .alert) - if error.account?.type == .feedbin { + let account = AccountError.account(from: error) + if account?.type == .feedbin { let credentialsTitle = NSLocalizedString("Update Credentials", comment: "Update Credentials") let credentialsAction = UIAlertAction(title: credentialsTitle, style: .default) { [weak self] _ in @@ -75,7 +76,7 @@ private extension UIViewController { let navController = UIStoryboard.account.instantiateViewController(withIdentifier: "FeedbinAccountNavigationViewController") as! UINavigationController navController.modalPresentationStyle = .formSheet let addViewController = navController.topViewController as! FeedbinAccountViewController - addViewController.account = error.account + addViewController.account = account self?.present(navController, animated: true) }