From 2915cb44e71ea0aa2c5926d548539400afcbd45c Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Sun, 1 Nov 2026 21:27:18 -0800 Subject: [PATCH] Parse HTML thumbnails off the main thread at fetch time. Remove batching. --- .../Timeline/TimelineViewController.swift | 39 +---- .../Images/ArticleThumbnailFinder.swift | 135 +++++++----------- .../ArticleThumbnailFinderTests.swift | 50 ++----- Shared/Timeline/FetchRequestOperation.swift | 31 +++- .../MainTimelineViewController.swift | 32 +---- iOS/SceneCoordinator.swift | 2 +- 6 files changed, 100 insertions(+), 189 deletions(-) diff --git a/Mac/MainWindow/Timeline/TimelineViewController.swift b/Mac/MainWindow/Timeline/TimelineViewController.swift index 0f4d3ad16..cbbde94c3 100644 --- a/Mac/MainWindow/Timeline/TimelineViewController.swift +++ b/Mac/MainWindow/Timeline/TimelineViewController.swift @@ -143,8 +143,6 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr return } - findThumbnailURLs() - if let representedObjects = representedObjects, representedObjects.count == 1 && representedObjects.first is Feed { showFeedNames = { for article in articles { @@ -285,7 +283,6 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr 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(handleArticleThumbnailURLsDidBecomeAvailable(_:)), name: .articleThumbnailURLsDidBecomeAvailable, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleArticleThumbnailDidBecomeAvailable(_:)), name: .articleThumbnailDidBecomeAvailable, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleArticleThumbnailDownloadDidFail(_:)), name: .articleThumbnailDownloadDidFail, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleNetworkStatusDidChange(_:)), name: .networkStatusDidChange, object: nil) @@ -758,13 +755,6 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr } } - @objc func handleArticleThumbnailURLsDidBecomeAvailable(_ notification: Notification) { - guard thumbnailMode != nil, let articleIDs = notification.userInfo?[ArticleThumbnailFinder.articleIDsKey] as? Set else { - return - } - thumbnailURLsDidChange(for: articleIDs) - } - @objc func handleArticleThumbnailDidBecomeAvailable(_ notification: Notification) { guard let thumbnailMode, let url = notification.userInfo?[ArticleThumbnailFinder.urlKey] as? String else { return @@ -782,17 +772,8 @@ final class TimelineViewController: NSViewController, UndoableCommandRunner, Unr guard thumbnailMode != nil, let articleIDs = notification.userInfo?[ArticleThumbnailFinder.articleIDsKey] as? Set else { return } - let rowsUsingURL = indexesForArticleIDs(articleIDs) - guard !rowsUsingURL.isEmpty else { - return - } - // A failed provided image falls back to images in the HTML. Those are found first, so a row that has one doesn’t shrink and then grow back. - let articlesUsingURL = rowsUsingURL.compactMap { articles.articleAtRow($0) } - Task { - await ArticleThumbnailFinder.shared.findThumbnailURLs(for: articlesUsingURL).value - // Articles that used the failed URL now get their next source, or none. - thumbnailURLsDidChange(for: articleIDs) - } + // Articles that used the failed URL now get their next source, or none. + thumbnailURLsDidChange(for: articleIDs) } @objc func handleNetworkStatusDidChange(_ notification: Notification) { @@ -1268,7 +1249,6 @@ private extension TimelineViewController { } func layoutDidChange() { - findThumbnailURLs() performBlockAndRestoreSelection { configureTableView(for: layout) updateShowIcons() @@ -1399,12 +1379,14 @@ private extension TimelineViewController { } func thumbnailsDisplayDidChange() { + if thumbnailsDisplay.thumbnailMode == nil { + ArticleThumbnailFinder.shared.emptyHTMLThumbnailCache() + } updateCellAppearances() updateLargeThumbnailRowHeight() guard layout == .standard else { return } - findThumbnailURLs() performBlockAndRestoreSelection { tableView.reloadData() } @@ -1413,15 +1395,6 @@ private extension TimelineViewController { } } - /// Finds thumbnails in the HTML of articles with no provided image. Local work, no downloads. - /// Row heights and text width depend on having a thumbnail URL, so this runs before rows are laid out. - func findThumbnailURLs() { - guard thumbnailMode != nil else { - return - } - ArticleThumbnailFinder.shared.findThumbnailURLs(for: articles) - } - // MARK: - Appearance Change private func updateCellAppearances() { @@ -1514,7 +1487,7 @@ private extension TimelineViewController { precondition(Thread.isMainThread) cancelPendingAsyncFetches() let fetchers = representedObjects.compactMap { $0 as? ArticleFetcher } - let fetchOperation = FetchRequestOperation(id: fetchSerialNumber, readFilterEnabledTable: readFilterEnabledTable, fetchers: fetchers) { [weak self] (articles, operation) in + let fetchOperation = FetchRequestOperation(id: fetchSerialNumber, readFilterEnabledTable: readFilterEnabledTable, fetchers: fetchers, findsThumbnailURLs: thumbnailMode != nil) { [weak self] (articles, operation) in precondition(Thread.isMainThread) guard !operation.isCanceled, let strongSelf = self, operation.id == strongSelf.fetchSerialNumber else { return diff --git a/Modules/Images/Sources/Images/ArticleThumbnailFinder.swift b/Modules/Images/Sources/Images/ArticleThumbnailFinder.swift index 404171bb8..7d166a355 100644 --- a/Modules/Images/Sources/Images/ArticleThumbnailFinder.swift +++ b/Modules/Images/Sources/Images/ArticleThumbnailFinder.swift @@ -18,10 +18,6 @@ import RSWeb import ActivityLog extension Notification.Name { - /// Posted when `findThumbnailURLs(for:)` parses thumbnails from article HTML. - /// userInfo key: `ArticleThumbnailFinder.articleIDsKey` (`Set`). - public static let articleThumbnailURLsDidBecomeAvailable = Notification.Name("ArticleThumbnailURLsDidBecomeAvailable") - /// Posted when a thumbnail image requested by `thumbnail(for:mode:)` is ready. /// userInfo key: `ArticleThumbnailFinder.urlKey` (the thumbnail URL). public static let articleThumbnailDidBecomeAvailable = Notification.Name("ArticleThumbnailDidBecomeAvailable") @@ -39,8 +35,9 @@ extension Notification.Name { /// tries them in that order. Large mode tries the article’s image and attachments /// before the provided thumbnail, which is usually too small to fill the timeline’s width. /// -/// The first three sources are property reads. The HTML is parsed by `findThumbnailURLs(for:)`, -/// and the results are cached in memory, so each article’s HTML is parsed once per launch. +/// The first three sources are property reads. The HTML is parsed off the main thread by +/// `findThumbnailURLs(for:)` at fetch time, or by `thumbnailURL(for:mode:)` on a cache miss. +/// The results are cached in memory until the app goes to the background or memory is low. /// Parsing 1,000 articles takes about 0.036 seconds on an M1 Max in a release build, measured /// on 8,660 real articles: median 0.000018 seconds and 2,463 bytes of HTML per article. /// @@ -63,7 +60,6 @@ extension Notification.Name { private let imageDatabase: ImageDatabase private var htmlThumbnailURLs = [String: [String]]() // articleID: thumbnailURLs, in document order. Empty when the HTML has none. - private var articleIDsBeingDiscovered = Set() private let imageCache = NSCache() // See cacheKey private let decodeQueue = ThumbnailTaskQueue(maximumRunningCount: maximumConcurrentDecodes, maximumWaitingCount: maximumWaitingDecodes) private var decodeKeysInProgress = Set() @@ -88,12 +84,6 @@ extension Notification.Name { #endif /// HTML images kept per article, so one that fails or is too small falls through to the next. nonisolated private static let maxHTMLThumbnailURLsPerArticle = 3 - /// Articles parsed at a time off the main thread. - static let parsingBatchSize = 100 - /// Parsed on the main thread, so that rows laid out next can use the results. - static let maximumArticlesParsedBeforeReturning = 1000 - /// Entries in htmlThumbnailURLs, a few hundred bytes each. Past this, it’s emptied, and the next discovery parses its articles again. - private static let maxCachedArticleCount = 50_000 /// Entries per mode in chosenThumbnailURLs. Past this, that mode’s entries are emptied. private static let maxChosenThumbnailURLCount = 50_000 private static let maximumConcurrentDecodes = 4 @@ -104,8 +94,8 @@ extension Notification.Name { self.imageDatabase = imageDatabase self.imageCache.totalCostLimit = Self.imageCacheByteLimit - // Not flushed on appDidGoToBackground, which would make thumbnails flash on resume. NotificationCenter.default.addObserver(self, selector: #selector(handleLowMemory(_:)), name: .lowMemory, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(handleAppDidGoToBackground(_:)), name: .appDidGoToBackground, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleNetworkStatusDidChange(_:)), name: .networkStatusDidChange, object: nil) } @@ -133,14 +123,14 @@ extension Notification.Name { try await DownloadedImageCache.shared.imageData(for: url, usesDownloadQueue: false, checksForUpdates: false, activityOwner: .thumbnailDownloader, activityKind: .downloadThumbnail(imageURL: url), activityDetail: articleTitle) } - /// Nil when the article has no usable image, or when its HTML hasn’t been checked yet. + /// Nil when the article has no usable image. Parses the article’s HTML when it isn’t cached. public func thumbnailURL(for article: Article, mode: Mode) -> String? { let articleID = article.articleID if let chosenThumbnailURL = chosenThumbnailURLs[mode]?[articleID], chosenThumbnailURL.hasSameImages(as: article) { return chosenThumbnailURL.thumbnailURL } - let thumbnailURL = providedThumbnailURL(for: article, mode: mode) ?? htmlThumbnailURLs[articleID]?.first { !hasFailed($0) } + let thumbnailURL = providedThumbnailURL(for: article, mode: mode) ?? cachedOrParsedHTMLThumbnailURLs(for: article).first { !hasFailed($0) } if chosenThumbnailURLs[mode, default: [:]].count >= Self.maxChosenThumbnailURLCount { chosenThumbnailURLs[mode] = nil } @@ -148,38 +138,28 @@ extension Notification.Name { return thumbnailURL } - /// Looks for thumbnails in the HTML of articles that have no usable provided image. - /// The first articles are parsed before this returns, so that rows laid out next can use the results. - /// The rest are parsed off the main thread in batches, in the order given. - /// `.articleThumbnailURLsDidBecomeAvailable` is posted after this returns, for those that have thumbnails: once for the first articles, then after each batch. - /// The returned task finishes after the last batch. - @discardableResult public func findThumbnailURLs(for articles: some Collection
) -> Task { - if htmlThumbnailURLs.count > Self.maxCachedArticleCount { - htmlThumbnailURLs.removeAll() - } - - let articleHTMLs = articles.filter(needsHTMLDiscovery).compactMap(ArticleHTML.init) - let recordsParsedBeforeReturning = Self.thumbnailRecords(Array(articleHTMLs.prefix(Self.maximumArticlesParsedBeforeReturning))) - cacheRecords(recordsParsedBeforeReturning) - - let articleHTMLsToParseLater = Array(articleHTMLs.dropFirst(Self.maximumArticlesParsedBeforeReturning)) - let articleIDsToParseLater = articleHTMLsToParseLater.map(\.articleID) - articleIDsBeingDiscovered.formUnion(articleIDsToParseLater) - - return Task { - defer { - articleIDsBeingDiscovered.subtract(articleIDsToParseLater) - } - - postThumbnailURLsDidBecomeAvailable(recordsParsedBeforeReturning) - - for batchStart in stride(from: 0, to: articleHTMLsToParseLater.count, by: Self.parsingBatchSize) { - let batchEnd = min(batchStart + Self.parsingBatchSize, articleHTMLsToParseLater.count) - let parsedRecords = await Self.parseThumbnailURLs(Array(articleHTMLsToParseLater[batchStart..) async { + var articleHTMLs = [ArticleHTML]() + for article in articles where needsHTMLParsing(article) { + if let articleHTML = ArticleHTML(article) { + articleHTMLs.append(articleHTML) + } else { + htmlThumbnailURLs[article.articleID] = [] } } + guard !articleHTMLs.isEmpty else { + return + } + + let parsedThumbnailURLs = await Self.parsedThumbnailURLs(articleHTMLs) + htmlThumbnailURLs.merge(parsedThumbnailURLs) { _, parsedURLs in parsedURLs } + } + + /// Empties the results of parsing article HTML, which `thumbnailURL(for:mode:)` parses again as needed. + public func emptyHTMLThumbnailCache() { + htmlThumbnailURLs.removeAll() + chosenThumbnailURLs.removeAll() } func thumbnailDidFail(url: String, error: ImageDownloadError) { @@ -209,7 +189,12 @@ extension Notification.Name { @objc func handleLowMemory(_ notification: Notification) { imageCache.removeAllObjects() - chosenThumbnailURLs.removeAll() + emptyHTMLThumbnailCache() + } + + /// Leaves imageCache alone, since emptying it would make thumbnails flash on resume. + @objc func handleAppDidGoToBackground(_ notification: Notification) { + emptyHTMLThumbnailCache() } /// What failed to decode may have been a captive portal’s login page, not the image. @@ -243,13 +228,6 @@ private extension ArticleThumbnailFinder { } } - /// The result of looking for thumbnails in an article’s HTML. - /// `thumbnailURLs` is in document order, and empty when the HTML has no usable image. - struct ArticleThumbnailRecord: Sendable { - let articleID: String - let thumbnailURLs: [String] - } - struct ArticleHTML: Sendable { let articleID: String let html: String @@ -263,6 +241,11 @@ private extension ArticleThumbnailFinder { self.html = html self.baseURL = article.baseURL } + + /// In document order. Empty when the HTML has no usable image. + nonisolated func parsedThumbnailURLs() -> [String] { + HTMLImageParser.significantImageURLStrings(html: html, baseURL: baseURL, maximumCount: maxHTMLThumbnailURLsPerArticle) + } } /// The same URL can be cached at both sizes. @@ -348,42 +331,30 @@ private extension ArticleThumbnailFinder { imageDatabase.recentlyFailed(url: urlString) || imageDatabase.isUnsuitableForThumbnail(url: urlString) || urlsThatFailedToDecode.contains(urlString) } - func needsHTMLDiscovery(_ article: Article) -> Bool { - let articleID = article.articleID - if isCached(articleID) || articleIDsBeingDiscovered.contains(articleID) { + func needsHTMLParsing(_ article: Article) -> Bool { + guard htmlThumbnailURLs[article.articleID] == nil else { return false } - // Without HTML results, thumbnailURL is the provided image. Which one is chosen depends on mode, but whether there is one doesn’t. - return thumbnailURL(for: article, mode: .small) == nil + // Which provided image is chosen depends on mode, but whether there is one doesn’t. + return providedThumbnailURL(for: article, mode: .small) == nil } - func isCached(_ articleID: String) -> Bool { - htmlThumbnailURLs[articleID] != nil - } - - func cacheRecords(_ records: [ArticleThumbnailRecord]) { - forgetChosenThumbnailURLs(records.map(\.articleID)) - for record in records { - htmlThumbnailURLs[record.articleID] = record.thumbnailURLs + func cachedOrParsedHTMLThumbnailURLs(for article: Article) -> [String] { + if let thumbnailURLs = htmlThumbnailURLs[article.articleID] { + return thumbnailURLs } + let thumbnailURLs = ArticleHTML(article)?.parsedThumbnailURLs() ?? [] + htmlThumbnailURLs[article.articleID] = thumbnailURLs + return thumbnailURLs } - func postThumbnailURLsDidBecomeAvailable(_ records: [ArticleThumbnailRecord]) { - let foundArticleIDs = Set(records.filter { !$0.thumbnailURLs.isEmpty }.map(\.articleID)) - if !foundArticleIDs.isEmpty { - NotificationCenter.default.post(name: .articleThumbnailURLsDidBecomeAvailable, object: self, userInfo: [Self.articleIDsKey: foundArticleIDs]) - } - } - - @concurrent static func parseThumbnailURLs(_ articleHTMLs: [ArticleHTML]) async -> [ArticleThumbnailRecord] { - thumbnailRecords(articleHTMLs) - } - - nonisolated static func thumbnailRecords(_ articleHTMLs: [ArticleHTML]) -> [ArticleThumbnailRecord] { - articleHTMLs.map { articleHTML in - let thumbnailURLs = HTMLImageParser.significantImageURLStrings(html: articleHTML.html, baseURL: articleHTML.baseURL, maximumCount: maxHTMLThumbnailURLsPerArticle) - return ArticleThumbnailRecord(articleID: articleHTML.articleID, thumbnailURLs: thumbnailURLs) + /// articleID: thumbnailURLs + @concurrent static func parsedThumbnailURLs(_ articleHTMLs: [ArticleHTML]) async -> [String: [String]] { + var thumbnailURLs = [String: [String]]() + for articleHTML in articleHTMLs { + thumbnailURLs[articleHTML.articleID] = articleHTML.parsedThumbnailURLs() } + return thumbnailURLs } static func firstSignificantImageAttachmentURL(_ article: Article) -> String? { diff --git a/Modules/Images/Tests/ImagesTests/ArticleThumbnailFinderTests.swift b/Modules/Images/Tests/ImagesTests/ArticleThumbnailFinderTests.swift index e8d0737c2..31fc414e1 100644 --- a/Modules/Images/Tests/ImagesTests/ArticleThumbnailFinderTests.swift +++ b/Modules/Images/Tests/ImagesTests/ArticleThumbnailFinderTests.swift @@ -60,9 +60,7 @@ private typealias ArticleAttachment = Articles.Attachment let articleWithImage = makeArticle(articleID: "1", contentHTML: html) let articleWithoutImage = makeArticle(articleID: "2", contentHTML: "

No images.

") - #expect(finder.thumbnailURL(for: articleWithImage, mode: .small) == nil) - - await finder.findThumbnailURLs(for: [articleWithImage, articleWithoutImage]).value + await finder.findThumbnailURLs(for: [articleWithImage, articleWithoutImage]) #expect(finder.thumbnailURL(for: articleWithImage, mode: .small) == "https://example.com/uploads/photo.jpg") #expect(finder.thumbnailURL(for: articleWithoutImage, mode: .small) == nil) @@ -76,15 +74,20 @@ private typealias ArticleAttachment = Articles.Attachment let finder = ArticleThumbnailFinder(imageDatabase: imageDatabase) let article = makeArticle(contentHTML: #"

"#, thumbnailURL: "https://example.com/thumbnail.jpg") - // The HTML isn’t parsed while the provided image is usable. - await finder.findThumbnailURLs(for: [article]).value + await finder.findThumbnailURLs(for: [article]) #expect(finder.thumbnailURL(for: article, mode: .small) == "https://example.com/thumbnail.jpg") imageDatabase.recordFailure(url: "https://example.com/thumbnail.jpg", statusCode: 404) finder.thumbnailURLDidFail("https://example.com/thumbnail.jpg") - #expect(finder.thumbnailURL(for: article, mode: .small) == nil) + #expect(finder.thumbnailURL(for: article, mode: .small) == "https://example.com/uploads/photo.jpg") + } - await finder.findThumbnailURLs(for: [article]).value + @Test func htmlThumbnailIsParsedOnCacheMissAndAfterCacheIsEmptied() { + let finder = ArticleThumbnailFinder(imageDatabase: ImageDatabase(databasePath: ":memory:")) + let article = makeArticle(contentHTML: #"

"#) + #expect(finder.thumbnailURL(for: article, mode: .small) == "https://example.com/uploads/photo.jpg") + + finder.handleAppDidGoToBackground(Notification(name: .appDidGoToBackground)) #expect(finder.thumbnailURL(for: article, mode: .small) == "https://example.com/uploads/photo.jpg") } @@ -116,24 +119,6 @@ private typealias ArticleAttachment = Articles.Attachment #expect(finder.thumbnailURL(for: differentImages, mode: .small) == "https://example.com/new-image.jpg") } - @Test func articlesPastTheLimitAreParsedAfterReturningAndPostedInBatches() async throws { - let finder = ArticleThumbnailFinder(imageDatabase: ImageDatabase(databasePath: ":memory:")) - let limit = ArticleThumbnailFinder.maximumArticlesParsedBeforeReturning - let batchSize = ArticleThumbnailFinder.parsingBatchSize - let articles = (0...(limit + batchSize)).map { makeArticle(articleID: String($0), contentHTML: #"

"#) } - let lastArticleParsedBeforeReturning = articles[limit - 1] - let lastArticle = try #require(articles.last) - let recorder = ThumbnailURLNotificationRecorder(finder: finder) - - let parsing = finder.findThumbnailURLs(for: articles) - #expect(finder.thumbnailURL(for: lastArticleParsedBeforeReturning, mode: .small) == "https://example.com/uploads/photo.jpg") - #expect(finder.thumbnailURL(for: lastArticle, mode: .small) == nil) - - await parsing.value - #expect(finder.thumbnailURL(for: lastArticle, mode: .small) == "https://example.com/uploads/photo.jpg") - #expect(recorder.articleIDCounts == [limit, batchSize, 1]) - } - @Test func thumbnailTooSmallIsRejected() async throws { let smallImageData = try #require(jpegData(width: 48, height: 48)) @@ -176,21 +161,6 @@ private typealias ArticleAttachment = Articles.Attachment // MARK: - Helpers -@MainActor private final class ThumbnailURLNotificationRecorder { - - private(set) var articleIDCounts = [Int]() - - init(finder: ArticleThumbnailFinder) { - NotificationCenter.default.addObserver(self, selector: #selector(handleArticleThumbnailURLsDidBecomeAvailable(_:)), name: .articleThumbnailURLsDidBecomeAvailable, object: finder) - } - - @objc func handleArticleThumbnailURLsDidBecomeAvailable(_ notification: Notification) { - if let articleIDs = notification.userInfo?[ArticleThumbnailFinder.articleIDsKey] as? Set { - articleIDCounts.append(articleIDs.count) - } - } -} - private func makeArticle(articleID: String = "1", contentHTML: String? = nil, imageURL: String? = nil, thumbnailURL: String? = nil, attachments: [ArticleAttachment]? = nil) -> Article { let status = ArticleStatus(articleID: articleID, read: false, starred: false, dateArrived: Date()) return Article(accountID: "account", articleID: articleID, feedID: "feed", uniqueID: articleID, title: nil, contentHTML: contentHTML, contentText: nil, markdown: nil, url: "https://example.com/posts/\(articleID)", externalURL: nil, summary: nil, imageURL: imageURL, thumbnailURL: thumbnailURL, datePublished: nil, dateModified: nil, authors: nil, attachments: attachments, status: status) diff --git a/Shared/Timeline/FetchRequestOperation.swift b/Shared/Timeline/FetchRequestOperation.swift index 0de7a9d07..b644bdf28 100644 --- a/Shared/Timeline/FetchRequestOperation.swift +++ b/Shared/Timeline/FetchRequestOperation.swift @@ -13,6 +13,7 @@ import RSDatabase import Account import Articles import ErrorLog +import Images // Main thread only. // Runs an asynchronous fetch. @@ -33,12 +34,14 @@ typealias FetchRequestOperationResultBlock = (Set
, FetchRequestOperatio var isCanceled = false var isFinished = false private let fetchers: [ArticleFetcher] + private let findsThumbnailURLs: Bool - init(id: Int, readFilterEnabledTable: [SidebarItemIdentifier: Bool], fetchers: [ArticleFetcher], resultBlock: @escaping FetchRequestOperationResultBlock) { + init(id: Int, readFilterEnabledTable: [SidebarItemIdentifier: Bool], fetchers: [ArticleFetcher], findsThumbnailURLs: Bool, resultBlock: @escaping FetchRequestOperationResultBlock) { precondition(Thread.isMainThread) self.id = id self.readFilterEnabledTable = readFilterEnabledTable self.fetchers = fetchers + self.findsThumbnailURLs = findsThumbnailURLs self.resultBlock = resultBlock } @@ -74,7 +77,7 @@ typealias FetchRequestOperationResultBlock = (Set
, FetchRequestOperatio var fetchersReturned = 0 var fetchedArticles = Set
() - @MainActor func process(_ articles: Set
) { + @MainActor func process(_ articles: Set
) async { precondition(Thread.isMainThread) guard !self.isCanceled else { callCompletionIfNeeded() @@ -86,6 +89,13 @@ typealias FetchRequestOperationResultBlock = (Set
, FetchRequestOperatio fetchedArticles.formUnion(articles) fetchersReturned += 1 if fetchersReturned == numberOfFetchers { + if findsThumbnailURLs { + await ArticleThumbnailFinder.shared.findThumbnailURLs(for: fetchedArticles) + guard !self.isCanceled else { + callCompletionIfNeeded() + return + } + } self.isFinished = true self.resultBlock(fetchedArticles, self) callCompletionIfNeeded() @@ -101,7 +111,7 @@ typealias FetchRequestOperationResultBlock = (Set
, FetchRequestOperatio articles = await fetcher.fetchArticlesAsync() } - process(articles) + await process(articles) } // Belt-and-suspenders: ensure the queue never deadlocks even if @@ -121,12 +131,14 @@ typealias FetchRequestOperationResultBlock = (Set
, FetchRequestOperatio var isCanceled = false var isFinished = false private let fetchers: [ArticleFetcher] + private let findsThumbnailURLs: Bool - init(id: Int, hidingReadArticlesState: HidingReadArticlesState, fetchers: [ArticleFetcher], resultBlock: @escaping FetchRequestOperationResultBlock) { + init(id: Int, hidingReadArticlesState: HidingReadArticlesState, fetchers: [ArticleFetcher], findsThumbnailURLs: Bool, resultBlock: @escaping FetchRequestOperationResultBlock) { precondition(Thread.isMainThread) self.id = id self.hidingReadArticlesState = hidingReadArticlesState self.fetchers = fetchers + self.findsThumbnailURLs = findsThumbnailURLs self.resultBlock = resultBlock } @@ -162,7 +174,7 @@ typealias FetchRequestOperationResultBlock = (Set
, FetchRequestOperatio var fetchersReturned = 0 var fetchedArticles = Set
() - @MainActor func process(_ articles: Set
) { + @MainActor func process(_ articles: Set
) async { precondition(Thread.isMainThread) guard !self.isCanceled else { callCompletionIfNeeded() @@ -174,6 +186,13 @@ typealias FetchRequestOperationResultBlock = (Set
, FetchRequestOperatio fetchedArticles.formUnion(articles) fetchersReturned += 1 if fetchersReturned == numberOfFetchers { + if findsThumbnailURLs { + await ArticleThumbnailFinder.shared.findThumbnailURLs(for: fetchedArticles) + guard !self.isCanceled else { + callCompletionIfNeeded() + return + } + } self.isFinished = true self.resultBlock(fetchedArticles, self) callCompletionIfNeeded() @@ -194,7 +213,7 @@ typealias FetchRequestOperationResultBlock = (Set
, FetchRequestOperatio } else { articles = await fetcher.fetchArticlesAsync() } - process(articles) + await process(articles) } // Ensure the queue never deadlocks even if diff --git a/iOS/MainTimeline/MainTimelineViewController.swift b/iOS/MainTimeline/MainTimelineViewController.swift index eed562846..f8a39f46d 100644 --- a/iOS/MainTimeline/MainTimelineViewController.swift +++ b/iOS/MainTimeline/MainTimelineViewController.swift @@ -757,7 +757,6 @@ private extension MainTimelineViewController { NotificationCenter.default.addObserver(self, selector: #selector(timelineIconSizeDidChange(_:)), name: .timelineIconSizeDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(timelineNumberOfLinesDidChange(_:)), name: .timelineNumberOfLinesDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleTimelineThumbnailsDisplayDidChange(_:)), name: .timelineThumbnailsDisplayDidChange, object: nil) - NotificationCenter.default.addObserver(self, selector: #selector(handleArticleThumbnailURLsDidBecomeAvailable(_:)), name: .articleThumbnailURLsDidBecomeAvailable, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleArticleThumbnailDidBecomeAvailable(_:)), name: .articleThumbnailDidBecomeAvailable, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleArticleThumbnailDownloadDidFail(_:)), name: .articleThumbnailDownloadDidFail, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleNetworkStatusDidChange(_:)), name: .networkStatusDidChange, object: nil) @@ -1082,8 +1081,6 @@ private extension MainTimelineViewController { return } - findThumbnailURLs() - var snapshot = NSDiffableDataSourceSnapshot() snapshot.appendSections([0]) snapshot.appendItems(articles ?? ArticleArray(), toSection: 0) @@ -1108,15 +1105,6 @@ private extension MainTimelineViewController { reloadCells(visibleArticles().filter { articleIDs.contains($0.articleID) }) } - /// Finds thumbnails in the HTML of articles with no provided image. Local work, no downloads. - /// Results for the first articles are ready when this returns, so rows laid out next get their final heights. - func findThumbnailURLs() { - guard thumbnailMode != nil, let articles, !articles.isEmpty else { - return - } - ArticleThumbnailFinder.shared.findThumbnailURLs(for: articles) - } - func visibleArticles() -> [Article] { guard let collectionView, let dataSource else { return [] @@ -1199,15 +1187,10 @@ private extension MainTimelineViewController { return } thumbnailsDisplay = AppDefaults.timelineThumbnailsDisplay - findThumbnailURLs() - reloadAllCells() - } - - @objc func handleArticleThumbnailURLsDidBecomeAvailable(_ notification: Notification) { - guard thumbnailMode != nil, let articleIDs = notification.userInfo?[ArticleThumbnailFinder.articleIDsKey] as? Set else { - return + if thumbnailMode == nil { + ArticleThumbnailFinder.shared.emptyHTMLThumbnailCache() } - thumbnailURLsDidChange(for: articleIDs) + reloadAllCells() } @objc func handleArticleThumbnailDidBecomeAvailable(_ notification: Notification) { @@ -1227,13 +1210,8 @@ private extension MainTimelineViewController { guard thumbnailMode != nil, let articleIDs = notification.userInfo?[ArticleThumbnailFinder.articleIDsKey] as? Set else { return } - // A failed provided image falls back to images in the HTML. Those are found first, so a row that has one doesn’t shrink and then grow back. - let articlesUsingURL = articles?.filter { articleIDs.contains($0.articleID) } ?? [] - Task { - await ArticleThumbnailFinder.shared.findThumbnailURLs(for: articlesUsingURL).value - // Articles that used the failed URL now get their next source, or none. - thumbnailURLsDidChange(for: articleIDs) - } + // Articles that used the failed URL now get their next source, or none. + thumbnailURLsDidChange(for: articleIDs) } @objc func handleNetworkStatusDidChange(_ notification: Notification) { diff --git a/iOS/SceneCoordinator.swift b/iOS/SceneCoordinator.swift index 29f4de5b1..a21087bee 100644 --- a/iOS/SceneCoordinator.swift +++ b/iOS/SceneCoordinator.swift @@ -2563,7 +2563,7 @@ private extension SceneCoordinator { cancelPendingAsyncFetches() let fetchers = representedObjects.compactMap { $0 as? ArticleFetcher } - let fetchOperation = FetchRequestOperation(id: fetchSerialNumber, hidingReadArticlesState: hidingReadArticlesState, fetchers: fetchers) { [weak self] (articles, operation) in + let fetchOperation = FetchRequestOperation(id: fetchSerialNumber, hidingReadArticlesState: hidingReadArticlesState, fetchers: fetchers, findsThumbnailURLs: AppDefaults.timelineThumbnailsDisplay.thumbnailMode != nil) { [weak self] (articles, operation) in precondition(Thread.isMainThread) guard !operation.isCanceled, let strongSelf = self, operation.id == strongSelf.fetchSerialNumber else { return