Merge branch 'task/app-swift6'

This commit is contained in:
Brent Simmons committed 2025-11-18 20:22:57 -08:00
commit 6d55acbb14
91 files changed
+909 -1123

No files matched your search

+80 -106
View File
@@ -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)
}
}
+63 -251
View File
@@ -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
}
}
}
+3 -3
View File
@@ -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
}
@@ -317,7 +317,7 @@ final class AppDefaults {
}
}
func registerDefaults() {
@MainActor func registerDefaults() {
#if DEBUG
let showDebugMenu = true
#else
+38 -26
View File
@@ -20,9 +20,9 @@ import Sparkle
let appName = "NetNewsWire"
var appDelegate: AppDelegate!
@MainActor 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")
@@ -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)
@@ -189,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
@@ -199,6 +201,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSUserInterfaceValidat
self.toggleInspectorWindow(self)
}
ArticleThemesManager.shared.start()
NetworkMonitor.shared.start()
ExtensionContainersFile.shared.start()
ExtensionFeedAddRequestFile.shared.start()
@@ -338,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) {
@@ -450,23 +451,34 @@ 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
// Wrapper to safely transfer non-Sendable values to MainActor
struct UnsafeSendable<T>: @unchecked Sendable {
let value: T
}
switch response.actionIdentifier {
case UserNotificationManager.ActionIdentifier.markAsRead:
handleMarkAsRead(userInfo: userInfo)
case UserNotificationManager.ActionIdentifier.markAsStarred:
handleMarkAsStarred(userInfo: userInfo)
default:
mainWindowController?.handle(response)
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:
mainWindowController?.handle(response)
}
wrappedCompletionHandler.value()
}
completionHandler()
}
// MARK: Add Feed
+1 -1
View File
@@ -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"
+22 -16
View File
@@ -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()
}
}
@@ -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.
@@ -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()
}
}
@@ -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)
}
@@ -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()
@@ -196,7 +200,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 +208,7 @@ extension DetailWebViewController: WKNavigationDelegate, WKUIDelegate {
decisionHandler(.cancel)
return
}
decisionHandler(.allow)
}
@@ -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<KeyboardShortcut>
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
@@ -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)
+1 -2
View File
@@ -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
}
@@ -11,8 +11,7 @@ import RSCore
// image - title - unreadCount
struct SidebarCellLayout {
@MainActor struct SidebarCellLayout {
let faviconRect: CGRect
let titleRect: CGRect
let unreadCountRect: CGRect
@@ -8,7 +8,7 @@
import AppKit
protocol RenameWindowControllerDelegate {
@MainActor protocol RenameWindowControllerDelegate {
func renameWindowController(_ windowController: RenameWindowController, didRenameObject: Any, withNewName: String)
}
@@ -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() {
@@ -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.")
@@ -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)
+1 -2
View File
@@ -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
@@ -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
@@ -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
@@ -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 {
@@ -73,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
@@ -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
@@ -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
@@ -12,7 +12,7 @@ import SwiftUI
import RSCore
// MARK: - AccountsPreferencesAddAccountDelegate
protocol AccountsPreferencesAddAccountDelegate {
@MainActor protocol AccountsPreferencesAddAccountDelegate {
func presentSheetForAccount(_ accountType: AccountType)
}
@@ -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()
}
}
@@ -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()
@@ -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<String, ValidationWrapper>()
static var validationQueue = DispatchQueue(label: "Toolbar Validation")
nonisolated(unsafe) static var gPingPongMap = Dictionary<String, ValidationWrapper>()
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) {
@@ -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
}
@@ -19,18 +19,24 @@
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 {
// 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<T>: @unchecked Sendable {
let value: T
}
extension AppDelegate: AppDelegateAppleEvents {
// MARK: GetURL Apple Event
@@ -92,14 +98,22 @@ extension AppDelegate : AppDelegateAppleEvents {
}
final class NetNewsWireCreateElementCommand : NSCreateCommand {
@MainActor 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<Any?> 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
}
@@ -11,10 +11,10 @@ import Account
import Articles
@objc(ScriptableArticle)
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 @@ final class ScriptableArticle: NSObject, UniqueIdScriptingObject, ScriptingObjec
}
@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 @@ final class ScriptableArticle: NSObject, UniqueIdScriptingObject, ScriptingObjec
// 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
}
+9 -10
View File
@@ -11,20 +11,19 @@ import Account
import Articles
@objc(ScriptableAuthor)
final class ScriptableAuthor: NSObject, UniqueIdScriptingObject {
@MainActor final class ScriptableAuthor: NSObject, UniqueIDScriptingObject {
let author: Author
nonisolated(unsafe) 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)
nonisolated override var objectSpecifier: NSScriptObjectSpecifier? {
let scriptObjectSpecifier = container.makeFormUniqueIDScriptObjectSpecifier(forObject: self)
return scriptObjectSpecifier
}
@objc(scriptingSpecifierDescriptor)
@@ -34,14 +33,14 @@ final class ScriptableAuthor: NSObject, UniqueIdScriptingObject {
// 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
}
+7 -7
View File
@@ -12,10 +12,10 @@ import Account
import Articles
@objc(ScriptableFeed)
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 @@ final class ScriptableFeed: NSObject, UniqueIdScriptingObject, ScriptingObjectCo
}
@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 @@ final class ScriptableFeed: NSObject, UniqueIdScriptingObject, ScriptingObjectCo
// MARK: --- ScriptingObject protocol ---
var scriptingKey: String {
nonisolated var scriptingKey: String {
return "feeds"
}
@@ -44,13 +44,13 @@ 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 {
nonisolated var scriptingUniqueID:Any {
return feed.feedID
}
// MARK: --- ScriptingObjectContainer protocol ---
var scriptingClassDescription: NSScriptClassDescription {
nonisolated var scriptingClassDescription: NSScriptClassDescription {
return self.classDescription as! NSScriptClassDescription
}
+7 -7
View File
@@ -12,10 +12,10 @@ import Articles
import RSCore
@objc(ScriptableFolder)
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 @@ final class ScriptableFolder: NSObject, UniqueIdScriptingObject, ScriptingObject
}
@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 @@ 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 {
nonisolated var scriptingUniqueID:Any {
return folder.folderID
}
// MARK: --- ScriptingObjectContainer protocol ---
var scriptingClassDescription: NSScriptClassDescription {
nonisolated var scriptingClassDescription: NSScriptClassDescription {
return self.classDescription as! NSScriptClassDescription
}
@@ -9,8 +9,7 @@
import Foundation
import Articles
protocol ScriptingMainWindowController {
@MainActor protocol ScriptingMainWindowController {
var scriptingCurrentArticle: Article? { get }
var scriptingSelectedArticles: [Article] { get }
}
@@ -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"
}
+7 -7
View File
@@ -8,15 +8,15 @@
import Foundation
@MainActor protocol ScriptingObject {
var objectSpecifier: NSScriptObjectSpecifier? { get }
var scriptingKey: String { get }
protocol ScriptingObject {
var objectSpecifier: NSScriptObjectSpecifier? { get }
var scriptingKey: String { get }
}
@MainActor protocol NamedScriptingObject: ScriptingObject {
var name:String { get }
protocol NamedScriptingObject: ScriptingObject {
var name:String { get }
}
@MainActor protocol UniqueIdScriptingObject: ScriptingObject {
var scriptingUniqueId:Any { get }
protocol UniqueIDScriptingObject: ScriptingObject {
var scriptingUniqueID: Any { get }
}
@@ -9,14 +9,14 @@
import AppKit
import Account
@MainActor protocol ScriptingObjectContainer: ScriptingObject {
protocol ScriptingObjectContainer: ScriptingObject {
var scriptingClassDescription:NSScriptClassDescription { get }
func deleteElement(_ element:ScriptingObject)
}
@MainActor extension ScriptingObjectContainer {
extension ScriptingObjectContainer {
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,11 +26,11 @@ import Account
return specifier
}
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
let uniqueId = object.scriptingUniqueId
let uniqueId = object.scriptingUniqueID
let specifier = NSUniqueIDSpecifier(containerClassDescription:containerClassDescription,
containerSpecifier:containerScriptObjectSpecifier, key:scriptingKey, uniqueID: uniqueId)
return specifier
+16 -5
View File
@@ -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
}
@@ -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 {
+4 -4
View File
@@ -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?
@@ -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? {
+2 -2
View File
@@ -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
@@ -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<Success>: @unchecked Sendable {
weak var zone: (any CloudKitZone)?
let completion: (Result<Success, Error>) -> 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<CKSubscription, Error>) -> 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, Error>) -> 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!)))
}
}
}
@@ -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
@@ -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
@@ -75,22 +75,28 @@ public struct Platform {
private extension Platform {
static func dataFolder(forApplication appName: String?) -> URL? {
var dataFolder: URL?
do {
var dataFolder = try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
#if os(macOS)
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)
}
#else // iOS
dataFolder = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
#endif
dataFolder = dataFolder.appendingPathComponent(appName)
if let dataFolder {
try FileManager.default.createDirectory(at: dataFolder, withIntermediateDirectories: true, attributes: nil)
}
return dataFolder
} catch {
Self.logger.error("Platform.dataFolder error: \(error.localizedDescription)")
}
return nil
return dataFolder
}
static func dataFile(forApplication appName: String?, filename: String) -> URL? {
@@ -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:
+54 -54
View File
@@ -10,7 +10,7 @@ import Foundation
import Account
import Secrets
public enum ArticleExtractorState {
public enum ArticleExtractorState: Sendable {
case ready
case processing
case failedToParse
@@ -18,24 +18,23 @@ public enum ArticleExtractorState {
case cancelled
}
protocol ArticleExtractorDelegate {
func articleExtractionDidFail(with: Error)
func articleExtractionDidComplete(extractedArticle: ExtractedArticle)
@MainActor protocol ArticleExtractorDelegate {
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()
}
}
@@ -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()
+4 -6
View File
@@ -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
}
}
@@ -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 {
+6 -6
View File
@@ -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"
+43 -20
View File
@@ -7,6 +7,7 @@
//
import Foundation
import Synchronization
import RSCore
public extension Notification.Name {
@@ -14,19 +15,16 @@ public extension Notification.Name {
static let CurrentArticleThemeDidChangeNotification = Notification.Name("CurrentArticleThemeDidChangeNotification")
}
final class ArticleThemesManager: NSObject, NSFilePresenter {
static var shared: ArticleThemesManager!
final class ArticleThemesManager: NSObject, NSFilePresenter, Sendable {
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 {
return AppDefaults.shared.currentThemeName ?? AppDefaults.defaultThemeName
AppDefaults.shared.currentThemeName ?? AppDefaults.defaultThemeName
}
set {
if newValue != currentThemeName {
@@ -38,20 +36,37 @@ final class ArticleThemesManager: NSObject, NSFilePresenter {
}
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)
}
}
init(folderPath: String) {
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.currentTheme = ArticleTheme.defaultTheme
self.presentedItemURL = URL(fileURLWithPath: folderPath)
super.init()
@@ -61,6 +76,14 @@ final class ArticleThemesManager: NSObject, NSFilePresenter {
assertionFailure("Could not create folder for Themes.")
abort()
}
}
@MainActor func start() {
guard !didStart else {
assertionFailure("ArticlesThemesManager.start called when already started.")
return
}
didStart = true
updateThemeNames()
updateCurrentTheme()
@@ -115,7 +138,6 @@ final class ArticleThemesManager: NSObject, NSFilePresenter {
NotificationCenter.default.post(name: .didFailToImportThemeWithError, object: nil, userInfo: ["error": error])
return nil
}
}
func deleteTheme(themeName: String) {
@@ -123,7 +145,6 @@ final class ArticleThemesManager: NSObject, NSFilePresenter {
try? FileManager.default.removeItem(atPath: filename)
}
}
}
// MARK : Private
@@ -139,13 +160,15 @@ private extension ArticleThemesManager {
let allThemeNames = appThemeNames.union(installedThemeNames)
let sortedThemeNames = allThemeNames.sorted(by: { $0.compare($1, options: .caseInsensitive) == .orderedAscending })
if sortedThemeNames != themeNames {
themeNames = sortedThemeNames
Task { @MainActor in
if sortedThemeNames != themeNames {
themeNames = sortedThemeNames
}
}
}
func defaultArticleTheme() -> ArticleTheme {
return articleThemeWithThemeName(AppDefaults.defaultThemeName)!
articleThemeWithThemeName(AppDefaults.defaultThemeName)!
}
func updateCurrentTheme() {
+1 -1
View File
@@ -14,7 +14,7 @@ import UIKit
import RSCore
final class IconImage {
final class IconImage: @unchecked Sendable {
lazy var isDark: Bool = {
return image.isDark()
+1 -1
View File
@@ -27,7 +27,7 @@ extension RSImage {
}
extension IconImage {
static var appIcon: IconImage? = {
static let appIcon: IconImage? = {
if let image = RSImage.appIconImage {
return IconImage(image)
}
+1 -1
View File
@@ -40,7 +40,7 @@ extension RSImage {
// MARK: - IconScalerQueue
private final class IconScalerQueue {
private final class IconScalerQueue: Sendable {
static let shared = IconScalerQueue()
+51 -62
View File
@@ -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
await 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
await 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)
}
}
+6 -4
View File
@@ -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 {
+26 -21
View File
@@ -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
await 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])
}
}
+6 -3
View File
@@ -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)
@@ -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 {
@@ -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)
}
@@ -8,7 +8,7 @@
import XCTest
final class ScriptingTests: AppleScriptXCTestCase {
@MainActor final class ScriptingTests: AppleScriptXCTestCase {
override func setUp() {
super.setUp()
+1 -1
View File
@@ -10,7 +10,7 @@ import UIKit
import RSCore
import Account
protocol AddFeedFolderViewControllerDelegate {
@MainActor protocol AddFeedFolderViewControllerDelegate {
func didSelect(container: Container)
}
+62 -214
View File
@@ -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
}
}
}
+3 -3
View File
@@ -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)!
@@ -241,7 +241,7 @@ final class AppDefaults {
}
}
static func registerDefaults() {
@MainActor static func registerDefaults() {
let defaults: [String : Any] = [Key.userInterfaceColorPalette: UserInterfaceColorPalette.automatic.rawValue,
Key.timelineGroupByFeed: false,
Key.refreshClearsReadArticles: false,
+33 -31
View File
@@ -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")
@@ -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 {
@@ -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()
@@ -190,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<T>: @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
@@ -349,13 +352,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)")
+1 -1
View File
@@ -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)
+4 -2
View File
@@ -42,8 +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)
}
}
+9 -7
View File
@@ -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()
}
}
}
+3 -4
View File
@@ -15,7 +15,7 @@ import Articles
import SafariServices
import MessageUI
protocol WebViewControllerDelegate: AnyObject {
@MainActor protocol WebViewControllerDelegate: AnyObject {
func webViewController(_: WebViewController, articleExtractorButtonStateDidUpdate: ArticleExtractorButtonState)
}
@@ -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
+1 -1
View File
@@ -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 {
+12 -14
View File
@@ -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()
}
}
+2 -2
View File
@@ -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] {
@@ -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() {
@@ -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) {
@@ -8,7 +8,7 @@
import UIKit
protocol MainFeedCollectionViewFolderCellDelegate: AnyObject {
@MainActor protocol MainFeedCollectionViewFolderCellDelegate: AnyObject {
func mainFeedCollectionFolderViewCellDisclosureDidToggle(_ sender: MainFeedCollectionViewFolderCell, expanding: Bool)
}
@@ -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) {
@@ -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! {
+10 -8
View File
@@ -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() {
@@ -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() {
@@ -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() {
@@ -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) {
@@ -15,7 +15,7 @@ extension UIView: MarkAsReadAlertControllerSourceType {}
extension UIBarButtonItem: MarkAsReadAlertControllerSourceType {}
struct MarkAsReadAlertController {
@MainActor struct MarkAsReadAlertController {
static func confirm<T>(_ controller: UIViewController?,
coordinator: SceneCoordinator?,
+8 -6
View File
@@ -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) {
+1 -1
View File
@@ -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)
@@ -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)
}
+5 -6
View File
@@ -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?) {
@@ -10,7 +10,7 @@ import UIKit
import Account
import RSCore
protocol ShareFolderPickerControllerDelegate: AnyObject {
@MainActor protocol ShareFolderPickerControllerDelegate: AnyObject {
func shareFolderPickerDidSelect(_ container: ExtensionContainer)
}
+17 -4
View File
@@ -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()
+1 -1
View File
@@ -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)
+1 -1
View File
@@ -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)
+2 -1
View File
@@ -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