From c137f24fc164efd36beeed20fe16945d23d92bef Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Mon, 2 Nov 2026 11:39:14 -0800 Subject: [PATCH] Decode images and compute luminance on background. --- .../Images/AuthorAvatarDownloader.swift | 12 ++++---- .../Sources/Images/FeedIconDownloader.swift | 30 +++++++++---------- Modules/Images/Sources/Images/IconImage.swift | 26 +++++++++++++--- .../Images/SingleFaviconDownloader.swift | 12 +++----- Modules/RSCore/Sources/RSCore/RSImage.swift | 30 +++++++++++++++++++ 5 files changed, 76 insertions(+), 34 deletions(-) diff --git a/Modules/Images/Sources/Images/AuthorAvatarDownloader.swift b/Modules/Images/Sources/Images/AuthorAvatarDownloader.swift index c8a96c33a..c98ee6f7d 100644 --- a/Modules/Images/Sources/Images/AuthorAvatarDownloader.swift +++ b/Modules/Images/Sources/Images/AuthorAvatarDownloader.swift @@ -90,18 +90,16 @@ extension Notification.Name { @MainActor private extension AuthorAvatarDownloader { func scaleAndCacheImageData(_ imageData: Data, _ avatarURL: String) { - RSImage.image(with: imageData) { (image) in - MainActor.assumeIsolated { - if let image { - self.handleImageDidBecomeAvailable(avatarURL, image) - } + Task { @MainActor in + if let iconImage = await IconImage.decodedIconImage(imageData) { + handleImageDidBecomeAvailable(avatarURL, iconImage) } } } - func handleImageDidBecomeAvailable(_ avatarURL: String, _ image: RSImage) { + func handleImageDidBecomeAvailable(_ avatarURL: String, _ iconImage: IconImage) { if cache[avatarURL] == nil { - cache[avatarURL] = IconImage(image) + cache[avatarURL] = iconImage } if waitingForAvatarURLs.contains(avatarURL) { waitingForAvatarURLs.remove(avatarURL) diff --git a/Modules/Images/Sources/Images/FeedIconDownloader.swift b/Modules/Images/Sources/Images/FeedIconDownloader.swift index ad6c33391..667f13e1a 100644 --- a/Modules/Images/Sources/Images/FeedIconDownloader.swift +++ b/Modules/Images/Sources/Images/FeedIconDownloader.swift @@ -65,12 +65,12 @@ extension Notification.Name { if homePagesWithNoIconURL.contains(homePageURL) { return } - icon(forHomePageURL: homePageURL, feed: feed) { image, iconURL in + icon(forHomePageURL: homePageURL, feed: feed) { iconImage, iconURL in if self.cache[feed] != nil { return // already cached } - if let image, let iconURL { - self.cache[feed] = IconImage(image) + if let iconImage, let iconURL { + self.cache[feed] = iconImage self.cacheIconURLForFeedURL(iconURL: iconURL, feedURL: feed.url) self.postFeedIconDidBecomeAvailableNotification(feed) } @@ -79,13 +79,13 @@ extension Notification.Name { @MainActor func checkFeedIconURL() { if let iconURL = feed.iconURL, !Self.shouldIgnoreFeedIconURL(feed) { - icon(forURL: iconURL, feed: feed) { (image, isDefinitive) in + icon(forURL: iconURL, feed: feed) { (iconImage, isDefinitive) in Task { @MainActor in if self.cache[feed] != nil { return // already cached } - if let image = image { - self.cache[feed] = IconImage(image) + if let iconImage { + self.cache[feed] = iconImage self.postFeedIconDidBecomeAvailableNotification(feed) } else if isDefinitive { // The declared icon failed or isn’t an image. A still-downloading @@ -106,12 +106,12 @@ extension Notification.Name { let feedDeclaresIconURL = feed.iconURL != nil && !Self.shouldIgnoreFeedIconURL(feed) if !feedDeclaresIconURL, let previouslyFoundIconURL = ImageDatabase.shared.iconURL(forFeedURL: feed.url) { - icon(forURL: previouslyFoundIconURL, feed: feed) { image, isDefinitive in + icon(forURL: previouslyFoundIconURL, feed: feed) { iconImage, isDefinitive in if self.cache[feed] != nil { return // already cached } - if let image { - self.cache[feed] = IconImage(image) + if let iconImage { + self.cache[feed] = iconImage self.postFeedIconDidBecomeAvailableNotification(feed) } else if isDefinitive { // The site may have moved its icon, so the home page is checked again. @@ -240,7 +240,7 @@ private extension FeedIconDownloader { return components.string ?? url } - func icon(forHomePageURL homePageURL: String, feed: Feed, _ resultBlock: @escaping @MainActor (RSImage?, String?) -> Void) { + func icon(forHomePageURL homePageURL: String, feed: Feed, _ resultBlock: @escaping @MainActor (IconImage?, String?) -> Void) { if Self.shouldSkipDownloadingFeedIcon(homePageURL) { resultBlock(nil, nil) return @@ -259,9 +259,9 @@ private extension FeedIconDownloader { if let url = metadata.bestWebsiteIconURL() { homePagesWithNoIconURL.remove(homePageURL) - icon(forURL: url, feed: feed) { image, _ in + icon(forURL: url, feed: feed) { iconImage, _ in Task { @MainActor in - resultBlock(image, url) + resultBlock(iconImage, url) } } return @@ -276,13 +276,13 @@ private extension FeedIconDownloader { /// /// After a transient failure, `isDefinitive` is true, so the caller can fall back to the home page icon, /// and the feed still waits for this image, which replaces the fallback when it arrives. - func icon(forURL url: String, feed: Feed, _ imageResultBlock: @escaping @MainActor (RSImage?, _ isDefinitive: Bool) -> Void) { + func icon(forURL url: String, feed: Feed, _ imageResultBlock: @escaping @MainActor (IconImage?, _ isDefinitive: Bool) -> Void) { let url = Self.sanitizedIconURL(url) if let imageData = imageData(for: url, feed: feed) { - RSImage.image(with: imageData) { image in - imageResultBlock(image, true) + Task { @MainActor in + imageResultBlock(await IconImage.decodedIconImage(imageData), true) } return } diff --git a/Modules/Images/Sources/Images/IconImage.swift b/Modules/Images/Sources/Images/IconImage.swift index 10ad4f1ef..5743eaaa6 100644 --- a/Modules/Images/Sources/Images/IconImage.swift +++ b/Modules/Images/Sources/Images/IconImage.swift @@ -24,7 +24,7 @@ public final class IconImage: @unchecked Sendable { public let isBackgroundSuppressed: Bool public let preferredColor: RSColor? - private let cachedLuminanceType = Mutex(nil) + private let cachedLuminanceType: Mutex private static let luminanceQueue = DispatchQueue(label: "com.ranchero.NetNewsWire.IconImage.luminance", qos: .utility, attributes: .concurrent) public var isDark: Bool { @@ -40,10 +40,28 @@ public final class IconImage: @unchecked Sendable { self.isSymbol = isSymbol self.preferredColor = preferredColor self.isBackgroundSuppressed = isBackgroundSuppressed + self.cachedLuminanceType = Mutex(nil) if !isBackgroundSuppressed && Thread.isMainThread { preloadLuminanceType() } } + + private init(_ image: RSImage, luminanceType: ImageLuminanceType) { + self.image = image + self.isSymbol = false + self.preferredColor = nil + self.isBackgroundSuppressed = false + self.cachedLuminanceType = Mutex(luminanceType) + } + + /// Decodes the image and computes its luminance off the main thread, so neither happens when a view first shows it. + @concurrent public static func decodedIconImage(_ data: Data) async -> IconImage? { + guard let image = RSImage.decodedImage(data: data) else { + return nil + } + let luminanceType = Self.luminanceType(for: Self.cgImage(of: image)) + return IconImage(image, luminanceType: luminanceType) + } } private extension IconImage { @@ -53,7 +71,7 @@ private extension IconImage { return luminanceType } - let luminanceType = IconImage.luminanceType(for: luminanceCGImage()) + let luminanceType = IconImage.luminanceType(for: IconImage.cgImage(of: image)) cachedLuminanceType.withLock { if $0 == nil { $0 = luminanceType @@ -68,7 +86,7 @@ private extension IconImage { return } - let cgImage = luminanceCGImage() + let cgImage = IconImage.cgImage(of: image) IconImage.luminanceQueue.async { let luminanceType = IconImage.luminanceType(for: cgImage) self.cachedLuminanceType.withLock { @@ -79,7 +97,7 @@ private extension IconImage { } } - func luminanceCGImage() -> CGImage? { + static func cgImage(of image: RSImage) -> CGImage? { #if os(macOS) image.cgImage(forProposedRect: nil, context: nil, hints: nil) #else diff --git a/Modules/Images/Sources/Images/SingleFaviconDownloader.swift b/Modules/Images/Sources/Images/SingleFaviconDownloader.swift index 744cf725c..3a346f073 100644 --- a/Modules/Images/Sources/Images/SingleFaviconDownloader.swift +++ b/Modules/Images/Sources/Images/SingleFaviconDownloader.swift @@ -62,9 +62,9 @@ private extension SingleFaviconDownloader { func findFavicon() async { let kind = ActivityKind.downloadFavicon(faviconURL: faviconURL) lastFailureWasTransient = false - if let scaledData = await DownloadedImageCache.shared.derivedImageData(for: faviconURL, suffix: DownloadedImageCache.scaledIconSuffix), let image = await Self.image(scaledData) { + if let scaledData = await DownloadedImageCache.shared.derivedImageData(for: faviconURL, suffix: DownloadedImageCache.scaledIconSuffix), let iconImage = await IconImage.decodedIconImage(scaledData) { DownloadedImageCache.shared.imageWasUsed(faviconURL, checksForUpdates: true) - iconImage = IconImage(image) + self.iconImage = iconImage ImageDatabase.shared.clearFailure(url: faviconURL) postDidLoadFaviconNotification() return @@ -73,12 +73,12 @@ private extension SingleFaviconDownloader { let storedData = try await DownloadedImageCache.shared.imageData(for: faviconURL, usesDownloadQueue: false, checksForUpdates: true, activityOwner: .faviconDownloader, activityKind: kind, activityDetail: homePageURL) let scaledData = await Self.scaledImageData(storedData, maxPixelSize: RSImage.maxIconPixelSize) // DownloadedImageCache records download failures, but can’t know whether the data decodes as an icon. - if let image = await Self.image(scaledData) { + if let iconImage = await IconImage.decodedIconImage(scaledData) { // An image that’s already small enough needs no second file. if scaledData != storedData { await DownloadedImageCache.shared.saveDerivedImageData(scaledData, for: faviconURL, suffix: DownloadedImageCache.scaledIconSuffix) } - iconImage = IconImage(image) + self.iconImage = iconImage ImageDatabase.shared.clearFailure(url: faviconURL) } else { ImageDatabase.shared.recordFailure(url: faviconURL) @@ -94,10 +94,6 @@ private extension SingleFaviconDownloader { RSImage.scaledImageData(data, maxPixelSize: maxPixelSize) ?? data } - @concurrent static func image(_ data: Data) async -> RSImage? { - RSImage(data: data) - } - func postDidLoadFaviconNotification() { assert(Thread.isMainThread) isFinding = false diff --git a/Modules/RSCore/Sources/RSCore/RSImage.swift b/Modules/RSCore/Sources/RSCore/RSImage.swift index 2c8a1ef7f..fffe63ef7 100644 --- a/Modules/RSCore/Sources/RSCore/RSImage.swift +++ b/Modules/RSCore/Sources/RSCore/RSImage.swift @@ -132,6 +132,36 @@ public extension RSImage { } } + /// Makes an image whose pixels are already decoded, so the first draw doesn’t decode it. + /// Call it off the main thread. + static func decodedImage(data: Data) -> RSImage? { +#if os(macOS) + guard let image = NSImage(data: data) else { + return nil + } + guard let imageSource = CGImageSourceCreateWithData(data as CFData, nil), let largestFrame = largestFrame(in: imageSource) else { + return image + } + let options: [CFString: Any] = [ + kCGImageSourceCreateThumbnailWithTransform: true, + kCGImageSourceCreateThumbnailFromImageAlways: true, + kCGImageSourceThumbnailMaxPixelSize: max(largestFrame.width, largestFrame.height), + kCGImageSourceShouldCacheImmediately: true + ] + // Thumbnail rather than CreateImageAtIndex, which mishandles indexed-color ICO files. + guard let cgImage = CGImageSourceCreateThumbnailAtIndex(imageSource, largestFrame.index, options as CFDictionary) else { + return image + } + // Same size in points as NSImage(data:), which reads it from the image’s resolution. + return NSImage(cgImage: cgImage, size: image.size) +#else + guard let image = UIImage(data: data) else { + return nil + } + return image.preparingForDisplay() ?? image +#endif + } + /// Pixel dimensions of the largest frame, read from the image header without decoding. /// Returns nil if the data can't be read as an image. static func largestFramePixelSize(_ data: Data) -> (width: Int, height: Int)? {