From 653789b913d9be501ceb55518283bf6db32fdd49 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Tue, 18 Nov 2025 10:00:50 -0800 Subject: [PATCH 01/14] Use Swift 6.2 with the app. Fix some concurrency issues. --- Mac/CrashReporter/CrashReporter.swift | 2 +- .../FeedInspectorViewController.swift | 38 +++++++++++-------- Mac/Inspector/InspectorWindowController.swift | 2 +- .../Detail/DetailWebViewController.swift | 2 +- ....swift => MainWindowKeyboardHandler.swift} | 7 +--- .../AppKit/KeyboardDelegateProtocol.swift | 4 +- xcconfig/NetNewsWire_project.xcconfig | 3 +- 7 files changed, 31 insertions(+), 27 deletions(-) rename Mac/MainWindow/Keyboard/{MainWIndowKeyboardHandler.swift => MainWindowKeyboardHandler.swift} (88%) diff --git a/Mac/CrashReporter/CrashReporter.swift b/Mac/CrashReporter/CrashReporter.swift index ba78f3e7f..8ba518ad5 100644 --- a/Mac/CrashReporter/CrashReporter.swift +++ b/Mac/CrashReporter/CrashReporter.swift @@ -17,7 +17,7 @@ import CrashReporter // At some point this code should probably move into RSCore, so Rainier and any other // future apps can use it. -struct CrashReporter { +@MainActor struct CrashReporter { struct DefaultsKey { static let sendCrashLogsAutomaticallyKey = "SendCrashLogsAutomatically" diff --git a/Mac/Inspector/FeedInspectorViewController.swift b/Mac/Inspector/FeedInspectorViewController.swift index 8731bb392..7e8c73a7c 100644 --- a/Mac/Inspector/FeedInspectorViewController.swift +++ b/Mac/Inspector/FeedInspectorViewController.swift @@ -7,9 +7,10 @@ // import AppKit +import UserNotifications +import Synchronization import Articles import Account -import UserNotifications final class FeedInspectorViewController: NSViewController, Inspector { @@ -28,7 +29,7 @@ final class FeedInspectorViewController: NSViewController, Inspector { } } - private var userNotificationSettings: UNNotificationSettings? + private var authorizationStatus: UNAuthorizationStatus? // MARK: Inspector @@ -63,7 +64,7 @@ final class FeedInspectorViewController: NSViewController, Inspector { // MARK: Actions @IBAction func isNotifyAboutNewArticlesChanged(_ sender: Any) { - guard userNotificationSettings != nil else { + guard authorizationStatus != nil else { DispatchQueue.main.async { self.isNotifyAboutNewArticlesCheckBox.setNextState() } @@ -71,7 +72,9 @@ final class FeedInspectorViewController: NSViewController, Inspector { } UNUserNotificationCenter.current().getNotificationSettings { (settings) in - self.updateNotificationSettings() + Task { @MainActor in + self.updateNotificationSettings() + } if settings.authorizationStatus == .denied { DispatchQueue.main.async { @@ -84,15 +87,17 @@ final class FeedInspectorViewController: NSViewController, Inspector { } } else { UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert]) { (granted, error) in - self.updateNotificationSettings() - if granted { - DispatchQueue.main.async { - self.feed?.isNotifyAboutNewArticles = (self.isNotifyAboutNewArticlesCheckBox?.state ?? .off) == .on ? true : false - NSApplication.shared.registerForRemoteNotifications() - } - } else { - DispatchQueue.main.async { - self.isNotifyAboutNewArticlesCheckBox.setNextState() + Task { @MainActor in + self.updateNotificationSettings() + if granted { + DispatchQueue.main.async { + self.feed?.isNotifyAboutNewArticles = (self.isNotifyAboutNewArticlesCheckBox?.state ?? .off) == .on ? true : false + NSApplication.shared.registerForRemoteNotifications() + } + } else { + DispatchQueue.main.async { + self.isNotifyAboutNewArticlesCheckBox.setNextState() + } } } } @@ -180,9 +185,10 @@ private extension FeedInspectorViewController { func updateNotificationSettings() { UNUserNotificationCenter.current().getNotificationSettings { (settings) in - self.userNotificationSettings = settings - if settings.authorizationStatus == .authorized { - DispatchQueue.main.async { + let authorizationStatus = settings.authorizationStatus + Task { @MainActor in + self.authorizationStatus = authorizationStatus + if self.authorizationStatus == .authorized { NSApplication.shared.registerForRemoteNotifications() } } diff --git a/Mac/Inspector/InspectorWindowController.swift b/Mac/Inspector/InspectorWindowController.swift index c8c5c4434..35ca11ebf 100644 --- a/Mac/Inspector/InspectorWindowController.swift +++ b/Mac/Inspector/InspectorWindowController.swift @@ -8,7 +8,7 @@ import AppKit -protocol Inspector: AnyObject { +@MainActor protocol Inspector: AnyObject { var objects: [Any]? { get set } var isFallbackInspector: Bool { get } // Can handle nothing-to-inspect or unexpected type of objects. diff --git a/Mac/MainWindow/Detail/DetailWebViewController.swift b/Mac/MainWindow/Detail/DetailWebViewController.swift index db4f15790..5fd87b419 100644 --- a/Mac/MainWindow/Detail/DetailWebViewController.swift +++ b/Mac/MainWindow/Detail/DetailWebViewController.swift @@ -12,7 +12,7 @@ import RSCore import RSWeb import Articles -protocol DetailWebViewControllerDelegate: AnyObject { +@MainActor protocol DetailWebViewControllerDelegate: AnyObject { func mouseDidEnter(_: DetailWebViewController, link: String) func mouseDidExit(_: DetailWebViewController) } diff --git a/Mac/MainWindow/Keyboard/MainWIndowKeyboardHandler.swift b/Mac/MainWindow/Keyboard/MainWindowKeyboardHandler.swift similarity index 88% rename from Mac/MainWindow/Keyboard/MainWIndowKeyboardHandler.swift rename to Mac/MainWindow/Keyboard/MainWindowKeyboardHandler.swift index 04483edca..0b781a7d9 100644 --- a/Mac/MainWindow/Keyboard/MainWIndowKeyboardHandler.swift +++ b/Mac/MainWindow/Keyboard/MainWindowKeyboardHandler.swift @@ -1,5 +1,5 @@ // -// MainWIndowKeyboardHandler.swift +// MainWindowKeyboardHandler.swift // NetNewsWire // // Created by Brent Simmons on 12/19/17. @@ -9,13 +9,11 @@ import AppKit import RSCore -final class MainWindowKeyboardHandler: KeyboardDelegate { - +@MainActor final class MainWindowKeyboardHandler: KeyboardDelegate { static let shared = MainWindowKeyboardHandler() let globalShortcuts: Set init() { - let f = Bundle.main.path(forResource: "GlobalKeyboardShortcuts", ofType: "plist")! let rawShortcuts = NSArray(contentsOfFile: f)! as! [[String: Any]] @@ -23,7 +21,6 @@ final class MainWindowKeyboardHandler: KeyboardDelegate { } func keydown(_ event: NSEvent, in view: NSView) -> Bool { - let key = KeyboardKey(with: event) guard let matchingShortcut = KeyboardShortcut.findMatchingShortcut(in: globalShortcuts, key: key) else { return false diff --git a/Modules/RSCore/Sources/RSCore/AppKit/KeyboardDelegateProtocol.swift b/Modules/RSCore/Sources/RSCore/AppKit/KeyboardDelegateProtocol.swift index c97676f8f..5bf60bf40 100644 --- a/Modules/RSCore/Sources/RSCore/AppKit/KeyboardDelegateProtocol.swift +++ b/Modules/RSCore/Sources/RSCore/AppKit/KeyboardDelegateProtocol.swift @@ -9,8 +9,8 @@ #if os(macOS) import AppKit -@objc public protocol KeyboardDelegate: AnyObject { +@MainActor @objc public protocol KeyboardDelegate: AnyObject { // Return true if handled. - @MainActor func keydown(_: NSEvent, in view: NSView) -> Bool + func keydown(_: NSEvent, in view: NSView) -> Bool } #endif diff --git a/xcconfig/NetNewsWire_project.xcconfig b/xcconfig/NetNewsWire_project.xcconfig index 5c8b92c38..70fc6fe66 100644 --- a/xcconfig/NetNewsWire_project.xcconfig +++ b/xcconfig/NetNewsWire_project.xcconfig @@ -51,8 +51,9 @@ IPHONEOS_DEPLOYMENT_TARGET = 26.0 //SDKROOT = macosx SWIFT_EMIT_LOC_STRINGS = YES SWIFT_SWIFT3_OBJC_INFERENCE = Off -SWIFT_VERSION = 5.10 +SWIFT_VERSION = 6.2 SWIFT_TREAT_WARNINGS_AS_ERRORS = YES +OTHER_SWIFT_FLAGS = $(inherited) -enable-upcoming-feature NonisolatedNonsendingByDefault -enable-upcoming-feature InferIsolatedConformances // https://forums.swift.org/t/swift-packages-in-multiple-targets-results-in-this-will-result-in-duplication-of-library-code-errors/34892/33 DISABLE_DIAMOND_PROBLEM_DIAGNOSTIC = YES From 8f57f914dd91d8f7071b47ae7c31bc855b9475c9 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Tue, 18 Nov 2025 13:25:47 -0800 Subject: [PATCH 02/14] Fix various concurrency issues. --- Mac/AppAssets.swift | 314 ++++-------------- Mac/AppDelegate.swift | 2 +- .../LegacyArticleExtractorButton.swift | 2 +- .../Sidebar/Cell/SidebarCellLayout.swift | 3 +- .../Renaming/RenameWindowController.swift | 2 +- .../Sidebar/SidebarStatusBarView.swift | 16 +- ...idebarViewController+ContextualMenus.swift | 2 +- .../Sidebar/SidebarViewController.swift | 2 +- Mac/MainWindow/Sidebar/UnreadCountView.swift | 3 +- .../Cell/MultilineTextFieldSizer.swift | 2 +- .../Cell/SingleLineTextFieldSizer.swift | 2 +- .../TimelineContainerViewController.swift | 3 +- .../Timeline/TimelineViewController.swift | 4 +- .../AccountsPreferencesViewController.swift | 2 +- .../GeneralPrefencesViewController.swift | 4 - Mac/Scriptability/Account+Scriptability.swift | 4 +- .../AppDelegate+Scriptability.swift | 6 +- Mac/Scriptability/Article+Scriptability.swift | 4 +- Mac/Scriptability/Author+Scriptability.swift | 17 +- Mac/Scriptability/Feed+Scriptability.swift | 4 +- Mac/Scriptability/Folder+Scriptability.swift | 4 +- .../MainWindowController+Scriptability.swift | 3 +- Mac/Scriptability/ScriptingObject.swift | 4 +- .../ScriptingObjectContainer.swift | 4 +- .../OAuthAccountAuthorizationOperation.swift | 4 +- .../RSCore/Sources/RSCore/Shared/Blocks.swift | 2 +- .../Sources/RSCore/Shared/RSImage.swift | 12 + .../Article Extractor/ArticleExtractor.swift | 4 +- .../WebViewConfiguration.swift | 4 +- Shared/ArticleStyles/ArticleTheme.swift | 10 +- .../ArticleThemeDownloader.swift | 4 +- Shared/ArticleStyles/ArticleThemePlist.swift | 12 +- Shared/Extensions/IconImage.swift | 2 +- Shared/Extensions/RSImage-AppIcons.swift | 2 +- Shared/Extensions/RSImage-Extensions.swift | 2 +- Shared/Favicons/SingleFaviconDownloader.swift | 113 +++---- Shared/Images/FeedIconDownloader.swift | 10 +- Shared/Images/ImageDownloader.swift | 47 +-- .../ExtensionFeedAddRequestFile.swift | 31 +- 39 files changed, 248 insertions(+), 424 deletions(-) diff --git a/Mac/AppAssets.swift b/Mac/AppAssets.swift index 3e0ec7023..04f77116a 100644 --- a/Mac/AppAssets.swift +++ b/Mac/AppAssets.swift @@ -11,284 +11,97 @@ import RSCore import Account struct AppAssets { - - static var accountBazQux: RSImage! = { - return RSImage(named: "accountBazQux") - }() - - static var accountCloudKit: RSImage! = { - return RSImage(named: "accountCloudKit") - }() - - static var accountFeedbin: RSImage! = { - return RSImage(named: "accountFeedbin") - }() - - static var accountFeedly: RSImage! = { - return RSImage(named: "accountFeedly") - }() - - static var accountFreshRSS: RSImage! = { - return RSImage(named: "accountFreshRSS") - }() - - static var accountInoreader: RSImage! = { - return RSImage(named: "accountInoreader") - }() - - static var accountLocal: RSImage! = { - return RSImage(named: "accountLocal") - }() - - static var accountNewsBlur: RSImage! = { - return RSImage(named: "accountNewsBlur") - }() - - static var accountTheOldReader: RSImage! = { - return RSImage(named: "accountTheOldReader") - }() - + static let accountBazQux = RSImage(named: "accountBazQux")! + static let accountCloudKit = RSImage(named: "accountCloudKit")! + static let accountFeedbin = RSImage(named: "accountFeedbin")! + static let accountFeedly = RSImage(named: "accountFeedly")! + static let accountFreshRSS = RSImage(named: "accountFreshRSS")! + static let accountInoreader = RSImage(named: "accountInoreader")! + static let accountLocal = RSImage(named: "accountLocal")! + static let accountNewsBlur = RSImage(named: "accountNewsBlur")! + static let accountTheOldReader = RSImage(named: "accountTheOldReader")! static let nnwFeedIcon = RSImage(named: "nnwFeedIcon")! + static let addNewSidebarItemImage = NSImage(systemSymbolName: "plus", accessibilityDescription: nil)! + static let articleExtractorError = RSImage(named: "articleExtractorError")! + static let articleExtractorOff = RSImage(named: "articleExtractorOff")! + static let articleExtractorOn = RSImage(named: "articleExtractorOn")! + static let articleTheme = NSImage(systemSymbolName: "doc.richtext", accessibilityDescription: nil)! + static let cleanUpImage = NSImage(systemSymbolName: "bubbles.and.sparkles", accessibilityDescription: nil)! + static let copyImage = NSImage(systemSymbolName: "document.on.document", accessibilityDescription: nil)! + static let deleteImage = NSImage(systemSymbolName: "xmark.bin", accessibilityDescription: nil)! + static let marsEditIcon = RSImage(named: "MarsEditIcon")! + static let microblogIcon = RSImage(named: "MicroblogIcon")! + static let faviconTemplateImage = RSImage(named: "faviconTemplateImage")! + static let filterActive = NSImage(systemSymbolName: "line.horizontal.3.decrease.circle.fill", accessibilityDescription: nil)! + static let filterInactive = NSImage(systemSymbolName: "line.horizontal.3.decrease.circle", accessibilityDescription: nil)! + static let iconLightBackgroundColor = NSColor(named: NSColor.Name("iconLightBackgroundColor"))! + static let iconDarkBackgroundColor = NSColor(named: NSColor.Name("iconDarkBackgroundColor"))! + static let legacyArticleExtractor = RSImage(named: "legacyArticleExtractor")! + static let legacyArticleExtractorError = RSImage(named: "legacyArticleExtractorError")! + static let legacyArticleExtractorInactiveDark = RSImage(named: "legacyArticleExtractorInactiveDark")! + static let legacyArticleExtractorInactiveLight = RSImage(named: "legacyArticleExtractorInactiveLight")! + static let legacyArticleExtractorProgress1 = RSImage(named: "legacyArticleExtractorProgress1")! + static let legacyArticleExtractorProgress2 = RSImage(named: "legacyArticleExtractorProgress2")! + static let legacyArticleExtractorProgress3 = RSImage(named: "legacyArticleExtractorProgress3")! + static let legacyArticleExtractorProgress4 = RSImage(named: "legacyArticleExtractorProgress4")! - static var addNewSidebarItemImage: RSImage = { - return NSImage(systemSymbolName: "plus", accessibilityDescription: nil)! - }() - - static var articleExtractorError: RSImage = { - return RSImage(named: "articleExtractorError")! - }() - - static var articleExtractorOff: RSImage = { - return RSImage(named: "articleExtractorOff")! - }() - - static var articleExtractorOn: RSImage = { - return RSImage(named: "articleExtractorOn")! - }() - - - static var articleTheme: RSImage = { - return NSImage(systemSymbolName: "doc.richtext", accessibilityDescription: nil)! - }() - - - static var cleanUpImage: RSImage = { - return NSImage(systemSymbolName: "bubbles.and.sparkles", accessibilityDescription: nil)! - }() - - static var copyImage: RSImage = { - return NSImage(systemSymbolName: "document.on.document", accessibilityDescription: nil)! - }() - - static var deleteImage: RSImage = { - return NSImage(systemSymbolName: "xmark.bin", accessibilityDescription: nil)! - }() - - static var marsEditIcon: RSImage = { - return RSImage(named: "MarsEditIcon")! - }() - - static var microblogIcon: RSImage = { - return RSImage(named: "MicroblogIcon")! - }() - - static var faviconTemplateImage: RSImage = { - return RSImage(named: "faviconTemplateImage")! - }() - - static var filterActive: RSImage = { - return NSImage(systemSymbolName: "line.horizontal.3.decrease.circle.fill", accessibilityDescription: nil)! - }() - - static var filterInactive: RSImage = { - return NSImage(systemSymbolName: "line.horizontal.3.decrease.circle", accessibilityDescription: nil)! - }() - - static var iconLightBackgroundColor: NSColor = { - return NSColor(named: NSColor.Name("iconLightBackgroundColor"))! - }() - - static var iconDarkBackgroundColor: NSColor = { - return NSColor(named: NSColor.Name("iconDarkBackgroundColor"))! - }() - - static var legacyArticleExtractor: RSImage! = { - return RSImage(named: "legacyArticleExtractor") - }() - - static var legacyArticleExtractorError: RSImage! = { - return RSImage(named: "legacyArticleExtractorError") - }() - - static var legacyArticleExtractorInactiveDark: RSImage! = { - return RSImage(named: "legacyArticleExtractorInactiveDark") - }() - - static var legacyArticleExtractorInactiveLight: RSImage! = { - return RSImage(named: "legacyArticleExtractorInactiveLight") - }() - - static var legacyArticleExtractorProgress1: RSImage! = { - return RSImage(named: "legacyArticleExtractorProgress1") - }() - - static var legacyArticleExtractorProgress2: RSImage! = { - return RSImage(named: "legacyArticleExtractorProgress2") - }() - - static var legacyArticleExtractorProgress3: RSImage! = { - return RSImage(named: "legacyArticleExtractorProgress3") - }() - - static var legacyArticleExtractorProgress4: RSImage! = { - return RSImage(named: "legacyArticleExtractorProgress4") - }() - - static var mainFolderImage: IconImage { + static let mainFolderImage: IconImage = { let image = NSImage(systemSymbolName: "folder", accessibilityDescription: nil)! let preferredColor = NSColor(named: "AccentColor")! return IconImage(image, isSymbol: true, isBackgroundSuppressed: true, preferredColor: preferredColor.cgColor) - } - - - static var markAllAsReadMenuImage: RSImage = { - let image = RSImage(named: "markAllAsRead") - return image! - }() - - static var markAllAsReadImage: RSImage = { - let image = RSImage(named: "markAllAsRead") - return image! - }() - - static var markBelowAsReadImage: RSImage = { - let image = RSImage(named: "markBelowAsRead") - return image! - }() - - static var markAboveAsReadImage: RSImage = { - let image = RSImage(named: "markAboveAsRead") - return image! }() - static var nextUnreadImage: RSImage = { - return NSImage(systemSymbolName: "chevron.down.circle", accessibilityDescription: nil)! - }() + static let markAllAsReadMenuImage = RSImage(named: "markAllAsRead")! + static let markAllAsReadImage = RSImage(named: "markAllAsRead")! + static let markBelowAsReadImage = RSImage(named: "markBelowAsRead")! + static let markAboveAsReadImage = RSImage(named: "markAboveAsRead")! - static var notificationImage: RSImage = { - return NSImage(systemSymbolName: "bell.badge", accessibilityDescription: nil)! - }() + static let nextUnreadImage = NSImage(systemSymbolName: "chevron.down.circle", accessibilityDescription: nil)! + static let notificationImage = NSImage(systemSymbolName: "bell.badge", accessibilityDescription: nil)! + static let openInBrowserImage = NSImage(systemSymbolName: "safari", accessibilityDescription: nil)! - static var openInBrowserImage: RSImage = { - return NSImage(systemSymbolName: "safari", accessibilityDescription: nil)! - }() + static let preferencesToolbarAccountsImage = NSImage(systemSymbolName: "at", accessibilityDescription: nil)! + static let preferencesToolbarGeneralImage = NSImage(systemSymbolName: "gearshape", accessibilityDescription: nil)! + static let preferencesToolbarAdvancedImage = NSImage(systemSymbolName: "gearshape.2", accessibilityDescription: nil)! + static let readClosedImage = NSImage(systemSymbolName: "largecircle.fill.circle", accessibilityDescription: nil)! + static let readOpenImage = NSImage(systemSymbolName: "circle", accessibilityDescription: nil)! + static let refreshImage = NSImage(systemSymbolName: "arrow.clockwise", accessibilityDescription: nil)! + static let renameImage = NSImage(systemSymbolName: "pencil", accessibilityDescription: nil)! + static let searchFeedImage = IconImage(RSImage(named: NSImage.smartBadgeTemplateName)!, isSymbol: true, isBackgroundSuppressed: true) + static let shareImage = NSImage(systemSymbolName: "square.and.arrow.up", accessibilityDescription: nil)! + static let sidebarToggleImage = NSImage(systemSymbolName: "sidebar.left", accessibilityDescription: nil)! + static let starClosedImage = NSImage(systemSymbolName: "star.fill", accessibilityDescription: nil)! + static let starOpenImage = NSImage(systemSymbolName: "star", accessibilityDescription: nil)! - static var preferencesToolbarAccountsImage: RSImage = { - return NSImage(systemSymbolName: "at", accessibilityDescription: nil)! - }() - - static var preferencesToolbarGeneralImage: RSImage = { - return NSImage(systemSymbolName: "gearshape", accessibilityDescription: nil)! - }() - - static var preferencesToolbarAdvancedImage: RSImage = { - return NSImage(systemSymbolName: "gearshape.2", accessibilityDescription: nil)! - }() - - - static var readClosedImage: RSImage = { - return NSImage(systemSymbolName: "largecircle.fill.circle", accessibilityDescription: nil)! - }() - - - static var readOpenImage: RSImage = { - return NSImage(systemSymbolName: "circle", accessibilityDescription: nil)! - }() - - - static var refreshImage: RSImage = { - return NSImage(systemSymbolName: "arrow.clockwise", accessibilityDescription: nil)! - }() - - static var renameImage: RSImage = { - return NSImage(systemSymbolName: "pencil", accessibilityDescription: nil)! - }() - - static var searchFeedImage: IconImage = { - return IconImage(RSImage(named: NSImage.smartBadgeTemplateName)!, isSymbol: true, isBackgroundSuppressed: true) - }() - - - static var shareImage: RSImage = { - return NSImage(systemSymbolName: "square.and.arrow.up", accessibilityDescription: nil)! - }() - - - static var sidebarToggleImage: RSImage = { - return NSImage(systemSymbolName: "sidebar.left", accessibilityDescription: nil)! - }() - - - static var starClosedImage: RSImage = { - return NSImage(systemSymbolName: "star.fill", accessibilityDescription: nil)! - }() - - - static var starOpenImage: RSImage = { - return NSImage(systemSymbolName: "star", accessibilityDescription: nil)! - }() - - static var starredFeedImage: IconImage = { + static let starredFeedImage: IconImage = { let image = NSImage(systemSymbolName: "star.fill", accessibilityDescription: nil)! let preferredColor = NSColor(named: "StarColor")! return IconImage(image, isSymbol: true, isBackgroundSuppressed: true, preferredColor: preferredColor.cgColor) }() - static var timelineSeparatorColor: NSColor = { - return NSColor(named: "timelineSeparatorColor")! - }() + static let timelineSeparatorColor = NSColor(named: "timelineSeparatorColor")! + static let timelineStarSelected = RSImage(named: "timelineStar")?.tinted(with: .white) + static let timelineStarUnselected = RSImage(named: "timelineStar")?.tinted(with: starColor) - static var timelineStarSelected: RSImage! = { - return RSImage(named: "timelineStar")?.tinted(with: .white) - }() - - static var timelineStarUnselected: RSImage! = { - return RSImage(named: "timelineStar")?.tinted(with: starColor) - }() - - static var todayFeedImage: IconImage = { + static let todayFeedImage: IconImage = { let image = NSImage(systemSymbolName: "sun.max.fill", accessibilityDescription: nil)! let preferredColor = NSColor.orange return IconImage(image, isSymbol: true, isBackgroundSuppressed: true, preferredColor: preferredColor.cgColor) }() - static var unreadFeedImage: IconImage = { + static let unreadFeedImage: IconImage = { let image = NSImage(systemSymbolName: "largecircle.fill.circle", accessibilityDescription: nil)! let preferredColor = NSColor(named: "AccentColor")! return IconImage(image, isSymbol: true, isBackgroundSuppressed: true, preferredColor: preferredColor.cgColor) }() - static var swipeMarkReadImage: RSImage = { - return RSImage(systemSymbolName: "circle", accessibilityDescription: "Mark Read")! - }() - - static var swipeMarkUnreadImage: RSImage = { - return RSImage(systemSymbolName: "largecircle.fill.circle", accessibilityDescription: "Mark Unread")! - }() - - static var swipeMarkStarredImage: RSImage = { - return RSImage(systemSymbolName: "star.fill", accessibilityDescription: "Star")! - }() - - static var swipeMarkUnstarredImage: RSImage = { - return RSImage(systemSymbolName: "star", accessibilityDescription: "Unstar")! - }() - - static var starColor: NSColor = { - return NSColor(named: NSColor.Name("StarColor"))! - }() + static let swipeMarkReadImage = RSImage(systemSymbolName: "circle", accessibilityDescription: "Mark Read")! + static let swipeMarkUnreadImage = RSImage(systemSymbolName: "largecircle.fill.circle", accessibilityDescription: "Mark Unread")! + static let swipeMarkStarredImage = RSImage(systemSymbolName: "star.fill", accessibilityDescription: "Star")! + static let swipeMarkUnstarredImage = RSImage(systemSymbolName: "star", accessibilityDescription: "Unstar")! + static let starColor = NSColor(named: NSColor.Name("StarColor"))! static func image(for accountType: AccountType) -> NSImage? { switch accountType { @@ -312,5 +125,4 @@ struct AppAssets { return AppAssets.accountTheOldReader } } - } diff --git a/Mac/AppDelegate.swift b/Mac/AppDelegate.swift index 8571a3f05..6461d62f9 100644 --- a/Mac/AppDelegate.swift +++ b/Mac/AppDelegate.swift @@ -22,7 +22,7 @@ let appName = "NetNewsWire" var appDelegate: AppDelegate! -@NSApplicationMain +@main final class AppDelegate: NSObject, NSApplicationDelegate, NSUserInterfaceValidations, UNUserNotificationCenterDelegate, UnreadCountProvider, SPUStandardUserDriverDelegate, SPUUpdaterDelegate { static private let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "AppDelegate") diff --git a/Mac/MainWindow/LegacyArticleExtractorButton.swift b/Mac/MainWindow/LegacyArticleExtractorButton.swift index aa2bbdeba..ee634e8f5 100644 --- a/Mac/MainWindow/LegacyArticleExtractorButton.swift +++ b/Mac/MainWindow/LegacyArticleExtractorButton.swift @@ -93,7 +93,7 @@ final class LegacyArticleExtractorButton: NSButton { let images = [imageProgress1, imageProgress2, imageProgress3, imageProgress4, imageProgress3, imageProgress2, imageProgress1] let imageLayer = CALayer() - imageLayer.bounds = CGRect(x: 0, y: 0, width: imageProgress1?.size.width ?? 0, height: imageProgress1?.size.height ?? 0) + imageLayer.bounds = CGRect(x: 0, y: 0, width: imageProgress1.size.width, height: imageProgress1.size.height) imageLayer.position = CGPoint(x: bounds.midX, y: floor(bounds.midY)) hostedLayer.addSublayer(imageLayer) diff --git a/Mac/MainWindow/Sidebar/Cell/SidebarCellLayout.swift b/Mac/MainWindow/Sidebar/Cell/SidebarCellLayout.swift index 0cf32d22a..bee49702d 100644 --- a/Mac/MainWindow/Sidebar/Cell/SidebarCellLayout.swift +++ b/Mac/MainWindow/Sidebar/Cell/SidebarCellLayout.swift @@ -11,8 +11,7 @@ import RSCore // image - title - unreadCount -struct SidebarCellLayout { - +@MainActor struct SidebarCellLayout { let faviconRect: CGRect let titleRect: CGRect let unreadCountRect: CGRect diff --git a/Mac/MainWindow/Sidebar/Renaming/RenameWindowController.swift b/Mac/MainWindow/Sidebar/Renaming/RenameWindowController.swift index 229a791ad..ea11f432d 100644 --- a/Mac/MainWindow/Sidebar/Renaming/RenameWindowController.swift +++ b/Mac/MainWindow/Sidebar/Renaming/RenameWindowController.swift @@ -8,7 +8,7 @@ import AppKit -protocol RenameWindowControllerDelegate { +@MainActor protocol RenameWindowControllerDelegate { func renameWindowController(_ windowController: RenameWindowController, didRenameObject: Any, withNewName: String) } diff --git a/Mac/MainWindow/Sidebar/SidebarStatusBarView.swift b/Mac/MainWindow/Sidebar/SidebarStatusBarView.swift index 236bc8003..d22095d2b 100644 --- a/Mac/MainWindow/Sidebar/SidebarStatusBarView.swift +++ b/Mac/MainWindow/Sidebar/SidebarStatusBarView.swift @@ -13,7 +13,6 @@ import RSWeb import Account final class SidebarStatusBarView: NSView { - @IBOutlet var progressIndicator: NSProgressIndicator! @IBOutlet var progressLabel: NSTextField! @IBOutlet var bottomConstraint: NSLayoutConstraint! @@ -26,15 +25,16 @@ final class SidebarStatusBarView: NSView { } override func awakeFromNib() { + MainActor.assumeIsolated { + progressIndicator.isHidden = true + progressLabel.isHidden = true - progressIndicator.isHidden = true - progressLabel.isHidden = true + let progressLabelFontSize = progressLabel.font?.pointSize ?? 13.0 + progressLabel.font = NSFont.monospacedDigitSystemFont(ofSize: progressLabelFontSize, weight: NSFont.Weight.regular) + progressLabel.stringValue = "" - let progressLabelFontSize = progressLabel.font?.pointSize ?? 13.0 - progressLabel.font = NSFont.monospacedDigitSystemFont(ofSize: progressLabelFontSize, weight: NSFont.Weight.regular) - progressLabel.stringValue = "" - - NotificationCenter.default.addObserver(self, selector: #selector(progressDidChange(_:)), name: .combinedRefreshProgressDidChange, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(progressDidChange(_:)), name: .combinedRefreshProgressDidChange, object: nil) + } } @objc func updateUI() { diff --git a/Mac/MainWindow/Sidebar/SidebarViewController+ContextualMenus.swift b/Mac/MainWindow/Sidebar/SidebarViewController+ContextualMenus.swift index c792a171e..a07e9c33d 100644 --- a/Mac/MainWindow/Sidebar/SidebarViewController+ContextualMenus.swift +++ b/Mac/MainWindow/Sidebar/SidebarViewController+ContextualMenus.swift @@ -145,7 +145,7 @@ extension SidebarViewController { NotificationCenter.default.post(Notification(name: .DidUpdateFeedPreferencesFromContextMenu)) } - func showNotificationsNotEnabledAlert() { + nonisolated func showNotificationsNotEnabledAlert() { DispatchQueue.main.async { let alert = NSAlert() alert.messageText = NSLocalizedString("Notifications are not enabled", comment: "Notifications are not enabled.") diff --git a/Mac/MainWindow/Sidebar/SidebarViewController.swift b/Mac/MainWindow/Sidebar/SidebarViewController.swift index 0dfb87502..5de1b8d29 100644 --- a/Mac/MainWindow/Sidebar/SidebarViewController.swift +++ b/Mac/MainWindow/Sidebar/SidebarViewController.swift @@ -16,7 +16,7 @@ extension Notification.Name { static let appleSideBarDefaultIconSizeChanged = Notification.Name("AppleSideBarDefaultIconSizeChanged") } -protocol SidebarDelegate: AnyObject { +@MainActor protocol SidebarDelegate: AnyObject { func sidebarSelectionDidChange(_: SidebarViewController, selectedObjects: [AnyObject]?) func unreadCount(for: AnyObject) -> Int func sidebarInvalidatedRestorationState(_: SidebarViewController) diff --git a/Mac/MainWindow/Sidebar/UnreadCountView.swift b/Mac/MainWindow/Sidebar/UnreadCountView.swift index 67f9a7ea8..9005fc4a1 100644 --- a/Mac/MainWindow/Sidebar/UnreadCountView.swift +++ b/Mac/MainWindow/Sidebar/UnreadCountView.swift @@ -9,8 +9,7 @@ import AppKit final class UnreadCountView : NSView { - - struct Appearance { + @MainActor struct Appearance { static let padding = NSEdgeInsets(top: 1.0, left: 7.0, bottom: 1.0, right: 7.0) static let cornerRadius: CGFloat = 8.0 static let backgroundColor = NSColor.clear diff --git a/Mac/MainWindow/Timeline/Cell/MultilineTextFieldSizer.swift b/Mac/MainWindow/Timeline/Cell/MultilineTextFieldSizer.swift index c9af1fbee..88fdd1797 100644 --- a/Mac/MainWindow/Timeline/Cell/MultilineTextFieldSizer.swift +++ b/Mac/MainWindow/Timeline/Cell/MultilineTextFieldSizer.swift @@ -26,7 +26,7 @@ struct TextFieldSizeInfo { let numberOfLinesUsed: Int // A two-line text field may only use one line, for instance. This would equal 1, then. } -final class MultilineTextFieldSizer { +@MainActor final class MultilineTextFieldSizer { private let numberOfLines: Int private let font: NSFont diff --git a/Mac/MainWindow/Timeline/Cell/SingleLineTextFieldSizer.swift b/Mac/MainWindow/Timeline/Cell/SingleLineTextFieldSizer.swift index db598d3fa..b116d36ba 100644 --- a/Mac/MainWindow/Timeline/Cell/SingleLineTextFieldSizer.swift +++ b/Mac/MainWindow/Timeline/Cell/SingleLineTextFieldSizer.swift @@ -12,7 +12,7 @@ import AppKit // Uses a cache. // Main thready only. -final class SingleLineTextFieldSizer { +@MainActor final class SingleLineTextFieldSizer { let font: NSFont private let textField: NSTextField diff --git a/Mac/MainWindow/Timeline/TimelineContainerViewController.swift b/Mac/MainWindow/Timeline/TimelineContainerViewController.swift index 48da43069..33a8ca8ab 100644 --- a/Mac/MainWindow/Timeline/TimelineContainerViewController.swift +++ b/Mac/MainWindow/Timeline/TimelineContainerViewController.swift @@ -10,11 +10,10 @@ import AppKit import Account import Articles -protocol TimelineContainerViewControllerDelegate: AnyObject { +@MainActor protocol TimelineContainerViewControllerDelegate: AnyObject { func timelineSelectionDidChange(_: TimelineContainerViewController, articles: [Article]?, mode: TimelineSourceMode) func timelineRequestedFeedSelection(_: TimelineContainerViewController, feed: Feed) func timelineInvalidatedRestorationState(_: TimelineContainerViewController) - } final class TimelineContainerViewController: NSViewController { diff --git a/Mac/MainWindow/Timeline/TimelineViewController.swift b/Mac/MainWindow/Timeline/TimelineViewController.swift index b6fba2d7f..ffdc8b9ef 100644 --- a/Mac/MainWindow/Timeline/TimelineViewController.swift +++ b/Mac/MainWindow/Timeline/TimelineViewController.swift @@ -12,13 +12,13 @@ import Articles import Account import os.log -protocol TimelineDelegate: AnyObject { +@MainActor protocol TimelineDelegate: AnyObject { func timelineSelectionDidChange(_: TimelineViewController, selectedArticles: [Article]?) func timelineRequestedFeedSelection(_: TimelineViewController, feed: Feed) func timelineInvalidatedRestorationState(_: TimelineViewController) } -enum TimelineShowFeedName { +enum TimelineShowFeedName: Sendable { case none case byline case feed diff --git a/Mac/Preferences/Accounts/AccountsPreferencesViewController.swift b/Mac/Preferences/Accounts/AccountsPreferencesViewController.swift index e741982d2..f439f5040 100644 --- a/Mac/Preferences/Accounts/AccountsPreferencesViewController.swift +++ b/Mac/Preferences/Accounts/AccountsPreferencesViewController.swift @@ -12,7 +12,7 @@ import SwiftUI import RSCore // MARK: - AccountsPreferencesAddAccountDelegate -protocol AccountsPreferencesAddAccountDelegate { +@MainActor protocol AccountsPreferencesAddAccountDelegate { func presentSheetForAccount(_ accountType: AccountType) } diff --git a/Mac/Preferences/General/GeneralPrefencesViewController.swift b/Mac/Preferences/General/GeneralPrefencesViewController.swift index 8ad06f129..36337b94a 100644 --- a/Mac/Preferences/General/GeneralPrefencesViewController.swift +++ b/Mac/Preferences/General/GeneralPrefencesViewController.swift @@ -13,9 +13,6 @@ import UserNotifications import UniformTypeIdentifiers final class GeneralPreferencesViewController: NSViewController { - - private var userNotificationSettings: UNNotificationSettings? - @IBOutlet weak var articleThemePopup: NSPopUpButton! @IBOutlet weak var defaultBrowserPopup: NSPopUpButton! @@ -137,7 +134,6 @@ private extension GeneralPreferencesViewController { func updateNotificationSettings() { UNUserNotificationCenter.current().getNotificationSettings { (settings) in - self.userNotificationSettings = settings if settings.authorizationStatus == .authorized { DispatchQueue.main.async { NSApplication.shared.registerForRemoteNotifications() diff --git a/Mac/Scriptability/Account+Scriptability.swift b/Mac/Scriptability/Account+Scriptability.swift index b85a70438..220a174c1 100644 --- a/Mac/Scriptability/Account+Scriptability.swift +++ b/Mac/Scriptability/Account+Scriptability.swift @@ -12,7 +12,7 @@ import Articles import RSCore @objc(ScriptableAccount) -@MainActor final class ScriptableAccount: NSObject, UniqueIdScriptingObject, ScriptingObjectContainer { +@MainActor final class ScriptableAccount: NSObject, UniqueIDScriptingObject, ScriptingObjectContainer { let account:Account init (_ account:Account) { @@ -57,7 +57,7 @@ import RSCore // I am not sure if account should prefer to be specified by name or by ID // but in either case it seems like the accountID would be used as the keydata, so I chose ID @objc(uniqueId) - var scriptingUniqueId:Any { + var scriptingUniqueID:Any { return account.accountID } diff --git a/Mac/Scriptability/AppDelegate+Scriptability.swift b/Mac/Scriptability/AppDelegate+Scriptability.swift index aa4229a03..6cb105f81 100644 --- a/Mac/Scriptability/AppDelegate+Scriptability.swift +++ b/Mac/Scriptability/AppDelegate+Scriptability.swift @@ -19,18 +19,18 @@ import Foundation import Articles -protocol AppDelegateAppleEvents { +@MainActor protocol AppDelegateAppleEvents { func installAppleEventHandlers() func getURL(_ event: NSAppleEventDescriptor, _ withReplyEvent: NSAppleEventDescriptor) } -protocol ScriptingAppDelegate { +@MainActor protocol ScriptingAppDelegate { var scriptingCurrentArticle: Article? {get} var scriptingSelectedArticles: [Article] {get} var scriptingMainWindowController:ScriptingMainWindowController? {get} } -extension AppDelegate : AppDelegateAppleEvents { +extension AppDelegate: AppDelegateAppleEvents { // MARK: GetURL Apple Event diff --git a/Mac/Scriptability/Article+Scriptability.swift b/Mac/Scriptability/Article+Scriptability.swift index 328b0cad7..a5c92c227 100644 --- a/Mac/Scriptability/Article+Scriptability.swift +++ b/Mac/Scriptability/Article+Scriptability.swift @@ -11,7 +11,7 @@ import Account import Articles @objc(ScriptableArticle) -final class ScriptableArticle: NSObject, UniqueIdScriptingObject, ScriptingObjectContainer { +@MainActor final class ScriptableArticle: NSObject, UniqueIDScriptingObject, ScriptingObjectContainer { let article:Article let container:ScriptingObjectContainer @@ -39,7 +39,7 @@ final class ScriptableArticle: NSObject, UniqueIdScriptingObject, ScriptingObjec // article.uniqueID here is the feed unique id @objc(uniqueId) - var scriptingUniqueId:Any { + var scriptingUniqueID:Any { return article.uniqueID } diff --git a/Mac/Scriptability/Author+Scriptability.swift b/Mac/Scriptability/Author+Scriptability.swift index 33bcd6104..b830de805 100644 --- a/Mac/Scriptability/Author+Scriptability.swift +++ b/Mac/Scriptability/Author+Scriptability.swift @@ -11,20 +11,19 @@ import Account import Articles @objc(ScriptableAuthor) -final class ScriptableAuthor: NSObject, UniqueIdScriptingObject { +@MainActor final class ScriptableAuthor: NSObject, UniqueIDScriptingObject { + let author: Author + let container: ScriptingObjectContainer - let author:Author - let container:ScriptingObjectContainer - - init (_ author:Author, container:ScriptingObjectContainer) { + init (_ author: Author, container: ScriptingObjectContainer) { self.author = author self.container = container } @objc(objectSpecifier) - override var objectSpecifier: NSScriptObjectSpecifier? { - let scriptObjectSpecifier = self.container.makeFormUniqueIDScriptObjectSpecifier(forObject:self) - return (scriptObjectSpecifier) + override var objectSpecifier: NSScriptObjectSpecifier? { + let scriptObjectSpecifier = container.makeFormUniqueIDScriptObjectSpecifier(forObject: self) + return scriptObjectSpecifier } @objc(scriptingSpecifierDescriptor) @@ -41,7 +40,7 @@ final class ScriptableAuthor: NSObject, UniqueIdScriptingObject { // MARK: --- UniqueIdScriptingObject protocol --- @objc(uniqueId) - var scriptingUniqueId:Any { + var scriptingUniqueID:Any { return author.authorID } diff --git a/Mac/Scriptability/Feed+Scriptability.swift b/Mac/Scriptability/Feed+Scriptability.swift index 9e2982e1c..2e76452b3 100644 --- a/Mac/Scriptability/Feed+Scriptability.swift +++ b/Mac/Scriptability/Feed+Scriptability.swift @@ -12,7 +12,7 @@ import Account import Articles @objc(ScriptableFeed) -final class ScriptableFeed: NSObject, UniqueIdScriptingObject, ScriptingObjectContainer { +@MainActor final class ScriptableFeed: NSObject, UniqueIDScriptingObject, ScriptingObjectContainer { let feed:Feed let container:ScriptingObjectContainer @@ -44,7 +44,7 @@ final class ScriptableFeed: NSObject, UniqueIdScriptingObject, ScriptingObjectCo // I am not sure if account should prefer to be specified by name or by ID // but in either case it seems like the accountID would be used as the keydata, so I chose ID @objc(uniqueId) - var scriptingUniqueId:Any { + var scriptingUniqueID:Any { return feed.feedID } diff --git a/Mac/Scriptability/Folder+Scriptability.swift b/Mac/Scriptability/Folder+Scriptability.swift index be33bcdf7..58de28f71 100644 --- a/Mac/Scriptability/Folder+Scriptability.swift +++ b/Mac/Scriptability/Folder+Scriptability.swift @@ -12,7 +12,7 @@ import Articles import RSCore @objc(ScriptableFolder) -final class ScriptableFolder: NSObject, UniqueIdScriptingObject, ScriptingObjectContainer { +@MainActor final class ScriptableFolder: NSObject, UniqueIDScriptingObject, ScriptingObjectContainer { let folder:Folder let container:ScriptingObjectContainer @@ -40,7 +40,7 @@ final class ScriptableFolder: NSObject, UniqueIdScriptingObject, ScriptingObject // but in either case it seems like the accountID would be used as the keydata, so I chose ID @objc(uniqueId) - var scriptingUniqueId:Any { + var scriptingUniqueID:Any { return folder.folderID } diff --git a/Mac/Scriptability/MainWindowController+Scriptability.swift b/Mac/Scriptability/MainWindowController+Scriptability.swift index e83a29711..dcd66ee39 100644 --- a/Mac/Scriptability/MainWindowController+Scriptability.swift +++ b/Mac/Scriptability/MainWindowController+Scriptability.swift @@ -9,8 +9,7 @@ import Foundation import Articles -protocol ScriptingMainWindowController { +@MainActor protocol ScriptingMainWindowController { var scriptingCurrentArticle: Article? { get } var scriptingSelectedArticles: [Article] { get } } - diff --git a/Mac/Scriptability/ScriptingObject.swift b/Mac/Scriptability/ScriptingObject.swift index 93e1b3a22..0a5bf9576 100644 --- a/Mac/Scriptability/ScriptingObject.swift +++ b/Mac/Scriptability/ScriptingObject.swift @@ -17,6 +17,6 @@ import Foundation var name:String { get } } -@MainActor 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 23891b56d..d7ebb8a22 100644 --- a/Mac/Scriptability/ScriptingObjectContainer.swift +++ b/Mac/Scriptability/ScriptingObjectContainer.swift @@ -26,11 +26,11 @@ import Account return specifier } - func makeFormUniqueIDScriptObjectSpecifier(forObject object:UniqueIdScriptingObject) -> NSScriptObjectSpecifier? { + func makeFormUniqueIDScriptObjectSpecifier(forObject object:UniqueIDScriptingObject) -> NSScriptObjectSpecifier? { let containerClassDescription = self.scriptingClassDescription let containerScriptObjectSpecifier = self.objectSpecifier let scriptingKey = object.scriptingKey - let uniqueId = object.scriptingUniqueId + let uniqueId = object.scriptingUniqueID let specifier = NSUniqueIDSpecifier(containerClassDescription:containerClassDescription, containerSpecifier:containerScriptObjectSpecifier, key:scriptingKey, uniqueID: uniqueId) return specifier diff --git a/Modules/Account/Sources/Account/Feedly/OAuthAccountAuthorizationOperation.swift b/Modules/Account/Sources/Account/Feedly/OAuthAccountAuthorizationOperation.swift index cf8ccd98b..6983d8f30 100644 --- a/Modules/Account/Sources/Account/Feedly/OAuthAccountAuthorizationOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/OAuthAccountAuthorizationOperation.swift @@ -10,12 +10,12 @@ import Foundation import AuthenticationServices import RSCore -public protocol OAuthAccountAuthorizationOperationDelegate: AnyObject { +@MainActor public protocol OAuthAccountAuthorizationOperationDelegate: AnyObject { func oauthAccountAuthorizationOperation(_ operation: OAuthAccountAuthorizationOperation, didCreate account: Account) func oauthAccountAuthorizationOperation(_ operation: OAuthAccountAuthorizationOperation, didFailWith error: Error) } -public enum OAuthAccountAuthorizationOperationError: LocalizedError { +public enum OAuthAccountAuthorizationOperationError: LocalizedError, Sendable { case duplicateAccount public var errorDescription: String? { diff --git a/Modules/RSCore/Sources/RSCore/Shared/Blocks.swift b/Modules/RSCore/Sources/RSCore/Shared/Blocks.swift index 28565e6a0..4a0a95eda 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 = @Sendable (RSImage?) -> Void +public typealias ImageResultBlock = @MainActor (RSImage?) -> Void diff --git a/Modules/RSCore/Sources/RSCore/Shared/RSImage.swift b/Modules/RSCore/Sources/RSCore/Shared/RSImage.swift index e85404135..66f33bf4c 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/RSImage.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/RSImage.swift @@ -104,6 +104,18 @@ public extension RSImage { #endif } + /// Asynchronously initializes an image from data. + /// + /// - Parameters: + /// - data: The data object containing the image data. + static func image(data: Data) async -> RSImage? { + await withCheckedContinuation { continuation in + RSImage.image(with: data) { image in + continuation.resume(returning: image) + } + } + } + /// Asynchronously initializes an image from data. /// /// - Parameters: diff --git a/Shared/Article Extractor/ArticleExtractor.swift b/Shared/Article Extractor/ArticleExtractor.swift index d6b38ae7b..976a60966 100644 --- a/Shared/Article Extractor/ArticleExtractor.swift +++ b/Shared/Article Extractor/ArticleExtractor.swift @@ -10,7 +10,7 @@ import Foundation import Account import Secrets -public enum ArticleExtractorState { +public enum ArticleExtractorState: Sendable { case ready case processing case failedToParse @@ -18,7 +18,7 @@ public enum ArticleExtractorState { case cancelled } -protocol ArticleExtractorDelegate { +@MainActor protocol ArticleExtractorDelegate { func articleExtractionDidFail(with: Error) func articleExtractionDidComplete(extractedArticle: ExtractedArticle) } diff --git a/Shared/Article Rendering/WebViewConfiguration.swift b/Shared/Article Rendering/WebViewConfiguration.swift index a59a615b1..ca5773889 100644 --- a/Shared/Article Rendering/WebViewConfiguration.swift +++ b/Shared/Article Rendering/WebViewConfiguration.swift @@ -9,9 +9,9 @@ import Foundation import WebKit -final class WebViewConfiguration { +@MainActor final class WebViewConfiguration { - @MainActor static func configuration(with urlSchemeHandler: WKURLSchemeHandler) -> WKWebViewConfiguration { + static func configuration(with urlSchemeHandler: WKURLSchemeHandler) -> WKWebViewConfiguration { assert(Thread.isMainThread) let configuration = WKWebViewConfiguration() diff --git a/Shared/ArticleStyles/ArticleTheme.swift b/Shared/ArticleStyles/ArticleTheme.swift index 9c1e031a1..e9583a95c 100644 --- a/Shared/ArticleStyles/ArticleTheme.swift +++ b/Shared/ArticleStyles/ArticleTheme.swift @@ -8,7 +8,7 @@ import Foundation -struct ArticleTheme: Equatable { +struct ArticleTheme: Equatable, Sendable { static let defaultTheme = ArticleTheme() static let nnwThemeSuffix = ".nnwtheme" @@ -46,16 +46,15 @@ struct ArticleTheme: Equatable { let corePath = Bundle.main.path(forResource: "core", ofType: "css")! let stylesheetPath = Bundle.main.path(forResource: "stylesheet", ofType: "css")! - css = Self.stringAtPath(corePath)! + "\n" + Self.stringAtPath(stylesheetPath)! + self.css = Self.stringAtPath(corePath)! + "\n" + Self.stringAtPath(stylesheetPath)! let templatePath = Bundle.main.path(forResource: "template", ofType: "html")! - template = Self.stringAtPath(templatePath)! + self.template = Self.stringAtPath(templatePath)! - isAppTheme = true + self.isAppTheme = true } init(url: URL, isAppTheme: Bool) throws { - _ = url.startAccessingSecurityScopedResource() defer { url.stopAccessingSecurityScopedResource() @@ -106,5 +105,4 @@ struct ArticleTheme: Equatable { let filename = (path as NSString).lastPathComponent return filenameWithThemeSuffixRemoved(filename) == themeName } - } diff --git a/Shared/ArticleStyles/ArticleThemeDownloader.swift b/Shared/ArticleStyles/ArticleThemeDownloader.swift index 28f33e039..584ee80d0 100644 --- a/Shared/ArticleStyles/ArticleThemeDownloader.swift +++ b/Shared/ArticleStyles/ArticleThemeDownloader.swift @@ -9,7 +9,8 @@ import Foundation import Zip -public class ArticleThemeDownloader { +public final class ArticleThemeDownloader: Sendable { + public static let shared = ArticleThemeDownloader() public enum ArticleThemeDownloaderError: LocalizedError { case noThemeFile @@ -22,7 +23,6 @@ public class ArticleThemeDownloader { } } - public static let shared = ArticleThemeDownloader() private init() {} public func handleFile(at location: URL) throws { diff --git a/Shared/ArticleStyles/ArticleThemePlist.swift b/Shared/ArticleStyles/ArticleThemePlist.swift index 306b1dc8a..bac3ac888 100644 --- a/Shared/ArticleStyles/ArticleThemePlist.swift +++ b/Shared/ArticleStyles/ArticleThemePlist.swift @@ -8,12 +8,12 @@ import Foundation -public struct ArticleThemePlist: Codable, Equatable { - public var name: String - public var themeIdentifier: String - public var creatorHomePage: String - public var creatorName: String - public var version: Int +public struct ArticleThemePlist: Codable, Equatable, Sendable { + public let name: String + public let themeIdentifier: String + public let creatorHomePage: String + public let creatorName: String + public let version: Int enum CodingKeys: String, CodingKey { case name = "Name" diff --git a/Shared/Extensions/IconImage.swift b/Shared/Extensions/IconImage.swift index 3a813d68f..a8c72df59 100644 --- a/Shared/Extensions/IconImage.swift +++ b/Shared/Extensions/IconImage.swift @@ -14,7 +14,7 @@ import UIKit import RSCore -final class IconImage { +final class IconImage: @unchecked Sendable { lazy var isDark: Bool = { return image.isDark() diff --git a/Shared/Extensions/RSImage-AppIcons.swift b/Shared/Extensions/RSImage-AppIcons.swift index f464eef33..cd9dc4e74 100644 --- a/Shared/Extensions/RSImage-AppIcons.swift +++ b/Shared/Extensions/RSImage-AppIcons.swift @@ -27,7 +27,7 @@ extension RSImage { } extension IconImage { - static var appIcon: IconImage? = { + static let appIcon: IconImage? = { if let image = RSImage.appIconImage { return IconImage(image) } diff --git a/Shared/Extensions/RSImage-Extensions.swift b/Shared/Extensions/RSImage-Extensions.swift index a7dcee82d..12f59350b 100644 --- a/Shared/Extensions/RSImage-Extensions.swift +++ b/Shared/Extensions/RSImage-Extensions.swift @@ -40,7 +40,7 @@ extension RSImage { // MARK: - IconScalerQueue -private final class IconScalerQueue { +private final class IconScalerQueue: Sendable { static let shared = IconScalerQueue() diff --git a/Shared/Favicons/SingleFaviconDownloader.swift b/Shared/Favicons/SingleFaviconDownloader.swift index 92c1f67a8..6d05f994b 100644 --- a/Shared/Favicons/SingleFaviconDownloader.swift +++ b/Shared/Favicons/SingleFaviconDownloader.swift @@ -15,47 +15,44 @@ import RSWeb // Post .DidLoadFavicon notification once it’s in memory. extension Notification.Name { - static let DidLoadFavicon = Notification.Name("DidLoadFaviconNotification") } -final class SingleFaviconDownloader { - - enum DiskStatus { +@MainActor final class SingleFaviconDownloader { + private enum DiskStatus { case unknown, notOnDisk, onDisk } let faviconURL: String - var iconImage: IconImage? let homePageURL: String? + var iconImage: IconImage? + static private let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "SingleFaviconDownloader") + private let diskCache: BinaryDiskCache + private let queue: DispatchQueue + private let diskKey: String + private var lastDownloadAttemptDate: Date private var diskStatus = DiskStatus.unknown - private var diskCache: BinaryDiskCache - private let queue: DispatchQueue - - private var diskKey: String { - return faviconURL.md5String - } init(faviconURL: String, homePageURL: String?, diskCache: BinaryDiskCache, queue: DispatchQueue) { - self.faviconURL = faviconURL self.homePageURL = homePageURL self.diskCache = diskCache self.queue = queue self.lastDownloadAttemptDate = Date() + self.diskKey = faviconURL.md5String - findFavicon() + Task { @MainActor in + findFavicon() + } } func downloadFaviconIfNeeded() -> Bool { - // If we don’t have an image, and lastDownloadAttemptDate is a while ago, try again. - - if let _ = iconImage { + guard iconImage == nil else { return false } @@ -63,9 +60,11 @@ final class SingleFaviconDownloader { if Date().timeIntervalSince(lastDownloadAttemptDate) < retryInterval { return false } - lastDownloadAttemptDate = Date() - findFavicon() + + Task { @MainActor in + findFavicon() + } return true } @@ -73,58 +72,53 @@ final class SingleFaviconDownloader { private extension SingleFaviconDownloader { - func findFavicon() { + func findFavicon() async { + if let image = await readFromDisk() { + diskStatus = .onDisk + iconImage = IconImage(image) + postDidLoadFaviconNotification() + return + } - readFromDisk { (image) in + diskStatus = .notOnDisk - if let image = image { - self.diskStatus = .onDisk - self.iconImage = IconImage(image) - self.postDidLoadFaviconNotification() - return - } - - self.diskStatus = .notOnDisk - - self.downloadFavicon { (image) in - - if let image = image { - self.iconImage = IconImage(image) - } - - self.postDidLoadFaviconNotification() + if let image = await downloadFavicon() { + iconImage = IconImage(image) + postDidLoadFaviconNotification() + } + } + func readFromDisk() async -> RSImage? { + await withCheckedContinuation { continuation in + readFromDisk { image in + continuation.resume(returning: image) } } } - func readFromDisk(_ completion: @escaping @Sendable (RSImage?) -> Void) { - + private func readFromDisk(_ completion: @escaping @MainActor (RSImage?) -> Void) { guard diskStatus != .notOnDisk else { completion(nil) return } queue.async { - if let data = self.diskCache[self.diskKey], !data.isEmpty { RSImage.image(with: data, imageResultBlock: completion) return } - DispatchQueue.main.async { + Task { @MainActor in completion(nil) } } } func saveToDisk(_ data: Data) { - queue.async { - do { try self.diskCache.setData(data, forKey: self.diskKey) - DispatchQueue.main.async { + Task { @MainActor in self.diskStatus = .onDisk } } @@ -132,35 +126,30 @@ private extension SingleFaviconDownloader { } } - func downloadFavicon(_ completion: @escaping @Sendable (RSImage?) -> Void) { + func downloadFavicon() async -> RSImage? { + assert(Thread.isMainThread) guard let url = URL(string: faviconURL) else { - completion(nil) - return + return nil } - Task { @MainActor in - Downloader.shared.download(url) { (data, response, error) in - - if let data = data, !data.isEmpty, let response = response, response.statusIsOK, error == nil { - self.saveToDisk(data) - RSImage.image(with: data, imageResultBlock: completion) - return - } - - if let error = error { - Self.logger.error("Error downloading image at \(url.absoluteString): \(error.localizedDescription)") - } - - completion(nil) + do { + let (data, response) = try await Downloader.shared.download(url) + if let data, !data.isEmpty, let response, response.statusIsOK { + saveToDisk(data) + let image = await RSImage.image(data: data) + return image } + + } catch { + Self.logger.error("Error downloading image at \(url.absoluteString): \(error.localizedDescription)") } + + return nil } func postDidLoadFaviconNotification() { - assert(Thread.isMainThread) NotificationCenter.default.post(name: .DidLoadFavicon, object: self) } - } diff --git a/Shared/Images/FeedIconDownloader.swift b/Shared/Images/FeedIconDownloader.swift index b12543691..69aadba18 100644 --- a/Shared/Images/FeedIconDownloader.swift +++ b/Shared/Images/FeedIconDownloader.swift @@ -76,7 +76,7 @@ extension Notification.Name { @MainActor func checkFeedIconURL() { if let iconURL = feed.iconURL { icon(forURL: iconURL, feed: feed) { (image) in - MainActor.assumeIsolated { + Task { @MainActor in if let image = image { self.cache[feed] = IconImage(image) self.cacheIconURLForFeedURL(iconURL: iconURL, feedURL: feed.url) @@ -130,7 +130,7 @@ private extension FeedIconDownloader { SpecialCase.urlStringContainSpecialCase(urlString, specialCasesToSkip) } - func icon(forHomePageURL homePageURL: String, feed: Feed, _ resultBlock: @escaping (RSImage?, String?) -> Void) { + func icon(forHomePageURL homePageURL: String, feed: Feed, _ resultBlock: @escaping @MainActor (RSImage?, String?) -> Void) { if Self.shouldSkipDownloadingFeedIcon(homePageURL) { resultBlock(nil, nil) return @@ -149,7 +149,9 @@ private extension FeedIconDownloader { if let url = metadata.bestWebsiteIconURL() { homePagesWithNoIconURL.remove(homePageURL) icon(forURL: url, feed: feed) { image in - resultBlock(image, url) + Task { @MainActor in + resultBlock(image, url) + } } return } @@ -158,7 +160,7 @@ private extension FeedIconDownloader { resultBlock(nil, nil) } - func icon(forURL url: String, feed: Feed, _ imageResultBlock: @escaping @Sendable (RSImage?) -> Void) { + func icon(forURL url: String, feed: Feed, _ imageResultBlock: @escaping ImageResultBlock) { waitingForFeedURLs[url] = feed guard let imageData = imageDownloader.image(for: url) else { diff --git a/Shared/Images/ImageDownloader.swift b/Shared/Images/ImageDownloader.swift index f1a0d09cf..5f44e8ea9 100644 --- a/Shared/Images/ImageDownloader.swift +++ b/Shared/Images/ImageDownloader.swift @@ -10,7 +10,6 @@ import Foundation import os.log import RSCore import RSWeb -import RSCore extension Notification.Name { static let imageDidBecomeAvailable = Notification.Name("ImageDidBecomeAvailableNotification") // UserInfoKey.url @@ -19,7 +18,7 @@ extension Notification.Name { @MainActor final class ImageDownloader { public static let shared = ImageDownloader() - static private let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "ImageDownloader") + nonisolated static private let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "ImageDownloader") nonisolated private let diskCache: BinaryDiskCache private let queue: DispatchQueue @@ -40,7 +39,10 @@ extension Notification.Name { return data } - findImage(url) + Task { @MainActor in + findImage(url) + } + return nil } } @@ -53,31 +55,33 @@ private extension ImageDownloader { postImageDidBecomeAvailableNotification(url) } - func findImage(_ url: String) { + func findImage(_ url: String) async { guard !urlsInProgress.contains(url) && !badURLs.contains(url) else { return } urlsInProgress.insert(url) - readFromDisk(url) { (image) in - if let image { - self.cacheImage(url, image) - self.urlsInProgress.remove(url) - return - } + if let image = await readFromDisk(url: url) { + cacheImage(url, image) + urlsInProgress.remove(url) + return + } - Task { @MainActor in - let image = await self.downloadImage(url) + if let image = await downloadImage(url) { + cacheImage(url, image) + urlsInProgress.remove(url) + } + } - if let image { - self.cacheImage(url, image) - } - self.urlsInProgress.remove(url) + func readFromDisk(url: String) async -> Data? { + await withCheckedContinuation { continuation in + readFromDisk(url) { data in + continuation.resume(returning: data) } } } - func readFromDisk(_ url: String, _ completion: @escaping (Data?) -> Void) { + func readFromDisk(_ url: String, _ completion: @escaping @MainActor (Data?) -> Void) { queue.async { if let data = self.diskCache[self.diskKey(url)], !data.isEmpty { DispatchQueue.main.async { @@ -100,13 +104,13 @@ private extension ImageDownloader { do { let (data, response) = try await Downloader.shared.download(imageURL) - if let data = data, !data.isEmpty, let response = response, response.statusIsOK { - self.saveToDisk(url, data) + if let data, !data.isEmpty, let response, response.statusIsOK { + saveToDisk(url, data) return data } if let response = response as? HTTPURLResponse, response.statusCode >= HTTPResponseCode.badRequest && response.statusCode <= HTTPResponseCode.notAcceptable { - self.badURLs.insert(url) + badURLs.insert(url) } return nil @@ -127,6 +131,7 @@ private extension ImageDownloader { } func postImageDidBecomeAvailableNotification(_ url: String) { - NotificationCenter.default.postOnMainThread(name: .imageDidBecomeAvailable, object: self, userInfo: [UserInfoKey.url: url]) + assert(Thread.isMainThread) + NotificationCenter.default.post(name: .imageDidBecomeAvailable, object: self, userInfo: [UserInfoKey.url: url]) } } diff --git a/Shared/ShareExtension/ExtensionFeedAddRequestFile.swift b/Shared/ShareExtension/ExtensionFeedAddRequestFile.swift index d53d41522..e65ba5914 100644 --- a/Shared/ShareExtension/ExtensionFeedAddRequestFile.swift +++ b/Shared/ShareExtension/ExtensionFeedAddRequestFile.swift @@ -7,15 +7,16 @@ // import Foundation +import Synchronization import os.log import Account -final class ExtensionFeedAddRequestFile: NSObject, NSFilePresenter { +final class ExtensionFeedAddRequestFile: NSObject, NSFilePresenter, Sendable { static let shared = ExtensionFeedAddRequestFile() static private let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "ExtensionFeedAddRequestFile") - private static var filePath: String = { + private static let filePath: String = { let appGroup = Bundle.main.object(forInfoDictionaryKey: "AppGroup") as! String let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroup) return containerURL!.appendingPathComponent("extension_feed_add_request.plist").path @@ -35,14 +36,23 @@ final class ExtensionFeedAddRequestFile: NSObject, NSFilePresenter { operationQueue } - private var isActive = false + private let didStart = Mutex(false) func start() { - guard !isActive else { - assertionFailure("start called when already active") + var shouldBail = false + didStart.withLock { didStart in + if didStart { + shouldBail = true + assertionFailure("start called when already did start") + return + } + + didStart = true + } + + if shouldBail { return } - isActive = true NSFileCoordinator.addFilePresenter(self) Task { @MainActor in @@ -57,7 +67,10 @@ final class ExtensionFeedAddRequestFile: NSObject, NSFilePresenter { } func resume() { - assert(isActive) + didStart.withLock { didStart in + assert(didStart) + } + NSFileCoordinator.addFilePresenter(self) Task { @MainActor in process() @@ -65,7 +78,9 @@ final class ExtensionFeedAddRequestFile: NSObject, NSFilePresenter { } func suspend() { - assert(isActive) + didStart.withLock { didStart in + assert(didStart) + } NSFileCoordinator.removeFilePresenter(self) } From 350aea07884303e23fde52070a395195eb2cb813 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Tue, 18 Nov 2025 13:28:09 -0800 Subject: [PATCH 03/14] Fix various concurrency issues. --- Mac/AppDefaults.swift | 4 ++-- Shared/Favicons/SingleFaviconDownloader.swift | 4 ++-- Shared/Images/ImageDownloader.swift | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Mac/AppDefaults.swift b/Mac/AppDefaults.swift index 3bff00800..90ab80dbc 100644 --- a/Mac/AppDefaults.swift +++ b/Mac/AppDefaults.swift @@ -15,7 +15,7 @@ enum FontSize: Int { case veryLarge = 3 } -final class AppDefaults { +final class AppDefaults: Sendable { static let defaultThemeName = "Default" @@ -64,7 +64,7 @@ final class AppDefaults { return false }() - var isFirstRun: Bool = { + let isFirstRun: Bool = { if let _ = UserDefaults.standard.object(forKey: Key.firstRunDate) as? Date { return false } diff --git a/Shared/Favicons/SingleFaviconDownloader.swift b/Shared/Favicons/SingleFaviconDownloader.swift index 6d05f994b..0f43cb8cd 100644 --- a/Shared/Favicons/SingleFaviconDownloader.swift +++ b/Shared/Favicons/SingleFaviconDownloader.swift @@ -46,7 +46,7 @@ extension Notification.Name { self.diskKey = faviconURL.md5String Task { @MainActor in - findFavicon() + await findFavicon() } } @@ -63,7 +63,7 @@ extension Notification.Name { lastDownloadAttemptDate = Date() Task { @MainActor in - findFavicon() + await findFavicon() } return true diff --git a/Shared/Images/ImageDownloader.swift b/Shared/Images/ImageDownloader.swift index 5f44e8ea9..4bae103f4 100644 --- a/Shared/Images/ImageDownloader.swift +++ b/Shared/Images/ImageDownloader.swift @@ -40,7 +40,7 @@ extension Notification.Name { } Task { @MainActor in - findImage(url) + await findImage(url) } return nil From 3c24f9139a1f0b445a503c0ddc67577d4b76edc2 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Tue, 18 Nov 2025 14:33:24 -0800 Subject: [PATCH 04/14] Fix various concurrency issues. --- Mac/AppDelegate.swift | 26 ++--- .../Detail/DetailWebViewController.swift | 4 +- Mac/MainWindow/MainWindowController.swift | 3 +- .../SafariExtensionHandler.swift | 6 +- .../AppDelegate+Scriptability.swift | 2 +- Mac/Scriptability/ScriptingObject.swift | 8 +- .../ScriptingObjectContainer.swift | 8 +- Mac/ShareExtension/ShareViewController.swift | 21 +++- .../Sources/RSCore/Shared/Platform.swift | 10 +- .../Article Extractor/ArticleExtractor.swift | 104 +++++++++--------- .../ArticleStyles/ArticleThemesManager.swift | 80 ++++++++------ iOS/Add/AddFeedFolderViewController.swift | 2 +- 12 files changed, 150 insertions(+), 124 deletions(-) diff --git a/Mac/AppDelegate.swift b/Mac/AppDelegate.swift index 6461d62f9..e74c0592d 100644 --- a/Mac/AppDelegate.swift +++ b/Mac/AppDelegate.swift @@ -20,7 +20,7 @@ import Sparkle let appName = "NetNewsWire" -var appDelegate: AppDelegate! +@MainActor var appDelegate: AppDelegate! @main final class AppDelegate: NSObject, NSApplicationDelegate, NSUserInterfaceValidations, UNUserNotificationCenterDelegate, UnreadCountProvider, SPUStandardUserDriverDelegate, SPUUpdaterDelegate { @@ -105,8 +105,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSUserInterfaceValidat crashReporter.enable() 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) @@ -450,23 +448,25 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSUserInterfaceValidat // MARK: UNUserNotificationCenterDelegate - func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { + nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler([.banner, .badge, .sound]) } - func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { + nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { let userInfo = response.notification.request.content.userInfo - switch response.actionIdentifier { - case UserNotificationManager.ActionIdentifier.markAsRead: - handleMarkAsRead(userInfo: userInfo) - case UserNotificationManager.ActionIdentifier.markAsStarred: - handleMarkAsStarred(userInfo: userInfo) - default: - mainWindowController?.handle(response) + Task { @MainActor in + switch response.actionIdentifier { + case UserNotificationManager.ActionIdentifier.markAsRead: + handleMarkAsRead(userInfo: userInfo) + case UserNotificationManager.ActionIdentifier.markAsStarred: + handleMarkAsStarred(userInfo: userInfo) + default: + mainWindowController?.handle(response) + } + completionHandler() } - completionHandler() } // MARK: Add Feed diff --git a/Mac/MainWindow/Detail/DetailWebViewController.swift b/Mac/MainWindow/Detail/DetailWebViewController.swift index 5fd87b419..d15f7501d 100644 --- a/Mac/MainWindow/Detail/DetailWebViewController.swift +++ b/Mac/MainWindow/Detail/DetailWebViewController.swift @@ -196,7 +196,7 @@ extension DetailWebViewController: WKNavigationDelegate, WKUIDelegate { // WKNavigationDelegate - public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { + func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping @MainActor @Sendable (WKNavigationActionPolicy) -> Void) { if navigationAction.navigationType == .linkActivated { if let url = navigationAction.request.url { self.openInBrowser(url, flags: navigationAction.modifierFlags) @@ -204,7 +204,7 @@ extension DetailWebViewController: WKNavigationDelegate, WKUIDelegate { decisionHandler(.cancel) return } - + decisionHandler(.allow) } diff --git a/Mac/MainWindow/MainWindowController.swift b/Mac/MainWindow/MainWindowController.swift index bdc283050..05f4ee417 100644 --- a/Mac/MainWindow/MainWindowController.swift +++ b/Mac/MainWindow/MainWindowController.swift @@ -1310,8 +1310,7 @@ private extension MainWindowController { } func startArticleExtractorForCurrentLink() { - if let link = currentLink, let extractor = ArticleExtractor(link) { - extractor.delegate = self + if let link = currentLink, let extractor = ArticleExtractor(link, delegate: self) { extractor.process() articleExtractor = extractor } diff --git a/Mac/SafariExtension/SafariExtensionHandler.swift b/Mac/SafariExtension/SafariExtensionHandler.swift index d4366203d..88d8a92df 100644 --- a/Mac/SafariExtension/SafariExtensionHandler.swift +++ b/Mac/SafariExtension/SafariExtensionHandler.swift @@ -6,7 +6,7 @@ // Copyright © 2018 Ranchero Software. All rights reserved. // -import SafariServices +@preconcurrency import SafariServices final class SafariExtensionHandler: SFSafariExtensionHandler { @@ -29,8 +29,8 @@ final class SafariExtensionHandler: SFSafariExtensionHandler { } // Maps from UUID to a validation wrapper - static var gPingPongMap = Dictionary() - static var validationQueue = DispatchQueue(label: "Toolbar Validation") + nonisolated(unsafe) static var gPingPongMap = Dictionary() + static let validationQueue = DispatchQueue(label: "Toolbar Validation") // Bottleneck for calling through to a validation handler we have saved, and removing it from the list. static func callValidationHandler(forHandlerID handlerID: String, withShouldValidate shouldValidate: Bool) { diff --git a/Mac/Scriptability/AppDelegate+Scriptability.swift b/Mac/Scriptability/AppDelegate+Scriptability.swift index 6cb105f81..1391f644a 100644 --- a/Mac/Scriptability/AppDelegate+Scriptability.swift +++ b/Mac/Scriptability/AppDelegate+Scriptability.swift @@ -92,7 +92,7 @@ extension AppDelegate: AppDelegateAppleEvents { } final class NetNewsWireCreateElementCommand : NSCreateCommand { - @MainActor override func performDefaultImplementation() -> Any? { + override func performDefaultImplementation() -> Any? { let classDescription = self.createClassDescription if (classDescription.className == "feed") { return ScriptableFeed.handleCreateElement(command:self) diff --git a/Mac/Scriptability/ScriptingObject.swift b/Mac/Scriptability/ScriptingObject.swift index 0a5bf9576..a2a5768b3 100644 --- a/Mac/Scriptability/ScriptingObject.swift +++ b/Mac/Scriptability/ScriptingObject.swift @@ -9,14 +9,14 @@ import Foundation @MainActor protocol ScriptingObject { - var objectSpecifier: NSScriptObjectSpecifier? { get } - var scriptingKey: String { get } + @MainActor var objectSpecifier: NSScriptObjectSpecifier? { get } + @MainActor var scriptingKey: String { get } } @MainActor protocol NamedScriptingObject: ScriptingObject { - var name:String { get } + @MainActor var name:String { get } } @MainActor protocol UniqueIDScriptingObject: ScriptingObject { - var scriptingUniqueID: Any { get } + @MainActor var scriptingUniqueID: Any { get } } diff --git a/Mac/Scriptability/ScriptingObjectContainer.swift b/Mac/Scriptability/ScriptingObjectContainer.swift index d7ebb8a22..a1ca69435 100644 --- a/Mac/Scriptability/ScriptingObjectContainer.swift +++ b/Mac/Scriptability/ScriptingObjectContainer.swift @@ -10,13 +10,13 @@ import AppKit import Account @MainActor protocol ScriptingObjectContainer: ScriptingObject { - var scriptingClassDescription:NSScriptClassDescription { get } - func deleteElement(_ element:ScriptingObject) + @MainActor var scriptingClassDescription:NSScriptClassDescription { get } + @MainActor func deleteElement(_ element:ScriptingObject) } @MainActor extension ScriptingObjectContainer { - func makeFormNameScriptObjectSpecifier(forObject object:NamedScriptingObject) -> NSScriptObjectSpecifier? { + @MainActor func makeFormNameScriptObjectSpecifier(forObject object:NamedScriptingObject) -> NSScriptObjectSpecifier? { let containerClassDescription = self.scriptingClassDescription let containerScriptObjectSpecifier = self.objectSpecifier let scriptingKey = object.scriptingKey @@ -26,7 +26,7 @@ import Account return specifier } - func makeFormUniqueIDScriptObjectSpecifier(forObject object:UniqueIDScriptingObject) -> NSScriptObjectSpecifier? { + @MainActor func makeFormUniqueIDScriptObjectSpecifier(forObject object:UniqueIDScriptingObject) -> NSScriptObjectSpecifier? { let containerClassDescription = self.scriptingClassDescription let containerScriptObjectSpecifier = self.objectSpecifier let scriptingKey = object.scriptingKey diff --git a/Mac/ShareExtension/ShareViewController.swift b/Mac/ShareExtension/ShareViewController.swift index fe2cbc33d..15ba28ac7 100644 --- a/Mac/ShareExtension/ShareViewController.swift +++ b/Mac/ShareExtension/ShareViewController.swift @@ -8,13 +8,25 @@ import Cocoa import UniformTypeIdentifiers +import Synchronization final class ShareViewController: NSViewController { - @IBOutlet weak var nameTextField: NSTextField! @IBOutlet weak var folderPopUpButton: NSPopUpButton! - private var url: URL? + private struct State: Sendable { + var url: URL? + } + private let state = Mutex(State()) + + nonisolated private var url: URL? { + get { + state.withLock { $0.url } + } + set { + state.withLock { $0.url = newValue } + } + } private var extensionContainers: ExtensionContainers? override var nibName: NSNib.Name? { @@ -79,11 +91,10 @@ final class ShareViewController: NSViewController { } }) } - - } + } @IBAction func send(_ sender: AnyObject?) { - guard let url = url, let selectedContainer = selectedContainer(), let containerID = selectedContainer.containerID else { + guard let url, let selectedContainer = selectedContainer(), let containerID = selectedContainer.containerID else { self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil) return } diff --git a/Modules/RSCore/Sources/RSCore/Shared/Platform.swift b/Modules/RSCore/Sources/RSCore/Shared/Platform.swift index 4ecb64ad7..a976d2c69 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/Platform.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/Platform.swift @@ -76,16 +76,18 @@ private extension Platform { static func dataFolder(forApplication appName: String?) -> URL? { do { + #if os(macOS) var dataFolder = try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: false) if let appName = appName ?? Bundle.main.infoDictionary?["CFBundleExecutable"] as? String { - dataFolder = dataFolder.appendingPathComponent(appName) - - try FileManager.default.createDirectory(at: dataFolder, withIntermediateDirectories: true, attributes: nil) } + #else // iOS + let dataFolder = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) + #endif + + try FileManager.default.createDirectory(at: dataFolder, withIntermediateDirectories: true, attributes: nil) - return dataFolder } catch { Self.logger.error("Platform.dataFolder error: \(error.localizedDescription)") } diff --git a/Shared/Article Extractor/ArticleExtractor.swift b/Shared/Article Extractor/ArticleExtractor.swift index 976a60966..d063399ad 100644 --- a/Shared/Article Extractor/ArticleExtractor.swift +++ b/Shared/Article Extractor/ArticleExtractor.swift @@ -19,23 +19,22 @@ public enum ArticleExtractorState: Sendable { } @MainActor protocol ArticleExtractorDelegate { - func articleExtractionDidFail(with: Error) - func articleExtractionDidComplete(extractedArticle: ExtractedArticle) + func articleExtractionDidFail(with: Error) + func articleExtractionDidComplete(extractedArticle: ExtractedArticle) } -final class ArticleExtractor { +@MainActor final class ArticleExtractor { + let articleLink: String + let delegate: ArticleExtractorDelegate + var article: ExtractedArticle? + var state = ArticleExtractorState.ready + private let url: URL private var dataTask: URLSessionDataTask? = nil - var state: ArticleExtractorState! - var article: ExtractedArticle? - var delegate: ArticleExtractorDelegate? - var articleLink: String? - - private var url: URL! - - public init?(_ articleLink: String) { + public init?(_ articleLink: String, delegate: ArticleExtractorDelegate) { self.articleLink = articleLink + self.delegate = delegate let clientURL = "https://extract.feedbin.com/parser" let username = SecretKey.mercuryClientID @@ -56,56 +55,57 @@ final class ArticleExtractor { state = .processing - dataTask = URLSession.shared.dataTask(with: url) { [weak self] data, response, error in + dataTask = URLSession.shared.dataTask(with: url) { [weak self] data, response, error in + Task { @MainActor in + guard let self else { + return + } - guard let self = self else { return } - - if let error = error { - self.state = .failedToParse - DispatchQueue.main.async { - self.delegate?.articleExtractionDidFail(with: error) - } - return - } - - guard let data = data else { - self.state = .failedToParse - DispatchQueue.main.async { - self.delegate?.articleExtractionDidFail(with: URLError(.cannotDecodeContentData)) - } - return - } - - do { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .iso8601 - self.article = try decoder.decode(ExtractedArticle.self, from: data) - - DispatchQueue.main.async { - if self.article?.content == nil { - self.state = .failedToParse - self.delegate?.articleExtractionDidFail(with: URLError(.cannotDecodeContentData)) - } else { - self.state = .complete - self.delegate?.articleExtractionDidComplete(extractedArticle: self.article!) + if let error = error { + self.state = .failedToParse + DispatchQueue.main.async { + self.delegate.articleExtractionDidFail(with: error) } - } - } catch { - self.state = .failedToParse - DispatchQueue.main.async { - self.delegate?.articleExtractionDidFail(with: error) - } - } + return + } - } + guard let data = data else { + self.state = .failedToParse + DispatchQueue.main.async { + self.delegate.articleExtractionDidFail(with: URLError(.cannotDecodeContentData)) + } + return + } + + do { + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .iso8601 + let decodedArticle = try decoder.decode(ExtractedArticle.self, from: data) + + Task { @MainActor in + self.article = decodedArticle + if decodedArticle.content == nil { + self.state = .failedToParse + self.delegate.articleExtractionDidFail(with: URLError(.cannotDecodeContentData)) + } else { + self.state = .complete + self.delegate.articleExtractionDidComplete(extractedArticle: decodedArticle) + } + } + } catch { + self.state = .failedToParse + Task { @MainActor in + self.delegate.articleExtractionDidFail(with: error) + } + } + } + } dataTask!.resume() - } public func cancel() { state = .cancelled dataTask?.cancel() } - } diff --git a/Shared/ArticleStyles/ArticleThemesManager.swift b/Shared/ArticleStyles/ArticleThemesManager.swift index 1a5938700..430665f8b 100644 --- a/Shared/ArticleStyles/ArticleThemesManager.swift +++ b/Shared/ArticleStyles/ArticleThemesManager.swift @@ -14,15 +14,12 @@ public extension Notification.Name { static let CurrentArticleThemeDidChangeNotification = Notification.Name("CurrentArticleThemeDidChangeNotification") } -final class ArticleThemesManager: NSObject, NSFilePresenter { - - static var shared: ArticleThemesManager! +@MainActor final class ArticleThemesManager: NSObject, NSFilePresenter { + static let shared = ArticleThemesManager() public let folderPath: String - lazy var presentedItemOperationQueue = OperationQueue.main - var presentedItemURL: URL? { - return URL(fileURLWithPath: folderPath) - } + let presentedItemOperationQueue = OperationQueue.main // NSFilePresenter + let presentedItemURL: URL? // NSFilePresenter var currentThemeName: String { get { @@ -49,8 +46,12 @@ final class ArticleThemesManager: NSObject, NSFilePresenter { } } - init(folderPath: String) { + private var didStart = false + + override init() { + let folderPath = Platform.dataSubfolder(forApplication: nil, folderName: "Themes")! self.folderPath = folderPath + self.presentedItemURL = URL(fileURLWithPath: folderPath) self.currentTheme = ArticleTheme.defaultTheme super.init() @@ -61,6 +62,14 @@ final class ArticleThemesManager: NSObject, NSFilePresenter { assertionFailure("Could not create folder for Themes.") abort() } + } + + func start() { + guard !didStart else { + assertionFailure("ArticlesThemesManager.start called when already started.") + return + } + didStart = true updateThemeNames() updateCurrentTheme() @@ -68,7 +77,7 @@ final class ArticleThemesManager: NSObject, NSFilePresenter { NSFileCoordinator.addFilePresenter(self) } - func presentedSubitemDidChange(at url: URL) { + nonisolated func presentedSubitemDidChange(at url: URL) { updateThemeNames() updateCurrentTheme() } @@ -123,50 +132,55 @@ final class ArticleThemesManager: NSObject, NSFilePresenter { try? FileManager.default.removeItem(atPath: filename) } } - } // MARK : Private private extension ArticleThemesManager { - func updateThemeNames() { - let appThemeFilenames = Bundle.main.paths(forResourcesOfType: ArticleTheme.nnwThemeSuffix, inDirectory: nil) - let appThemeNames = Set(appThemeFilenames.map { ArticleTheme.themeNameForPath($0) }) + nonisolated func updateThemeNames() { + MainActor.assumeIsolated { + let appThemeFilenames = Bundle.main.paths(forResourcesOfType: ArticleTheme.nnwThemeSuffix, inDirectory: nil) + let appThemeNames = Set(appThemeFilenames.map { ArticleTheme.themeNameForPath($0) }) - let installedThemeNames = Set(allThemePaths(folderPath).map { ArticleTheme.themeNameForPath($0) }) + let installedThemeNames = Set(allThemePaths(folderPath).map { ArticleTheme.themeNameForPath($0) }) - let allThemeNames = appThemeNames.union(installedThemeNames) + let allThemeNames = appThemeNames.union(installedThemeNames) - let sortedThemeNames = allThemeNames.sorted(by: { $0.compare($1, options: .caseInsensitive) == .orderedAscending }) - if sortedThemeNames != themeNames { - themeNames = sortedThemeNames + let sortedThemeNames = allThemeNames.sorted(by: { $0.compare($1, options: .caseInsensitive) == .orderedAscending }) + Task { @MainActor in + if sortedThemeNames != themeNames { + themeNames = sortedThemeNames + } + } } } func defaultArticleTheme() -> ArticleTheme { - return articleThemeWithThemeName(AppDefaults.defaultThemeName)! + articleThemeWithThemeName(AppDefaults.defaultThemeName)! } - func updateCurrentTheme() { - var themeName = currentThemeName - if !themeNames.contains(themeName) { - themeName = AppDefaults.defaultThemeName - currentThemeName = AppDefaults.defaultThemeName - } + nonisolated func updateCurrentTheme() { + MainActor.assumeIsolated { + var themeName = currentThemeName + if !themeNames.contains(themeName) { + themeName = AppDefaults.defaultThemeName + currentThemeName = AppDefaults.defaultThemeName + } - var articleTheme = articleThemeWithThemeName(themeName) - if articleTheme == nil { - articleTheme = defaultArticleTheme() - currentThemeName = AppDefaults.defaultThemeName - } + var articleTheme = articleThemeWithThemeName(themeName) + if articleTheme == nil { + articleTheme = defaultArticleTheme() + currentThemeName = AppDefaults.defaultThemeName + } - if let articleTheme = articleTheme, articleTheme != currentTheme { - currentTheme = articleTheme + if let articleTheme = articleTheme, articleTheme != currentTheme { + currentTheme = articleTheme + } } } - func allThemePaths(_ folder: String) -> [String] { + nonisolated func allThemePaths(_ folder: String) -> [String] { let filepaths = FileManager.default.filePaths(inFolder: folder) return filepaths?.filter { $0.hasSuffix(ArticleTheme.nnwThemeSuffix) } ?? [] } diff --git a/iOS/Add/AddFeedFolderViewController.swift b/iOS/Add/AddFeedFolderViewController.swift index b66a360fe..ee7edee03 100644 --- a/iOS/Add/AddFeedFolderViewController.swift +++ b/iOS/Add/AddFeedFolderViewController.swift @@ -10,7 +10,7 @@ import UIKit import RSCore import Account -protocol AddFeedFolderViewControllerDelegate { +@MainActor protocol AddFeedFolderViewControllerDelegate { func didSelect(container: Container) } From 8ecba60d7193c1863ff419c12b9c08336848c01e Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Tue, 18 Nov 2025 15:29:29 -0800 Subject: [PATCH 05/14] Fix AppleScript implementation concurrency errors. --- Mac/Scriptability/Account+Scriptability.swift | 15 +++---- .../AppDelegate+Scriptability.swift | 44 +++++++++++++------ Mac/Scriptability/Article+Scriptability.swift | 14 +++--- Mac/Scriptability/Author+Scriptability.swift | 8 ++-- Mac/Scriptability/Feed+Scriptability.swift | 14 +++--- Mac/Scriptability/Folder+Scriptability.swift | 14 +++--- .../NSApplication+Scriptability.swift | 8 ++-- Mac/Scriptability/ScriptingObject.swift | 14 +++--- .../ScriptingObjectContainer.swift | 12 ++--- Modules/Account/Sources/Account/Account.swift | 2 +- Modules/Account/Sources/Account/Feed.swift | 8 ++-- Modules/Account/Sources/Account/Folder.swift | 4 +- 12 files changed, 87 insertions(+), 70 deletions(-) diff --git a/Mac/Scriptability/Account+Scriptability.swift b/Mac/Scriptability/Account+Scriptability.swift index 220a174c1..ec858e7c4 100644 --- a/Mac/Scriptability/Account+Scriptability.swift +++ b/Mac/Scriptability/Account+Scriptability.swift @@ -12,7 +12,7 @@ import Articles import RSCore @objc(ScriptableAccount) -@MainActor final class ScriptableAccount: NSObject, UniqueIDScriptingObject, ScriptingObjectContainer { +@MainActor final class ScriptableAccount: NSObject, UniqueIDScriptingObject, @preconcurrency ScriptingObjectContainer { let account:Account init (_ account:Account) { @@ -20,10 +20,9 @@ import RSCore } @objc(objectSpecifier) - override var objectSpecifier: NSScriptObjectSpecifier? { - let myContainer = NSApplication.shared - let scriptObjectSpecifier = myContainer.makeFormUniqueIDScriptObjectSpecifier(forObject:self) - return (scriptObjectSpecifier) + nonisolated override var objectSpecifier: NSScriptObjectSpecifier? { + let myContainer = MainActor.assumeIsolated { NSApplication.shared } + return myContainer.makeFormUniqueIDScriptObjectSpecifier(forObject:self) } @objc(scriptingIsActive) @@ -48,7 +47,7 @@ import RSCore // MARK: --- ScriptingObject protocol --- - var scriptingKey: String { + nonisolated var scriptingKey: String { return "accounts" } @@ -57,13 +56,13 @@ import RSCore // I am not sure if account should prefer to be specified by name or by ID // but in either case it seems like the accountID would be used as the keydata, so I chose ID @objc(uniqueId) - var scriptingUniqueID:Any { + nonisolated var scriptingUniqueID:Any { return account.accountID } // MARK: --- ScriptingObjectContainer protocol --- - var scriptingClassDescription: NSScriptClassDescription { + nonisolated var scriptingClassDescription: NSScriptClassDescription { return self.classDescription as! NSScriptClassDescription } diff --git a/Mac/Scriptability/AppDelegate+Scriptability.swift b/Mac/Scriptability/AppDelegate+Scriptability.swift index 1391f644a..672c8febb 100644 --- a/Mac/Scriptability/AppDelegate+Scriptability.swift +++ b/Mac/Scriptability/AppDelegate+Scriptability.swift @@ -30,6 +30,12 @@ import Articles var scriptingMainWindowController:ScriptingMainWindowController? {get} } +// Wrapper to safely transfer non-Sendable values across isolation boundaries +// This is safe for AppleScript commands because they always execute on the main thread +private struct UnsafeSendable: @unchecked Sendable { + let value: T +} + extension AppDelegate: AppDelegateAppleEvents { // MARK: GetURL Apple Event @@ -92,14 +98,22 @@ extension AppDelegate: AppDelegateAppleEvents { } final class NetNewsWireCreateElementCommand : NSCreateCommand { - override func performDefaultImplementation() -> Any? { - let classDescription = self.createClassDescription - if (classDescription.className == "feed") { - return ScriptableFeed.handleCreateElement(command:self) - } else if (classDescription.className == "folder") { - return ScriptableFolder.handleCreateElement(command:self) + // AppleScript commands always execute on the main thread, so using assumeIsolated is safe + // even though NSCreateCommand doesn't have concurrency annotations + nonisolated override func performDefaultImplementation() -> Any? { + let unsafeSelf = UnsafeSendable(value: self) + let wrapped = MainActor.assumeIsolated { () -> UnsafeSendable in + let instance = unsafeSelf.value + let classDescription: NSScriptClassDescription = instance.createClassDescription + let command: NSCreateCommand = instance + if (classDescription.className == "feed") { + return UnsafeSendable(value: ScriptableFeed.handleCreateElement(command:command)) + } else if (classDescription.className == "folder") { + return UnsafeSendable(value: ScriptableFolder.handleCreateElement(command:command)) + } + return UnsafeSendable(value: nil) } - return nil + return wrapped.value } } @@ -111,7 +125,7 @@ final class NetNewsWireCreateElementCommand : NSCreateCommand { is ambiguity about whether specifiers are lists or single objects, the code switches based on which it is. */ -@MainActor final class NetNewsWireDeleteCommand : NSDeleteCommand { +final class NetNewsWireDeleteCommand : NSDeleteCommand { /* delete(objectToDelete:, from container:) @@ -156,11 +170,15 @@ final class NetNewsWireCreateElementCommand : NSCreateCommand { 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:) */ - @MainActor override func performDefaultImplementation() -> Any? { - if let receiversSpecifier = self.receiversSpecifier { - if let receiverObjects = receiversSpecifier.objectsByEvaluatingSpecifier { - self.delete(specifier:self.keySpecifier, from:receiverObjects) - } + // AppleScript commands always execute on the main thread, so using assumeIsolated is safe + // even though NSDeleteCommand doesn't have concurrency annotations + nonisolated override func performDefaultImplementation() -> Any? { + let unsafeSelf = UnsafeSendable(value: self) + MainActor.assumeIsolated { + let instance = unsafeSelf.value + if let receiverObjects = instance.receiversSpecifier?.objectsByEvaluatingSpecifier { + instance.delete(specifier:instance.keySpecifier, from:receiverObjects) + } } return nil } diff --git a/Mac/Scriptability/Article+Scriptability.swift b/Mac/Scriptability/Article+Scriptability.swift index a5c92c227..cfe60d89e 100644 --- a/Mac/Scriptability/Article+Scriptability.swift +++ b/Mac/Scriptability/Article+Scriptability.swift @@ -11,10 +11,10 @@ import Account import Articles @objc(ScriptableArticle) -@MainActor final class ScriptableArticle: NSObject, UniqueIDScriptingObject, ScriptingObjectContainer { +@MainActor final class ScriptableArticle: NSObject, UniqueIDScriptingObject, @preconcurrency ScriptingObjectContainer { let article:Article - let container:ScriptingObjectContainer + nonisolated(unsafe) let container:ScriptingObjectContainer init (_ article:Article, container:ScriptingObjectContainer) { self.article = article @@ -22,14 +22,14 @@ import Articles } @objc(objectSpecifier) - override var objectSpecifier: NSScriptObjectSpecifier? { + nonisolated override var objectSpecifier: NSScriptObjectSpecifier? { let scriptObjectSpecifier = self.container.makeFormUniqueIDScriptObjectSpecifier(forObject:self) - return (scriptObjectSpecifier) + return scriptObjectSpecifier } // MARK: --- ScriptingObject protocol --- - var scriptingKey: String { + nonisolated var scriptingKey: String { return "articles" } @@ -39,13 +39,13 @@ import Articles // article.uniqueID here is the feed unique id @objc(uniqueId) - var scriptingUniqueID:Any { + nonisolated var scriptingUniqueID:Any { return article.uniqueID } // MARK: --- ScriptingObjectContainer protocol --- - var scriptingClassDescription: NSScriptClassDescription { + nonisolated var scriptingClassDescription: NSScriptClassDescription { return self.classDescription as! NSScriptClassDescription } diff --git a/Mac/Scriptability/Author+Scriptability.swift b/Mac/Scriptability/Author+Scriptability.swift index b830de805..705a563b4 100644 --- a/Mac/Scriptability/Author+Scriptability.swift +++ b/Mac/Scriptability/Author+Scriptability.swift @@ -13,7 +13,7 @@ import Articles @objc(ScriptableAuthor) @MainActor final class ScriptableAuthor: NSObject, UniqueIDScriptingObject { let author: Author - let container: ScriptingObjectContainer + nonisolated(unsafe) let container: ScriptingObjectContainer init (_ author: Author, container: ScriptingObjectContainer) { self.author = author @@ -21,7 +21,7 @@ import Articles } @objc(objectSpecifier) - override var objectSpecifier: NSScriptObjectSpecifier? { + nonisolated override var objectSpecifier: NSScriptObjectSpecifier? { let scriptObjectSpecifier = container.makeFormUniqueIDScriptObjectSpecifier(forObject: self) return scriptObjectSpecifier } @@ -33,14 +33,14 @@ import Articles // MARK: --- ScriptingObject protocol --- - var scriptingKey: String { + nonisolated var scriptingKey: String { return "authors" } // MARK: --- UniqueIdScriptingObject protocol --- @objc(uniqueId) - var scriptingUniqueID:Any { + nonisolated var scriptingUniqueID:Any { return author.authorID } diff --git a/Mac/Scriptability/Feed+Scriptability.swift b/Mac/Scriptability/Feed+Scriptability.swift index 2e76452b3..109497c5a 100644 --- a/Mac/Scriptability/Feed+Scriptability.swift +++ b/Mac/Scriptability/Feed+Scriptability.swift @@ -12,10 +12,10 @@ import Account import Articles @objc(ScriptableFeed) -@MainActor final class ScriptableFeed: NSObject, UniqueIDScriptingObject, ScriptingObjectContainer { +@MainActor final class ScriptableFeed: NSObject, UniqueIDScriptingObject, @preconcurrency ScriptingObjectContainer { let feed:Feed - let container:ScriptingObjectContainer + nonisolated(unsafe) let container:ScriptingObjectContainer init (_ feed:Feed, container:ScriptingObjectContainer) { self.feed = feed @@ -23,9 +23,9 @@ import Articles } @objc(objectSpecifier) - override var objectSpecifier: NSScriptObjectSpecifier? { + nonisolated override var objectSpecifier: NSScriptObjectSpecifier? { let scriptObjectSpecifier = self.container.makeFormUniqueIDScriptObjectSpecifier(forObject:self) - return (scriptObjectSpecifier) + return scriptObjectSpecifier } @objc(scriptingSpecifierDescriptor) @@ -35,7 +35,7 @@ import Articles // MARK: --- ScriptingObject protocol --- - var scriptingKey: String { + nonisolated var scriptingKey: String { return "feeds" } @@ -44,13 +44,13 @@ import Articles // I am not sure if account should prefer to be specified by name or by ID // but in either case it seems like the accountID would be used as the keydata, so I chose ID @objc(uniqueId) - var scriptingUniqueID:Any { + nonisolated var scriptingUniqueID:Any { return feed.feedID } // MARK: --- ScriptingObjectContainer protocol --- - var scriptingClassDescription: NSScriptClassDescription { + nonisolated var scriptingClassDescription: NSScriptClassDescription { return self.classDescription as! NSScriptClassDescription } diff --git a/Mac/Scriptability/Folder+Scriptability.swift b/Mac/Scriptability/Folder+Scriptability.swift index 58de28f71..197208d94 100644 --- a/Mac/Scriptability/Folder+Scriptability.swift +++ b/Mac/Scriptability/Folder+Scriptability.swift @@ -12,10 +12,10 @@ import Articles import RSCore @objc(ScriptableFolder) -@MainActor final class ScriptableFolder: NSObject, UniqueIDScriptingObject, ScriptingObjectContainer { +@MainActor final class ScriptableFolder: NSObject, UniqueIDScriptingObject, @preconcurrency ScriptingObjectContainer { let folder:Folder - let container:ScriptingObjectContainer + nonisolated(unsafe) let container:ScriptingObjectContainer init (_ folder:Folder, container:ScriptingObjectContainer) { self.folder = folder @@ -23,14 +23,14 @@ import RSCore } @objc(objectSpecifier) - override var objectSpecifier: NSScriptObjectSpecifier? { + nonisolated override var objectSpecifier: NSScriptObjectSpecifier? { let scriptObjectSpecifier = self.container.makeFormUniqueIDScriptObjectSpecifier(forObject:self) - return (scriptObjectSpecifier) + return scriptObjectSpecifier } // MARK: --- ScriptingObject protocol --- - var scriptingKey: String { + nonisolated var scriptingKey: String { return "folders" } @@ -40,13 +40,13 @@ import RSCore // but in either case it seems like the accountID would be used as the keydata, so I chose ID @objc(uniqueId) - var scriptingUniqueID:Any { + nonisolated var scriptingUniqueID:Any { return folder.folderID } // MARK: --- ScriptingObjectContainer protocol --- - var scriptingClassDescription: NSScriptClassDescription { + nonisolated var scriptingClassDescription: NSScriptClassDescription { return self.classDescription as! NSScriptClassDescription } diff --git a/Mac/Scriptability/NSApplication+Scriptability.swift b/Mac/Scriptability/NSApplication+Scriptability.swift index dba8ea9f9..72d6ed62f 100644 --- a/Mac/Scriptability/NSApplication+Scriptability.swift +++ b/Mac/Scriptability/NSApplication+Scriptability.swift @@ -10,19 +10,19 @@ import AppKit import Account import Articles -extension NSApplication : ScriptingObjectContainer { +extension NSApplication : @preconcurrency ScriptingObjectContainer { // MARK: --- ScriptingObjectContainer protocol --- - var scriptingClassDescription: NSScriptClassDescription { - return NSApplication.shared.classDescription as! NSScriptClassDescription + nonisolated var scriptingClassDescription: NSScriptClassDescription { + return self.classDescription as! NSScriptClassDescription } func deleteElement(_ element:ScriptingObject) { print ("delete event not handled") } - var scriptingKey: String { + nonisolated var scriptingKey: String { return "application" } diff --git a/Mac/Scriptability/ScriptingObject.swift b/Mac/Scriptability/ScriptingObject.swift index a2a5768b3..a03be12d0 100644 --- a/Mac/Scriptability/ScriptingObject.swift +++ b/Mac/Scriptability/ScriptingObject.swift @@ -8,15 +8,15 @@ import Foundation -@MainActor protocol ScriptingObject { - @MainActor var objectSpecifier: NSScriptObjectSpecifier? { get } - @MainActor var scriptingKey: String { get } +protocol ScriptingObject { + var objectSpecifier: NSScriptObjectSpecifier? { get } + var scriptingKey: String { get } } -@MainActor protocol NamedScriptingObject: ScriptingObject { - @MainActor var name:String { get } +protocol NamedScriptingObject: ScriptingObject { + var name:String { get } } -@MainActor protocol UniqueIDScriptingObject: ScriptingObject { - @MainActor var scriptingUniqueID: Any { get } +protocol UniqueIDScriptingObject: ScriptingObject { + var scriptingUniqueID: Any { get } } diff --git a/Mac/Scriptability/ScriptingObjectContainer.swift b/Mac/Scriptability/ScriptingObjectContainer.swift index a1ca69435..df4505c38 100644 --- a/Mac/Scriptability/ScriptingObjectContainer.swift +++ b/Mac/Scriptability/ScriptingObjectContainer.swift @@ -9,14 +9,14 @@ import AppKit import Account -@MainActor protocol ScriptingObjectContainer: ScriptingObject { - @MainActor var scriptingClassDescription:NSScriptClassDescription { get } - @MainActor func deleteElement(_ element:ScriptingObject) +protocol ScriptingObjectContainer: ScriptingObject { + var scriptingClassDescription:NSScriptClassDescription { get } + func deleteElement(_ element:ScriptingObject) } -@MainActor extension ScriptingObjectContainer { +extension ScriptingObjectContainer { - @MainActor func makeFormNameScriptObjectSpecifier(forObject object:NamedScriptingObject) -> NSScriptObjectSpecifier? { + nonisolated func makeFormNameScriptObjectSpecifier(forObject object:NamedScriptingObject) -> NSScriptObjectSpecifier? { let containerClassDescription = self.scriptingClassDescription let containerScriptObjectSpecifier = self.objectSpecifier let scriptingKey = object.scriptingKey @@ -26,7 +26,7 @@ import Account return specifier } - @MainActor func makeFormUniqueIDScriptObjectSpecifier(forObject object:UniqueIDScriptingObject) -> NSScriptObjectSpecifier? { + nonisolated func makeFormUniqueIDScriptObjectSpecifier(forObject object:UniqueIDScriptingObject) -> NSScriptObjectSpecifier? { let containerClassDescription = self.scriptingClassDescription let containerScriptObjectSpecifier = self.objectSpecifier let scriptingKey = object.scriptingKey diff --git a/Modules/Account/Sources/Account/Account.swift b/Modules/Account/Sources/Account/Account.swift index de1883680..0acb62ef0 100644 --- a/Modules/Account/Sources/Account/Account.swift +++ b/Modules/Account/Sources/Account/Account.swift @@ -85,7 +85,7 @@ public enum FetchType { public var account: Account? { return self } - public let accountID: String + nonisolated public let accountID: String public let type: AccountType public var nameForDisplay: String { guard let name = name, !name.isEmpty else { diff --git a/Modules/Account/Sources/Account/Feed.swift b/Modules/Account/Sources/Account/Feed.swift index 62422eb07..97ee17368 100644 --- a/Modules/Account/Sources/Account/Feed.swift +++ b/Modules/Account/Sources/Account/Feed.swift @@ -12,10 +12,10 @@ import RSWeb import Articles @MainActor public final class Feed: SidebarItem, Renamable, Hashable { - public let feedID: String - public let accountID: String - public let url: String - public let sidebarItemID: SidebarItemIdentifier? + nonisolated public let feedID: String + nonisolated public let accountID: String + nonisolated public let url: String + nonisolated public let sidebarItemID: SidebarItemIdentifier? public weak var account: Account? diff --git a/Modules/Account/Sources/Account/Folder.swift b/Modules/Account/Sources/Account/Folder.swift index 3d6a4a181..81451bb9e 100644 --- a/Modules/Account/Sources/Account/Folder.swift +++ b/Modules/Account/Sources/Account/Folder.swift @@ -11,7 +11,7 @@ import Articles import RSCore public final class Folder: SidebarItem, Renamable, Container, Hashable { - public let accountID: String + nonisolated public let accountID: String public weak var account: Account? public var defaultReadFilterType: ReadFilterType { @@ -36,7 +36,7 @@ public final class Folder: SidebarItem, Renamable, Container, Hashable { } static let untitledName = NSLocalizedString("Untitled ƒ", comment: "Folder name") - public let folderID: Int // not saved: per-run only + nonisolated public let folderID: Int // not saved: per-run only public var externalID: String? = nil static var incrementingID = 0 From d4dc837d9fdb376db0c46963bded86125eb80786 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Tue, 18 Nov 2025 16:01:37 -0800 Subject: [PATCH 06/14] Fix various concurrency issues. --- Mac/AppDelegate.swift | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/Mac/AppDelegate.swift b/Mac/AppDelegate.swift index e74c0592d..36fbd2362 100644 --- a/Mac/AppDelegate.swift +++ b/Mac/AppDelegate.swift @@ -454,9 +454,18 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSUserInterfaceValidat nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { - let userInfo = response.notification.request.content.userInfo + // Wrapper to safely transfer non-Sendable values to MainActor + struct UnsafeSendable: @unchecked Sendable { + let value: T + } + + let wrappedResponse = UnsafeSendable(value: response) + let wrappedCompletionHandler = UnsafeSendable(value: completionHandler) Task { @MainActor in + let response = wrappedResponse.value + let userInfo = response.notification.request.content.userInfo + switch response.actionIdentifier { case UserNotificationManager.ActionIdentifier.markAsRead: handleMarkAsRead(userInfo: userInfo) @@ -465,7 +474,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSUserInterfaceValidat default: mainWindowController?.handle(response) } - completionHandler() + wrappedCompletionHandler.value() } } From e2d346de80b1bda79c3fde0c0d84de4e53a8d0cd Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Tue, 18 Nov 2025 16:02:22 -0800 Subject: [PATCH 07/14] Fix various concurrency issues. --- .../Sources/CloudKitSync/CloudKitZone.swift | 64 ++++++++++++------- 1 file changed, 40 insertions(+), 24 deletions(-) diff --git a/Modules/CloudKitSync/Sources/CloudKitSync/CloudKitZone.swift b/Modules/CloudKitSync/Sources/CloudKitSync/CloudKitZone.swift index 68a35ddb4..08c2913ff 100644 --- a/Modules/CloudKitSync/Sources/CloudKitSync/CloudKitZone.swift +++ b/Modules/CloudKitSync/Sources/CloudKitSync/CloudKitZone.swift @@ -27,6 +27,13 @@ public enum CloudKitZoneError: LocalizedError, Sendable { } } +// Wrapper to safely transfer non-Sendable values in @Sendable closures +// Generic over the Success type of the Result +fileprivate struct CloudKitZoneCaptures: @unchecked Sendable { + weak var zone: (any CloudKitZone)? + let completion: (Result) -> Void +} + public protocol CloudKitZoneDelegate: AnyObject { func cloudKitDidModify(changed: [CKRecord], deleted: [CloudKitRecordKey]) async throws } @@ -315,10 +322,13 @@ public extension CloudKitZone { let recordID = CKRecord.ID(recordName: externalID, zoneID: zoneID) - database?.fetch(withRecordID: recordID) { [weak self] record, error in + // Wrapper to safely transfer non-Sendable values in @Sendable closure + let captures = CloudKitZoneCaptures(zone: self, completion: completion) + + database?.fetch(withRecordID: recordID) { record, error in Task { @MainActor in - guard let self = self else { - completion(.failure(CloudKitZoneError.unknown)) + guard let self = captures.zone else { + captures.completion(.failure(CloudKitZoneError.unknown)) return } @@ -326,34 +336,34 @@ public extension CloudKitZone { case .success: DispatchQueue.main.async { if let record = record { - completion(.success(record)) + captures.completion(.success(record)) } else { - completion(.failure(CloudKitZoneError.unknown)) + captures.completion(.failure(CloudKitZoneError.unknown)) } } case .zoneNotFound: self.createZoneRecord() { result in switch result { case .success: - self.fetch(externalID: externalID, completion: completion) + self.fetch(externalID: externalID, completion: captures.completion) case .failure(let error): DispatchQueue.main.async { - completion(.failure(error)) + captures.completion(.failure(error)) } } } case .retry(let timeToWait): Self.logger.debug("CloudKit: \(self.zoneID.zoneName) zone fetch retry in \(timeToWait) seconds") self.retryIfPossible(after: timeToWait) { - self.fetch(externalID: externalID, completion: completion) + self.fetch(externalID: externalID, completion: captures.completion) } case .userDeletedZone: DispatchQueue.main.async { - completion(.failure(CloudKitZoneError.userDeletedZone)) + captures.completion(.failure(CloudKitZoneError.userDeletedZone)) } default: DispatchQueue.main.async { - completion(.failure(CloudKitError(error!))) + captures.completion(.failure(CloudKitError(error!))) } } } @@ -450,37 +460,40 @@ public extension CloudKitZone { /// Save the CKSubscription func save(_ subscription: CKSubscription, completion: @escaping (Result) -> Void) { - database?.save(subscription) { [weak self] savedSubscription, error in + // Wrapper to safely transfer non-Sendable values in @Sendable closure + let captures = CloudKitZoneCaptures(zone: self, completion: completion) + + database?.save(subscription) { savedSubscription, error in Task { @MainActor in - guard let self = self else { - completion(.failure(CloudKitZoneError.unknown)) + guard let self = captures.zone else { + captures.completion(.failure(CloudKitZoneError.unknown)) return } switch CloudKitZoneResult.resolve(error) { case .success: DispatchQueue.main.async { - completion(.success((savedSubscription!))) + captures.completion(.success((savedSubscription!))) } case .zoneNotFound: self.createZoneRecord() { result in switch result { case .success: - self.save(subscription, completion: completion) + self.save(subscription, completion: captures.completion) case .failure(let error): DispatchQueue.main.async { - completion(.failure(error)) + captures.completion(.failure(error)) } } } case .retry(let timeToWait): Self.logger.debug("CloudKit: \(self.zoneID.zoneName) save subscription retry in \(timeToWait) seconds") self.retryIfPossible(after: timeToWait) { - self.save(subscription, completion: completion) + self.save(subscription, completion: captures.completion) } default: DispatchQueue.main.async { - completion(.failure(CloudKitError(error!))) + captures.completion(.failure(CloudKitError(error!))) } } } @@ -593,26 +606,29 @@ public extension CloudKitZone { /// Delete a CKSubscription func delete(subscriptionID: String, completion: @escaping (Result) -> Void) { - database?.delete(withSubscriptionID: subscriptionID) { [weak self] _, error in + // Wrapper to safely transfer non-Sendable values in @Sendable closure + let captures = CloudKitZoneCaptures(zone: self, completion: completion) + + database?.delete(withSubscriptionID: subscriptionID) { _, error in Task { @MainActor in - guard let self = self else { - completion(.failure(CloudKitZoneError.unknown)) + guard let self = captures.zone else { + captures.completion(.failure(CloudKitZoneError.unknown)) return } switch CloudKitZoneResult.resolve(error) { case .success: DispatchQueue.main.async { - completion(.success(())) + captures.completion(.success(())) } case .retry(let timeToWait): Self.logger.debug("CloudKit: \(self.zoneID.zoneName) delete subscription retry in \(timeToWait) seconds") self.retryIfPossible(after: timeToWait) { - self.delete(subscriptionID: subscriptionID, completion: completion) + self.delete(subscriptionID: subscriptionID, completion: captures.completion) } default: DispatchQueue.main.async { - completion(.failure(CloudKitError(error!))) + captures.completion(.failure(CloudKitError(error!))) } } } From 415a6f46617bc4fbd83cc99e92cbfd551869e459 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Tue, 18 Nov 2025 16:29:59 -0800 Subject: [PATCH 08/14] Fix various concurrency issues. --- iOS/AppAssets.swift | 276 ++++-------------- iOS/AppDefaults.swift | 4 +- iOS/Article/ArticleSearchBar.swift | 2 +- iOS/Article/OpenInSafariActivity.swift | 1 - iOS/Article/WebViewController.swift | 2 +- ...MainFeedCollectionHeaderReusableView.swift | 18 +- .../MainFeedCollectionViewCell.swift | 8 +- .../MainFeedCollectionViewFolderCell.swift | 6 +- iOS/MainFeed/RefreshProgressView.swift | 18 +- .../Cells/MainTimelineFeedCell.swift | 8 +- .../Cells/MainTimelineIconFeedCell.swift | 10 +- .../MarkAsReadAlertController.swift | 2 +- iOS/Settings/ArticleThemeImporter.swift | 2 +- iOS/Settings/ModernTimelineSliderCell.swift | 11 +- iOS/UIKit Extensions/Animations.swift | 2 +- iOS/UIKit Extensions/InteractiveLabel.swift | 2 +- 16 files changed, 114 insertions(+), 258 deletions(-) diff --git a/iOS/AppAssets.swift b/iOS/AppAssets.swift index c103bef0f..de93d3ebf 100644 --- a/iOS/AppAssets.swift +++ b/iOS/AppAssets.swift @@ -10,254 +10,103 @@ import RSCore import Account struct AppAssets { - - static var accountBazQuxImage: UIImage = { - return UIImage(named: "accountBazQux")! - }() - - static var accountCloudKitImage: UIImage = { - return UIImage(named: "accountCloudKit")! - }() - - static var accountFeedbinImage: UIImage = { - return UIImage(named: "accountFeedbin")! - }() - - static var accountFeedlyImage: UIImage = { - return UIImage(named: "accountFeedly")! - }() - - static var accountFreshRSSImage: UIImage = { - return UIImage(named: "accountFreshRSS")! - }() - - static var accountInoreaderImage: UIImage = { - return UIImage(named: "accountInoreader")! - }() - - static var accountLocalPadImage: UIImage = { - return UIImage(named: "accountLocalPad")! - }() - - static var accountLocalPhoneImage: UIImage = { - return UIImage(named: "accountLocalPhone")! - }() - - static var accountNewsBlurImage: UIImage = { - return UIImage(named: "accountNewsBlur")! - }() - - static var accountTheOldReaderImage: UIImage = { - return UIImage(named: "accountTheOldReader")! - }() - + static let accountBazQuxImage = RSImage(named: "accountBazQux")! + static let accountCloudKitImage = RSImage(named: "accountCloudKit")! + static let accountFeedbinImage = RSImage(named: "accountFeedbin")! + static let accountFeedlyImage = RSImage(named: "accountFeedly")! + static let accountFreshRSSImage = RSImage(named: "accountFreshRSS")! + static let accountInoreaderImage = RSImage(named: "accountInoreader")! + static let accountLocalPadImage = RSImage(named: "accountLocalPad")! + static let accountLocalPhoneImage = RSImage(named: "accountLocalPhone")! + static let accountNewsBlurImage = RSImage(named: "accountNewsBlur")! + static let accountTheOldReaderImage = RSImage(named: "accountTheOldReader")! static let nnwFeedIcon = RSImage(named: "nnwFeedIcon")! + static let articleExtractorError = RSImage(named: "articleExtractorError")! + static let articleExtractorOff = RSImage(named: "articleExtractorOff")! + static let articleExtractorOffSF = RSImage(systemName: "doc.plaintext")! - static var articleExtractorError: UIImage = { - return UIImage(named: "articleExtractorError")! - }() - - static var articleExtractorOff: UIImage = { - return UIImage(named: "articleExtractorOff")! - }() - - static var articleExtractorOffSF: UIImage = { - return UIImage(systemName: "doc.plaintext")! - }() - - @MainActor static var articleExtractorOffTinted: UIImage = { + @MainActor static let articleExtractorOffTinted: UIImage = { let image = UIImage(named: "articleExtractorOff")! return image.tinted(color: AppAssets.primaryAccentColor)! }() - static var articleExtractorOn: UIImage = { - return UIImage(named: "articleExtractorOn")! - }() + static let articleExtractorOn = RSImage(named: "articleExtractorOn")! + static let articleExtractorOnSF = RSImage(named: "articleExtractorOnSF")! - static var articleExtractorOnSF: UIImage = { - return UIImage(named: "articleExtractorOnSF")! - }() - - @MainActor static var articleExtractorOnTinted: UIImage = { + @MainActor static let articleExtractorOnTinted: UIImage = { let image = UIImage(named: "articleExtractorOn")! return image.tinted(color: AppAssets.primaryAccentColor)! }() - static var iconBackgroundColor: UIColor = { - return UIColor(named: "iconBackgroundColor")! - }() + static let iconBackgroundColor = UIColor(named: "iconBackgroundColor")! - static var circleClosedImage: UIImage = { - return UIImage(systemName: "largecircle.fill.circle")! - }() + static let circleClosedImage = RSImage(systemName: "largecircle.fill.circle")! + static let circleOpenImage = RSImage(systemName: "circle")! + static let disclosureImage = RSImage(named: "disclosure")! + static let copyImage = RSImage(systemName: "doc.on.doc")! + static let deactivateImage = RSImage(systemName: "minus.circle")! + static let editImage = RSImage(systemName: "square.and.pencil")! + static let faviconTemplateImage = RSImage(named: "faviconTemplateImage")! + static let filterImage = RSImage(systemName: "line.3.horizontal.decrease")! + static let folderOutlinePlus = RSImage(systemName: "folder.badge.plus")! + static let fullScreenBackgroundColor = UIColor(named: "fullScreenBackgroundColor")! + static let infoImage = RSImage(systemName: "info.circle")! + static let markAllAsReadImage = RSImage(named: "markAllAsRead")! + static let markBelowAsReadImage = RSImage(systemName: "arrowtriangle.down.circle")! + static let markAboveAsReadImage = RSImage(systemName: "arrowtriangle.up.circle")! - static var circleOpenImage: UIImage = { - return UIImage(systemName: "circle")! - }() + static let mainFolderImage = IconImage(RSImage(systemName: "folder")!, isSymbol: true, isBackgroundSuppressed: true, preferredColor: AppAssets.secondaryAccentColor.cgColor) - static var disclosureImage: UIImage = { - return UIImage(named: "disclosure")! - }() + static let mainFolderImageNonIcon = RSImage(systemName: "folder")!.withRenderingMode(.alwaysOriginal).withTintColor(.secondaryLabel) + static let moreImage = RSImage(systemName: "ellipsis.circle")! + static let nextArticleImage = RSImage(systemName: "chevron.down")! + static let nextUnreadArticleImage = RSImage(systemName: "chevron.down.circle")! + static let plus = RSImage(systemName: "plus")! + static let prevArticleImage = RSImage(systemName: "chevron.up")! + static let openInSidebarImage = RSImage(systemName: "arrow.turn.down.left")! + static let primaryAccentColor = UIColor(named: "primaryAccentColor")! + static let safariImage = RSImage(systemName: "safari")! + static let searchFeedImage = IconImage(UIImage(systemName: "magnifyingglass")!, isSymbol: true) + static let secondaryAccentColor = UIColor(named: "secondaryAccentColor")! + static let sectionHeaderColor = UIColor(named: "sectionHeaderColor")! + static let shareImage = RSImage(systemName: "square.and.arrow.up")! + static let smartFeedImage = RSImage(systemName: "gear")! + static let starColor = UIColor(named: "starColor")! + static let starClosedImage = RSImage(systemName: "star.fill")! + static let starOpenImage = RSImage(systemName: "star")! - static var copyImage: UIImage = { - return UIImage(systemName: "doc.on.doc")! - }() - - static var deactivateImage: UIImage = { - UIImage(systemName: "minus.circle")! - }() - - static var editImage: UIImage = { - UIImage(systemName: "square.and.pencil")! - }() - - static var faviconTemplateImage: RSImage = { - return RSImage(named: "faviconTemplateImage")! - }() - - static var filterImage: UIImage = { - UIImage(systemName: "line.3.horizontal.decrease")! - }() - - static var folderOutlinePlus: UIImage = { - UIImage(systemName: "folder.badge.plus")! - }() - - static var fullScreenBackgroundColor: UIColor = { - return UIColor(named: "fullScreenBackgroundColor")! - }() - - static var infoImage: UIImage = { - UIImage(systemName: "info.circle")! - }() - - static var markAllAsReadImage: UIImage = { - return UIImage(named: "markAllAsRead")! - }() - - static var markBelowAsReadImage: UIImage = { - return UIImage(systemName: "arrowtriangle.down.circle")! - }() - - static var markAboveAsReadImage: UIImage = { - return UIImage(systemName: "arrowtriangle.up.circle")! - }() - - static var mainFolderImage: IconImage = { - return IconImage(UIImage(systemName: "folder")!, isSymbol: true, isBackgroundSuppressed: true, preferredColor: AppAssets.secondaryAccentColor.cgColor) - }() - - static var mainFolderImageNonIcon: UIImage = { - return UIImage(systemName: "folder")!.withRenderingMode(.alwaysOriginal).withTintColor(.secondaryLabel) - }() - - static var moreImage: UIImage = { - return UIImage(systemName: "ellipsis.circle")! - }() - - static var nextArticleImage: UIImage = { - return UIImage(systemName: "chevron.down")! - }() - - static var nextUnreadArticleImage: UIImage = { - return UIImage(systemName: "chevron.down.circle")! - }() - - static var plus: UIImage = { - UIImage(systemName: "plus")! - }() - - static var prevArticleImage: UIImage = { - return UIImage(systemName: "chevron.up")! - }() - - static var openInSidebarImage: UIImage = { - return UIImage(systemName: "arrow.turn.down.left")! - }() - - static var primaryAccentColor: UIColor { - return UIColor(named: "primaryAccentColor")! - } - - static var safariImage: UIImage = { - return UIImage(systemName: "safari")! - }() - - static var searchFeedImage: IconImage = { - return IconImage(UIImage(systemName: "magnifyingglass")!, isSymbol: true) - }() - - static var secondaryAccentColor: UIColor { - return UIColor(named: "secondaryAccentColor")! - } - - static var sectionHeaderColor: UIColor = { - return UIColor(named: "sectionHeaderColor")! - }() - - static var shareImage: UIImage = { - return UIImage(systemName: "square.and.arrow.up")! - }() - - static var smartFeedImage: UIImage = { - return UIImage(systemName: "gear")! - }() - - static var starColor: UIColor = { - return UIColor(named: "starColor")! - }() - - static var starClosedImage: UIImage = { - return UIImage(systemName: "star.fill")! - }() - - static var starOpenImage: UIImage = { - return UIImage(systemName: "star")! - }() - - static var starredFeedImage: IconImage { + static let starredFeedImage: IconImage = { let image = UIImage(systemName: "star.fill")! return IconImage(image, isSymbol: true, isBackgroundSuppressed: true, preferredColor: AppAssets.starColor.cgColor) - } - - static var tickMarkColor: UIColor = { - return UIColor(named: "tickMarkColor")! }() - static var timelineStarImage: UIImage = { + static let tickMarkColor = UIColor(named: "tickMarkColor")! + + static let timelineStarImage: UIImage = { let image = UIImage(systemName: "star.fill")! return image.withTintColor(AppAssets.starColor, renderingMode: .alwaysOriginal) }() - static var todayFeedImage: IconImage { + static let todayFeedImage: IconImage = { let image = UIImage(systemName: "sun.max.fill")! return IconImage(image, isSymbol: true, isBackgroundSuppressed: true, preferredColor: UIColor.systemOrange.cgColor) - } - - static var trashImage: UIImage = { - return UIImage(systemName: "trash")! }() - static var unreadCellIndicatorImage: IconImage { + static let trashImage = RSImage(systemName: "trash")! + static let unreadCellIndicatorImage: IconImage = { let image = UIImage(systemName: "circle.fill")! return IconImage(image, isSymbol: true, isBackgroundSuppressed: true, preferredColor: AppAssets.secondaryAccentColor.cgColor) - } + }() - static var unreadFeedImage: IconImage { + static let unreadFeedImage: IconImage = { let image = UIImage(systemName: "largecircle.fill.circle")! return IconImage(image, isSymbol: true, isBackgroundSuppressed: true, preferredColor: AppAssets.secondaryAccentColor.cgColor) - } - - static var vibrantTextColor: UIColor = { - return UIColor(named: "vibrantTextColor")! }() - static var controlBackgroundColor: UIColor = { - return UIColor(named: "controlBackgroundColor")! - }() + static let vibrantTextColor = UIColor(named: "vibrantTextColor")! + static let controlBackgroundColor = UIColor(named: "controlBackgroundColor")! - - static func image(for accountType: AccountType) -> UIImage? { + @MainActor static func image(for accountType: AccountType) -> UIImage? { switch accountType { case .onMyMac: if UIDevice.current.userInterfaceIdiom == .pad { @@ -283,5 +132,4 @@ struct AppAssets { return AppAssets.accountTheOldReaderImage } } - } diff --git a/iOS/AppDefaults.swift b/iOS/AppDefaults.swift index 1ecc7de11..5c38c48e0 100644 --- a/iOS/AppDefaults.swift +++ b/iOS/AppDefaults.swift @@ -30,14 +30,14 @@ extension Notification.Name { public static let userInterfaceColorPaletteDidUpdate = Notification.Name(rawValue: "UserInterfaceColorPaletteDidUpdateNotification") } -final class AppDefaults { +final class AppDefaults: Sendable { static let defaultThemeName = "Default" static let shared = AppDefaults() private init() {} - static var store: UserDefaults = { + nonisolated(unsafe) static let store: UserDefaults = { let appIdentifierPrefix = Bundle.main.object(forInfoDictionaryKey: "AppIdentifierPrefix") as! String let suiteName = "\(appIdentifierPrefix)group.\(Bundle.main.bundleIdentifier!)" return UserDefaults.init(suiteName: suiteName)! diff --git a/iOS/Article/ArticleSearchBar.swift b/iOS/Article/ArticleSearchBar.swift index de3181a6f..32eac6f1e 100644 --- a/iOS/Article/ArticleSearchBar.swift +++ b/iOS/Article/ArticleSearchBar.swift @@ -8,7 +8,7 @@ import UIKit -@objc protocol SearchBarDelegate: NSObjectProtocol { +@objc @MainActor protocol SearchBarDelegate: NSObjectProtocol { @objc optional func nextWasPressed(_ searchBar: ArticleSearchBar) @objc optional func previousWasPressed(_ searchBar: ArticleSearchBar) @objc optional func doneWasPressed(_ searchBar: ArticleSearchBar) diff --git a/iOS/Article/OpenInSafariActivity.swift b/iOS/Article/OpenInSafariActivity.swift index 837850e1f..61b16e341 100644 --- a/iOS/Article/OpenInSafariActivity.swift +++ b/iOS/Article/OpenInSafariActivity.swift @@ -45,5 +45,4 @@ final class OpenInBrowserActivity: UIActivity { UIApplication.shared.open(url, options: [:], completionHandler: nil) activityDidFinish(true) } - } diff --git a/iOS/Article/WebViewController.swift b/iOS/Article/WebViewController.swift index e96e32910..8e7fb6c13 100644 --- a/iOS/Article/WebViewController.swift +++ b/iOS/Article/WebViewController.swift @@ -15,7 +15,7 @@ import Articles import SafariServices import MessageUI -protocol WebViewControllerDelegate: AnyObject { +@MainActor protocol WebViewControllerDelegate: AnyObject { func webViewController(_: WebViewController, articleExtractorButtonStateDidUpdate: ArticleExtractorButtonState) } diff --git a/iOS/MainFeed/Collection View Cells/MainFeedCollectionHeaderReusableView.swift b/iOS/MainFeed/Collection View Cells/MainFeedCollectionHeaderReusableView.swift index 531cf4777..8a3d71c29 100644 --- a/iOS/MainFeed/Collection View Cells/MainFeedCollectionHeaderReusableView.swift +++ b/iOS/MainFeed/Collection View Cells/MainFeedCollectionHeaderReusableView.swift @@ -8,12 +8,11 @@ import UIKit -protocol MainFeedCollectionHeaderReusableViewDelegate: AnyObject { +@MainActor protocol MainFeedCollectionHeaderReusableViewDelegate: AnyObject { func mainFeedCollectionHeaderReusableViewDidTapDisclosureIndicator(_ view: MainFeedCollectionHeaderReusableView) } -class MainFeedCollectionHeaderReusableView: UICollectionReusableView { - +final class MainFeedCollectionHeaderReusableView: UICollectionReusableView { var delegate: MainFeedCollectionHeaderReusableViewDelegate? @IBOutlet weak var headerTitle: UILabel! @@ -21,7 +20,6 @@ class MainFeedCollectionHeaderReusableView: UICollectionReusableView { @IBOutlet weak var unreadCountLabel: UILabel! private var unreadLabelWidthConstraint: NSLayoutConstraint? - override var accessibilityLabel: String? { set {} get { @@ -66,11 +64,13 @@ class MainFeedCollectionHeaderReusableView: UICollectionReusableView { } override func awakeFromNib() { - super.awakeFromNib() - unreadLabelWidthConstraint = unreadCountLabel.widthAnchor.constraint(lessThanOrEqualToConstant: 80) - unreadLabelWidthConstraint?.isActive = true - configureUI() - addTapGesture() + MainActor.assumeIsolated { + super.awakeFromNib() + unreadLabelWidthConstraint = unreadCountLabel.widthAnchor.constraint(lessThanOrEqualToConstant: 80) + unreadLabelWidthConstraint?.isActive = true + configureUI() + addTapGesture() + } } func configureUI() { diff --git a/iOS/MainFeed/Collection View Cells/MainFeedCollectionViewCell.swift b/iOS/MainFeed/Collection View Cells/MainFeedCollectionViewCell.swift index f4df3725f..f162f8056 100644 --- a/iOS/MainFeed/Collection View Cells/MainFeedCollectionViewCell.swift +++ b/iOS/MainFeed/Collection View Cells/MainFeedCollectionViewCell.swift @@ -75,9 +75,11 @@ class MainFeedCollectionViewCell: UICollectionViewCell { } override func awakeFromNib() { - super.awakeFromNib() - faviconLeadingConstraint = faviconView.leadingAnchor.constraint(equalTo: contentView.safeAreaLayoutGuide.leadingAnchor) - faviconLeadingConstraint?.isActive = true + MainActor.assumeIsolated { + super.awakeFromNib() + faviconLeadingConstraint = faviconView.leadingAnchor.constraint(equalTo: contentView.safeAreaLayoutGuide.leadingAnchor) + faviconLeadingConstraint?.isActive = true + } } override func updateConfiguration(using state: UICellConfigurationState) { diff --git a/iOS/MainFeed/Collection View Cells/MainFeedCollectionViewFolderCell.swift b/iOS/MainFeed/Collection View Cells/MainFeedCollectionViewFolderCell.swift index 9f984311f..b85bf02a4 100644 --- a/iOS/MainFeed/Collection View Cells/MainFeedCollectionViewFolderCell.swift +++ b/iOS/MainFeed/Collection View Cells/MainFeedCollectionViewFolderCell.swift @@ -57,8 +57,10 @@ class MainFeedCollectionViewFolderCell: UICollectionViewCell { } override func awakeFromNib() { - super.awakeFromNib() - disclosureButton.addInteraction(UIPointerInteraction()) + MainActor.assumeIsolated { + super.awakeFromNib() + disclosureButton.addInteraction(UIPointerInteraction()) + } } func updateExpandedState(animate: Bool) { diff --git a/iOS/MainFeed/RefreshProgressView.swift b/iOS/MainFeed/RefreshProgressView.swift index 9bb79b50e..b7be8ec8a 100644 --- a/iOS/MainFeed/RefreshProgressView.swift +++ b/iOS/MainFeed/RefreshProgressView.swift @@ -15,14 +15,16 @@ final class RefreshProgressView: UIView { @IBOutlet weak var label: UILabel! override func awakeFromNib() { - - NotificationCenter.default.addObserver(self, selector: #selector(progressDidChange(_:)), name: .combinedRefreshProgressDidChange, object: nil) - NotificationCenter.default.addObserver(self, selector: #selector(contentSizeCategoryDidChange(_:)), name: UIContentSizeCategory.didChangeNotification, object: nil) - update() - scheduleUpdateRefreshLabel() - - isAccessibilityElement = true - accessibilityTraits = [.updatesFrequently, .notEnabled] + MainActor.assumeIsolated { + + NotificationCenter.default.addObserver(self, selector: #selector(progressDidChange(_:)), name: .combinedRefreshProgressDidChange, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(contentSizeCategoryDidChange(_:)), name: UIContentSizeCategory.didChangeNotification, object: nil) + update() + scheduleUpdateRefreshLabel() + + isAccessibilityElement = true + accessibilityTraits = [.updatesFrequently, .notEnabled] + } } func update() { diff --git a/iOS/MainTimeline/Cells/MainTimelineFeedCell.swift b/iOS/MainTimeline/Cells/MainTimelineFeedCell.swift index fbe62a0d6..20981ffef 100644 --- a/iOS/MainTimeline/Cells/MainTimelineFeedCell.swift +++ b/iOS/MainTimeline/Cells/MainTimelineFeedCell.swift @@ -25,9 +25,11 @@ class MainTimelineFeedCell: UITableViewCell { var isPreview: Bool = false override func awakeFromNib() { - super.awakeFromNib() - indicatorView.alpha = 0.0 - configureStackView() + MainActor.assumeIsolated { + super.awakeFromNib() + indicatorView.alpha = 0.0 + configureStackView() + } } private func configureStackView() { diff --git a/iOS/MainTimeline/Cells/MainTimelineIconFeedCell.swift b/iOS/MainTimeline/Cells/MainTimelineIconFeedCell.swift index fd9a195d0..6e8616169 100644 --- a/iOS/MainTimeline/Cells/MainTimelineIconFeedCell.swift +++ b/iOS/MainTimeline/Cells/MainTimelineIconFeedCell.swift @@ -26,10 +26,12 @@ class MainTimelineIconFeedCell: UITableViewCell { var isPreview: Bool = false override func awakeFromNib() { - super.awakeFromNib() - indicatorView.alpha = 0.0 - iconView.translatesAutoresizingMaskIntoConstraints = false - configureStackView() + MainActor.assumeIsolated { + super.awakeFromNib() + indicatorView.alpha = 0.0 + iconView.translatesAutoresizingMaskIntoConstraints = false + configureStackView() + } } private func configureStackView() { diff --git a/iOS/MainTimeline/MarkAsReadAlertController.swift b/iOS/MainTimeline/MarkAsReadAlertController.swift index 90f8b8801..c7425d8df 100644 --- a/iOS/MainTimeline/MarkAsReadAlertController.swift +++ b/iOS/MainTimeline/MarkAsReadAlertController.swift @@ -15,7 +15,7 @@ extension UIView: MarkAsReadAlertControllerSourceType {} extension UIBarButtonItem: MarkAsReadAlertControllerSourceType {} -struct MarkAsReadAlertController { +@MainActor struct MarkAsReadAlertController { static func confirm(_ controller: UIViewController?, coordinator: SceneCoordinator?, diff --git a/iOS/Settings/ArticleThemeImporter.swift b/iOS/Settings/ArticleThemeImporter.swift index bf38e59f1..7385791c5 100644 --- a/iOS/Settings/ArticleThemeImporter.swift +++ b/iOS/Settings/ArticleThemeImporter.swift @@ -8,7 +8,7 @@ import UIKit -struct ArticleThemeImporter { +@MainActor struct ArticleThemeImporter { static func importTheme(controller: UIViewController, url: URL) throws { let theme = try ArticleTheme(url: url, isAppTheme: false) diff --git a/iOS/Settings/ModernTimelineSliderCell.swift b/iOS/Settings/ModernTimelineSliderCell.swift index c39d21e34..a27346f92 100644 --- a/iOS/Settings/ModernTimelineSliderCell.swift +++ b/iOS/Settings/ModernTimelineSliderCell.swift @@ -13,17 +13,16 @@ enum SliderConfiguration { case iconSize } -class ModernTimelineSliderCell: UITableViewCell { - - +final class ModernTimelineSliderCell: UITableViewCell { @IBOutlet weak var slider: UISlider! private let container = UIView() - override func awakeFromNib() { - super.awakeFromNib() - setup() + MainActor.assumeIsolated { + super.awakeFromNib() + setup() + } } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { diff --git a/iOS/UIKit Extensions/Animations.swift b/iOS/UIKit Extensions/Animations.swift index 18b256f7a..2c72552b6 100644 --- a/iOS/UIKit Extensions/Animations.swift +++ b/iOS/UIKit Extensions/Animations.swift @@ -9,7 +9,7 @@ import Foundation /// Used to select which animations should be performed -public struct Animations: OptionSet { +public struct Animations: OptionSet, Sendable { /// Selections and deselections will be animated. public static let select = Animations(rawValue: 1) diff --git a/iOS/UIKit Extensions/InteractiveLabel.swift b/iOS/UIKit Extensions/InteractiveLabel.swift index 80f7f8688..af5b9a114 100644 --- a/iOS/UIKit Extensions/InteractiveLabel.swift +++ b/iOS/UIKit Extensions/InteractiveLabel.swift @@ -9,7 +9,7 @@ import UIKit @IBDesignable -final class InteractiveLabel: UILabel, UIEditMenuInteractionDelegate { +final class InteractiveLabel: UILabel, @preconcurrency UIEditMenuInteractionDelegate { override init(frame: CGRect) { super.init(frame: frame) From 563d1febbc2fbcc1014e8fa499d59591543a2481 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Tue, 18 Nov 2025 16:39:51 -0800 Subject: [PATCH 09/14] Fix various concurrency issues. --- Mac/AppDelegate.swift | 1 + Shared/Settings/AddCloudKitAccount.swift | 9 ++++--- iOS/AppDelegate.swift | 12 +++------ .../FeedInspectorViewController.swift | 26 +++++++++---------- iOS/KeyboardManager.swift | 4 +-- .../MainFeedCollectionViewFolderCell.swift | 2 +- 6 files changed, 25 insertions(+), 29 deletions(-) diff --git a/Mac/AppDelegate.swift b/Mac/AppDelegate.swift index 36fbd2362..5a4a9a5aa 100644 --- a/Mac/AppDelegate.swift +++ b/Mac/AppDelegate.swift @@ -197,6 +197,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSUserInterfaceValidat self.toggleInspectorWindow(self) } + ArticleThemesManager.shared.start() NetworkMonitor.shared.start() ExtensionContainersFile.shared.start() ExtensionFeedAddRequestFile.shared.start() diff --git a/Shared/Settings/AddCloudKitAccount.swift b/Shared/Settings/AddCloudKitAccount.swift index ae2974e38..f161ed0c0 100644 --- a/Shared/Settings/AddCloudKitAccount.swift +++ b/Shared/Settings/AddCloudKitAccount.swift @@ -14,7 +14,7 @@ import AppKit import UIKit #endif -enum AddCloudKitAccountError: LocalizedError, RecoverableError { +enum AddCloudKitAccountError: LocalizedError, RecoverableError, Sendable { case iCloudDriveMissing @@ -43,7 +43,10 @@ enum AddCloudKitAccountError: LocalizedError, RecoverableError { return false } - AddCloudKitAccountUtilities.openiCloudSettings() + Task { @MainActor in + AddCloudKitAccountUtilities.openiCloudSettings() + } + return true } } @@ -54,7 +57,7 @@ struct AddCloudKitAccountUtilities { FileManager.default.ubiquityIdentityToken != nil } - static func openiCloudSettings() { + @MainActor static func openiCloudSettings() { #if os(macOS) if let url = URL(string: "x-apple.systempreferences:com.apple.preferences.AppleIDPrefPane") { NSWorkspace.shared.open(url) diff --git a/iOS/AppDelegate.swift b/iOS/AppDelegate.swift index 1affa471f..7e7e5f799 100644 --- a/iOS/AppDelegate.swift +++ b/iOS/AppDelegate.swift @@ -16,9 +16,9 @@ import Account import Articles import Secrets -var appDelegate: AppDelegate! +@MainActor var appDelegate: AppDelegate! -@UIApplicationMain +@main final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, UnreadCountProvider { private let backgroundTaskDispatchQueue = DispatchQueue.init(label: "BGTaskScheduler") @@ -52,15 +52,8 @@ final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationC super.init() appDelegate = self - let documentFolder = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! - let documentAccountsFolder = documentFolder.appendingPathComponent("Accounts").absoluteString - AccountManager.shared.start() - let documentThemesFolder = documentFolder.appendingPathComponent("Themes").absoluteString - let documentThemesFolderPath = String(documentThemesFolder.suffix(from: documentAccountsFolder.index(documentThemesFolder.startIndex, offsetBy: 7))) - ArticleThemesManager.shared = ArticleThemesManager(folderPath: documentThemesFolderPath) - NotificationCenter.default.addObserver(self, selector: #selector(unreadCountDidChange(_:)), name: .UnreadCountDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(accountRefreshDidFinish(_:)), name: .AccountRefreshDidFinish, object: nil) } @@ -100,6 +93,7 @@ final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationC UNUserNotificationCenter.current().delegate = self UserNotificationManager.shared.start() + ArticleThemesManager.shared.start() NetworkMonitor.shared.start() ExtensionContainersFile.shared.start() ExtensionFeedAddRequestFile.shared.start() diff --git a/iOS/Inspector/FeedInspectorViewController.swift b/iOS/Inspector/FeedInspectorViewController.swift index c734d8bea..a5e532e99 100644 --- a/iOS/Inspector/FeedInspectorViewController.swift +++ b/iOS/Inspector/FeedInspectorViewController.swift @@ -33,7 +33,7 @@ final class FeedInspectorViewController: UITableViewController { return feed.homePageURL == nil } - private var userNotificationSettings: UNNotificationSettings? + private var authorizationStatus: UNAuthorizationStatus? override func viewDidLoad() { tableView.register(InspectorIconHeaderView.self, forHeaderFooterViewReuseIdentifier: "SectionHeader") @@ -72,25 +72,23 @@ final class FeedInspectorViewController: UITableViewController { } @IBAction func notifyAboutNewArticlesChanged(_ sender: Any) { - guard let settings = userNotificationSettings else { + guard let authorizationStatus else { notifyAboutNewArticlesSwitch.isOn = !notifyAboutNewArticlesSwitch.isOn return } - if settings.authorizationStatus == .denied { + if authorizationStatus == .denied { notifyAboutNewArticlesSwitch.isOn = !notifyAboutNewArticlesSwitch.isOn present(notificationUpdateErrorAlert(), animated: true, completion: nil) - } else if settings.authorizationStatus == .authorized { + } else if authorizationStatus == .authorized { feed.isNotifyAboutNewArticles = notifyAboutNewArticlesSwitch.isOn } else { UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .sound, .alert]) { (granted, error) in - self.updateNotificationSettings() - if granted { - DispatchQueue.main.async { + Task { @MainActor in + self.updateNotificationSettings() + if granted { self.feed.isNotifyAboutNewArticles = self.notifyAboutNewArticlesSwitch.isOn UIApplication.shared.registerForRemoteNotifications() - } - } else { - DispatchQueue.main.async { + } else { self.notifyAboutNewArticlesSwitch.isOn = !self.notifyAboutNewArticlesSwitch.isOn } } @@ -199,12 +197,12 @@ extension FeedInspectorViewController: UITextFieldDelegate { extension FeedInspectorViewController { - @objc - func updateNotificationSettings() { + @objc func updateNotificationSettings() { UNUserNotificationCenter.current().getNotificationSettings { (settings) in + let updatedAuthorizationStatus = settings.authorizationStatus DispatchQueue.main.async { - self.userNotificationSettings = settings - if settings.authorizationStatus == .authorized { + self.authorizationStatus = updatedAuthorizationStatus + if self.authorizationStatus == .authorized { UIApplication.shared.registerForRemoteNotifications() } } diff --git a/iOS/KeyboardManager.swift b/iOS/KeyboardManager.swift index c32b7ba32..d2c71f65f 100644 --- a/iOS/KeyboardManager.swift +++ b/iOS/KeyboardManager.swift @@ -8,14 +8,14 @@ import UIKit -enum KeyboardType: String { +enum KeyboardType: String, Sendable { case global = "GlobalKeyboardShortcuts" case sidebar = "SidebarKeyboardShortcuts" case timeline = "TimelineKeyboardShortcuts" case detail = "DetailKeyboardShortcuts" } -final class KeyboardManager { +@MainActor final class KeyboardManager { private(set) var _keyCommands: [UIKeyCommand] var keyCommands: [UIKeyCommand] { diff --git a/iOS/MainFeed/Collection View Cells/MainFeedCollectionViewFolderCell.swift b/iOS/MainFeed/Collection View Cells/MainFeedCollectionViewFolderCell.swift index b85bf02a4..bfd6ff86a 100644 --- a/iOS/MainFeed/Collection View Cells/MainFeedCollectionViewFolderCell.swift +++ b/iOS/MainFeed/Collection View Cells/MainFeedCollectionViewFolderCell.swift @@ -8,7 +8,7 @@ import UIKit -protocol MainFeedCollectionViewFolderCellDelegate: AnyObject { +@MainActor protocol MainFeedCollectionViewFolderCellDelegate: AnyObject { func mainFeedCollectionFolderViewCellDisclosureDidToggle(_ sender: MainFeedCollectionViewFolderCell, expanding: Bool) } From b7c7c09ea66f5aabc40d9a4b63dfc75a90e01721 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Tue, 18 Nov 2025 19:07:17 -0800 Subject: [PATCH 10/14] Fix various concurrency issues. --- iOS/AppDelegate.swift | 7 +++---- iOS/Article/OpenInSafariActivity.swift | 5 ++++- iOS/Article/WebViewController.swift | 5 ++--- iOS/MainFeed/MainFeedCollectionViewController.swift | 2 +- 4 files changed, 10 insertions(+), 9 deletions(-) diff --git a/iOS/AppDelegate.swift b/iOS/AppDelegate.swift index 7e7e5f799..1404a72d2 100644 --- a/iOS/AppDelegate.swift +++ b/iOS/AppDelegate.swift @@ -34,7 +34,7 @@ final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationC } } - private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "Application") + nonisolated private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "Application") var unreadCount = 0 { didSet { @@ -343,13 +343,12 @@ private extension AppDelegate { /// Schedules a background app refresh based on `AppDefaults.refreshInterval`. func scheduleBackgroundFeedRefresh() { - let request = BGAppRefreshTaskRequest(identifier: "com.ranchero.NetNewsWire.FeedRefresh") - request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60) - // We send this to a dedicated serial queue because as of 11/05/19 on iOS 13.2 the call to the // task scheduler can hang indefinitely. backgroundTaskDispatchQueue.async { do { + let request = BGAppRefreshTaskRequest(identifier: "com.ranchero.NetNewsWire.FeedRefresh") + request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60) try BGTaskScheduler.shared.submit(request) } catch { Self.logger.error("Could not schedule app refresh: \(error.localizedDescription)") diff --git a/iOS/Article/OpenInSafariActivity.swift b/iOS/Article/OpenInSafariActivity.swift index 61b16e341..e7a743d22 100644 --- a/iOS/Article/OpenInSafariActivity.swift +++ b/iOS/Article/OpenInSafariActivity.swift @@ -42,7 +42,10 @@ final class OpenInBrowserActivity: UIActivity { return } - UIApplication.shared.open(url, options: [:], completionHandler: nil) + Task { @MainActor in + UIApplication.shared.open(url, options: [:], completionHandler: nil) + } + activityDidFinish(true) } } diff --git a/iOS/Article/WebViewController.swift b/iOS/Article/WebViewController.swift index 8e7fb6c13..8b8646b23 100644 --- a/iOS/Article/WebViewController.swift +++ b/iOS/Article/WebViewController.swift @@ -361,7 +361,7 @@ extension WebViewController: WKNavigationDelegate { } } - func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { + func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping @MainActor @Sendable (WKNavigationActionPolicy) -> Void) { if navigationAction.navigationType == .linkActivated { guard let url = navigationAction.request.url else { @@ -613,8 +613,7 @@ private extension WebViewController { func startArticleExtractor() { guard articleExtractor == nil else { return } - if let link = article?.preferredLink, let extractor = ArticleExtractor(link) { - extractor.delegate = self + if let link = article?.preferredLink, let extractor = ArticleExtractor(link, delegate: self) { extractor.process() articleExtractor = extractor articleExtractorButtonState = .animated diff --git a/iOS/MainFeed/MainFeedCollectionViewController.swift b/iOS/MainFeed/MainFeedCollectionViewController.swift index 2ddebb20d..b5703f1ae 100644 --- a/iOS/MainFeed/MainFeedCollectionViewController.swift +++ b/iOS/MainFeed/MainFeedCollectionViewController.swift @@ -22,7 +22,7 @@ private let reuseIdentifier = "FeedCell" private let folderIdentifier = "Folder" private let containerReuseIdentifier = "Container" -class MainFeedCollectionViewController: UICollectionViewController, UndoableCommandRunner { +final class MainFeedCollectionViewController: UICollectionViewController, UndoableCommandRunner { @IBOutlet weak var filterButton: UIBarButtonItem! @IBOutlet weak var addNewItemButton: UIBarButtonItem! { From d1635d8046d0585939eaa9455a18b8a95b3692bf Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Tue, 18 Nov 2025 19:07:55 -0800 Subject: [PATCH 11/14] Fix various concurrency issues. --- Intents/AddWebFeedIntentHandler.swift | 186 ++++++++---------- .../ShareExtension/ExtensionContainers.swift | 3 +- 2 files changed, 82 insertions(+), 107 deletions(-) diff --git a/Intents/AddWebFeedIntentHandler.swift b/Intents/AddWebFeedIntentHandler.swift index 27fe48eb6..401434cc6 100644 --- a/Intents/AddWebFeedIntentHandler.swift +++ b/Intents/AddWebFeedIntentHandler.swift @@ -8,8 +8,7 @@ import Intents -public enum AddWebFeedIntentHandlerError: LocalizedError { - +public enum AddWebFeedIntentHandlerError: LocalizedError, Sendable { case communicationFailure public var errorDescription: String? { @@ -27,126 +26,101 @@ public class AddWebFeedIntentHandler: NSObject, AddWebFeedIntentHandling { super.init() } - public func resolveUrl(for intent: AddWebFeedIntent, with completion: @escaping (AddWebFeedUrlResolutionResult) -> Void) { + public func resolveUrl(for intent: AddWebFeedIntent) async -> AddWebFeedUrlResolutionResult { guard let url = intent.url else { - completion(.unsupported(forReason: .required)) - return + return .unsupported(forReason: .required) } - completion(.success(with: url)) + return .success(with: url) } - public func provideAccountNameOptions(for intent: AddWebFeedIntent, with completion: @escaping ([String]?, Error?) -> Void) { - Task { @MainActor in - guard let extensionContainers = ExtensionContainersFile.read() else { - completion(nil, AddWebFeedIntentHandlerError.communicationFailure) - return - } - - let accountNames = extensionContainers.accounts.map { $0.name } - completion(accountNames, nil) + public func provideAccountNameOptions(for intent: AddWebFeedIntent) async throws -> [String] { + guard let extensionContainers = await ExtensionContainersFile.read() else { + throw AddWebFeedIntentHandlerError.communicationFailure } + + let accountNames = extensionContainers.accounts.map { $0.name } + return accountNames } - public func resolveAccountName(for intent: AddWebFeedIntent, with completion: @escaping (AddWebFeedAccountNameResolutionResult) -> Void) { - Task { @MainActor in - guard let accountName = intent.accountName else { - completion(AddWebFeedAccountNameResolutionResult.notRequired()) - return - } + public func resolveAccountName(for intent: AddWebFeedIntent) async -> AddWebFeedAccountNameResolutionResult { + guard let accountName = intent.accountName else { + return .notRequired() + } + + guard let extensionContainers = await ExtensionContainersFile.read() else { + return .unsupported(forReason: .communication) + } + if extensionContainers.findAccount(forName: accountName) == nil { + return .unsupported(forReason: .invalid) + } - guard let extensionContainers = ExtensionContainersFile.read() else { - completion(.unsupported(forReason: .communication)) - return - } + return .success(with: accountName) + } - if extensionContainers.findAccount(forName: accountName) == nil { - completion(.unsupported(forReason: .invalid)) + public func provideFolderNameOptions(for intent: AddWebFeedIntent) async throws -> [String] { + guard let extensionContainers = await ExtensionContainersFile.read() else { + throw AddWebFeedIntentHandlerError.communicationFailure + } + + guard let accountName = intent.accountName, let account = extensionContainers.findAccount(forName: accountName) else { + return [String]() + } + + let folderNames = account.folders.map { $0.name } + return folderNames + } + + public func resolveFolderName(for intent: AddWebFeedIntent) async -> AddWebFeedFolderNameResolutionResult { + guard let accountName = intent.accountName, let folderName = intent.folderName else { + return .notRequired() + } + + guard let extensionContainers = await ExtensionContainersFile.read() else { + return .unsupported(forReason: .communication) + } + guard let account = extensionContainers.findAccount(forName: accountName) else { + return .unsupported(forReason: .invalid) + } + + let folder = account.findFolder(forName: folderName) + if folder == nil { + return .unsupported(forReason: .invalid) + } + + return .success(with: folderName) + } + + public func handle(intent: AddWebFeedIntent) async -> AddWebFeedIntentResponse { + guard let url = intent.url, let extensionContainers = await ExtensionContainersFile.read() else { + return AddWebFeedIntentResponse(code: .failure, userActivity: nil) + } + + let account: ExtensionAccount? = { + if let accountName = intent.accountName { + return extensionContainers.findAccount(forName: accountName) } else { - completion(.success(with: accountName)) + return extensionContainers.accounts.first } + }() + + guard let validAccount = account else { + return AddWebFeedIntentResponse(code: .failure, userActivity: nil) } - } - public func provideFolderNameOptions(for intent: AddWebFeedIntent, with completion: @escaping ([String]?, Error?) -> Void) { - 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 - } - - let folderNames = account.folders.map { $0.name } - completion(folderNames, nil) - } - } - - public func resolveFolderName(for intent: AddWebFeedIntent, with completion: @escaping (AddWebFeedFolderNameResolutionResult) -> Void) { - 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)) + let container: ExtensionContainer? = { + if let folderName = intent.folderName { + return validAccount.findFolder(forName: folderName) } else { - completion(.success(with: folderName)) + return validAccount } - return - } - } + }() - public func handle(intent: AddWebFeedIntent, completion: @escaping (AddWebFeedIntentResponse) -> Void) { - Task { @MainActor in - 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 - } - }() - - 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 - } - }() - - 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)) + guard let validContainer = container, let containerID = validContainer.containerID else { + return AddWebFeedIntentResponse(code: .failure, userActivity: nil) } - } + let request = ExtensionFeedAddRequest(name: nil, feedURL: url, destinationContainerID: containerID) + ExtensionFeedAddRequestFile.save(request) + return AddWebFeedIntentResponse(code: .success, userActivity: nil) + } } diff --git a/Shared/ShareExtension/ExtensionContainers.swift b/Shared/ShareExtension/ExtensionContainers.swift index f2c792243..be9099706 100644 --- a/Shared/ShareExtension/ExtensionContainers.swift +++ b/Shared/ShareExtension/ExtensionContainers.swift @@ -9,9 +9,10 @@ import Foundation import Account -protocol ExtensionContainer: ContainerIdentifiable, Codable { +protocol ExtensionContainer: Codable { var name: String { get } var accountID: String { get } + var containerID: ContainerIdentifier? { get } } struct ExtensionContainers: Codable { From ddaafac4eb59bdb5057217659c6c66ff7942583c Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Tue, 18 Nov 2025 19:58:19 -0800 Subject: [PATCH 12/14] Fix return value. --- .../RSCore/Sources/RSCore/Shared/Platform.swift | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/Modules/RSCore/Sources/RSCore/Shared/Platform.swift b/Modules/RSCore/Sources/RSCore/Shared/Platform.swift index a976d2c69..624f7c7b3 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/Platform.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/Platform.swift @@ -75,24 +75,28 @@ public struct Platform { private extension Platform { static func dataFolder(forApplication appName: String?) -> URL? { + var dataFolder: URL? + do { #if os(macOS) - var dataFolder = try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: false) + dataFolder = try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: false) if let appName = appName ?? Bundle.main.infoDictionary?["CFBundleExecutable"] as? String { - dataFolder = dataFolder.appendingPathComponent(appName) + dataFolder = dataFolder?.appendingPathComponent(appName) } #else // iOS - let dataFolder = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) + dataFolder = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) #endif - try FileManager.default.createDirectory(at: dataFolder, withIntermediateDirectories: true, attributes: nil) + if let dataFolder { + try FileManager.default.createDirectory(at: dataFolder, withIntermediateDirectories: true, attributes: nil) + } } catch { Self.logger.error("Platform.dataFolder error: \(error.localizedDescription)") } - return nil + return dataFolder } static func dataFile(forApplication appName: String?, filename: String) -> URL? { From 20d363433de7aaae16e7a1659cfe8621bb01621a Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Tue, 18 Nov 2025 19:58:48 -0800 Subject: [PATCH 13/14] Fix various concurrency issues. --- Mac/AppDefaults.swift | 2 +- .../ArticleStyles/ArticleThemesManager.swift | 87 ++++++++++--------- .../ScriptingTests/ScriptingTests.swift | 2 +- iOS/AppDefaults.swift | 2 +- iOS/AppDelegate.swift | 45 ++++++---- iOS/ErrorHandler.swift | 2 +- .../ShareFolderPickerController.swift | 2 +- iOS/ShareExtension/ShareViewController.swift | 21 ++++- 8 files changed, 97 insertions(+), 66 deletions(-) diff --git a/Mac/AppDefaults.swift b/Mac/AppDefaults.swift index 90ab80dbc..2b8050e12 100644 --- a/Mac/AppDefaults.swift +++ b/Mac/AppDefaults.swift @@ -317,7 +317,7 @@ final class AppDefaults: Sendable { } } - func registerDefaults() { + @MainActor func registerDefaults() { #if DEBUG let showDebugMenu = true #else diff --git a/Shared/ArticleStyles/ArticleThemesManager.swift b/Shared/ArticleStyles/ArticleThemesManager.swift index 430665f8b..053558cb1 100644 --- a/Shared/ArticleStyles/ArticleThemesManager.swift +++ b/Shared/ArticleStyles/ArticleThemesManager.swift @@ -7,6 +7,7 @@ // import Foundation +import Synchronization import RSCore public extension Notification.Name { @@ -14,7 +15,7 @@ public extension Notification.Name { static let CurrentArticleThemeDidChangeNotification = Notification.Name("CurrentArticleThemeDidChangeNotification") } -@MainActor final class ArticleThemesManager: NSObject, NSFilePresenter { +final class ArticleThemesManager: NSObject, NSFilePresenter, Sendable { static let shared = ArticleThemesManager() public let folderPath: String @@ -23,7 +24,7 @@ public extension Notification.Name { var currentThemeName: String { get { - return AppDefaults.shared.currentThemeName ?? AppDefaults.defaultThemeName + AppDefaults.shared.currentThemeName ?? AppDefaults.defaultThemeName } set { if newValue != currentThemeName { @@ -35,24 +36,37 @@ public extension Notification.Name { } var currentTheme: ArticleTheme { - didSet { - NotificationCenter.default.post(name: .CurrentArticleThemeDidChangeNotification, object: self) + get { + state.withLock { $0.currentTheme } + } + set { + state.withLock { $0.currentTheme = newValue } + NotificationCenter.default.postOnMainThread(name: .CurrentArticleThemeDidChangeNotification, object: self) } } - var themeNames = [AppDefaults.defaultThemeName] { - didSet { - NotificationCenter.default.post(name: .ArticleThemeNamesDidChangeNotification, object: self) + var themeNames: [String] { + get { + state.withLock { $0.themeNames } + } + set { + state.withLock { $0.themeNames = newValue } + NotificationCenter.default.postOnMainThread(name: .ArticleThemeNamesDidChangeNotification, object: self) } } - private var didStart = false + private struct State { + var currentTheme = ArticleTheme.defaultTheme + var themeNames = [AppDefaults.defaultThemeName] + } + private let state = Mutex(State()) + + @MainActor private var didStart = false override init() { let folderPath = Platform.dataSubfolder(forApplication: nil, folderName: "Themes")! self.folderPath = folderPath self.presentedItemURL = URL(fileURLWithPath: folderPath) - self.currentTheme = ArticleTheme.defaultTheme super.init() @@ -64,7 +78,7 @@ public extension Notification.Name { } } - func start() { + @MainActor func start() { guard !didStart else { assertionFailure("ArticlesThemesManager.start called when already started.") return @@ -77,7 +91,7 @@ public extension Notification.Name { NSFileCoordinator.addFilePresenter(self) } - nonisolated func presentedSubitemDidChange(at url: URL) { + func presentedSubitemDidChange(at url: URL) { updateThemeNames() updateCurrentTheme() } @@ -124,7 +138,6 @@ public extension Notification.Name { NotificationCenter.default.post(name: .didFailToImportThemeWithError, object: nil, userInfo: ["error": error]) return nil } - } func deleteTheme(themeName: String) { @@ -138,20 +151,18 @@ public extension Notification.Name { private extension ArticleThemesManager { - nonisolated func updateThemeNames() { - MainActor.assumeIsolated { - let appThemeFilenames = Bundle.main.paths(forResourcesOfType: ArticleTheme.nnwThemeSuffix, inDirectory: nil) - let appThemeNames = Set(appThemeFilenames.map { ArticleTheme.themeNameForPath($0) }) + func updateThemeNames() { + let appThemeFilenames = Bundle.main.paths(forResourcesOfType: ArticleTheme.nnwThemeSuffix, inDirectory: nil) + let appThemeNames = Set(appThemeFilenames.map { ArticleTheme.themeNameForPath($0) }) - let installedThemeNames = Set(allThemePaths(folderPath).map { ArticleTheme.themeNameForPath($0) }) + let installedThemeNames = Set(allThemePaths(folderPath).map { ArticleTheme.themeNameForPath($0) }) - let allThemeNames = appThemeNames.union(installedThemeNames) + let allThemeNames = appThemeNames.union(installedThemeNames) - let sortedThemeNames = allThemeNames.sorted(by: { $0.compare($1, options: .caseInsensitive) == .orderedAscending }) - Task { @MainActor in - if sortedThemeNames != themeNames { - themeNames = sortedThemeNames - } + let sortedThemeNames = allThemeNames.sorted(by: { $0.compare($1, options: .caseInsensitive) == .orderedAscending }) + Task { @MainActor in + if sortedThemeNames != themeNames { + themeNames = sortedThemeNames } } } @@ -160,27 +171,25 @@ private extension ArticleThemesManager { articleThemeWithThemeName(AppDefaults.defaultThemeName)! } - nonisolated func updateCurrentTheme() { - MainActor.assumeIsolated { - var themeName = currentThemeName - if !themeNames.contains(themeName) { - themeName = AppDefaults.defaultThemeName - currentThemeName = AppDefaults.defaultThemeName - } + func updateCurrentTheme() { + var themeName = currentThemeName + if !themeNames.contains(themeName) { + themeName = AppDefaults.defaultThemeName + currentThemeName = AppDefaults.defaultThemeName + } - var articleTheme = articleThemeWithThemeName(themeName) - if articleTheme == nil { - articleTheme = defaultArticleTheme() - currentThemeName = AppDefaults.defaultThemeName - } + var articleTheme = articleThemeWithThemeName(themeName) + if articleTheme == nil { + articleTheme = defaultArticleTheme() + currentThemeName = AppDefaults.defaultThemeName + } - if let articleTheme = articleTheme, articleTheme != currentTheme { - currentTheme = articleTheme - } + if let articleTheme = articleTheme, articleTheme != currentTheme { + currentTheme = articleTheme } } - nonisolated func allThemePaths(_ folder: String) -> [String] { + func allThemePaths(_ folder: String) -> [String] { let filepaths = FileManager.default.filePaths(inFolder: folder) return filepaths?.filter { $0.hasSuffix(ArticleTheme.nnwThemeSuffix) } ?? [] } diff --git a/Tests/NetNewsWireTests/ScriptingTests/ScriptingTests.swift b/Tests/NetNewsWireTests/ScriptingTests/ScriptingTests.swift index dcec9ef5d..b2c1202b0 100644 --- a/Tests/NetNewsWireTests/ScriptingTests/ScriptingTests.swift +++ b/Tests/NetNewsWireTests/ScriptingTests/ScriptingTests.swift @@ -8,7 +8,7 @@ import XCTest -final class ScriptingTests: AppleScriptXCTestCase { +@MainActor final class ScriptingTests: AppleScriptXCTestCase { override func setUp() { super.setUp() diff --git a/iOS/AppDefaults.swift b/iOS/AppDefaults.swift index 5c38c48e0..967cf40a5 100644 --- a/iOS/AppDefaults.swift +++ b/iOS/AppDefaults.swift @@ -241,7 +241,7 @@ final class AppDefaults: Sendable { } } - static func registerDefaults() { + @MainActor static func registerDefaults() { let defaults: [String : Any] = [Key.userInterfaceColorPalette: UserInterfaceColorPalette.automatic.rawValue, Key.timelineGroupByFeed: false, Key.refreshClearsReadArticles: false, diff --git a/iOS/AppDelegate.swift b/iOS/AppDelegate.swift index 1404a72d2..5865dc09f 100644 --- a/iOS/AppDelegate.swift +++ b/iOS/AppDelegate.swift @@ -184,31 +184,40 @@ final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationC } } - func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { + nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler([.list, .banner, .badge, .sound]) } - func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { - defer { completionHandler() } + nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { - let userInfo = response.notification.request.content.userInfo - - switch response.actionIdentifier { - case UserNotificationManager.ActionIdentifier.markAsRead: - handleMarkAsRead(userInfo: userInfo) - case UserNotificationManager.ActionIdentifier.markAsStarred: - handleMarkAsStarred(userInfo: userInfo) - default: - if let sceneDelegate = response.targetScene?.delegate as? SceneDelegate { - sceneDelegate.handle(response) - DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: { - sceneDelegate.coordinator.dismissIfLaunchingFromExternalAction() - }) - } + // Wrapper to safely transfer non-Sendable values to MainActor + struct UnsafeSendable: @unchecked Sendable { + let value: T } - } + let wrappedResponse = UnsafeSendable(value: response) + let wrappedCompletionHandler = UnsafeSendable(value: completionHandler) + Task { @MainActor in + let response = wrappedResponse.value + let userInfo = response.notification.request.content.userInfo + + switch response.actionIdentifier { + case UserNotificationManager.ActionIdentifier.markAsRead: + handleMarkAsRead(userInfo: userInfo) + case UserNotificationManager.ActionIdentifier.markAsStarred: + handleMarkAsStarred(userInfo: userInfo) + default: + if let sceneDelegate = response.targetScene?.delegate as? SceneDelegate { + sceneDelegate.handle(response) + DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: { + sceneDelegate.coordinator.dismissIfLaunchingFromExternalAction() + }) + } + } + wrappedCompletionHandler.value() + } + } } // MARK: App Initialization diff --git a/iOS/ErrorHandler.swift b/iOS/ErrorHandler.swift index 2cc2d2c58..7b6afbf6e 100644 --- a/iOS/ErrorHandler.swift +++ b/iOS/ErrorHandler.swift @@ -14,7 +14,7 @@ struct ErrorHandler: Sendable { private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "ErrorHandler") - @Sendable public static func present(_ viewController: UIViewController) -> (Error) -> () { + @Sendable public static func present(_ viewController: UIViewController) -> @Sendable (Error) -> () { return { [weak viewController] error in Task { @MainActor in if UIApplication.shared.applicationState == .active { diff --git a/iOS/ShareExtension/ShareFolderPickerController.swift b/iOS/ShareExtension/ShareFolderPickerController.swift index 83a4751f1..b471d3570 100644 --- a/iOS/ShareExtension/ShareFolderPickerController.swift +++ b/iOS/ShareExtension/ShareFolderPickerController.swift @@ -10,7 +10,7 @@ import UIKit import Account import RSCore -protocol ShareFolderPickerControllerDelegate: AnyObject { +@MainActor protocol ShareFolderPickerControllerDelegate: AnyObject { func shareFolderPickerDidSelect(_ container: ExtensionContainer) } diff --git a/iOS/ShareExtension/ShareViewController.swift b/iOS/ShareExtension/ShareViewController.swift index 250d987b4..3d19c5d6f 100644 --- a/iOS/ShareExtension/ShareViewController.swift +++ b/iOS/ShareExtension/ShareViewController.swift @@ -8,20 +8,33 @@ import UIKit import MobileCoreServices -import Account +import Synchronization +import UniformTypeIdentifiers import Social +import Account import RSCore import RSTree -import UniformTypeIdentifiers final class ShareViewController: SLComposeServiceViewController, ShareFolderPickerControllerDelegate { - - private var url: URL? private var extensionContainers: ExtensionContainers? private var flattenedContainers: [ExtensionContainer]! private var selectedContainer: ExtensionContainer? private var folderItem: SLComposeSheetConfigurationItem! + private struct State { + var url: URL? + } + private let state = Mutex(State()) + + nonisolated private var url: URL? { + get { + state.withLock { $0.url } + } + set { + state.withLock { $0.url = newValue } + } + } + override func viewDidLoad() { extensionContainers = ExtensionContainersFile.read() From 833d06c076bd30142c3ad87e969145b5e1760978 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Tue, 18 Nov 2025 20:22:48 -0800 Subject: [PATCH 14/14] Fix various concurrency issues. --- Mac/AppDelegate.swift | 24 ++++++++++--------- .../Detail/DetailViewController.swift | 16 +++++++------ .../Detail/DetailWebViewController.swift | 8 +++++-- .../TimelineContainerViewController.swift | 12 ++++++---- .../Timeline/TimelineViewController.swift | 16 +++++++------ .../AdvancedPreferencesViewController.swift | 8 +++++-- iOS/Article/PreloadedWebView.swift | 16 +++++++------ .../MainTimelineViewController.swift | 20 +++++++++------- iOS/SceneCoordinator.swift | 14 ++++++----- ...imelineCustomizerTableViewController.swift | 9 +++++-- 10 files changed, 85 insertions(+), 58 deletions(-) diff --git a/Mac/AppDelegate.swift b/Mac/AppDelegate.swift index 5a4a9a5aa..8519fb3dc 100644 --- a/Mac/AppDelegate.swift +++ b/Mac/AppDelegate.swift @@ -187,7 +187,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSUserInterfaceValidat } NotificationCenter.default.addObserver(self, selector: #selector(feedSettingDidChange(_:)), name: .feedSettingDidChange, object: nil) - NotificationCenter.default.addObserver(self, selector: #selector(userDefaultsDidChange(_:)), name: UserDefaults.didChangeNotification, object: nil) + NotificationCenter.default.addObserver(forName: UserDefaults.didChangeNotification, object: nil, queue: .main) { [weak self] _ in + Task { @MainActor in + self?.userDefaultsDidChange() + } + } DispatchQueue.main.async { self.unreadCount = AccountManager.shared.unreadCount @@ -337,18 +341,16 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSUserInterfaceValidat } } - @objc func userDefaultsDidChange(_ note: Notification) { - Task { @MainActor in - updateSortMenuItems() - updateGroupByFeedMenuItem() + func userDefaultsDidChange() { + updateSortMenuItems() + updateGroupByFeedMenuItem() - if lastRefreshInterval != AppDefaults.shared.refreshInterval { - refreshTimer?.update() - lastRefreshInterval = AppDefaults.shared.refreshInterval - } - - updateDockBadge() + if lastRefreshInterval != AppDefaults.shared.refreshInterval { + refreshTimer?.update() + lastRefreshInterval = AppDefaults.shared.refreshInterval } + + updateDockBadge() } @objc func didWakeNotification(_ note: Notification) { diff --git a/Mac/MainWindow/Detail/DetailViewController.swift b/Mac/MainWindow/Detail/DetailViewController.swift index 5205b63f8..1cc6ee4d1 100644 --- a/Mac/MainWindow/Detail/DetailViewController.swift +++ b/Mac/MainWindow/Detail/DetailViewController.swift @@ -65,7 +65,11 @@ final class DetailViewController: NSViewController, WKUIDelegate { override func viewDidLoad() { currentWebViewController = regularWebViewController - NotificationCenter.default.addObserver(self, selector: #selector(userDefaultsDidChange(_:)), name: UserDefaults.didChangeNotification, object: nil) + NotificationCenter.default.addObserver(forName: UserDefaults.didChangeNotification, object: nil, queue: .main) { [weak self] _ in + Task { @MainActor in + self?.userDefaultsDidChange() + } + } } // MARK: - API @@ -155,12 +159,10 @@ private extension DetailViewController { } } - @objc func userDefaultsDidChange(_ : Notification) { - Task { @MainActor in - if AppDefaults.shared.isArticleContentJavascriptEnabled != isArticleContentJavascriptEnabled { - isArticleContentJavascriptEnabled = AppDefaults.shared.isArticleContentJavascriptEnabled - createNewWebViewsAndRestoreState() - } + func userDefaultsDidChange() { + if AppDefaults.shared.isArticleContentJavascriptEnabled != isArticleContentJavascriptEnabled { + isArticleContentJavascriptEnabled = AppDefaults.shared.isArticleContentJavascriptEnabled + createNewWebViewsAndRestoreState() } } diff --git a/Mac/MainWindow/Detail/DetailWebViewController.swift b/Mac/MainWindow/Detail/DetailWebViewController.swift index d15f7501d..e02be2ff9 100644 --- a/Mac/MainWindow/Detail/DetailWebViewController.swift +++ b/Mac/MainWindow/Detail/DetailWebViewController.swift @@ -111,7 +111,11 @@ final class DetailWebViewController: NSViewController { NotificationCenter.default.addObserver(self, selector: #selector(feedIconDidBecomeAvailable(_:)), name: .feedIconDidBecomeAvailable, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(avatarDidBecomeAvailable(_:)), name: .AvatarDidBecomeAvailable, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(faviconDidBecomeAvailable(_:)), name: .FaviconDidBecomeAvailable, object: nil) - NotificationCenter.default.addObserver(self, selector: #selector(userDefaultsDidChange(_:)), name: UserDefaults.didChangeNotification, object: nil) + NotificationCenter.default.addObserver(forName: UserDefaults.didChangeNotification, object: nil, queue: .main) { [weak self] _ in + Task { @MainActor in + self?.userDefaultsDidChange() + } + } NotificationCenter.default.addObserver(self, selector: #selector(currentArticleThemeDidChangeNotification(_:)), name: .CurrentArticleThemeDidChangeNotification, object: nil) webView.loadFileURL(ArticleRenderer.blank.url, allowingReadAccessTo: ArticleRenderer.blank.baseURL) @@ -131,7 +135,7 @@ final class DetailWebViewController: NSViewController { reloadArticleImage() } - @objc func userDefaultsDidChange(_ note: Notification) { + func userDefaultsDidChange() { if articleTextSize != AppDefaults.shared.articleTextSize { articleTextSize = AppDefaults.shared.articleTextSize reloadHTMLMaintainingScrollPosition() diff --git a/Mac/MainWindow/Timeline/TimelineContainerViewController.swift b/Mac/MainWindow/Timeline/TimelineContainerViewController.swift index 33a8ca8ab..f73758845 100644 --- a/Mac/MainWindow/Timeline/TimelineContainerViewController.swift +++ b/Mac/MainWindow/Timeline/TimelineContainerViewController.swift @@ -72,15 +72,17 @@ final class TimelineContainerViewController: NSViewController { makeMenuItemTitleLarger(groupByFeedMenuItem) updateViewOptionsPopUpButton() - NotificationCenter.default.addObserver(self, selector: #selector(userDefaultsDidChange(_:)), name: UserDefaults.didChangeNotification, object: nil) + NotificationCenter.default.addObserver(forName: UserDefaults.didChangeNotification, object: nil, queue: .main) { [weak self] _ in + Task { @MainActor in + self?.userDefaultsDidChange() + } + } } // MARK: - Notifications - @objc func userDefaultsDidChange(_ note: Notification) { - Task { - updateViewOptionsPopUpButton() - } + func userDefaultsDidChange() { + updateViewOptionsPopUpButton() } // MARK: - API diff --git a/Mac/MainWindow/Timeline/TimelineViewController.swift b/Mac/MainWindow/Timeline/TimelineViewController.swift index ffdc8b9ef..b4ac2e631 100644 --- a/Mac/MainWindow/Timeline/TimelineViewController.swift +++ b/Mac/MainWindow/Timeline/TimelineViewController.swift @@ -240,7 +240,11 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr NotificationCenter.default.addObserver(self, selector: #selector(accountsDidChange(_:)), name: .UserDidAddAccount, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(accountsDidChange(_:)), name: .UserDidDeleteAccount, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(containerChildrenDidChange(_:)), name: .ChildrenDidChange, object: nil) - NotificationCenter.default.addObserver(self, selector: #selector(userDefaultsDidChange(_:)), name: UserDefaults.didChangeNotification, object: nil) + NotificationCenter.default.addObserver(forName: UserDefaults.didChangeNotification, object: nil, queue: .main) { [weak self] _ in + Task { @MainActor in + self?.userDefaultsDidChange() + } + } didRegisterForNotifications = true } } @@ -699,12 +703,10 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr } } - @objc func userDefaultsDidChange(_ note: Notification) { - Task { @MainActor in - self.fontSize = AppDefaults.shared.timelineFontSize - self.sortDirection = AppDefaults.shared.timelineSortDirection - self.groupByFeed = AppDefaults.shared.timelineGroupByFeed - } + @MainActor func userDefaultsDidChange() { + fontSize = AppDefaults.shared.timelineFontSize + sortDirection = AppDefaults.shared.timelineSortDirection + groupByFeed = AppDefaults.shared.timelineGroupByFeed } // MARK: - Reloading Data diff --git a/Mac/Preferences/Advanced/AdvancedPreferencesViewController.swift b/Mac/Preferences/Advanced/AdvancedPreferencesViewController.swift index bcab88a78..462a43d73 100644 --- a/Mac/Preferences/Advanced/AdvancedPreferencesViewController.swift +++ b/Mac/Preferences/Advanced/AdvancedPreferencesViewController.swift @@ -31,7 +31,11 @@ final class AdvancedPreferencesViewController: NSViewController { super.viewWillAppear() updateUI() if !didRegisterForNotification { - NotificationCenter.default.addObserver(self, selector: #selector(userDefaultsDidChange(_:)), name: UserDefaults.didChangeNotification, object: nil) + NotificationCenter.default.addObserver(forName: UserDefaults.didChangeNotification, object: nil, queue: .main) { [weak self] _ in + Task { @MainActor in + self?.userDefaultsDidChange() + } + } didRegisterForNotification = true } } @@ -43,7 +47,7 @@ final class AdvancedPreferencesViewController: NSViewController { wantsTestBuilds = (button === testBuildsButton) } - @objc func userDefaultsDidChange(_ sender: Any?) { + func userDefaultsDidChange() { updateUI() } } diff --git a/iOS/Article/PreloadedWebView.swift b/iOS/Article/PreloadedWebView.swift index 48c9f1435..dc8f2492b 100644 --- a/iOS/Article/PreloadedWebView.swift +++ b/iOS/Article/PreloadedWebView.swift @@ -17,7 +17,11 @@ final class PreloadedWebView: WKWebView { init(articleIconSchemeHandler: ArticleIconSchemeHandler) { let configuration = WebViewConfiguration.configuration(with: articleIconSchemeHandler) super.init(frame: .zero, configuration: configuration) - NotificationCenter.default.addObserver(self, selector: #selector(userDefaultsDidChange(_:)), name: UserDefaults.didChangeNotification, object: nil) + NotificationCenter.default.addObserver(forName: UserDefaults.didChangeNotification, object: nil, queue: .main) { [weak self] _ in + Task { @MainActor in + self?.userDefaultsDidChange() + } + } } required init?(coder: NSCoder) { @@ -38,12 +42,10 @@ final class PreloadedWebView: WKWebView { } } - @objc func userDefaultsDidChange(_ sender: Any) { - Task { @MainActor in - if configuration.defaultWebpagePreferences.allowsContentJavaScript != AppDefaults.shared.isArticleContentJavascriptEnabled { - configuration.defaultWebpagePreferences.allowsContentJavaScript = AppDefaults.shared.isArticleContentJavascriptEnabled - reload() - } + func userDefaultsDidChange() { + if configuration.defaultWebpagePreferences.allowsContentJavaScript != AppDefaults.shared.isArticleContentJavascriptEnabled { + configuration.defaultWebpagePreferences.allowsContentJavaScript = AppDefaults.shared.isArticleContentJavascriptEnabled + reload() } } } diff --git a/iOS/MainTimeline/MainTimelineViewController.swift b/iOS/MainTimeline/MainTimelineViewController.swift index bc4367023..a6ec88d5b 100644 --- a/iOS/MainTimeline/MainTimelineViewController.swift +++ b/iOS/MainTimeline/MainTimelineViewController.swift @@ -152,7 +152,11 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu // lets us know that it’s time to request an image. NotificationCenter.default.addObserver(self, selector: #selector(faviconDidBecomeAvailable(_:)), name: .htmlMetadataAvailable, object: nil) - NotificationCenter.default.addObserver(self, selector: #selector(userDefaultsDidChange(_:)), name: UserDefaults.didChangeNotification, object: nil) + NotificationCenter.default.addObserver(forName: UserDefaults.didChangeNotification, object: nil, queue: .main) { [weak self] _ in + Task { @MainActor in + self?.userDefaultsDidChange() + } + } NotificationCenter.default.addObserver(self, selector: #selector(contentSizeCategoryDidChange), name: UIContentSizeCategory.didChangeNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(displayNameDidChange), name: .DisplayNameDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground(_:)), name: UIApplication.willEnterForegroundNotification, object: nil) @@ -649,15 +653,13 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu } } - @objc func userDefaultsDidChange(_ note: Notification) { - Task { @MainActor in - if self.numberOfTextLines != AppDefaults.shared.timelineNumberOfLines || self.iconSize != AppDefaults.shared.timelineIconSize { - self.numberOfTextLines = AppDefaults.shared.timelineNumberOfLines - self.iconSize = AppDefaults.shared.timelineIconSize - self.reloadAllVisibleCells() - } - self.updateToolbar() + func userDefaultsDidChange() { + if self.numberOfTextLines != AppDefaults.shared.timelineNumberOfLines || self.iconSize != AppDefaults.shared.timelineIconSize { + self.numberOfTextLines = AppDefaults.shared.timelineNumberOfLines + self.iconSize = AppDefaults.shared.timelineIconSize + self.reloadAllVisibleCells() } + self.updateToolbar() } @objc func contentSizeCategoryDidChange(_ note: Notification) { diff --git a/iOS/SceneCoordinator.swift b/iOS/SceneCoordinator.swift index 057a6ca49..f2b5baefb 100644 --- a/iOS/SceneCoordinator.swift +++ b/iOS/SceneCoordinator.swift @@ -326,13 +326,17 @@ struct FeedNode: Hashable, Sendable { NotificationCenter.default.addObserver(self, selector: #selector(userDidAddAccount(_:)), name: .UserDidAddAccount, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(userDidDeleteAccount(_:)), name: .UserDidDeleteAccount, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(userDidAddFeed(_:)), name: .UserDidAddFeed, object: nil) - NotificationCenter.default.addObserver(self, selector: #selector(userDefaultsDidChange(_:)), name: UserDefaults.didChangeNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(accountDidDownloadArticles(_:)), name: .AccountDidDownloadArticles, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground(_:)), name: UIApplication.willEnterForegroundNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(importDownloadedTheme(_:)), name: .didEndDownloadingTheme, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(themeDownloadDidFail(_:)), name: .didFailToImportThemeWithError, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(updateNavigationBarSubtitles(_:)), name: .combinedRefreshProgressDidChange, object: nil) + NotificationCenter.default.addObserver(forName: UserDefaults.didChangeNotification, object: nil, queue: .main) { [weak self] _ in + Task { @MainActor in + self?.userDefaultsDidChange() + } + } } func restoreWindowState(_ activity: NSUserActivity?) { @@ -513,11 +517,9 @@ struct FeedNode: Hashable, Sendable { discloseFeed(feed, animations: [.scroll, .navigation]) } - @objc func userDefaultsDidChange(_ note: Notification) { - Task { @MainActor in - self.sortDirection = AppDefaults.shared.timelineSortDirection - self.groupByFeed = AppDefaults.shared.timelineGroupByFeed - } + func userDefaultsDidChange() { + sortDirection = AppDefaults.shared.timelineSortDirection + groupByFeed = AppDefaults.shared.timelineGroupByFeed } @objc func accountDidDownloadArticles(_ note: Notification) { diff --git a/iOS/Settings/ModernTimelineCustomizerTableViewController.swift b/iOS/Settings/ModernTimelineCustomizerTableViewController.swift index 82bc23db2..b8ca6a336 100644 --- a/iOS/Settings/ModernTimelineCustomizerTableViewController.swift +++ b/iOS/Settings/ModernTimelineCustomizerTableViewController.swift @@ -43,8 +43,12 @@ class ModernTimelineCustomizerTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() title = NSLocalizedString("Timeline Customizer", comment: "Timeline Customizer") - NotificationCenter.default.addObserver(self, selector: #selector(userDefaultsDidChange(_:)), name: UserDefaults.didChangeNotification, object: nil) + NotificationCenter.default.addObserver(forName: UserDefaults.didChangeNotification, object: nil, queue: .main) { [weak self] _ in + Task { @MainActor in + self?.userDefaultsDidChange() + } + } } @@ -126,7 +130,8 @@ class ModernTimelineCustomizerTableViewController: UITableViewController { } // MARK: - Notifications - @objc func userDefaultsDidChange(_ note: Notification) { + + func userDefaultsDidChange() { tableView.reloadSections(IndexSet(integersIn: 2...3), with: .none) }